allwright 1.70.0 → 1.71.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 +118 -108
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var zm=Object.create;var ca=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var Lm=Object.getOwnPropertyNames;var Um=Object.getPrototypeOf,qm=Object.prototype.hasOwnProperty;var we=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ce=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},hn=(t,e)=>{for(var n in e)ca(t,n,{get:e[n],enumerable:!0})},Fm=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lm(e))!qm.call(t,s)&&s!==n&&ca(t,s,{get:()=>e[s],enumerable:!(r=Dm(e,s))||r.enumerable});return t};var E=(t,e,n)=>(n=t!=null?zm(Um(t)):{},Fm(e||!t||!t.__esModule?ca(n,"default",{value:t,enumerable:!0}):n,t));var Us=ce(da=>{var Ei=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}},ua=class extends Ei{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};da.CommanderError=Ei;da.InvalidArgumentError=ua});var Ai=ce(pa=>{var{InvalidArgumentError:Bm}=Us(),ha=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 Bm(`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
|
|
2
|
+
"use strict";var zm=Object.create;var ca=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var Lm=Object.getOwnPropertyNames;var Um=Object.getPrototypeOf,qm=Object.prototype.hasOwnProperty;var we=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ce=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},hn=(t,e)=>{for(var n in e)ca(t,n,{get:e[n],enumerable:!0})},Fm=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lm(e))!qm.call(t,s)&&s!==n&&ca(t,s,{get:()=>e[s],enumerable:!(r=Dm(e,s))||r.enumerable});return t};var E=(t,e,n)=>(n=t!=null?zm(Um(t)):{},Fm(e||!t||!t.__esModule?ca(n,"default",{value:t,enumerable:!0}):n,t));var Us=ce(da=>{var Ei=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}},ua=class extends Ei{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};da.CommanderError=Ei;da.InvalidArgumentError=ua});var Ai=ce(pa=>{var{InvalidArgumentError:Bm}=Us(),ha=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 Bm(`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 Hm(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}pa.Argument=ha;pa.humanReadableArgName=Hm});var ma=ce(nu=>{var{humanReadableArgName:Km}=Ai(),fa=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=>Km(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(k,x){if(x){let I=`${k.padEnd(r+o)}${x}`;return n.wrap(I,s-i,r+o)}return k}function c(k){return k.join(`
|
|
3
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(k=>l(n.argumentTerm(k),n.argumentDescription(k)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let w=n.visibleOptions(e).map(k=>l(n.optionTerm(k),n.optionDescription(k)));if(w.length>0&&(u=u.concat(["Options:",c(w),""])),this.showGlobalOptions){let k=n.visibleGlobalOptions(e).map(x=>l(n.optionTerm(x),n.optionDescription(x)));k.length>0&&(u=u.concat(["Global Options:",c(k),""]))}let v=n.visibleCommands(e).map(k=>l(n.subcommandTerm(k),n.subcommandDescription(k)));return v.length>0&&(u=u.concat(["Commands:",c(v),""])),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
|
`,`
|
|
@@ -20,13 +20,13 @@ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
20
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 ve.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()}`,ve.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new tg(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=ou(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=ou(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
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=>Qm(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=Ut.basename(e,Ut.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=ve.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 au(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})}lu.Command=Sa});var pu=ce(st=>{var{Argument:uu}=Ai(),{Command:Ta}=cu(),{CommanderError:ng,InvalidArgumentError:du}=Us(),{Help:rg}=ma(),{Option:hu}=wa();st.program=new Ta;st.createCommand=t=>new Ta(t);st.createOption=(t,e)=>new hu(t,e);st.createArgument=(t,e)=>new uu(t,e);st.Command=Ta;st.Option=hu;st.Argument=uu;st.Help=rg;st.CommanderError=ng;st.InvalidArgumentError=du;st.InvalidOptionArgumentError=du});var oe,xa,D,xt,qs=we(()=>{(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})(oe||(oe={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(xa||(xa={}));D=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=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 A,sg,Ge,Ci=we(()=>{qs();A=oe.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"]),sg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ge=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,oe.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()}};Ge.create=t=>new Ge(t)});var ig,qt,Ia=we(()=>{Ci();qs();ig=(t,e)=>{let n;switch(t.code){case A.invalid_type:t.received===D.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,oe.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${oe.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${oe.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${oe.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.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}"`:oe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case A.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 A.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 A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=e.defaultError,oe.assertNever(t)}return{message:n}},qt=ig});function og(t){gu=t}function Hr(){return gu}var gu,$i=we(()=>{Ia();gu=qt});function M(t,e){let n=Hr(),r=Fs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===qt?void 0:qt].filter(s=>!!s)});t.common.issues.push(r)}var Fs,ag,Ae,Y,Dn,Ne,Pi,ji,pn,Gr,Ra=we(()=>{$i();Ia();Fs=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}},ag=[];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 Y;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 Y;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}}},Y=Object.freeze({status:"aborted"}),Dn=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),Pi=t=>t.status==="aborted",ji=t=>t.status==="dirty",pn=t=>t.status==="valid",Gr=t=>typeof Promise<"u"&&t instanceof Promise});var yu=we(()=>{});var B,bu=we(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(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 _u(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 Tg(t){return new RegExp(`^${_u(t)}$`)}function Su(t){let e=`${ku}T${_u(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 xg(t,e){return!!((e==="v4"||!e)&&yg.test(t)||(e==="v6"||!e)&&wg.test(t))}function Ig(t,e){if(!pg.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 Rg(t,e){return!!((e==="v4"||!e)&&bg.test(t)||(e==="v6"||!e)&&vg.test(t))}function Eg(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 Zr(t){if(t instanceof Ze){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=it.create(Zr(r))}return new Ze({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:Zr(t.element)}):t instanceof it?it.create(Zr(t.unwrap())):t instanceof Rt?Rt.create(Zr(t.unwrap())):t instanceof It?It.create(t.items.map(e=>Zr(e))):t}function Aa(t,e){let n=xt(t),r=xt(e);if(t===e)return{valid:!0,data:t};if(n===D.object&&r===D.object){let s=oe.objectKeys(e),i=oe.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Aa(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=Aa(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 Tu(t,e){return new Vn({values:t,typeName:X.ZodEnum,...te(e)})}function vu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function xu(t,e={},n){return t?mn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=vu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=vu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):mn.create()}var ot,wu,se,lg,cg,ug,dg,hg,pg,fg,mg,gg,Ea,yg,bg,wg,vg,kg,_g,ku,Sg,fn,Ln,Un,qn,Fn,Wr,Bn,Kn,mn,Bt,yt,Vr,Kt,Ze,Hn,Ft,Ni,Gn,It,Oi,Jr,Yr,Mi,Zn,Wn,Vn,Jn,gn,at,it,Rt,Yn,Xn,Xr,Ag,Bs,Ks,Qn,Cg,X,$g,Iu,Ru,Pg,jg,Eu,Ng,Og,Mg,zg,Dg,Lg,Ug,qg,Fg,Bg,Kg,Hg,Gg,Zg,Wg,Vg,Jg,Yg,Xg,Qg,ey,ty,ny,ry,sy,iy,oy,ay,ly,cy,uy,dy,hy,py,Au=we(()=>{Ci();$i();bu();Ra();qs();ot=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}},wu=(t,e)=>{if(pn(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 Ge(t.common.issues);return this._error=n,this._error}}};se=class{get description(){return this._def.description}_getType(e){return xt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:xt(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:xt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Gr(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:xt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return wu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return pn(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=>pn(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:xt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Gr(s)?s:Promise.resolve(s));return wu(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.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 at({schema:this,typeName:X.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 it.create(this,this._def)}nullable(){return Rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return gn.create(this,this._def)}or(e){return Hn.create([this,e],this._def)}and(e){return Gn.create(this,e,this._def)}transform(e){return new at({...te(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Yn({...te(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Bs({typeName:X.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Xn({...te(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ks.create(this,e)}readonly(){return Qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},lg=/^c[^\s-]{8,}$/i,cg=/^[0-9a-z]+$/,ug=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dg=/^[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,hg=/^[a-z0-9_-]{21}$/i,pg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fg=/^[-+]?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)?)??$/,mg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",yg=/^(?:(?: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])$/,bg=/^(?:(?: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])$/,wg=/^(([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]))$/,vg=/^(([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])$/,kg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_g=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ku="((\\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])))",Sg=new RegExp(`^${ku}$`);fn=class t extends se{_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:A.invalid_type,expected:D.string,received:i.parsedType}),Y}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:A.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:A.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:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&M(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")mg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ea||(Ea=new RegExp(gg,"u")),Ea.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")dg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")hg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")lg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")cg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ug.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ulid",code:A.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:A.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:A.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:A.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:A.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:A.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Su(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Sg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Tg(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?fg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?xg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Ig(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Rg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?kg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?_g.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:A.invalid_string,message:i.message}),r.dirty()):oe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.invalid_string,...B.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...B.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...B.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...B.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...B.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...B.errToObj(n)})}nonempty(e){return this.min(1,B.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}};fn.create=t=>new fn({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...te(t)});Ln=class t extends se{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:A.invalid_type,expected:D.number,received:i.parsedType}),Y}let r,s=new Ae;for(let i of this._def.checks)i.kind==="int"?oe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:A.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:A.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:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Eg(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:A.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:A.not_finite,message:i.message}),s.dirty()):oe.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.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"&&oe.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)}};Ln.create=t=>new Ln({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...te(t)});Un=class t extends se{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:A.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:A.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:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):oe.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:A.invalid_type,expected:D.bigint,received:n.parsedType}),Y}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.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}};Un.create=t=>new Un({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...te(t)});qn=class extends se{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.boolean,received:r.parsedType}),Y}return Ne(e.data)}};qn.create=t=>new qn({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...te(t)});Fn=class t extends se{_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:A.invalid_type,expected:D.date,received:i.parsedType}),Y}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return M(i,{code:A.invalid_date}),Y}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:A.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:A.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):oe.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:B.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:B.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}};Fn.create=t=>new Fn({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...te(t)});Wr=class extends se{_parse(e){if(this._getType(e)!==D.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.symbol,received:r.parsedType}),Y}return Ne(e.data)}};Wr.create=t=>new Wr({typeName:X.ZodSymbol,...te(t)});Bn=class extends se{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.undefined,received:r.parsedType}),Y}return Ne(e.data)}};Bn.create=t=>new Bn({typeName:X.ZodUndefined,...te(t)});Kn=class extends se{_parse(e){if(this._getType(e)!==D.null){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.null,received:r.parsedType}),Y}return Ne(e.data)}};Kn.create=t=>new Kn({typeName:X.ZodNull,...te(t)});mn=class extends se{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};mn.create=t=>new mn({typeName:X.ZodAny,...te(t)});Bt=class extends se{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};Bt.create=t=>new Bt({typeName:X.ZodUnknown,...te(t)});yt=class extends se{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:A.invalid_type,expected:D.never,received:n.parsedType}),Y}};yt.create=t=>new yt({typeName:X.ZodNever,...te(t)});Vr=class extends se{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.void,received:r.parsedType}),Y}return Ne(e.data)}};Vr.create=t=>new Vr({typeName:X.ZodVoid,...te(t)});Kt=class t extends se{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==D.array)return M(n,{code:A.invalid_type,expected:D.array,received:n.parsedType}),Y;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?A.too_big:A.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:A.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:A.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 ot(n,o,n.path,l)))).then(o=>Ae.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ot(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:B.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:B.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...te(e)});Ze=class t extends se{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=oe.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:A.invalid_type,expected:D.object,received:u.parsedType}),Y}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 ot(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&&(M(s,{code:A.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 ot(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,w=await h.value;u.push({key:f,value:w,alwaysSet:h.alwaysSet})}return u}).then(u=>Ae.mergeObjectSync(r,u)):Ae.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return B.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:B.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:X.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 oe.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 oe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Zr(this)}partial(e){let n={};for(let r of oe.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 oe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof it;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Tu(oe.objectKeys(this.shape))}};Ze.create=(t,e)=>new Ze({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:X.ZodObject,...te(e)});Ze.strictCreate=(t,e)=>new Ze({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:X.ZodObject,...te(e)});Ze.lazycreate=(t,e)=>new Ze({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:X.ZodObject,...te(e)});Hn=class extends se{_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 Ge(l.ctx.common.issues));return M(n,{code:A.invalid_union,unionErrors:o}),Y}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 Ge(c));return M(n,{code:A.invalid_union,unionErrors:l}),Y}}get options(){return this._def.options}};Hn.create=(t,e)=>new Hn({options:t,typeName:X.ZodUnion,...te(e)});Ft=t=>t instanceof Zn?Ft(t.schema):t instanceof at?Ft(t.innerType()):t instanceof Wn?[t.value]:t instanceof Vn?t.options:t instanceof Jn?oe.objectValues(t.enum):t instanceof Yn?Ft(t._def.innerType):t instanceof Bn?[void 0]:t instanceof Kn?[null]:t instanceof it?[void 0,...Ft(t.unwrap())]:t instanceof Rt?[null,...Ft(t.unwrap())]:t instanceof Bs||t instanceof Qn?Ft(t.unwrap()):t instanceof Xn?Ft(t._def.innerType):[],Ni=class t extends se{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return M(n,{code:A.invalid_type,expected:D.object,received:n.parsedType}),Y;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:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Y)}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=Ft(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:X.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...te(r)})}};Gn=class extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Pi(i)||Pi(o))return Y;let l=Aa(i.value,o.value);return l.valid?((ji(i)||ji(o))&&n.dirty(),{status:n.value,value:l.data}):(M(r,{code:A.invalid_intersection_types}),Y)};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}))}};Gn.create=(t,e,n)=>new Gn({left:t,right:e,typeName:X.ZodIntersection,...te(n)});It=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.array)return M(r,{code:A.invalid_type,expected:D.array,received:r.parsedType}),Y;if(r.data.length<this._def.items.length)return M(r,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:A.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 ot(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})}};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:X.ZodTuple,rest:null,...te(e)})};Oi=class t extends se{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:A.invalid_type,expected:D.object,received:r.parsedType}),Y;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ot(r,l,r.path,l)),value:o._parse(new ot(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 se?new t({keyType:e,valueType:n,typeName:X.ZodRecord,...te(r)}):new t({keyType:fn.create(),valueType:e,typeName:X.ZodRecord,...te(n)})}},Jr=class extends se{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:A.invalid_type,expected:D.map,received:r.parsedType}),Y;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new ot(r,l,r.path,[u,"key"])),value:i._parse(new ot(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 Y;(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 Y;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}}}};Jr.create=(t,e,n)=>new Jr({valueType:e,keyType:t,typeName:X.ZodMap,...te(n)});Yr=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.set)return M(r,{code:A.invalid_type,expected:D.set,received:r.parsedType}),Y;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(r,{code:A.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:A.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 Y;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 ot(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:B.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:B.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Yr.create=(t,e)=>new Yr({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...te(e)});Mi=class t extends se{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.function)return M(n,{code:A.invalid_type,expected:D.function,received:n.parsedType}),Y;function r(l,c){return Fs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Hr(),qt].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function s(l,c){return Fs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Hr(),qt].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof gn){let l=this;return Ne(async function(...c){let u=new Ge([]),h=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,h);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return Ne(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Ge([r(c,u.error)]);let h=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(h,i);if(!f.success)throw new Ge([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(Bt.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(Bt.create()),returns:n||Bt.create(),typeName:X.ZodFunction,...te(r)})}},Zn=class extends se{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})}};Zn.create=(t,e)=>new Zn({getter:t,typeName:X.ZodLazy,...te(e)});Wn=class extends se{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}};Wn.create=(t,e)=>new Wn({value:t,typeName:X.ZodLiteral,...te(e)});Vn=class t extends se{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:oe.joinValues(r),received:n.parsedType,code:A.invalid_type}),Y}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:A.invalid_enum_value,options:r}),Y}return Ne(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})}};Vn.create=Tu;Jn=class extends se{_parse(e){let n=oe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==D.string&&r.parsedType!==D.number){let s=oe.objectValues(n);return M(r,{expected:oe.joinValues(s),received:r.parsedType,code:A.invalid_type}),Y}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=oe.objectValues(n);return M(r,{received:r.data,code:A.invalid_enum_value,options:s}),Y}return Ne(e.data)}get enum(){return this._def.values}};Jn.create=(t,e)=>new Jn({values:t,typeName:X.ZodNativeEnum,...te(e)});gn=class extends se{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:A.invalid_type,expected:D.promise,received:n.parsedType}),Y;let r=n.parsedType===D.promise?n.data:Promise.resolve(n.data);return Ne(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};gn.create=(t,e)=>new gn({type:t,typeName:X.ZodPromise,...te(e)});at=class extends se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.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 Y;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?Y:c.status==="dirty"?Dn(c.value):n.value==="dirty"?Dn(c.value):c});{if(n.value==="aborted")return Y;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?Y:l.status==="dirty"?Dn(l.value):n.value==="dirty"?Dn(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"?Y:(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"?Y:(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(!pn(o))return Y;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=>pn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):Y);oe.assertNever(s)}};at.create=(t,e,n)=>new at({schema:t,typeName:X.ZodEffects,effect:e,...te(n)});at.createWithPreprocess=(t,e,n)=>new at({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...te(n)});it=class extends se{_parse(e){return this._getType(e)===D.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(t,e)=>new it({innerType:t,typeName:X.ZodOptional,...te(e)});Rt=class extends se{_parse(e){return this._getType(e)===D.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Rt.create=(t,e)=>new Rt({innerType:t,typeName:X.ZodNullable,...te(e)});Yn=class extends se{_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}};Yn.create=(t,e)=>new Yn({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Xn=class extends se{_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 Gr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ge(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ge(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Xn.create=(t,e)=>new Xn({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Xr=class extends se{_parse(e){if(this._getType(e)!==D.nan){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.nan,received:r.parsedType}),Y}return{status:"valid",value:e.data}}};Xr.create=t=>new Xr({typeName:X.ZodNaN,...te(t)});Ag=Symbol("zod_brand"),Bs=class extends se{_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}},Ks=class t extends se{_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"?Y:i.status==="dirty"?(n.dirty(),Dn(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"?Y: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:X.ZodPipeline})}},Qn=class extends se{_parse(e){let n=this._def.innerType._parse(e),r=s=>(pn(s)&&(s.value=Object.freeze(s.value)),s);return Gr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Qn.create=(t,e)=>new Qn({innerType:t,typeName:X.ZodReadonly,...te(e)});Cg={object:Ze.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"})(X||(X={}));$g=(t,e={message:`Input not instance of ${t.name}`})=>xu(n=>n instanceof t,e),Iu=fn.create,Ru=Ln.create,Pg=Xr.create,jg=Un.create,Eu=qn.create,Ng=Fn.create,Og=Wr.create,Mg=Bn.create,zg=Kn.create,Dg=mn.create,Lg=Bt.create,Ug=yt.create,qg=Vr.create,Fg=Kt.create,Bg=Ze.create,Kg=Ze.strictCreate,Hg=Hn.create,Gg=Ni.create,Zg=Gn.create,Wg=It.create,Vg=Oi.create,Jg=Jr.create,Yg=Yr.create,Xg=Mi.create,Qg=Zn.create,ey=Wn.create,ty=Vn.create,ny=Jn.create,ry=gn.create,sy=at.create,iy=it.create,oy=Rt.create,ay=at.createWithPreprocess,ly=Ks.create,cy=()=>Iu().optional(),uy=()=>Ru().optional(),dy=()=>Eu().optional(),hy={string:(t=>fn.create({...t,coerce:!0})),number:(t=>Ln.create({...t,coerce:!0})),boolean:(t=>qn.create({...t,coerce:!0})),bigint:(t=>Un.create({...t,coerce:!0})),date:(t=>Fn.create({...t,coerce:!0}))},py=Y});var _={};hn(_,{BRAND:()=>Ag,DIRTY:()=>Dn,EMPTY_PATH:()=>ag,INVALID:()=>Y,NEVER:()=>py,OK:()=>Ne,ParseStatus:()=>Ae,Schema:()=>se,ZodAny:()=>mn,ZodArray:()=>Kt,ZodBigInt:()=>Un,ZodBoolean:()=>qn,ZodBranded:()=>Bs,ZodCatch:()=>Xn,ZodDate:()=>Fn,ZodDefault:()=>Yn,ZodDiscriminatedUnion:()=>Ni,ZodEffects:()=>at,ZodEnum:()=>Vn,ZodError:()=>Ge,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>Mi,ZodIntersection:()=>Gn,ZodIssueCode:()=>A,ZodLazy:()=>Zn,ZodLiteral:()=>Wn,ZodMap:()=>Jr,ZodNaN:()=>Xr,ZodNativeEnum:()=>Jn,ZodNever:()=>yt,ZodNull:()=>Kn,ZodNullable:()=>Rt,ZodNumber:()=>Ln,ZodObject:()=>Ze,ZodOptional:()=>it,ZodParsedType:()=>D,ZodPipeline:()=>Ks,ZodPromise:()=>gn,ZodReadonly:()=>Qn,ZodRecord:()=>Oi,ZodSchema:()=>se,ZodSet:()=>Yr,ZodString:()=>fn,ZodSymbol:()=>Wr,ZodTransformer:()=>at,ZodTuple:()=>It,ZodType:()=>se,ZodUndefined:()=>Bn,ZodUnion:()=>Hn,ZodUnknown:()=>Bt,ZodVoid:()=>Vr,addIssueToContext:()=>M,any:()=>Dg,array:()=>Fg,bigint:()=>jg,boolean:()=>Eu,coerce:()=>hy,custom:()=>xu,date:()=>Ng,datetimeRegex:()=>Su,defaultErrorMap:()=>qt,discriminatedUnion:()=>Gg,effect:()=>sy,enum:()=>ty,function:()=>Xg,getErrorMap:()=>Hr,getParsedType:()=>xt,instanceof:()=>$g,intersection:()=>Zg,isAborted:()=>Pi,isAsync:()=>Gr,isDirty:()=>ji,isValid:()=>pn,late:()=>Cg,lazy:()=>Qg,literal:()=>ey,makeIssue:()=>Fs,map:()=>Jg,nan:()=>Pg,nativeEnum:()=>ny,never:()=>Ug,null:()=>zg,nullable:()=>oy,number:()=>Ru,object:()=>Bg,objectUtil:()=>xa,oboolean:()=>dy,onumber:()=>uy,optional:()=>iy,ostring:()=>cy,pipeline:()=>ly,preprocess:()=>ay,promise:()=>ry,quotelessJson:()=>sg,record:()=>Vg,set:()=>Yg,setErrorMap:()=>og,strictObject:()=>Kg,string:()=>Iu,symbol:()=>Og,transformer:()=>sy,tuple:()=>Wg,undefined:()=>Mg,union:()=>Hg,unknown:()=>Lg,util:()=>oe,void:()=>qg});var Ca=we(()=>{$i();Ra();yu();qs();Au();Ci()});var Qr=we(()=>{Ca();Ca()});function le(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=Di.default.join(zi.default.homedir(),".config","allwright"),n=Di.default.join(zi.default.homedir(),".config","ticketpilot");return!Ht.default.existsSync(e)&&Ht.default.existsSync(n)?n:e}function Gt(){return Di.default.join(le(),"runner.json")}function ke(){let t=Gt();if(!Ht.default.existsSync(t))return null;let e=JSON.parse(Ht.default.readFileSync(t,"utf8"));return $a.parse(e)}function be(t){let e=le();Ht.default.mkdirSync(e,{recursive:!0,mode:448});let n=Gt(),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 Li(t,e){return`${t}:${e}`}function Zt(t,e,n){return t.environments[Li(e,n)]?.secrets??{}}function Ui(t,e){return t.repos[e]?.jira??t.jira}function qi(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ue(){let t=ke();if(!t)throw new Error(`No runner config found at ${Gt()}. Run \`allwright init\` first.`);return t}var Ht,zi,Di,Cu,$a,Ce=we(()=>{"use strict";Ht=E(require("node:fs"),1),zi=E(require("node:os"),1),Di=E(require("node:path"),1);Qr();Cu=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),$a=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(zi.default.hostname()),jira:Cu.optional(),repos:_.record(_.object({path:_.string(),jira:Cu.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 Hs=ce(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.getParsedType=pe.ZodParsedType=pe.objectUtil=pe.util=void 0;var Oa;(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})(Oa||(pe.util=Oa={}));var qu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(qu||(pe.objectUtil=qu={}));pe.ZodParsedType=Oa.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ky=t=>{switch(typeof t){case"undefined":return pe.ZodParsedType.undefined;case"string":return pe.ZodParsedType.string;case"number":return Number.isNaN(t)?pe.ZodParsedType.nan:pe.ZodParsedType.number;case"boolean":return pe.ZodParsedType.boolean;case"function":return pe.ZodParsedType.function;case"bigint":return pe.ZodParsedType.bigint;case"symbol":return pe.ZodParsedType.symbol;case"object":return Array.isArray(t)?pe.ZodParsedType.array:t===null?pe.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?pe.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?pe.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?pe.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?pe.ZodParsedType.date:pe.ZodParsedType.object;default:return pe.ZodParsedType.unknown}};pe.getParsedType=ky});var Zi=ce(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.ZodError=wn.quotelessJson=wn.ZodIssueCode=void 0;var Fu=Hs();wn.ZodIssueCode=Fu.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 _y=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");wn.quotelessJson=_y;var Gs=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,Fu.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()}};wn.ZodError=Gs;Gs.create=t=>new Gs(t)});var za=ce(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});var Oe=Zi(),nr=Hs(),Sy=(t,e)=>{let n;switch(t.code){case Oe.ZodIssueCode.invalid_type:t.received===nr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Oe.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,nr.util.jsonStringifyReplacer)}`;break;case Oe.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${nr.util.joinValues(t.keys,", ")}`;break;case Oe.ZodIssueCode.invalid_union:n="Invalid input";break;case Oe.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${nr.util.joinValues(t.options)}`;break;case Oe.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${nr.util.joinValues(t.options)}, received '${t.received}'`;break;case Oe.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Oe.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Oe.ZodIssueCode.invalid_date:n="Invalid date";break;case Oe.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}"`:nr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Oe.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 Oe.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 Oe.ZodIssueCode.custom:n="Invalid input";break;case Oe.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Oe.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Oe.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,nr.util.assertNever(t)}return{message:n}};Ma.default=Sy});var Wi=ce(vn=>{"use strict";var Ty=vn&&vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vn,"__esModule",{value:!0});vn.defaultErrorMap=void 0;vn.setErrorMap=xy;vn.getErrorMap=Iy;var Bu=Ty(za());vn.defaultErrorMap=Bu.default;var Ku=Bu.default;function xy(t){Ku=t}function Iy(){return Ku}});var La=ce(he=>{"use strict";var Ry=he&&he.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(he,"__esModule",{value:!0});he.isAsync=he.isValid=he.isDirty=he.isAborted=he.OK=he.DIRTY=he.INVALID=he.ParseStatus=he.EMPTY_PATH=he.makeIssue=void 0;he.addIssueToContext=Cy;var Ey=Wi(),Hu=Ry(za()),Ay=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}};he.makeIssue=Ay;he.EMPTY_PATH=[];function Cy(t,e){let n=(0,Ey.getErrorMap)(),r=(0,he.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Hu.default?void 0:Hu.default].filter(s=>!!s)});t.common.issues.push(r)}var Da=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 he.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 he.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}}};he.ParseStatus=Da;he.INVALID=Object.freeze({status:"aborted"});var $y=t=>({status:"dirty",value:t});he.DIRTY=$y;var Py=t=>({status:"valid",value:t});he.OK=Py;var jy=t=>t.status==="aborted";he.isAborted=jy;var Ny=t=>t.status==="dirty";he.isDirty=Ny;var Oy=t=>t.status==="valid";he.isValid=Oy;var My=t=>typeof Promise<"u"&&t instanceof Promise;he.isAsync=My});var Zu=ce(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0})});var Vu=ce(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.errorUtil=void 0;var Wu;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Wu||(Vi.errorUtil=Wu={}))});var ad=ce(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=ed;S.custom=nd;var N=Zi(),Ji=Wi(),H=Vu(),T=La(),O=Hs(),ct=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}},Ju=(t,e)=>{if((0,T.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new N.ZodError(t.common.issues);return this._error=n,this._error}}};function ne(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 re=class{get description(){return this._def.description}_getType(e){return(0,O.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,O.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,O.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,T.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ju(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Ju(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:N.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 et({schema:this,typeName:Q.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return lt.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Jt.create(this)}promise(){return Sn.create(this,this._def)}or(e){return cr.create([this,e],this._def)}and(e){return ur.create(this,e,this._def)}transform(e){return new et({...ne(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new mr({...ne(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Zs({typeName:Q.ZodBranded,type:this,...ne(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new gr({...ne(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ws.create(this,e)}readonly(){return yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=re;S.Schema=re;S.ZodSchema=re;var zy=/^c[^\s-]{8,}$/i,Dy=/^[0-9a-z]+$/,Ly=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Uy=/^[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,qy=/^[a-z0-9_-]{21}$/i,Fy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,By=/^[-+]?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)?)??$/,Ky=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Hy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ua,Gy=/^(?:(?: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])$/,Zy=/^(?:(?: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])$/,Wy=/^(([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]))$/,Vy=/^(([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])$/,Jy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Xu="((\\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(`^${Xu}$`);function Qu(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 Qy(t){return new RegExp(`^${Qu(t)}$`)}function ed(t){let e=`${Xu}T${Qu(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 eb(t,e){return!!((e==="v4"||!e)&&Gy.test(t)||(e==="v6"||!e)&&Wy.test(t))}function tb(t,e){if(!Fy.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 nb(t,e){return!!((e==="v4"||!e)&&Zy.test(t)||(e==="v6"||!e)&&Vy.test(t))}var kn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.string,received:i.parsedType}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Ky.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ua||(Ua=new RegExp(Hy,"u")),Ua.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Uy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")qy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")zy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Dy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ly.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"url",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"regex",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?ed(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Xy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Qy(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?By.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?eb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?tb(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?nb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Jy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Yy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):O.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:N.ZodIssueCode.invalid_string,...H.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.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,...H.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,...H.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...H.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...H.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...H.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...H.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...H.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...H.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...H.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,H.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=kn;kn.create=t=>new kn({checks:[],typeName:Q.ZodString,coerce:t?.coerce??!1,...ne(t)});function rb(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 rr=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)!==O.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?O.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?rb(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.not_finite,message:i.message}),s.dirty()):O.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,H.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:H.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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"&&O.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=rr;rr.create=t=>new rr({checks:[],typeName:Q.ZodNumber,coerce:t?.coerce||!1,...ne(t)});var sr=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)!==O.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):O.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,H.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.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:H.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.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=sr;sr.create=t=>new sr({checks:[],typeName:Q.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});var ir=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodBoolean=ir;ir.create=t=>new ir({typeName:Q.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});var or=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_date}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):O.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:H.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:H.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=or;or.create=t=>new or({checks:[],coerce:t?.coerce||!1,typeName:Q.ZodDate,...ne(t)});var is=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodSymbol=is;is.create=t=>new is({typeName:Q.ZodSymbol,...ne(t)});var ar=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodUndefined=ar;ar.create=t=>new ar({typeName:Q.ZodUndefined,...ne(t)});var lr=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodNull=lr;lr.create=t=>new lr({typeName:Q.ZodNull,...ne(t)});var _n=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=_n;_n.create=t=>new _n({typeName:Q.ZodAny,...ne(t)});var Vt=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=Vt;Vt.create=t=>new Vt({typeName:Q.ZodUnknown,...ne(t)});var bt=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.never,received:n.parsedType}),T.INVALID}};S.ZodNever=bt;bt.create=t=>new bt({typeName:Q.ZodNever,...ne(t)});var os=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodVoid=os;os.create=t=>new os({typeName:Q.ZodVoid,...ne(t)});var Jt=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==O.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.array,received:n.parsedType}),T.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,T.addIssueToContext)(n,{code:o?N.ZodIssueCode.too_big:N.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,T.addIssueToContext)(n,{code:N.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,T.addIssueToContext)(n,{code:N.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 ct(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ct(n,o,n.path,l)));return T.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:H.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:H.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:H.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=Jt;Jt.create=(t,e)=>new Jt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...ne(e)});function ss(t){if(t instanceof We){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=lt.create(ss(r))}return new We({...t._def,shape:()=>e})}else return t instanceof Jt?new Jt({...t._def,type:ss(t.element)}):t instanceof lt?lt.create(ss(t.unwrap())):t instanceof At?At.create(ss(t.unwrap())):t instanceof Et?Et.create(t.items.map(e=>ss(e))):t}var We=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=O.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==O.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:u.parsedType}),T.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 ct(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,T.addIssueToContext)(s,{code:N.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 ct(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,w=await h.value;u.push({key:f,value:w,alwaysSet:h.alwaysSet})}return u}).then(u=>T.ParseStatus.mergeObjectSync(r,u)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return H.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:H.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:Q.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 O.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 O.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ss(this)}partial(e){let n={};for(let r of O.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 O.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof lt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return td(O.util.objectKeys(this.shape))}};S.ZodObject=We;We.create=(t,e)=>new We({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:Q.ZodObject,...ne(e)});We.strictCreate=(t,e)=>new We({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:Q.ZodObject,...ne(e)});We.lazycreate=(t,e)=>new We({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:Q.ZodObject,...ne(e)});var cr=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 N.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_union,unionErrors:o}),T.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let 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 N.ZodError(c));return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};S.ZodUnion=cr;cr.create=(t,e)=>new cr({options:t,typeName:Q.ZodUnion,...ne(e)});var Wt=t=>t instanceof dr?Wt(t.schema):t instanceof et?Wt(t.innerType()):t instanceof hr?[t.value]:t instanceof pr?t.options:t instanceof fr?O.util.objectValues(t.enum):t instanceof mr?Wt(t._def.innerType):t instanceof ar?[void 0]:t instanceof lr?[null]:t instanceof lt?[void 0,...Wt(t.unwrap())]:t instanceof At?[null,...Wt(t.unwrap())]:t instanceof Zs||t instanceof yr?Wt(t.unwrap()):t instanceof gr?Wt(t._def.innerType):[],Yi=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:n.parsedType}),T.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),T.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Wt(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:Q.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ne(r)})}};S.ZodDiscriminatedUnion=Yi;function qa(t,e){let n=(0,O.getParsedType)(t),r=(0,O.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===O.ZodParsedType.object&&r===O.ZodParsedType.object){let s=O.util.objectKeys(e),i=O.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=qa(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===O.ZodParsedType.array&&r===O.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=qa(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===O.ZodParsedType.date&&r===O.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ur=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,T.isAborted)(i)||(0,T.isAborted)(o))return T.INVALID;let l=qa(i.value,o.value);return l.valid?(((0,T.isDirty)(i)||(0,T.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_intersection_types}),T.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};S.ZodIntersection=ur;ur.create=(t,e,n)=>new ur({left:t,right:e,typeName:Q.ZodIntersection,...ne(n)});var Et=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,T.addIssueToContext)(r,{code:N.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 ct(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>T.ParseStatus.mergeArray(n,o)):T.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};S.ZodTuple=Et;Et.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Et({items:t,typeName:Q.ZodTuple,rest:null,...ne(e)})};var 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!==O.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:r.parsedType}),T.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ct(r,l,r.path,l)),value:o._parse(new ct(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:Q.ZodRecord,...ne(r)}):new t({keyType:kn.create(),valueType:e,typeName:Q.ZodRecord,...ne(n)})}};S.ZodRecord=Xi;var as=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!==O.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new ct(r,l,r.path,[u,"key"])),value:i._parse(new ct(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 T.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 T.INVALID;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}}}};S.ZodMap=as;as.create=(t,e,n)=>new as({valueType:e,keyType:t,typeName:Q.ZodMap,...ne(n)});var ls=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.set,received:r.parsedType}),T.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,T.addIssueToContext)(r,{code:N.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,T.addIssueToContext)(r,{code:N.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 T.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 ct(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:H.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:H.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=ls;ls.create=(t,e)=>new ls({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...ne(e)});var Qi=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.function,received:n.parsedType}),T.INVALID;function r(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ji.getErrorMap)(),Ji.defaultErrorMap].filter(u=>!!u),issueData:{code:N.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ji.getErrorMap)(),Ji.defaultErrorMap].filter(u=>!!u),issueData:{code:N.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Sn){let l=this;return(0,T.OK)(async function(...c){let u=new N.ZodError([]),h=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,h);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new N.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 N.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:Et.create(e).rest(Vt.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||Et.create([]).rest(Vt.create()),returns:n||Vt.create(),typeName:Q.ZodFunction,...ne(r)})}};S.ZodFunction=Qi;var dr=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})}};S.ZodLazy=dr;dr.create=(t,e)=>new dr({getter:t,typeName:Q.ZodLazy,...ne(e)});var hr=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:N.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=hr;hr.create=(t,e)=>new hr({value:t,typeName:Q.ZodLiteral,...ne(e)});function td(t,e){return new pr({values:t,typeName:Q.ZodEnum,...ne(e)})}var pr=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:O.util.joinValues(r),received:n.parsedType,code:N.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{received:n.data,code:N.ZodIssueCode.invalid_enum_value,options:r}),T.INVALID}return(0,T.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};S.ZodEnum=pr;pr.create=td;var fr=class extends re{_parse(e){let n=O.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.ZodParsedType.string&&r.parsedType!==O.ZodParsedType.number){let s=O.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:O.util.joinValues(s),received:r.parsedType,code:N.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(O.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=O.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:N.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=fr;fr.create=(t,e)=>new fr({values:t,typeName:Q.ZodNativeEnum,...ne(e)});var Sn=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===O.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,T.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};S.ZodPromise=Sn;Sn.create=(t,e)=>new Sn({type:t,typeName:Q.ZodPromise,...ne(e)});var et=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,T.addIssueToContext)(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return T.INVALID;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?T.INVALID:c.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(c.value):c});{if(n.value==="aborted")return T.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:l.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let 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"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,T.isValid)(o))return T.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,T.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):T.INVALID);O.util.assertNever(s)}};S.ZodEffects=et;S.ZodTransformer=et;et.create=(t,e,n)=>new et({schema:t,typeName:Q.ZodEffects,effect:e,...ne(n)});et.createWithPreprocess=(t,e,n)=>new et({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...ne(n)});var lt=class extends re{_parse(e){return this._getType(e)===O.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=lt;lt.create=(t,e)=>new lt({innerType:t,typeName:Q.ZodOptional,...ne(e)});var At=class extends re{_parse(e){return this._getType(e)===O.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=At;At.create=(t,e)=>new At({innerType:t,typeName:Q.ZodNullable,...ne(e)});var mr=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===O.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=mr;mr.create=(t,e)=>new mr({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});var gr=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(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new N.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new N.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=gr;gr.create=(t,e)=>new gr({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});var cs=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=cs;cs.create=t=>new cs({typeName:Q.ZodNaN,...ne(t)});S.BRAND=Symbol("zod_brand");var Zs=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}};S.ZodBranded=Zs;var Ws=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"?T.INVALID:i.status==="dirty"?(n.dirty(),(0,T.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?T.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Q.ZodPipeline})}};S.ZodPipeline=Ws;var yr=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,T.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,T.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};S.ZodReadonly=yr;yr.create=(t,e)=>new yr({innerType:t,typeName:Q.ZodReadonly,...ne(e)});function Yu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function nd(t,e={},n){return t?_n.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Yu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Yu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):_n.create()}S.late={object:We.lazycreate};var Q;(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"})(Q||(S.ZodFirstPartyTypeKind=Q={}));var sb=(t,e={message:`Input not instance of ${t.name}`})=>nd(n=>n instanceof t,e);S.instanceof=sb;var rd=kn.create;S.string=rd;var sd=rr.create;S.number=sd;var ib=cs.create;S.nan=ib;var ob=sr.create;S.bigint=ob;var id=ir.create;S.boolean=id;var ab=or.create;S.date=ab;var lb=is.create;S.symbol=lb;var cb=ar.create;S.undefined=cb;var ub=lr.create;S.null=ub;var db=_n.create;S.any=db;var hb=Vt.create;S.unknown=hb;var pb=bt.create;S.never=pb;var fb=os.create;S.void=fb;var mb=Jt.create;S.array=mb;var gb=We.create;S.object=gb;var yb=We.strictCreate;S.strictObject=yb;var bb=cr.create;S.union=bb;var wb=Yi.create;S.discriminatedUnion=wb;var vb=ur.create;S.intersection=vb;var kb=Et.create;S.tuple=kb;var _b=Xi.create;S.record=_b;var Sb=as.create;S.map=Sb;var Tb=ls.create;S.set=Tb;var xb=Qi.create;S.function=xb;var Ib=dr.create;S.lazy=Ib;var Rb=hr.create;S.literal=Rb;var Eb=pr.create;S.enum=Eb;var Ab=fr.create;S.nativeEnum=Ab;var Cb=Sn.create;S.promise=Cb;var od=et.create;S.effect=od;S.transformer=od;var $b=lt.create;S.optional=$b;var Pb=At.create;S.nullable=Pb;var jb=et.createWithPreprocess;S.preprocess=jb;var Nb=Ws.create;S.pipeline=Nb;var Ob=()=>rd().optional();S.ostring=Ob;var Mb=()=>sd().optional();S.onumber=Mb;var zb=()=>id().optional();S.oboolean=zb;S.coerce={string:(t=>kn.create({...t,coerce:!0})),number:(t=>rr.create({...t,coerce:!0})),boolean:(t=>ir.create({...t,coerce:!0})),bigint:(t=>sr.create({...t,coerce:!0})),date:(t=>or.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var Fa=ce(ut=>{"use strict";var Db=ut&&ut.__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]})),us=ut&&ut.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Db(e,t,n)};Object.defineProperty(ut,"__esModule",{value:!0});us(Wi(),ut);us(La(),ut);us(Zu(),ut);us(Hs(),ut);us(ad(),ut);us(Zi(),ut)});var ud=ce(Ve=>{"use strict";var ld=Ve&&Ve.__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]})),Lb=Ve&&Ve.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ub=Ve&&Ve.__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)&&ld(e,t,n);return Lb(e,t),e},qb=Ve&&Ve.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ld(e,t,n)};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.z=void 0;var cd=Ub(Fa());Ve.z=cd;qb(Fa(),Ve);Ve.default=cd});var Te=ce(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.ChatLoadMsg=p.ChatListResultMsg=p.ChatListMsg=p.ChatUsageMsg=p.ChatStreamMsg=p.JiraUsersResultMsg=p.DeployClaimResultMsg=p.DeployClaimMsg=p.RuleDiagnoseResultMsg=p.ProjectTestResultMsg=p.RunStatusMsg=p.RunContextMsg=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.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=p.BUILTIN_REPLY_LANGUAGES=void 0;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=p.EnvPreflightMsg=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=p.DeploySuggestMsg=void 0;p.missingAgentCapabilities=Fb;p.replyPreferenceAppendix=Kb;p.pendingMigrationsAppendix=Hb;p.deployTargetsAppendix=Gb;p.isSelfMigrationFilename=Zb;p.parseRunnerMsg=Wb;p.parseServerMsg=Vb;var a=ud();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.78";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 Fb(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 Bb=t=>t.includes(p.NEEDS_INPUT_COMMENT_MARKER)||p.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));p.needsInputMarkerIn=Bb;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),maxCostUsd:a.z.number().positive().optional(),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.RunContextMsg=a.z.object({type:a.z.literal("run.context"),runId:a.z.string(),pieces:a.z.array(a.z.object({part:a.z.string().max(80),chars:a.z.number().int().nonnegative()})).max(30),totalChars:a.z.number().int().nonnegative(),sessionMode:a.z.enum(["fresh","chained","timeout-resume","preflight-resume"])});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 Kb(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?`
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function au(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})}lu.Command=Sa});var pu=ce(st=>{var{Argument:uu}=Ai(),{Command:Ta}=cu(),{CommanderError:ng,InvalidArgumentError:du}=Us(),{Help:rg}=ma(),{Option:hu}=wa();st.program=new Ta;st.createCommand=t=>new Ta(t);st.createOption=(t,e)=>new hu(t,e);st.createArgument=(t,e)=>new uu(t,e);st.Command=Ta;st.Option=hu;st.Argument=uu;st.Help=rg;st.CommanderError=ng;st.InvalidArgumentError=du;st.InvalidOptionArgumentError=du});var ae,xa,D,xt,qs=we(()=>{(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})(ae||(ae={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(xa||(xa={}));D=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=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 A,sg,Ge,$i=we(()=>{qs();A=ae.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"]),sg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ge=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,ae.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()}};Ge.create=t=>new Ge(t)});var ig,qt,Ia=we(()=>{$i();qs();ig=(t,e)=>{let n;switch(t.code){case A.invalid_type:t.received===D.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ae.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${ae.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.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}"`:ae.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case A.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 A.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 A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=e.defaultError,ae.assertNever(t)}return{message:n}},qt=ig});function og(t){gu=t}function Kr(){return gu}var gu,Ci=we(()=>{Ia();gu=qt});function M(t,e){let n=Kr(),r=Fs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===qt?void 0:qt].filter(s=>!!s)});t.common.issues.push(r)}var Fs,ag,Ae,Y,Dn,je,Pi,Ni,pn,Gr,Ra=we(()=>{Ci();Ia();Fs=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}},ag=[];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 Y;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 Y;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}}},Y=Object.freeze({status:"aborted"}),Dn=t=>({status:"dirty",value:t}),je=t=>({status:"valid",value:t}),Pi=t=>t.status==="aborted",Ni=t=>t.status==="dirty",pn=t=>t.status==="valid",Gr=t=>typeof Promise<"u"&&t instanceof Promise});var yu=we(()=>{});var B,bu=we(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(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 _u(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 Tg(t){return new RegExp(`^${_u(t)}$`)}function Su(t){let e=`${ku}T${_u(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 xg(t,e){return!!((e==="v4"||!e)&&yg.test(t)||(e==="v6"||!e)&&wg.test(t))}function Ig(t,e){if(!pg.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 Rg(t,e){return!!((e==="v4"||!e)&&bg.test(t)||(e==="v6"||!e)&&vg.test(t))}function Eg(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 Zr(t){if(t instanceof Ze){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=it.create(Zr(r))}return new Ze({...t._def,shape:()=>e})}else return t instanceof Ht?new Ht({...t._def,type:Zr(t.element)}):t instanceof it?it.create(Zr(t.unwrap())):t instanceof Rt?Rt.create(Zr(t.unwrap())):t instanceof It?It.create(t.items.map(e=>Zr(e))):t}function Aa(t,e){let n=xt(t),r=xt(e);if(t===e)return{valid:!0,data:t};if(n===D.object&&r===D.object){let s=ae.objectKeys(e),i=ae.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Aa(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=Aa(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 Tu(t,e){return new Vn({values:t,typeName:X.ZodEnum,...te(e)})}function vu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function xu(t,e={},n){return t?mn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=vu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=vu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):mn.create()}var ot,wu,se,lg,cg,ug,dg,hg,pg,fg,mg,gg,Ea,yg,bg,wg,vg,kg,_g,ku,Sg,fn,Ln,Un,qn,Fn,Wr,Bn,Hn,mn,Bt,yt,Vr,Ht,Ze,Kn,Ft,ji,Gn,It,Oi,Jr,Yr,Mi,Zn,Wn,Vn,Jn,gn,at,it,Rt,Yn,Xn,Xr,Ag,Bs,Hs,Qn,$g,X,Cg,Iu,Ru,Pg,Ng,Eu,jg,Og,Mg,zg,Dg,Lg,Ug,qg,Fg,Bg,Hg,Kg,Gg,Zg,Wg,Vg,Jg,Yg,Xg,Qg,ey,ty,ny,ry,sy,iy,oy,ay,ly,cy,uy,dy,hy,py,Au=we(()=>{$i();Ci();bu();Ra();qs();ot=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}},wu=(t,e)=>{if(pn(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 Ge(t.common.issues);return this._error=n,this._error}}};se=class{get description(){return this._def.description}_getType(e){return xt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:xt(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:xt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Gr(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:xt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return wu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return pn(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=>pn(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:xt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Gr(s)?s:Promise.resolve(s));return wu(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.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 at({schema:this,typeName:X.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 it.create(this,this._def)}nullable(){return Rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return gn.create(this,this._def)}or(e){return Kn.create([this,e],this._def)}and(e){return Gn.create(this,e,this._def)}transform(e){return new at({...te(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Yn({...te(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Bs({typeName:X.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Xn({...te(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Hs.create(this,e)}readonly(){return Qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},lg=/^c[^\s-]{8,}$/i,cg=/^[0-9a-z]+$/,ug=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dg=/^[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,hg=/^[a-z0-9_-]{21}$/i,pg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fg=/^[-+]?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)?)??$/,mg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",yg=/^(?:(?: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])$/,bg=/^(?:(?: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])$/,wg=/^(([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]))$/,vg=/^(([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])$/,kg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_g=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ku="((\\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])))",Sg=new RegExp(`^${ku}$`);fn=class t extends se{_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:A.invalid_type,expected:D.string,received:i.parsedType}),Y}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:A.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:A.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:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&M(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")mg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ea||(Ea=new RegExp(gg,"u")),Ea.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")dg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")hg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")lg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")cg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ug.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ulid",code:A.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:A.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:A.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:A.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:A.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:A.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Su(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Sg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Tg(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?fg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?xg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Ig(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Rg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?kg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?_g.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:A.invalid_string,message:i.message}),r.dirty()):ae.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.invalid_string,...B.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.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,...B.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,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...B.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...B.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...B.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...B.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...B.errToObj(n)})}nonempty(e){return this.min(1,B.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}};fn.create=t=>new fn({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...te(t)});Ln=class t extends se{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:A.invalid_type,expected:D.number,received:i.parsedType}),Y}let r,s=new Ae;for(let i of this._def.checks)i.kind==="int"?ae.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:A.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:A.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:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Eg(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:A.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:A.not_finite,message:i.message}),s.dirty()):ae.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.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"&&ae.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)}};Ln.create=t=>new Ln({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...te(t)});Un=class t extends se{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:A.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:A.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:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ae.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:A.invalid_type,expected:D.bigint,received:n.parsedType}),Y}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.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:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.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}};Un.create=t=>new Un({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...te(t)});qn=class extends se{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.boolean,received:r.parsedType}),Y}return je(e.data)}};qn.create=t=>new qn({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...te(t)});Fn=class t extends se{_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:A.invalid_type,expected:D.date,received:i.parsedType}),Y}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return M(i,{code:A.invalid_date}),Y}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:A.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:A.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ae.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:B.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:B.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}};Fn.create=t=>new Fn({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...te(t)});Wr=class extends se{_parse(e){if(this._getType(e)!==D.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.symbol,received:r.parsedType}),Y}return je(e.data)}};Wr.create=t=>new Wr({typeName:X.ZodSymbol,...te(t)});Bn=class extends se{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.undefined,received:r.parsedType}),Y}return je(e.data)}};Bn.create=t=>new Bn({typeName:X.ZodUndefined,...te(t)});Hn=class extends se{_parse(e){if(this._getType(e)!==D.null){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.null,received:r.parsedType}),Y}return je(e.data)}};Hn.create=t=>new Hn({typeName:X.ZodNull,...te(t)});mn=class extends se{constructor(){super(...arguments),this._any=!0}_parse(e){return je(e.data)}};mn.create=t=>new mn({typeName:X.ZodAny,...te(t)});Bt=class extends se{constructor(){super(...arguments),this._unknown=!0}_parse(e){return je(e.data)}};Bt.create=t=>new Bt({typeName:X.ZodUnknown,...te(t)});yt=class extends se{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:A.invalid_type,expected:D.never,received:n.parsedType}),Y}};yt.create=t=>new yt({typeName:X.ZodNever,...te(t)});Vr=class extends se{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.void,received:r.parsedType}),Y}return je(e.data)}};Vr.create=t=>new Vr({typeName:X.ZodVoid,...te(t)});Ht=class t extends se{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==D.array)return M(n,{code:A.invalid_type,expected:D.array,received:n.parsedType}),Y;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?A.too_big:A.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:A.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:A.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 ot(n,o,n.path,l)))).then(o=>Ae.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ot(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:B.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:B.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};Ht.create=(t,e)=>new Ht({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...te(e)});Ze=class t extends se{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=ae.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:A.invalid_type,expected:D.object,received:u.parsedType}),Y}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 ot(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&&(M(s,{code:A.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 ot(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,w=await h.value;u.push({key:f,value:w,alwaysSet:h.alwaysSet})}return u}).then(u=>Ae.mergeObjectSync(r,u)):Ae.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return B.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:B.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:X.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 ae.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 ae.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Zr(this)}partial(e){let n={};for(let r of ae.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 ae.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof it;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Tu(ae.objectKeys(this.shape))}};Ze.create=(t,e)=>new Ze({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:X.ZodObject,...te(e)});Ze.strictCreate=(t,e)=>new Ze({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:X.ZodObject,...te(e)});Ze.lazycreate=(t,e)=>new Ze({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:X.ZodObject,...te(e)});Kn=class extends se{_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 Ge(l.ctx.common.issues));return M(n,{code:A.invalid_union,unionErrors:o}),Y}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 Ge(c));return M(n,{code:A.invalid_union,unionErrors:l}),Y}}get options(){return this._def.options}};Kn.create=(t,e)=>new Kn({options:t,typeName:X.ZodUnion,...te(e)});Ft=t=>t instanceof Zn?Ft(t.schema):t instanceof at?Ft(t.innerType()):t instanceof Wn?[t.value]:t instanceof Vn?t.options:t instanceof Jn?ae.objectValues(t.enum):t instanceof Yn?Ft(t._def.innerType):t instanceof Bn?[void 0]:t instanceof Hn?[null]:t instanceof it?[void 0,...Ft(t.unwrap())]:t instanceof Rt?[null,...Ft(t.unwrap())]:t instanceof Bs||t instanceof Qn?Ft(t.unwrap()):t instanceof Xn?Ft(t._def.innerType):[],ji=class t extends se{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return M(n,{code:A.invalid_type,expected:D.object,received:n.parsedType}),Y;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:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Y)}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=Ft(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:X.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...te(r)})}};Gn=class extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Pi(i)||Pi(o))return Y;let l=Aa(i.value,o.value);return l.valid?((Ni(i)||Ni(o))&&n.dirty(),{status:n.value,value:l.data}):(M(r,{code:A.invalid_intersection_types}),Y)};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}))}};Gn.create=(t,e,n)=>new Gn({left:t,right:e,typeName:X.ZodIntersection,...te(n)});It=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.array)return M(r,{code:A.invalid_type,expected:D.array,received:r.parsedType}),Y;if(r.data.length<this._def.items.length)return M(r,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:A.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 ot(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})}};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:X.ZodTuple,rest:null,...te(e)})};Oi=class t extends se{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:A.invalid_type,expected:D.object,received:r.parsedType}),Y;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ot(r,l,r.path,l)),value:o._parse(new ot(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 se?new t({keyType:e,valueType:n,typeName:X.ZodRecord,...te(r)}):new t({keyType:fn.create(),valueType:e,typeName:X.ZodRecord,...te(n)})}},Jr=class extends se{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:A.invalid_type,expected:D.map,received:r.parsedType}),Y;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new ot(r,l,r.path,[u,"key"])),value:i._parse(new ot(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 Y;(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 Y;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}}}};Jr.create=(t,e,n)=>new Jr({valueType:e,keyType:t,typeName:X.ZodMap,...te(n)});Yr=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.set)return M(r,{code:A.invalid_type,expected:D.set,received:r.parsedType}),Y;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(r,{code:A.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:A.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 Y;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 ot(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:B.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:B.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Yr.create=(t,e)=>new Yr({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...te(e)});Mi=class t extends se{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.function)return M(n,{code:A.invalid_type,expected:D.function,received:n.parsedType}),Y;function r(l,c){return Fs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Kr(),qt].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function s(l,c){return Fs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Kr(),qt].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof gn){let l=this;return je(async function(...c){let u=new Ge([]),h=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,h);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return je(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Ge([r(c,u.error)]);let h=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(h,i);if(!f.success)throw new Ge([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(Bt.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(Bt.create()),returns:n||Bt.create(),typeName:X.ZodFunction,...te(r)})}},Zn=class extends se{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})}};Zn.create=(t,e)=>new Zn({getter:t,typeName:X.ZodLazy,...te(e)});Wn=class extends se{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}};Wn.create=(t,e)=>new Wn({value:t,typeName:X.ZodLiteral,...te(e)});Vn=class t extends se{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ae.joinValues(r),received:n.parsedType,code:A.invalid_type}),Y}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:A.invalid_enum_value,options:r}),Y}return je(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})}};Vn.create=Tu;Jn=class extends se{_parse(e){let n=ae.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==D.string&&r.parsedType!==D.number){let s=ae.objectValues(n);return M(r,{expected:ae.joinValues(s),received:r.parsedType,code:A.invalid_type}),Y}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ae.objectValues(n);return M(r,{received:r.data,code:A.invalid_enum_value,options:s}),Y}return je(e.data)}get enum(){return this._def.values}};Jn.create=(t,e)=>new Jn({values:t,typeName:X.ZodNativeEnum,...te(e)});gn=class extends se{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:A.invalid_type,expected:D.promise,received:n.parsedType}),Y;let r=n.parsedType===D.promise?n.data:Promise.resolve(n.data);return je(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};gn.create=(t,e)=>new gn({type:t,typeName:X.ZodPromise,...te(e)});at=class extends se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.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 Y;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?Y:c.status==="dirty"?Dn(c.value):n.value==="dirty"?Dn(c.value):c});{if(n.value==="aborted")return Y;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?Y:l.status==="dirty"?Dn(l.value):n.value==="dirty"?Dn(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"?Y:(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"?Y:(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(!pn(o))return Y;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=>pn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):Y);ae.assertNever(s)}};at.create=(t,e,n)=>new at({schema:t,typeName:X.ZodEffects,effect:e,...te(n)});at.createWithPreprocess=(t,e,n)=>new at({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...te(n)});it=class extends se{_parse(e){return this._getType(e)===D.undefined?je(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(t,e)=>new it({innerType:t,typeName:X.ZodOptional,...te(e)});Rt=class extends se{_parse(e){return this._getType(e)===D.null?je(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Rt.create=(t,e)=>new Rt({innerType:t,typeName:X.ZodNullable,...te(e)});Yn=class extends se{_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}};Yn.create=(t,e)=>new Yn({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Xn=class extends se{_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 Gr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ge(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ge(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Xn.create=(t,e)=>new Xn({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Xr=class extends se{_parse(e){if(this._getType(e)!==D.nan){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:D.nan,received:r.parsedType}),Y}return{status:"valid",value:e.data}}};Xr.create=t=>new Xr({typeName:X.ZodNaN,...te(t)});Ag=Symbol("zod_brand"),Bs=class extends se{_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}},Hs=class t extends se{_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"?Y:i.status==="dirty"?(n.dirty(),Dn(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"?Y: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:X.ZodPipeline})}},Qn=class extends se{_parse(e){let n=this._def.innerType._parse(e),r=s=>(pn(s)&&(s.value=Object.freeze(s.value)),s);return Gr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Qn.create=(t,e)=>new Qn({innerType:t,typeName:X.ZodReadonly,...te(e)});$g={object:Ze.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"})(X||(X={}));Cg=(t,e={message:`Input not instance of ${t.name}`})=>xu(n=>n instanceof t,e),Iu=fn.create,Ru=Ln.create,Pg=Xr.create,Ng=Un.create,Eu=qn.create,jg=Fn.create,Og=Wr.create,Mg=Bn.create,zg=Hn.create,Dg=mn.create,Lg=Bt.create,Ug=yt.create,qg=Vr.create,Fg=Ht.create,Bg=Ze.create,Hg=Ze.strictCreate,Kg=Kn.create,Gg=ji.create,Zg=Gn.create,Wg=It.create,Vg=Oi.create,Jg=Jr.create,Yg=Yr.create,Xg=Mi.create,Qg=Zn.create,ey=Wn.create,ty=Vn.create,ny=Jn.create,ry=gn.create,sy=at.create,iy=it.create,oy=Rt.create,ay=at.createWithPreprocess,ly=Hs.create,cy=()=>Iu().optional(),uy=()=>Ru().optional(),dy=()=>Eu().optional(),hy={string:(t=>fn.create({...t,coerce:!0})),number:(t=>Ln.create({...t,coerce:!0})),boolean:(t=>qn.create({...t,coerce:!0})),bigint:(t=>Un.create({...t,coerce:!0})),date:(t=>Fn.create({...t,coerce:!0}))},py=Y});var _={};hn(_,{BRAND:()=>Ag,DIRTY:()=>Dn,EMPTY_PATH:()=>ag,INVALID:()=>Y,NEVER:()=>py,OK:()=>je,ParseStatus:()=>Ae,Schema:()=>se,ZodAny:()=>mn,ZodArray:()=>Ht,ZodBigInt:()=>Un,ZodBoolean:()=>qn,ZodBranded:()=>Bs,ZodCatch:()=>Xn,ZodDate:()=>Fn,ZodDefault:()=>Yn,ZodDiscriminatedUnion:()=>ji,ZodEffects:()=>at,ZodEnum:()=>Vn,ZodError:()=>Ge,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>Mi,ZodIntersection:()=>Gn,ZodIssueCode:()=>A,ZodLazy:()=>Zn,ZodLiteral:()=>Wn,ZodMap:()=>Jr,ZodNaN:()=>Xr,ZodNativeEnum:()=>Jn,ZodNever:()=>yt,ZodNull:()=>Hn,ZodNullable:()=>Rt,ZodNumber:()=>Ln,ZodObject:()=>Ze,ZodOptional:()=>it,ZodParsedType:()=>D,ZodPipeline:()=>Hs,ZodPromise:()=>gn,ZodReadonly:()=>Qn,ZodRecord:()=>Oi,ZodSchema:()=>se,ZodSet:()=>Yr,ZodString:()=>fn,ZodSymbol:()=>Wr,ZodTransformer:()=>at,ZodTuple:()=>It,ZodType:()=>se,ZodUndefined:()=>Bn,ZodUnion:()=>Kn,ZodUnknown:()=>Bt,ZodVoid:()=>Vr,addIssueToContext:()=>M,any:()=>Dg,array:()=>Fg,bigint:()=>Ng,boolean:()=>Eu,coerce:()=>hy,custom:()=>xu,date:()=>jg,datetimeRegex:()=>Su,defaultErrorMap:()=>qt,discriminatedUnion:()=>Gg,effect:()=>sy,enum:()=>ty,function:()=>Xg,getErrorMap:()=>Kr,getParsedType:()=>xt,instanceof:()=>Cg,intersection:()=>Zg,isAborted:()=>Pi,isAsync:()=>Gr,isDirty:()=>Ni,isValid:()=>pn,late:()=>$g,lazy:()=>Qg,literal:()=>ey,makeIssue:()=>Fs,map:()=>Jg,nan:()=>Pg,nativeEnum:()=>ny,never:()=>Ug,null:()=>zg,nullable:()=>oy,number:()=>Ru,object:()=>Bg,objectUtil:()=>xa,oboolean:()=>dy,onumber:()=>uy,optional:()=>iy,ostring:()=>cy,pipeline:()=>ly,preprocess:()=>ay,promise:()=>ry,quotelessJson:()=>sg,record:()=>Vg,set:()=>Yg,setErrorMap:()=>og,strictObject:()=>Hg,string:()=>Iu,symbol:()=>Og,transformer:()=>sy,tuple:()=>Wg,undefined:()=>Mg,union:()=>Kg,unknown:()=>Lg,util:()=>ae,void:()=>qg});var $a=we(()=>{Ci();Ra();yu();qs();Au();$i()});var Qr=we(()=>{$a();$a()});function le(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=Di.default.join(zi.default.homedir(),".config","allwright"),n=Di.default.join(zi.default.homedir(),".config","ticketpilot");return!Kt.default.existsSync(e)&&Kt.default.existsSync(n)?n:e}function Gt(){return Di.default.join(le(),"runner.json")}function ke(){let t=Gt();if(!Kt.default.existsSync(t))return null;let e=JSON.parse(Kt.default.readFileSync(t,"utf8"));return Ca.parse(e)}function be(t){let e=le();Kt.default.mkdirSync(e,{recursive:!0,mode:448});let n=Gt(),r=n+".tmp";Kt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
24
|
+
`,{mode:384}),Kt.default.renameSync(r,n),Kt.default.chmodSync(n,384)}function Li(t,e){return`${t}:${e}`}function Zt(t,e,n){return t.environments[Li(e,n)]?.secrets??{}}function Ui(t,e){return t.repos[e]?.jira??t.jira}function qi(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ue(){let t=ke();if(!t)throw new Error(`No runner config found at ${Gt()}. Run \`allwright init\` first.`);return t}var Kt,zi,Di,$u,Ca,$e=we(()=>{"use strict";Kt=E(require("node:fs"),1),zi=E(require("node:os"),1),Di=E(require("node:path"),1);Qr();$u=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),Ca=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(zi.default.hostname()),jira:$u.optional(),repos:_.record(_.object({path:_.string(),jira:$u.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 Ks=ce(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.getParsedType=pe.ZodParsedType=pe.objectUtil=pe.util=void 0;var Oa;(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})(Oa||(pe.util=Oa={}));var qu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(qu||(pe.objectUtil=qu={}));pe.ZodParsedType=Oa.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ky=t=>{switch(typeof t){case"undefined":return pe.ZodParsedType.undefined;case"string":return pe.ZodParsedType.string;case"number":return Number.isNaN(t)?pe.ZodParsedType.nan:pe.ZodParsedType.number;case"boolean":return pe.ZodParsedType.boolean;case"function":return pe.ZodParsedType.function;case"bigint":return pe.ZodParsedType.bigint;case"symbol":return pe.ZodParsedType.symbol;case"object":return Array.isArray(t)?pe.ZodParsedType.array:t===null?pe.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?pe.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?pe.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?pe.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?pe.ZodParsedType.date:pe.ZodParsedType.object;default:return pe.ZodParsedType.unknown}};pe.getParsedType=ky});var Zi=ce(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.ZodError=wn.quotelessJson=wn.ZodIssueCode=void 0;var Fu=Ks();wn.ZodIssueCode=Fu.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 _y=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");wn.quotelessJson=_y;var Gs=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,Fu.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()}};wn.ZodError=Gs;Gs.create=t=>new Gs(t)});var za=ce(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});var Oe=Zi(),nr=Ks(),Sy=(t,e)=>{let n;switch(t.code){case Oe.ZodIssueCode.invalid_type:t.received===nr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Oe.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,nr.util.jsonStringifyReplacer)}`;break;case Oe.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${nr.util.joinValues(t.keys,", ")}`;break;case Oe.ZodIssueCode.invalid_union:n="Invalid input";break;case Oe.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${nr.util.joinValues(t.options)}`;break;case Oe.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${nr.util.joinValues(t.options)}, received '${t.received}'`;break;case Oe.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Oe.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Oe.ZodIssueCode.invalid_date:n="Invalid date";break;case Oe.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}"`:nr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Oe.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 Oe.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 Oe.ZodIssueCode.custom:n="Invalid input";break;case Oe.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Oe.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Oe.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,nr.util.assertNever(t)}return{message:n}};Ma.default=Sy});var Wi=ce(vn=>{"use strict";var Ty=vn&&vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vn,"__esModule",{value:!0});vn.defaultErrorMap=void 0;vn.setErrorMap=xy;vn.getErrorMap=Iy;var Bu=Ty(za());vn.defaultErrorMap=Bu.default;var Hu=Bu.default;function xy(t){Hu=t}function Iy(){return Hu}});var La=ce(he=>{"use strict";var Ry=he&&he.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(he,"__esModule",{value:!0});he.isAsync=he.isValid=he.isDirty=he.isAborted=he.OK=he.DIRTY=he.INVALID=he.ParseStatus=he.EMPTY_PATH=he.makeIssue=void 0;he.addIssueToContext=$y;var Ey=Wi(),Ku=Ry(za()),Ay=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}};he.makeIssue=Ay;he.EMPTY_PATH=[];function $y(t,e){let n=(0,Ey.getErrorMap)(),r=(0,he.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ku.default?void 0:Ku.default].filter(s=>!!s)});t.common.issues.push(r)}var Da=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 he.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 he.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}}};he.ParseStatus=Da;he.INVALID=Object.freeze({status:"aborted"});var Cy=t=>({status:"dirty",value:t});he.DIRTY=Cy;var Py=t=>({status:"valid",value:t});he.OK=Py;var Ny=t=>t.status==="aborted";he.isAborted=Ny;var jy=t=>t.status==="dirty";he.isDirty=jy;var Oy=t=>t.status==="valid";he.isValid=Oy;var My=t=>typeof Promise<"u"&&t instanceof Promise;he.isAsync=My});var Zu=ce(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0})});var Vu=ce(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.errorUtil=void 0;var Wu;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Wu||(Vi.errorUtil=Wu={}))});var ad=ce(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=ed;S.custom=nd;var j=Zi(),Ji=Wi(),K=Vu(),T=La(),O=Ks(),ct=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}},Ju=(t,e)=>{if((0,T.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new j.ZodError(t.common.issues);return this._error=n,this._error}}};function ne(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 re=class{get description(){return this._def.description}_getType(e){return(0,O.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,O.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,O.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,T.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ju(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Ju(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:j.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 et({schema:this,typeName:Q.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return lt.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Jt.create(this)}promise(){return Sn.create(this,this._def)}or(e){return cr.create([this,e],this._def)}and(e){return ur.create(this,e,this._def)}transform(e){return new et({...ne(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new mr({...ne(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Zs({typeName:Q.ZodBranded,type:this,...ne(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new gr({...ne(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ws.create(this,e)}readonly(){return yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=re;S.Schema=re;S.ZodSchema=re;var zy=/^c[^\s-]{8,}$/i,Dy=/^[0-9a-z]+$/,Ly=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Uy=/^[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,qy=/^[a-z0-9_-]{21}$/i,Fy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,By=/^[-+]?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)?)??$/,Hy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ky="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ua,Gy=/^(?:(?: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])$/,Zy=/^(?:(?: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])$/,Wy=/^(([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]))$/,Vy=/^(([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])$/,Jy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Xu="((\\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(`^${Xu}$`);function Qu(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 Qy(t){return new RegExp(`^${Qu(t)}$`)}function ed(t){let e=`${Xu}T${Qu(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 eb(t,e){return!!((e==="v4"||!e)&&Gy.test(t)||(e==="v6"||!e)&&Wy.test(t))}function tb(t,e){if(!Fy.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 nb(t,e){return!!((e==="v4"||!e)&&Zy.test(t)||(e==="v6"||!e)&&Vy.test(t))}var kn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.string,received:i.parsedType}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Hy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ua||(Ua=new RegExp(Ky,"u")),Ua.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Uy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")qy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")zy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Dy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ly.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"url",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"regex",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?ed(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Xy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Qy(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?By.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?eb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?tb(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?nb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Jy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Yy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:j.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):O.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:j.ZodIssueCode.invalid_string,...K.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...K.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...K.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...K.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...K.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...K.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...K.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,...K.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,...K.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...K.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...K.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...K.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...K.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...K.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...K.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...K.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...K.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,K.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=kn;kn.create=t=>new kn({checks:[],typeName:Q.ZodString,coerce:t?.coerce??!1,...ne(t)});function rb(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 rr=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)!==O.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?O.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?rb(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.not_finite,message:i.message}),s.dirty()):O.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,K.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,K.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,K.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,K.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:K.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:K.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:K.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.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"&&O.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=rr;rr.create=t=>new rr({checks:[],typeName:Q.ZodNumber,coerce:t?.coerce||!1,...ne(t)});var sr=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)!==O.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):O.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,K.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,K.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,K.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,K.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:K.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:K.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:K.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=sr;sr.create=t=>new sr({checks:[],typeName:Q.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});var ir=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodBoolean=ir;ir.create=t=>new ir({typeName:Q.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});var or=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:j.ZodIssueCode.invalid_date}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:j.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):O.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:K.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:K.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=or;or.create=t=>new or({checks:[],coerce:t?.coerce||!1,typeName:Q.ZodDate,...ne(t)});var is=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodSymbol=is;is.create=t=>new is({typeName:Q.ZodSymbol,...ne(t)});var ar=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodUndefined=ar;ar.create=t=>new ar({typeName:Q.ZodUndefined,...ne(t)});var lr=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodNull=lr;lr.create=t=>new lr({typeName:Q.ZodNull,...ne(t)});var _n=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=_n;_n.create=t=>new _n({typeName:Q.ZodAny,...ne(t)});var Vt=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=Vt;Vt.create=t=>new Vt({typeName:Q.ZodUnknown,...ne(t)});var bt=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.never,received:n.parsedType}),T.INVALID}};S.ZodNever=bt;bt.create=t=>new bt({typeName:Q.ZodNever,...ne(t)});var os=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodVoid=os;os.create=t=>new os({typeName:Q.ZodVoid,...ne(t)});var Jt=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==O.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.array,received:n.parsedType}),T.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,T.addIssueToContext)(n,{code:o?j.ZodIssueCode.too_big:j.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,T.addIssueToContext)(n,{code:j.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,T.addIssueToContext)(n,{code:j.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 ct(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ct(n,o,n.path,l)));return T.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:K.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:K.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:K.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=Jt;Jt.create=(t,e)=>new Jt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...ne(e)});function ss(t){if(t instanceof We){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=lt.create(ss(r))}return new We({...t._def,shape:()=>e})}else return t instanceof Jt?new Jt({...t._def,type:ss(t.element)}):t instanceof lt?lt.create(ss(t.unwrap())):t instanceof At?At.create(ss(t.unwrap())):t instanceof Et?Et.create(t.items.map(e=>ss(e))):t}var We=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=O.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==O.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:u.parsedType}),T.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 ct(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,T.addIssueToContext)(s,{code:j.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 ct(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,w=await h.value;u.push({key:f,value:w,alwaysSet:h.alwaysSet})}return u}).then(u=>T.ParseStatus.mergeObjectSync(r,u)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return K.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:K.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:Q.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 O.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 O.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ss(this)}partial(e){let n={};for(let r of O.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 O.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof lt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return td(O.util.objectKeys(this.shape))}};S.ZodObject=We;We.create=(t,e)=>new We({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:Q.ZodObject,...ne(e)});We.strictCreate=(t,e)=>new We({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:Q.ZodObject,...ne(e)});We.lazycreate=(t,e)=>new We({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:Q.ZodObject,...ne(e)});var cr=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 j.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_union,unionErrors:o}),T.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let 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 j.ZodError(c));return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};S.ZodUnion=cr;cr.create=(t,e)=>new cr({options:t,typeName:Q.ZodUnion,...ne(e)});var Wt=t=>t instanceof dr?Wt(t.schema):t instanceof et?Wt(t.innerType()):t instanceof hr?[t.value]:t instanceof pr?t.options:t instanceof fr?O.util.objectValues(t.enum):t instanceof mr?Wt(t._def.innerType):t instanceof ar?[void 0]:t instanceof lr?[null]:t instanceof lt?[void 0,...Wt(t.unwrap())]:t instanceof At?[null,...Wt(t.unwrap())]:t instanceof Zs||t instanceof yr?Wt(t.unwrap()):t instanceof gr?Wt(t._def.innerType):[],Yi=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:n.parsedType}),T.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),T.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Wt(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:Q.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ne(r)})}};S.ZodDiscriminatedUnion=Yi;function qa(t,e){let n=(0,O.getParsedType)(t),r=(0,O.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===O.ZodParsedType.object&&r===O.ZodParsedType.object){let s=O.util.objectKeys(e),i=O.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=qa(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===O.ZodParsedType.array&&r===O.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=qa(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===O.ZodParsedType.date&&r===O.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ur=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,T.isAborted)(i)||(0,T.isAborted)(o))return T.INVALID;let l=qa(i.value,o.value);return l.valid?(((0,T.isDirty)(i)||(0,T.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_intersection_types}),T.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};S.ZodIntersection=ur;ur.create=(t,e,n)=>new ur({left:t,right:e,typeName:Q.ZodIntersection,...ne(n)});var Et=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,T.addIssueToContext)(r,{code:j.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 ct(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>T.ParseStatus.mergeArray(n,o)):T.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};S.ZodTuple=Et;Et.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Et({items:t,typeName:Q.ZodTuple,rest:null,...ne(e)})};var 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!==O.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:r.parsedType}),T.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ct(r,l,r.path,l)),value:o._parse(new ct(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:Q.ZodRecord,...ne(r)}):new t({keyType:kn.create(),valueType:e,typeName:Q.ZodRecord,...ne(n)})}};S.ZodRecord=Xi;var as=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!==O.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new ct(r,l,r.path,[u,"key"])),value:i._parse(new ct(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 T.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 T.INVALID;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}}}};S.ZodMap=as;as.create=(t,e,n)=>new as({valueType:e,keyType:t,typeName:Q.ZodMap,...ne(n)});var ls=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.set,received:r.parsedType}),T.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,T.addIssueToContext)(r,{code:j.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,T.addIssueToContext)(r,{code:j.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 T.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 ct(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:K.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:K.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=ls;ls.create=(t,e)=>new ls({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...ne(e)});var Qi=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.function,received:n.parsedType}),T.INVALID;function r(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ji.getErrorMap)(),Ji.defaultErrorMap].filter(u=>!!u),issueData:{code:j.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ji.getErrorMap)(),Ji.defaultErrorMap].filter(u=>!!u),issueData:{code:j.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Sn){let l=this;return(0,T.OK)(async function(...c){let u=new j.ZodError([]),h=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,h);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new j.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 j.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:Et.create(e).rest(Vt.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||Et.create([]).rest(Vt.create()),returns:n||Vt.create(),typeName:Q.ZodFunction,...ne(r)})}};S.ZodFunction=Qi;var dr=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})}};S.ZodLazy=dr;dr.create=(t,e)=>new dr({getter:t,typeName:Q.ZodLazy,...ne(e)});var hr=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:j.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=hr;hr.create=(t,e)=>new hr({value:t,typeName:Q.ZodLiteral,...ne(e)});function td(t,e){return new pr({values:t,typeName:Q.ZodEnum,...ne(e)})}var pr=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:O.util.joinValues(r),received:n.parsedType,code:j.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{received:n.data,code:j.ZodIssueCode.invalid_enum_value,options:r}),T.INVALID}return(0,T.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};S.ZodEnum=pr;pr.create=td;var fr=class extends re{_parse(e){let n=O.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.ZodParsedType.string&&r.parsedType!==O.ZodParsedType.number){let s=O.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:O.util.joinValues(s),received:r.parsedType,code:j.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(O.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=O.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:j.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=fr;fr.create=(t,e)=>new fr({values:t,typeName:Q.ZodNativeEnum,...ne(e)});var Sn=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===O.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,T.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};S.ZodPromise=Sn;Sn.create=(t,e)=>new Sn({type:t,typeName:Q.ZodPromise,...ne(e)});var et=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,T.addIssueToContext)(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return T.INVALID;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?T.INVALID:c.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(c.value):c});{if(n.value==="aborted")return T.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:l.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let 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"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,T.isValid)(o))return T.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,T.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):T.INVALID);O.util.assertNever(s)}};S.ZodEffects=et;S.ZodTransformer=et;et.create=(t,e,n)=>new et({schema:t,typeName:Q.ZodEffects,effect:e,...ne(n)});et.createWithPreprocess=(t,e,n)=>new et({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...ne(n)});var lt=class extends re{_parse(e){return this._getType(e)===O.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=lt;lt.create=(t,e)=>new lt({innerType:t,typeName:Q.ZodOptional,...ne(e)});var At=class extends re{_parse(e){return this._getType(e)===O.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=At;At.create=(t,e)=>new At({innerType:t,typeName:Q.ZodNullable,...ne(e)});var mr=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===O.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=mr;mr.create=(t,e)=>new mr({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});var gr=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(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new j.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new j.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=gr;gr.create=(t,e)=>new gr({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});var cs=class extends re{_parse(e){if(this._getType(e)!==O.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:j.ZodIssueCode.invalid_type,expected:O.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=cs;cs.create=t=>new cs({typeName:Q.ZodNaN,...ne(t)});S.BRAND=Symbol("zod_brand");var Zs=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}};S.ZodBranded=Zs;var Ws=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"?T.INVALID:i.status==="dirty"?(n.dirty(),(0,T.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?T.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Q.ZodPipeline})}};S.ZodPipeline=Ws;var yr=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,T.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,T.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};S.ZodReadonly=yr;yr.create=(t,e)=>new yr({innerType:t,typeName:Q.ZodReadonly,...ne(e)});function Yu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function nd(t,e={},n){return t?_n.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Yu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Yu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):_n.create()}S.late={object:We.lazycreate};var Q;(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"})(Q||(S.ZodFirstPartyTypeKind=Q={}));var sb=(t,e={message:`Input not instance of ${t.name}`})=>nd(n=>n instanceof t,e);S.instanceof=sb;var rd=kn.create;S.string=rd;var sd=rr.create;S.number=sd;var ib=cs.create;S.nan=ib;var ob=sr.create;S.bigint=ob;var id=ir.create;S.boolean=id;var ab=or.create;S.date=ab;var lb=is.create;S.symbol=lb;var cb=ar.create;S.undefined=cb;var ub=lr.create;S.null=ub;var db=_n.create;S.any=db;var hb=Vt.create;S.unknown=hb;var pb=bt.create;S.never=pb;var fb=os.create;S.void=fb;var mb=Jt.create;S.array=mb;var gb=We.create;S.object=gb;var yb=We.strictCreate;S.strictObject=yb;var bb=cr.create;S.union=bb;var wb=Yi.create;S.discriminatedUnion=wb;var vb=ur.create;S.intersection=vb;var kb=Et.create;S.tuple=kb;var _b=Xi.create;S.record=_b;var Sb=as.create;S.map=Sb;var Tb=ls.create;S.set=Tb;var xb=Qi.create;S.function=xb;var Ib=dr.create;S.lazy=Ib;var Rb=hr.create;S.literal=Rb;var Eb=pr.create;S.enum=Eb;var Ab=fr.create;S.nativeEnum=Ab;var $b=Sn.create;S.promise=$b;var od=et.create;S.effect=od;S.transformer=od;var Cb=lt.create;S.optional=Cb;var Pb=At.create;S.nullable=Pb;var Nb=et.createWithPreprocess;S.preprocess=Nb;var jb=Ws.create;S.pipeline=jb;var Ob=()=>rd().optional();S.ostring=Ob;var Mb=()=>sd().optional();S.onumber=Mb;var zb=()=>id().optional();S.oboolean=zb;S.coerce={string:(t=>kn.create({...t,coerce:!0})),number:(t=>rr.create({...t,coerce:!0})),boolean:(t=>ir.create({...t,coerce:!0})),bigint:(t=>sr.create({...t,coerce:!0})),date:(t=>or.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var Fa=ce(ut=>{"use strict";var Db=ut&&ut.__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]})),us=ut&&ut.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Db(e,t,n)};Object.defineProperty(ut,"__esModule",{value:!0});us(Wi(),ut);us(La(),ut);us(Zu(),ut);us(Ks(),ut);us(ad(),ut);us(Zi(),ut)});var ud=ce(Ve=>{"use strict";var ld=Ve&&Ve.__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]})),Lb=Ve&&Ve.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ub=Ve&&Ve.__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)&&ld(e,t,n);return Lb(e,t),e},qb=Ve&&Ve.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ld(e,t,n)};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.z=void 0;var cd=Ub(Fa());Ve.z=cd;qb(Fa(),Ve);Ve.default=cd});var Te=ce(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.ChatLoadMsg=p.ChatListResultMsg=p.ChatListMsg=p.ChatUsageMsg=p.ChatStreamMsg=p.JiraUsersResultMsg=p.DeployClaimResultMsg=p.DeployClaimMsg=p.RuleDiagnoseResultMsg=p.ProjectTestResultMsg=p.RunStatusMsg=p.RunContextMsg=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.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=p.BUILTIN_REPLY_LANGUAGES=void 0;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=p.EnvPreflightMsg=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=p.DeploySuggestMsg=void 0;p.missingAgentCapabilities=Fb;p.replyPreferenceAppendix=Hb;p.pendingMigrationsAppendix=Kb;p.deployTargetsAppendix=Gb;p.isSelfMigrationFilename=Zb;p.parseRunnerMsg=Wb;p.parseServerMsg=Vb;var a=ud();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.79";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 Fb(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 Bb=t=>t.includes(p.NEEDS_INPUT_COMMENT_MARKER)||p.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));p.needsInputMarkerIn=Bb;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),maxCostUsd:a.z.number().positive().optional(),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.RunContextMsg=a.z.object({type:a.z.literal("run.context"),runId:a.z.string(),pieces:a.z.array(a.z.object({part:a.z.string().max(80),chars:a.z.number().int().nonnegative()})).max(30),totalChars:a.z.number().int().nonnegative(),sessionMode:a.z.enum(["fresh","chained","timeout-resume","preflight-resume"])});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 Hb(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 Kb(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
32
|
`+t.map(n=>`- ${p.SELF_MIGRATION_DIR}/${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.`}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","compose"]);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 Zb(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),remainingInBatch:a.z.number().int().min(0).default(0)}).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.RunContextMsg,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 Wb(t){return p.RunnerToServerMsg.parse(t)}function Vb(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.
|
|
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","compose"]);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),outputTruncated:a.z.boolean().default(!1)});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 Zb(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),remainingInBatch:a.z.number().int().min(0).default(0)}).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.RunContextMsg,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 Wb(t){return p.RunnerToServerMsg.parse(t)}function Vb(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
|
|
|
@@ -306,25 +306,25 @@ Rules for the steps:
|
|
|
306
306
|
- Prefer commands that are safe to re-run; a deploy may be retried.
|
|
307
307
|
- A check that fails SILENTLY is only half a check. A pre-check chaining five bare \`test\`/\`grep -q\` guards with && dies as an uninvestigable "exit code 1" - the operator retries blind, twice, and then stops trusting the deploy (this happened; the culprit was a \`test -f\` with no message four conditions deep). Every guard that can fail must SAY what it found: \`test -f apps/api/.env || { echo "apps/api/.env is missing"; exit 1; }\` - the echo is not decoration, it is the entire difference between a five-second fix and a lost evening.
|
|
308
308
|
- Order matters: install, build, test (if cheap), then release.
|
|
309
|
-
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var vd={};hn(vd,{DELETE_MANIFEST_FILE:()=>Yt,MAX_CHANGED_FILES:()=>Tn,MAX_CHANGED_LINES:()=>xn,abortMerge:()=>En,applyDeleteManifest:()=>ds,branchForIssue:()=>Ja,branchSha:()=>io,branchesDiffer:()=>sl,checkDiffSafety:()=>Rn,checkoutBranchInWorktree:()=>Ya,commitAll:()=>wr,commitMergeResolution:()=>tl,commitsBetween:()=>Wa,deleteStaleBranch:()=>
|
|
309
|
+
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var vd={};hn(vd,{DELETE_MANIFEST_FILE:()=>Yt,MAX_CHANGED_FILES:()=>Tn,MAX_CHANGED_LINES:()=>xn,abortMerge:()=>En,applyDeleteManifest:()=>ds,branchForIssue:()=>Ja,branchSha:()=>io,branchesDiffer:()=>sl,checkDiffSafety:()=>Rn,checkoutBranchInWorktree:()=>Ya,commitAll:()=>wr,commitMergeResolution:()=>tl,commitsBetween:()=>Wa,deleteStaleBranch:()=>Ka,diffAgainstDefault:()=>oo,envCheckoutPath:()=>wd,envCheckoutsRoot:()=>bd,fetchBase:()=>In,findConflictMarkers:()=>ao,headSha:()=>Je,mergeBaseIntoWorktree:()=>el,mergeTicketBranch:()=>Qa,originUrl:()=>kr,parseOwnerRepo:()=>wt,prepareEnvCheckout:()=>Xa,pruneWorktrees:()=>Va,pushBranch:()=>vr,pushEnvBranch:()=>rl,pushWipBranch:()=>Ba,removeWorktree:()=>$t,resetHard:()=>hs,servedBranchTip:()=>Za,statusSnapshot:()=>Ha,unresolvedAmong:()=>nl,worktreeAdd:()=>Ga,worktreeAddExisting:()=>Js,worktreeFingerprint:()=>so,worktreesRoot:()=>Xt});async function F(t,e,n={}){try{let{stdout:r}=await gd("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 ds(t){let e={deleted:[],refused:[]},n=me.default.join(t,Yt);if(!Ie.default.existsSync(n))return e;let r=me.default.resolve(t),s=Ie.default.readFileSync(n,"utf8").split(`
|
|
310
310
|
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(me.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=me.default.resolve(r,i);if(o!==r&&!o.startsWith(r+me.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=me.default.relative(r,o).split(me.default.sep).join("/");if(l===Yt)continue;if(yd.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Ie.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{Ie.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return Ie.default.rmSync(n,{force:!0}),e}async function Ba(t,e){await F(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function so(t){let e=await F(t,["status","--porcelain"]),n=await F(t,["diff","--numstat"]),r=e.split(`
|
|
311
311
|
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Ie.default.statSync(me.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
312
312
|
`);return`${e}
|
|
313
313
|
--
|
|
314
314
|
${n}
|
|
315
315
|
--
|
|
316
|
-
${r}`}async function
|
|
316
|
+
${r}`}async function Ha(t){let e=(await F(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await F(t,["log","--oneline","-1"])).trim(),r=(await F(t,["status","--porcelain"])).trim(),s=r?r.split(`
|
|
317
317
|
`):[],i=s.slice(0,15).join(`
|
|
318
318
|
`),o=s.length>15?`
|
|
319
319
|
(\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${n}
|
|
320
320
|
working tree: ${s.length?`
|
|
321
|
-
${i}${o}`:"clean"}`}function Xt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ie.default.existsSync(me.default.join(br.default.homedir(),".cache","ticketpilot"))?me.default.join(br.default.homedir(),".cache","ticketpilot"):me.default.join(br.default.homedir(),".cache","allwright"));return me.default.join(t,"worktrees")}async function In(t,e){try{await F(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
|
|
321
|
+
${i}${o}`:"clean"}`}function Xt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ie.default.existsSync(me.default.join(br.default.homedir(),".cache","ticketpilot"))?me.default.join(br.default.homedir(),".cache","ticketpilot"):me.default.join(br.default.homedir(),".cache","allwright"));return me.default.join(t,"worktrees")}async function In(t,e){try{await F(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 Ka(t,e){try{let n=await F(t,["worktree","list","--porcelain"]),r=Xt(),s=null;for(let i of n.split(`
|
|
322
322
|
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await F(t,["worktree","remove","--force",s]);await F(t,["worktree","prune"])}catch{}try{await F(t,["branch","-D",e])}catch{}}async function Ga(t,e,n,r){Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await F(t,["worktree","add","-b",n,e,`origin/${r}`])}async function wr(t,e){if(await F(t,["add","-A"]),!(await F(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await F(t,["-c",`user.name=${no}`,"-c",`user.email=${ro}`,"commit","-m",e])}async function Rn(t,e){let r=(await F(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
323
|
-
`).filter(Boolean),s=r.filter(u=>yd.some(h=>h.test(u))),i=await F(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<=Tn&&o+l<=xn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function vr(t,e){await F(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Je(t){return(await F(t,["rev-parse","HEAD"])).trim()}async function Za(t,e){let n=await F(t,["fetch","origin",e],{timeoutMs:12e4}).then(()=>!0).catch(()=>!1),r=async s=>F(t,["rev-parse","--verify",s]).then(i=>i.trim()).catch(()=>"");if(n){let s=await r("FETCH_HEAD");if(s)return s}return r(`refs/remotes/origin/${e}`)}async function Wa(t,e,n){return F(t,["rev-list","--count",`${e}..${n}`]).then(r=>r.trim()).catch(()=>"")}async function io(t,e){try{return(await F(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function hs(t,e){await F(t,["reset","--hard",e])}async function
|
|
323
|
+
`).filter(Boolean),s=r.filter(u=>yd.some(h=>h.test(u))),i=await F(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<=Tn&&o+l<=xn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function vr(t,e){await F(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Je(t){return(await F(t,["rev-parse","HEAD"])).trim()}async function Za(t,e){let n=await F(t,["fetch","origin",e],{timeoutMs:12e4}).then(()=>!0).catch(()=>!1),r=async s=>F(t,["rev-parse","--verify",s]).then(i=>i.trim()).catch(()=>"");if(n){let s=await r("FETCH_HEAD");if(s)return s}return r(`refs/remotes/origin/${e}`)}async function Wa(t,e,n){return F(t,["rev-list","--count",`${e}..${n}`]).then(r=>r.trim()).catch(()=>"")}async function io(t,e){try{return(await F(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function hs(t,e){await F(t,["reset","--hard",e])}async function $t(t,e){try{await F(t,["worktree","remove","--force",e])}catch{Ie.default.rmSync(e,{recursive:!0,force:!0})}}async function Va(t,e=[]){let n=new Set(e.map(s=>me.default.basename(me.default.resolve(s))).filter(s=>s.length>0)),r=Xt();if(Ie.default.existsSync(r))for(let s of Ie.default.readdirSync(r))n.has(s)||Ie.default.rmSync(me.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await F(s,["worktree","prune"])}catch{}}async function Ja(t,e){return await F(t,["fetch","origin","--prune"]).catch(()=>{}),(await F(t,["branch","-r","--list",`*${e}*`])).split(`
|
|
324
324
|
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function oo(t,e,n=6e4){let s=(await F(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(t,["diff","--stat",`${s}...${e}`]),o=await F(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function bd(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ie.default.existsSync(me.default.join(br.default.homedir(),".cache","ticketpilot"))?me.default.join(br.default.homedir(),".cache","ticketpilot"):me.default.join(br.default.homedir(),".cache","allwright"));return me.default.join(t,"env-checkouts")}function pd(t){return t.replace(/[^\w.-]+/g,"_")}async function Ya(t,e,n){await F(t,["fetch","origin"],{timeoutMs:3e5}),await F(t,["reset","--hard"]),await F(t,["checkout","-B",e,n])}function wd(t,e){return me.default.join(bd(),pd(t),pd(e))}async function Xa(t){let e=wd(t.repoName,t.envName);return await F(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Ie.default.existsSync(me.default.join(e,".git"))?await F(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Ie.default.rmSync(e,{recursive:!0,force:!0}),Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await F(t.repoPath,["worktree","prune"]).catch(()=>{}),await F(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await F(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await F(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function Qa(t,e,n){try{await F(t,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await F(t,["-c",`user.name=${no}`,"-c",`user.email=${ro}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function el(t,e){await F(t,["fetch","origin",e],{timeoutMs:3e5});try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await F(t,["-c",`user.name=${no}`,"-c",`user.email=${ro}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await F(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
325
325
|
`).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function En(t){await F(t,["merge","--abort"]).catch(()=>{})}async function tl(t,e){await F(t,["add","-A"]),await F(t,["-c",`user.name=${no}`,"-c",`user.email=${ro}`,"commit","--no-edit","-m",e])}async function nl(t,e){let n=new Set(await ao(t));return e.filter(r=>n.has(r))}async function ao(t){let e=new Set;try{let r=await F(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
|
|
326
326
|
`).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await F(t,["grep","-l","-I","-E","^={7}$"])).split(`
|
|
327
|
-
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Js(t,e,n){Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function rl(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function sl(t,e,n){try{return await gd("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 kr(t){return(await F(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 Ie,br,me,fd,md,gd,no,ro,Tn,xn,yd,Yt
|
|
327
|
+
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Js(t,e,n){Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function rl(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function sl(t,e,n){try{return await gd("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 kr(t){return(await F(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 Ie,br,me,fd,md,gd,no,ro,Tn,xn,yd,Yt,Ct=we(()=>{"use strict";Ie=E(require("node:fs"),1),br=E(require("node:os"),1),me=E(require("node:path"),1),fd=require("node:child_process"),md=require("node:util"),gd=(0,md.promisify)(fd.execFile),no="Allwright Agent",ro="agent@ticketpilot.local",Tn=200,xn=2e4,yd=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Yt=".ticketpilot-delete"});function co(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 ze(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Id(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",w=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:h,github:f,githubAs:w}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var _r=we(()=>{"use strict"});var _l,g,Qt=we(()=>{"use strict";_l=()=>new Date().toISOString(),g={info:t=>console.log(`${_l()} [info] ${t}`),warn:t=>console.warn(`${_l()} [warn] ${t}`),error:t=>console.error(`${_l()} [error] ${t}`)}});var ch={};hn(ch,{crawlSite:()=>_w,extractLinks:()=>ah,formatCrawlReport:()=>Sw,pageIssues:()=>lh});function ah(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 lh(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 _w(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 w=>{let v=Date.now();try{let k=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),x=await k.arrayBuffer(),I=x.byteLength,P=new TextDecoder().decode(x.slice(0,3e6));return{status:k.status,html:P,ms:Date.now()-v,bytes:I}}catch{return{status:0,html:"",ms:Date.now()-v,bytes:0}}};for(;o.length&&s.pages.length<30&&Date.now()-r<12e4;){let w=o.shift(),{status:v,html:k,ms:x,bytes:I}=await u(w),P=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",J=lh({status:v,html:k,url:w,ms:x});if(v===0&&J.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:v,ms:x,bytes:I,title:P,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:J}),P&&c.set(P,[...c.get(P)??[],w]),v===200&&k)for(let W of ah(k,w,n))i.has(W)||i.set(W,new Set),i.get(W).add(w),l.has(W)||(l.add(W),o.push(W))}let h=[...c.entries()].filter(([,w])=>w.length>1);for(let[w,v]of h.slice(0,5))s.notes.push(`${v.length} pages share the title "${w.slice(0,60)}" (${v.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 Sw(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(`
|
|
328
328
|
`);return`CRAWL OF THE RUNNING SITE (${t.baseUrl}) - gathered by the runner just now, GET only, same-origin only:
|
|
329
329
|
${e}
|
|
330
330
|
|
|
@@ -349,7 +349,7 @@ WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that
|
|
|
349
349
|
- installed: ${r.join(", ")||"(none of the usual ones)"}
|
|
350
350
|
- NOT installed: ${s.join(", ")||"(none missing)"}
|
|
351
351
|
- reverse proxy currently running: ${i.join(", ")||"(none)"}
|
|
352
|
-
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 wv(t){try{return new URL(t).hostname}catch{return""}}function
|
|
352
|
+
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 wv(t){try{return new URL(t).hostname}catch{return""}}function Hl(t){let e=t.urls.map(wv).filter(Boolean),n=Ro(t.repoPath),r=dv(e),s=[`
|
|
353
353
|
|
|
354
354
|
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}):
|
|
355
355
|
`+n.map(i=>` - ${i}`).join(`
|
|
@@ -358,7 +358,7 @@ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Tru
|
|
|
358
358
|
`+r.map(i=>` - ${i}`).join(`
|
|
359
359
|
`)+`
|
|
360
360
|
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(`
|
|
361
|
-
`)+bv()+Bl()}function op(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=Eo(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=Ro(l),u="";try{u=o.publicUrl?new URL(o.publicUrl).hostname:""}catch{u=""}let h=u?rp([u]):[],f=c.length?void 0:h.find(w=>pv(w.lines,l));if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0||!!f,blocking:!f,detail:c.length?c.join(" \xB7 "):f?`static site - ${f.file} serves files from ${l} directly, so there is no process to supervise`:`no systemd unit on this machine references ${l}. This goes green with either a unit whose WorkingDirectory or ExecStart names ${l}, or a reverse-proxy root serving this environment's hostname from it.`}),o.servePath?.trim()){let w=o.servePath.trim(),v=(P,J)=>{try{return(0,Mt.execFileSync)("git",J,{cwd:P,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},k=v(w,["rev-parse","HEAD"]),x=o.branch.trim()?v(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,I=k&&x&&k!==x?v(t.repoPath,["rev-list","--count",`${k}..${x}`]):null;e.push({environment:o.name,question:`The live checkout at ${w} serves the latest ${o.branch.trim()||"commit"}`,ok:k!==null&&(x===null||k===x),blocking:!1,detail:k?x===null?`serving ${k.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:k===x?`serving ${k.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${k.slice(0,10)}, but origin/${o.branch.trim()} is at ${x.slice(0,10)}`+(I?` - ${I} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${w} - wrong path, or not a git checkout`})}if(o.publicUrl){let w=u,v=h.map(sp);e.push({environment:o.name,question:`A reverse proxy here serves ${w||o.publicUrl}`,ok:v.length>0,blocking:!1,detail:v.length?v.join(" \xB7 "):`no proxy configuration on this machine mentions ${w||o.publicUrl}`})}if(o.publicUrl){let w=u;if(w){let v="";for(let k of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=tt.default.readFileSync(li.default.join(l,k),"utf8");break}catch{}if(v){let k=v.includes(w);e.push({environment:o.name,question:`DEPLOY.md mentions ${w}`,ok:k,blocking:!1,detail:k?"":"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 w=r.branches.includes(o.branch);e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:w,blocking:!0,detail:w?"":`origin was reached and does not have "${o.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var Mt,tt,li,uv,Qh,ep,Ao=we(()=>{"use strict";Mt=require("node:child_process"),tt=E(require("node:fs"),1),li=E(require("node:path"),1),uv=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],Qh=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],ep=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function Gl(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>vv.test(n)?`${n}=<redacted>`:e)}function nn(t,e){try{let r=(0,dp.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,up):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,up):null}}function kv(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=
|
|
361
|
+
`)+bv()+Bl()}function op(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=Eo(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=Ro(l),u="";try{u=o.publicUrl?new URL(o.publicUrl).hostname:""}catch{u=""}let h=u?rp([u]):[],f=c.length?void 0:h.find(w=>pv(w.lines,l));if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0||!!f,blocking:!f,detail:c.length?c.join(" \xB7 "):f?`static site - ${f.file} serves files from ${l} directly, so there is no process to supervise`:`no systemd unit on this machine references ${l}. This goes green with either a unit whose WorkingDirectory or ExecStart names ${l}, or a reverse-proxy root serving this environment's hostname from it.`}),o.servePath?.trim()){let w=o.servePath.trim(),v=(P,J)=>{try{return(0,Mt.execFileSync)("git",J,{cwd:P,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},k=v(w,["rev-parse","HEAD"]),x=o.branch.trim()?v(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,I=k&&x&&k!==x?v(t.repoPath,["rev-list","--count",`${k}..${x}`]):null;e.push({environment:o.name,question:`The live checkout at ${w} serves the latest ${o.branch.trim()||"commit"}`,ok:k!==null&&(x===null||k===x),blocking:!1,detail:k?x===null?`serving ${k.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:k===x?`serving ${k.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${k.slice(0,10)}, but origin/${o.branch.trim()} is at ${x.slice(0,10)}`+(I?` - ${I} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${w} - wrong path, or not a git checkout`})}if(o.publicUrl){let w=u,v=h.map(sp);e.push({environment:o.name,question:`A reverse proxy here serves ${w||o.publicUrl}`,ok:v.length>0,blocking:!1,detail:v.length?v.join(" \xB7 "):`no proxy configuration on this machine mentions ${w||o.publicUrl}`})}if(o.publicUrl){let w=u;if(w){let v="";for(let k of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=tt.default.readFileSync(li.default.join(l,k),"utf8");break}catch{}if(v){let k=v.includes(w);e.push({environment:o.name,question:`DEPLOY.md mentions ${w}`,ok:k,blocking:!1,detail:k?"":"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 w=r.branches.includes(o.branch);e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:w,blocking:!0,detail:w?"":`origin was reached and does not have "${o.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var Mt,tt,li,uv,Qh,ep,Ao=we(()=>{"use strict";Mt=require("node:child_process"),tt=E(require("node:fs"),1),li=E(require("node:path"),1),uv=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],Qh=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],ep=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function Gl(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>vv.test(n)?`${n}=<redacted>`:e)}function nn(t,e){try{let r=(0,dp.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,up):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,up):null}}function kv(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Kl.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Kl.default.readFileSync(hp.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function pp(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:Gl(l)})},s=kv(t.repoPath);for(let o of s)r(`systemctl status ${o}`,nn("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,nn("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,nn("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",nn("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)`,nn("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",nn("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",nn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",nn("id",[])),r(`ls -ld ${t.repoPath}`,nn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function fp(t){return t.length?`
|
|
362
362
|
|
|
363
363
|
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.
|
|
364
364
|
|
|
@@ -367,7 +367,7 @@ ${e.output}`).join(`
|
|
|
367
367
|
|
|
368
368
|
`)+`
|
|
369
369
|
|
|
370
|
-
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 dp,Hl,hp,up,vv,Zl=we(()=>{"use strict";dp=require("node:child_process"),Hl=E(require("node:fs"),1),hp=E(require("node:path"),1),up=4e3,vv=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var Ap={};hn(Ap,{MAX_CHAIN_DEPTH:()=>tc,breakChain:()=>ic,breakSingleModeChain:()=>cc,chainOf:()=>rc,chainSessionFor:()=>Do,loadBatchPlan:()=>nc,nextMemberWillChain:()=>uc,parsePlanAnswer:()=>dc,recordChainSession:()=>sc,recordSingleModeSession:()=>ac,saveBatchPlan:()=>zv,singleModeChainIntact:()=>lc,singleModeSessionFor:()=>oc});function zv(t){Rs.default.mkdirSync(ec(),{recursive:!0,mode:448}),Rs.default.writeFileSync(zo.default.join(ec(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function nc(t){if(!t)return null;try{return JSON.parse(Rs.default.readFileSync(zo.default.join(ec(),`${t}.json`),"utf8"))}catch{return null}}function rc(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function Do(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=rn.get(Mo(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=tc||!Rs.default.existsSync(s.worktreePath)?null:s}function sc(t,e,n,r){let s=rn.get(Mo(t,e));rn.set(Mo(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function ic(t,e){rn.delete(Mo(t,e))}function oc(t){let e=rn.get(ui(t));return!e||e.depth>=tc||!Rs.default.existsSync(e.worktreePath)?null:e}function ac(t,e,n,r){let s=rn.get(ui(t));rn.set(ui(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function lc(t,e){return rn.get(ui(t))?.lastIssue===e}function cc(t){rn.delete(ui(t))}function uc(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function dc(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 Rs,zo,tc,ec,rn,Mo,ui,Lo=we(()=>{"use strict";Rs=E(require("node:fs"),1),zo=E(require("node:path"),1);Ce();tc=3,ec=()=>zo.default.join(le(),"autopilot-plans");rn=new Map,Mo=(t,e)=>`${t}:${e[0]}`;ui=t=>`${t}:__single__`});var sn=ce((Cx,sf)=>{"use strict";var nf=["nodebuffer","arraybuffer","fragments"],rf=typeof Blob<"u";rf&&nf.push("blob");sf.exports={BINARY_TYPES:nf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:rf,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var hi=ce(($x,Bo)=>{"use strict";var{EMPTY_BUFFER:ck}=sn(),wc=Buffer[Symbol.species];function uk(t,e){if(t.length===0)return ck;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 wc(n.buffer,n.byteOffset,r):n}function of(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function af(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function dk(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function vc(t){if(vc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new wc(t):ArrayBuffer.isView(t)?e=new wc(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),vc.readOnly=!1),e}Bo.exports={concat:uk,mask:of,toArrayBuffer:dk,toBuffer:vc,unmask:af};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Bo.exports.mask=function(e,n,r,s,i){i<48?of(e,n,r,s,i):t.mask(e,n,r,s,i)},Bo.exports.unmask=function(e,n){e.length<32?af(e,n):t.unmask(e,n)}}catch{}});var uf=ce((Px,cf)=>{"use strict";var lf=Symbol("kDone"),kc=Symbol("kRun"),_c=class{constructor(e){this[lf]=()=>{this.pending--,this[kc]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[kc]()}[kc](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[lf])}}};cf.exports=_c});var Cs=ce((jx,ff)=>{"use strict";var pi=require("zlib"),df=hi(),hk=uf(),{kStatusCode:hf}=sn(),pk=Buffer[Symbol.species],fk=Buffer.from([0,0,255,255]),Ho=Symbol("permessage-deflate"),on=Symbol("total-length"),Es=Symbol("callback"),jn=Symbol("buffers"),As=Symbol("error"),Ko,Sc=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,!Ko){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ko=new hk(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[Es];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){Ko.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Ko.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"?pi.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=pi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ho]=this,this._inflate[on]=0,this._inflate[jn]=[],this._inflate.on("error",gk),this._inflate.on("data",pf)}this._inflate[Es]=r,this._inflate.write(e),n&&this._inflate.write(fk),this._inflate.flush(()=>{let i=this._inflate[As];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=df.concat(this._inflate[jn],this._inflate[on]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[on]=0,this._inflate[jn]=[],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"?pi.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=pi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[on]=0,this._deflate[jn]=[],this._deflate.on("data",mk)}this._deflate[Es]=r,this._deflate.write(e),this._deflate.flush(pi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=df.concat(this._deflate[jn],this._deflate[on]);n&&(i=new pk(i.buffer,i.byteOffset,i.length-4)),this._deflate[Es]=null,this._deflate[on]=0,this._deflate[jn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ff.exports=Sc;function mk(t){this[jn].push(t),this[on]+=t.length}function pf(t){if(this[on]+=t.length,this[Ho]._maxPayload<1||this[on]<=this[Ho]._maxPayload){this[jn].push(t);return}this[As]=new RangeError("Max payload size exceeded"),this[As].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[As][hf]=1009,this.removeListener("data",pf),this.reset()}function gk(t){if(this[Ho]._inflate=null,this[As]){this[Es](this[As]);return}t[hf]=1007,this[Es](t)}});var $s=ce((Nx,Go)=>{"use strict";var{isUtf8:mf}=require("buffer"),{hasBlob:yk}=sn(),bk=[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 wk(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Tc(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 vk(t){return yk&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Go.exports={isBlob:vk,isValidStatusCode:wk,isValidUTF8:Tc,tokenChars:bk};if(mf)Go.exports.isValidUTF8=function(t){return t.length<24?Tc(t):mf(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Go.exports.isValidUTF8=function(e){return e.length<32?Tc(e):t(e)}}catch{}});var Ac=ce((Ox,_f)=>{"use strict";var{Writable:kk}=require("stream"),gf=Cs(),{BINARY_TYPES:_k,EMPTY_BUFFER:yf,kStatusCode:Sk,kWebSocket:Tk}=sn(),{concat:xc,toArrayBuffer:xk,unmask:Ik}=hi(),{isValidStatusCode:Rk,isValidUTF8:bf}=$s(),Zo=Buffer[Symbol.species],ft=0,wf=1,vf=2,kf=3,Ic=4,Rc=5,Wo=6,Ec=class extends kk{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||_k[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[Tk]=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=ft}_write(e,n,r){if(this._opcode===8&&this._state==ft)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 Zo(r.buffer,r.byteOffset+e,r.length-e),new Zo(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 Zo(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 ft:this.getInfo(e);break;case wf:this.getPayloadLength16(e);break;case vf:this.getPayloadLength64(e);break;case kf:this.getMask();break;case Ic:this.getData(e);break;case Rc:case Wo: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[gf.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=wf:this._payloadLength===127?this._state=vf: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=kf:this._state=Ic}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ic}getData(e){let n=yf;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&&Ik(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=Rc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[gf.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===ft&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ft;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=xc(r,n):this._binaryType==="arraybuffer"?s=xk(xc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ft):(this._state=Wo,setImmediate(()=>{this.emit("message",s,!0),this._state=ft,this.startLoop(e)}))}else{let s=xc(r,n);if(!this._skipUTF8Validation&&!bf(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Rc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ft):(this._state=Wo,setImmediate(()=>{this.emit("message",s,!1),this._state=ft,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,yf),this.end();else{let r=e.readUInt16BE(0);if(!Rk(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Zo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!bf(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=ft;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ft):(this._state=Wo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ft,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[Sk]=s,o}};_f.exports=Ec});var Pc=ce((zx,xf)=>{"use strict";var{Duplex:Mx}=require("stream"),{randomFillSync:Ek}=require("crypto"),{types:{isUint8Array:Ak}}=require("util"),Sf=Cs(),{EMPTY_BUFFER:Ck,kWebSocket:$k,NOOP:Pk}=sn(),{isBlob:Ps,isValidStatusCode:jk}=$s(),{mask:Tf,toBuffer:Dr}=hi(),mt=Symbol("kByteLength"),Nk=Buffer.alloc(4),Vo=8*1024,Lr,js=Vo,St=0,Ok=1,Mk=2,Cc=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=Pk,this[$k]=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):(js===Vo&&(Lr===void 0&&(Lr=Buffer.alloc(Vo)),Ek(Lr,0,Vo),js=0),r[0]=Lr[js++],r[1]=Lr[js++],r[2]=Lr[js++],r[3]=Lr[js++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[mt]!==void 0?l=n[mt]:(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?(Tf(e,r,u,i,l),[u]):(Tf(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=Ck;else{if(typeof e!="number"||!jk(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={[mt]: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):Ps(e)?(s=e.size,i=!1):(e=Dr(e),s=e.length,i=Dr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[mt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ps(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):Ps(e)?(s=e.size,i=!1):(e=Dr(e),s=e.length,i=Dr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[mt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ps(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[Sf.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Ps(e)?(l=e.size,c=!1):(e=Dr(e),l=e.length,c=Dr.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={[mt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Ps(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[mt],this._state=Mk,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick($c,this,l,s);return}this._bufferedBytes-=r[mt];let o=Dr(i);n?this.dispatch(o,n,r,s):(this._state=St,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(zk,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Sf.extensionName];this._bufferedBytes+=r[mt],this._state=Ok,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");$c(this,c,s);return}this._bufferedBytes-=r[mt],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][mt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mt],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)}};xf.exports=Cc;function $c(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 zk(t,e,n){$c(t,e,n),t.onerror(e)}});var Nf=ce((Dx,jf)=>{"use strict";var{kForOnEventAttribute:fi,kListener:jc}=sn(),If=Symbol("kCode"),Rf=Symbol("kData"),Ef=Symbol("kError"),Af=Symbol("kMessage"),Cf=Symbol("kReason"),Ns=Symbol("kTarget"),$f=Symbol("kType"),Pf=Symbol("kWasClean"),an=class{constructor(e){this[Ns]=null,this[$f]=e}get target(){return this[Ns]}get type(){return this[$f]}};Object.defineProperty(an.prototype,"target",{enumerable:!0});Object.defineProperty(an.prototype,"type",{enumerable:!0});var Ur=class extends an{constructor(e,n={}){super(e),this[If]=n.code===void 0?0:n.code,this[Cf]=n.reason===void 0?"":n.reason,this[Pf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[If]}get reason(){return this[Cf]}get wasClean(){return this[Pf]}};Object.defineProperty(Ur.prototype,"code",{enumerable:!0});Object.defineProperty(Ur.prototype,"reason",{enumerable:!0});Object.defineProperty(Ur.prototype,"wasClean",{enumerable:!0});var Os=class extends an{constructor(e,n={}){super(e),this[Ef]=n.error===void 0?null:n.error,this[Af]=n.message===void 0?"":n.message}get error(){return this[Ef]}get message(){return this[Af]}};Object.defineProperty(Os.prototype,"error",{enumerable:!0});Object.defineProperty(Os.prototype,"message",{enumerable:!0});var mi=class extends an{constructor(e,n={}){super(e),this[Rf]=n.data===void 0?null:n.data}get data(){return this[Rf]}};Object.defineProperty(mi.prototype,"data",{enumerable:!0});var Dk={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[fi]&&s[jc]===e&&!s[fi])return;let r;if(t==="message")r=function(i,o){let l=new mi("message",{data:o?i:i.toString()});l[Ns]=this,Jo(e,this,l)};else if(t==="close")r=function(i,o){let l=new Ur("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ns]=this,Jo(e,this,l)};else if(t==="error")r=function(i){let o=new Os("error",{error:i,message:i.message});o[Ns]=this,Jo(e,this,o)};else if(t==="open")r=function(){let i=new an("open");i[Ns]=this,Jo(e,this,i)};else return;r[fi]=!!n[fi],r[jc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[jc]===e&&!n[fi]){this.removeListener(t,n);break}}};jf.exports={CloseEvent:Ur,ErrorEvent:Os,Event:an,EventTarget:Dk,MessageEvent:mi};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Yo=ce((Lx,Of)=>{"use strict";var{tokenChars:gi}=$s();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Lk(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&&gi[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 v=t.slice(c,h);u===44?(zt(e,v,n),n=Object.create(null)):o=v,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(h===-1&&gi[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),zt(n,t.slice(c,h),!0),u===44&&(zt(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(gi[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(gi[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&&gi[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 v=t.slice(c,h);r&&(v=v.replace(/\\/g,""),r=!1),zt(n,l,v),u===44&&(zt(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 w=t.slice(c,h);return o===void 0?zt(e,w,n):(l===void 0?zt(n,w,!0):r?zt(n,l,w.replace(/\\/g,"")):zt(n,l,w),zt(e,o,n)),e}function Uk(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(", ")}Of.exports={format:Uk,parse:Lk}});var ta=ce((Fx,Zf)=>{"use strict";var qk=require("events"),Fk=require("https"),Bk=require("http"),Df=require("net"),Kk=require("tls"),{randomBytes:Hk,createHash:Gk}=require("crypto"),{Duplex:Ux,Readable:qx}=require("stream"),{URL:Nc}=require("url"),Nn=Cs(),Zk=Ac(),Wk=Pc(),{isBlob:Vk}=$s(),{BINARY_TYPES:Mf,CLOSE_TIMEOUT:Jk,EMPTY_BUFFER:Xo,GUID:Yk,kForOnEventAttribute:Oc,kListener:Xk,kStatusCode:Qk,kWebSocket:Re,NOOP:Lf}=sn(),{EventTarget:{addEventListener:e_,removeEventListener:t_}}=Nf(),{format:n_,parse:r_}=Yo(),{toBuffer:s_}=hi(),Uf=Symbol("kAborted"),Mc=[8,13],ln=["CONNECTING","OPEN","CLOSING","CLOSED"],i_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends qk{constructor(e,n,r){super(),this._binaryType=Mf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xo,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]),qf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mf.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 Zk({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 Wk(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Re]=this,i[Re]=this,e[Re]=this,s.on("conclude",l_),s.on("drain",c_),s.on("error",u_),s.on("message",d_),s.on("ping",h_),s.on("pong",p_),i.onerror=f_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Kf),e.on("data",ea),e.on("end",Hf),e.on("error",Gf),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[Nn.extensionName]&&this._extensions[Nn.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){nt(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())}),Bf(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){zc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Xo,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){zc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Xo,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){zc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Nn.extensionName]||(s.compress=!1),this._sender.send(e||Xo,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){nt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ge,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Oc])return e[Xk];return null},set(e){for(let n of this.listeners(t))if(n[Oc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Oc]:!0})}})});ge.prototype.addEventListener=e_;ge.prototype.removeEventListener=t_;Zf.exports=ge;function qf(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Jk,protocolVersion:Mc[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,!Mc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Mc.join(", ")})`);let i;if(e instanceof Nc)i=e;else try{i=new Nc(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 x=new SyntaxError(c);if(t._redirects===0)throw x;Qo(t,x);return}let u=o?443:80,h=Hk(16).toString("base64"),f=o?Fk.request:Bk.request,w=new Set,v;if(s.createConnection=s.createConnection||(o?a_:o_),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&&(v=new Nn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=n_({[Nn.extensionName]:v.offer()})),n.length){for(let x of n){if(typeof x!="string"||!i_.test(x)||w.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let k;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[I,P]of Object.entries(x))r.headers[I.toLowerCase()]=P}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{nt(t,k,"Opening handshake has timed out")}),k.on("error",x=>{k===null||k[Uf]||(k=t._req=null,Qo(t,x))}),k.on("response",x=>{let I=x.headers.location,P=x.statusCode;if(I&&s.followRedirects&&P>=300&&P<400){if(++t._redirects>s.maxRedirects){nt(t,k,"Maximum redirects exceeded");return}k.abort();let J;try{J=new Nc(I,e)}catch{let b=new SyntaxError(`Invalid URL: ${I}`);Qo(t,b);return}qf(t,J,n,r)}else t.emit("unexpected-response",k,x)||nt(t,k,`Unexpected server response: ${x.statusCode}`)}),k.on("upgrade",(x,I,P)=>{if(t.emit("upgrade",x),t.readyState!==ge.CONNECTING)return;k=t._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){nt(t,I,"Invalid Upgrade header");return}let W=Gk("sha1").update(h+Yk).digest("base64");if(x.headers["sec-websocket-accept"]!==W){nt(t,I,"Invalid Sec-WebSocket-Accept header");return}let b=x.headers["sec-websocket-protocol"],$;if(b!==void 0?w.size?w.has(b)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":w.size&&($="Server sent no subprotocol"),$){nt(t,I,$);return}b&&(t._protocol=b);let K=x.headers["sec-websocket-extensions"];if(K!==void 0){if(!v){nt(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let C;try{C=r_(K)}catch{nt(t,I,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(C);if(q.length!==1||q[0]!==Nn.extensionName){nt(t,I,"Server indicated an extension that was not requested");return}try{v.accept(C[Nn.extensionName])}catch{nt(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Nn.extensionName]=v}t.setSocket(I,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 Qo(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function o_(t){return t.path=t.socketPath,Df.connect(t)}function a_(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Df.isIP(t.host)?"":t.host),Kk.connect(t)}function nt(t,e,n){t._readyState=ge.CLOSING;let r=new Error(n);Error.captureStackTrace(r,nt),e.setHeader?(e[Uf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function zc(t,e,n){if(e){let r=Vk(e)?e.size:s_(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ln[t.readyState]})`);process.nextTick(n,r)}}function l_(t,e){let n=this[Re];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Re]!==void 0&&(n._socket.removeListener("data",ea),process.nextTick(Ff,n._socket),t===1005?n.close():n.close(t,e))}function c_(){let t=this[Re];t.isPaused||t._socket.resume()}function u_(t){let e=this[Re];e._socket[Re]!==void 0&&(e._socket.removeListener("data",ea),process.nextTick(Ff,e._socket),e.close(t[Qk])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function zf(){this[Re].emitClose()}function d_(t,e){this[Re].emit("message",t,e)}function h_(t){let e=this[Re];e._autoPong&&e.pong(t,!this._isServer,Lf),e.emit("ping",t)}function p_(t){this[Re].emit("pong",t)}function Ff(t){t.resume()}function f_(t){let e=this[Re];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,Bf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Bf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Kf(){let t=this[Re];if(this.removeListener("close",Kf),this.removeListener("data",ea),this.removeListener("end",Hf),t._readyState=ge.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[Re]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",zf),t._receiver.on("finish",zf))}function ea(t){this[Re]._receiver.write(t)||this.pause()}function Hf(){let t=this[Re];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function Gf(){let t=this[Re];this.removeListener("error",Gf),this.on("error",Lf),t&&(t._readyState=ge.CLOSING,this.destroy())}});var Yf=ce((Kx,Jf)=>{"use strict";var Bx=ta(),{Duplex:m_}=require("stream");function Wf(t){t.emit("close")}function g_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vf(t){this.removeListener("error",Vf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function y_(t,e){let n=!0,r=new m_({...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(Wf,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(Wf,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",g_),r.on("error",Vf),r}Jf.exports=y_});var Dc=ce((Hx,Xf)=>{"use strict";var{tokenChars:b_}=$s();function w_(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&&b_[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}Xf.exports={parse:w_}});var im=ce((Zx,sm)=>{"use strict";var v_=require("events"),na=require("http"),{Duplex:Gx}=require("stream"),{createHash:k_}=require("crypto"),Qf=Yo(),qr=Cs(),__=Dc(),S_=ta(),{CLOSE_TIMEOUT:T_,GUID:x_,kWebSocket:I_}=sn(),R_=/^[+/0-9A-Za-z]{22}==$/,em=0,tm=1,rm=2,Lc=class extends v_{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:T_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:S_,...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=na.createServer((r,s)=>{let i=na.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=E_(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=em}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===rm){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(yi,this);return}if(e&&this.once("close",e),this._state!==tm)if(this._state=tm,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(yi,this):process.nextTick(yi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{yi(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",nm);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Fr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Fr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!R_.test(i)){Fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){bi(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=__.parse(c)}catch{Fr(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 w=new qr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=Qf.parse(h);v[qr.extensionName]&&(w.accept(v[qr.extensionName]),f[qr.extensionName]=w)}catch{Fr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let w={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(w,(v,k,x,I)=>{if(!v)return bi(n,k||401,x,I);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(w))return bi(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[I_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>em)return bi(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${k_("sha1").update(n+x_).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[qr.extensionName]){let f=e[qr.extensionName].params,w=Qf.format({[qr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${w}`),h._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
|
|
370
|
+
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 dp,Kl,hp,up,vv,Zl=we(()=>{"use strict";dp=require("node:child_process"),Kl=E(require("node:fs"),1),hp=E(require("node:path"),1),up=4e3,vv=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var Ap={};hn(Ap,{MAX_CHAIN_DEPTH:()=>tc,breakChain:()=>ic,breakSingleModeChain:()=>cc,chainOf:()=>rc,chainSessionFor:()=>Do,loadBatchPlan:()=>nc,nextMemberWillChain:()=>uc,parsePlanAnswer:()=>dc,recordChainSession:()=>sc,recordSingleModeSession:()=>ac,saveBatchPlan:()=>zv,singleModeChainIntact:()=>lc,singleModeSessionFor:()=>oc});function zv(t){Rs.default.mkdirSync(ec(),{recursive:!0,mode:448}),Rs.default.writeFileSync(zo.default.join(ec(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function nc(t){if(!t)return null;try{return JSON.parse(Rs.default.readFileSync(zo.default.join(ec(),`${t}.json`),"utf8"))}catch{return null}}function rc(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function Do(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=rn.get(Mo(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=tc||!Rs.default.existsSync(s.worktreePath)?null:s}function sc(t,e,n,r){let s=rn.get(Mo(t,e));rn.set(Mo(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function ic(t,e){rn.delete(Mo(t,e))}function oc(t){let e=rn.get(ui(t));return!e||e.depth>=tc||!Rs.default.existsSync(e.worktreePath)?null:e}function ac(t,e,n,r){let s=rn.get(ui(t));rn.set(ui(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function lc(t,e){return rn.get(ui(t))?.lastIssue===e}function cc(t){rn.delete(ui(t))}function uc(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function dc(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 Rs,zo,tc,ec,rn,Mo,ui,Lo=we(()=>{"use strict";Rs=E(require("node:fs"),1),zo=E(require("node:path"),1);$e();tc=3,ec=()=>zo.default.join(le(),"autopilot-plans");rn=new Map,Mo=(t,e)=>`${t}:${e[0]}`;ui=t=>`${t}:__single__`});var sn=ce(($x,sf)=>{"use strict";var nf=["nodebuffer","arraybuffer","fragments"],rf=typeof Blob<"u";rf&&nf.push("blob");sf.exports={BINARY_TYPES:nf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:rf,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var hi=ce((Cx,Bo)=>{"use strict";var{EMPTY_BUFFER:ck}=sn(),wc=Buffer[Symbol.species];function uk(t,e){if(t.length===0)return ck;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 wc(n.buffer,n.byteOffset,r):n}function of(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function af(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function dk(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function vc(t){if(vc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new wc(t):ArrayBuffer.isView(t)?e=new wc(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),vc.readOnly=!1),e}Bo.exports={concat:uk,mask:of,toArrayBuffer:dk,toBuffer:vc,unmask:af};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Bo.exports.mask=function(e,n,r,s,i){i<48?of(e,n,r,s,i):t.mask(e,n,r,s,i)},Bo.exports.unmask=function(e,n){e.length<32?af(e,n):t.unmask(e,n)}}catch{}});var uf=ce((Px,cf)=>{"use strict";var lf=Symbol("kDone"),kc=Symbol("kRun"),_c=class{constructor(e){this[lf]=()=>{this.pending--,this[kc]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[kc]()}[kc](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[lf])}}};cf.exports=_c});var $s=ce((Nx,ff)=>{"use strict";var pi=require("zlib"),df=hi(),hk=uf(),{kStatusCode:hf}=sn(),pk=Buffer[Symbol.species],fk=Buffer.from([0,0,255,255]),Ko=Symbol("permessage-deflate"),on=Symbol("total-length"),Es=Symbol("callback"),Nn=Symbol("buffers"),As=Symbol("error"),Ho,Sc=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,!Ho){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new hk(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[Es];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){Ho.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Ho.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"?pi.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=pi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ko]=this,this._inflate[on]=0,this._inflate[Nn]=[],this._inflate.on("error",gk),this._inflate.on("data",pf)}this._inflate[Es]=r,this._inflate.write(e),n&&this._inflate.write(fk),this._inflate.flush(()=>{let i=this._inflate[As];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=df.concat(this._inflate[Nn],this._inflate[on]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[on]=0,this._inflate[Nn]=[],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"?pi.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=pi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[on]=0,this._deflate[Nn]=[],this._deflate.on("data",mk)}this._deflate[Es]=r,this._deflate.write(e),this._deflate.flush(pi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=df.concat(this._deflate[Nn],this._deflate[on]);n&&(i=new pk(i.buffer,i.byteOffset,i.length-4)),this._deflate[Es]=null,this._deflate[on]=0,this._deflate[Nn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ff.exports=Sc;function mk(t){this[Nn].push(t),this[on]+=t.length}function pf(t){if(this[on]+=t.length,this[Ko]._maxPayload<1||this[on]<=this[Ko]._maxPayload){this[Nn].push(t);return}this[As]=new RangeError("Max payload size exceeded"),this[As].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[As][hf]=1009,this.removeListener("data",pf),this.reset()}function gk(t){if(this[Ko]._inflate=null,this[As]){this[Es](this[As]);return}t[hf]=1007,this[Es](t)}});var Cs=ce((jx,Go)=>{"use strict";var{isUtf8:mf}=require("buffer"),{hasBlob:yk}=sn(),bk=[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 wk(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Tc(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 vk(t){return yk&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Go.exports={isBlob:vk,isValidStatusCode:wk,isValidUTF8:Tc,tokenChars:bk};if(mf)Go.exports.isValidUTF8=function(t){return t.length<24?Tc(t):mf(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Go.exports.isValidUTF8=function(e){return e.length<32?Tc(e):t(e)}}catch{}});var Ac=ce((Ox,_f)=>{"use strict";var{Writable:kk}=require("stream"),gf=$s(),{BINARY_TYPES:_k,EMPTY_BUFFER:yf,kStatusCode:Sk,kWebSocket:Tk}=sn(),{concat:xc,toArrayBuffer:xk,unmask:Ik}=hi(),{isValidStatusCode:Rk,isValidUTF8:bf}=Cs(),Zo=Buffer[Symbol.species],ft=0,wf=1,vf=2,kf=3,Ic=4,Rc=5,Wo=6,Ec=class extends kk{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||_k[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[Tk]=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=ft}_write(e,n,r){if(this._opcode===8&&this._state==ft)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 Zo(r.buffer,r.byteOffset+e,r.length-e),new Zo(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 Zo(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 ft:this.getInfo(e);break;case wf:this.getPayloadLength16(e);break;case vf:this.getPayloadLength64(e);break;case kf:this.getMask();break;case Ic:this.getData(e);break;case Rc:case Wo: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[gf.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=wf:this._payloadLength===127?this._state=vf: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=kf:this._state=Ic}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ic}getData(e){let n=yf;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&&Ik(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=Rc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[gf.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===ft&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ft;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=xc(r,n):this._binaryType==="arraybuffer"?s=xk(xc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ft):(this._state=Wo,setImmediate(()=>{this.emit("message",s,!0),this._state=ft,this.startLoop(e)}))}else{let s=xc(r,n);if(!this._skipUTF8Validation&&!bf(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Rc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ft):(this._state=Wo,setImmediate(()=>{this.emit("message",s,!1),this._state=ft,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,yf),this.end();else{let r=e.readUInt16BE(0);if(!Rk(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Zo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!bf(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=ft;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ft):(this._state=Wo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ft,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[Sk]=s,o}};_f.exports=Ec});var Pc=ce((zx,xf)=>{"use strict";var{Duplex:Mx}=require("stream"),{randomFillSync:Ek}=require("crypto"),{types:{isUint8Array:Ak}}=require("util"),Sf=$s(),{EMPTY_BUFFER:$k,kWebSocket:Ck,NOOP:Pk}=sn(),{isBlob:Ps,isValidStatusCode:Nk}=Cs(),{mask:Tf,toBuffer:Dr}=hi(),mt=Symbol("kByteLength"),jk=Buffer.alloc(4),Vo=8*1024,Lr,Ns=Vo,St=0,Ok=1,Mk=2,$c=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=Pk,this[Ck]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||jk,n.generateMask?n.generateMask(r):(Ns===Vo&&(Lr===void 0&&(Lr=Buffer.alloc(Vo)),Ek(Lr,0,Vo),Ns=0),r[0]=Lr[Ns++],r[1]=Lr[Ns++],r[2]=Lr[Ns++],r[3]=Lr[Ns++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[mt]!==void 0?l=n[mt]:(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?(Tf(e,r,u,i,l),[u]):(Tf(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=$k;else{if(typeof e!="number"||!Nk(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={[mt]: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):Ps(e)?(s=e.size,i=!1):(e=Dr(e),s=e.length,i=Dr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[mt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ps(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):Ps(e)?(s=e.size,i=!1):(e=Dr(e),s=e.length,i=Dr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[mt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ps(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[Sf.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Ps(e)?(l=e.size,c=!1):(e=Dr(e),l=e.length,c=Dr.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={[mt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Ps(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[mt],this._state=Mk,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Cc,this,l,s);return}this._bufferedBytes-=r[mt];let o=Dr(i);n?this.dispatch(o,n,r,s):(this._state=St,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(zk,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Sf.extensionName];this._bufferedBytes+=r[mt],this._state=Ok,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Cc(this,c,s);return}this._bufferedBytes-=r[mt],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][mt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mt],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)}};xf.exports=$c;function Cc(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 zk(t,e,n){Cc(t,e,n),t.onerror(e)}});var jf=ce((Dx,Nf)=>{"use strict";var{kForOnEventAttribute:fi,kListener:Nc}=sn(),If=Symbol("kCode"),Rf=Symbol("kData"),Ef=Symbol("kError"),Af=Symbol("kMessage"),$f=Symbol("kReason"),js=Symbol("kTarget"),Cf=Symbol("kType"),Pf=Symbol("kWasClean"),an=class{constructor(e){this[js]=null,this[Cf]=e}get target(){return this[js]}get type(){return this[Cf]}};Object.defineProperty(an.prototype,"target",{enumerable:!0});Object.defineProperty(an.prototype,"type",{enumerable:!0});var Ur=class extends an{constructor(e,n={}){super(e),this[If]=n.code===void 0?0:n.code,this[$f]=n.reason===void 0?"":n.reason,this[Pf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[If]}get reason(){return this[$f]}get wasClean(){return this[Pf]}};Object.defineProperty(Ur.prototype,"code",{enumerable:!0});Object.defineProperty(Ur.prototype,"reason",{enumerable:!0});Object.defineProperty(Ur.prototype,"wasClean",{enumerable:!0});var Os=class extends an{constructor(e,n={}){super(e),this[Ef]=n.error===void 0?null:n.error,this[Af]=n.message===void 0?"":n.message}get error(){return this[Ef]}get message(){return this[Af]}};Object.defineProperty(Os.prototype,"error",{enumerable:!0});Object.defineProperty(Os.prototype,"message",{enumerable:!0});var mi=class extends an{constructor(e,n={}){super(e),this[Rf]=n.data===void 0?null:n.data}get data(){return this[Rf]}};Object.defineProperty(mi.prototype,"data",{enumerable:!0});var Dk={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[fi]&&s[Nc]===e&&!s[fi])return;let r;if(t==="message")r=function(i,o){let l=new mi("message",{data:o?i:i.toString()});l[js]=this,Jo(e,this,l)};else if(t==="close")r=function(i,o){let l=new Ur("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[js]=this,Jo(e,this,l)};else if(t==="error")r=function(i){let o=new Os("error",{error:i,message:i.message});o[js]=this,Jo(e,this,o)};else if(t==="open")r=function(){let i=new an("open");i[js]=this,Jo(e,this,i)};else return;r[fi]=!!n[fi],r[Nc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Nc]===e&&!n[fi]){this.removeListener(t,n);break}}};Nf.exports={CloseEvent:Ur,ErrorEvent:Os,Event:an,EventTarget:Dk,MessageEvent:mi};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Yo=ce((Lx,Of)=>{"use strict";var{tokenChars:gi}=Cs();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Lk(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&&gi[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 v=t.slice(c,h);u===44?(zt(e,v,n),n=Object.create(null)):o=v,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(h===-1&&gi[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),zt(n,t.slice(c,h),!0),u===44&&(zt(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(gi[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(gi[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&&gi[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 v=t.slice(c,h);r&&(v=v.replace(/\\/g,""),r=!1),zt(n,l,v),u===44&&(zt(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 w=t.slice(c,h);return o===void 0?zt(e,w,n):(l===void 0?zt(n,w,!0):r?zt(n,l,w.replace(/\\/g,"")):zt(n,l,w),zt(e,o,n)),e}function Uk(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(", ")}Of.exports={format:Uk,parse:Lk}});var ta=ce((Fx,Zf)=>{"use strict";var qk=require("events"),Fk=require("https"),Bk=require("http"),Df=require("net"),Hk=require("tls"),{randomBytes:Kk,createHash:Gk}=require("crypto"),{Duplex:Ux,Readable:qx}=require("stream"),{URL:jc}=require("url"),jn=$s(),Zk=Ac(),Wk=Pc(),{isBlob:Vk}=Cs(),{BINARY_TYPES:Mf,CLOSE_TIMEOUT:Jk,EMPTY_BUFFER:Xo,GUID:Yk,kForOnEventAttribute:Oc,kListener:Xk,kStatusCode:Qk,kWebSocket:Re,NOOP:Lf}=sn(),{EventTarget:{addEventListener:e_,removeEventListener:t_}}=jf(),{format:n_,parse:r_}=Yo(),{toBuffer:s_}=hi(),Uf=Symbol("kAborted"),Mc=[8,13],ln=["CONNECTING","OPEN","CLOSING","CLOSED"],i_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends qk{constructor(e,n,r){super(),this._binaryType=Mf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xo,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]),qf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mf.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 Zk({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 Wk(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Re]=this,i[Re]=this,e[Re]=this,s.on("conclude",l_),s.on("drain",c_),s.on("error",u_),s.on("message",d_),s.on("ping",h_),s.on("pong",p_),i.onerror=f_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Hf),e.on("data",ea),e.on("end",Kf),e.on("error",Gf),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[jn.extensionName]&&this._extensions[jn.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){nt(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())}),Bf(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){zc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Xo,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){zc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Xo,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){zc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[jn.extensionName]||(s.compress=!1),this._sender.send(e||Xo,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){nt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ge,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Oc])return e[Xk];return null},set(e){for(let n of this.listeners(t))if(n[Oc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Oc]:!0})}})});ge.prototype.addEventListener=e_;ge.prototype.removeEventListener=t_;Zf.exports=ge;function qf(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Jk,protocolVersion:Mc[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,!Mc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Mc.join(", ")})`);let i;if(e instanceof jc)i=e;else try{i=new jc(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 x=new SyntaxError(c);if(t._redirects===0)throw x;Qo(t,x);return}let u=o?443:80,h=Kk(16).toString("base64"),f=o?Fk.request:Bk.request,w=new Set,v;if(s.createConnection=s.createConnection||(o?a_:o_),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&&(v=new jn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=n_({[jn.extensionName]:v.offer()})),n.length){for(let x of n){if(typeof x!="string"||!i_.test(x)||w.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let k;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[I,P]of Object.entries(x))r.headers[I.toLowerCase()]=P}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{nt(t,k,"Opening handshake has timed out")}),k.on("error",x=>{k===null||k[Uf]||(k=t._req=null,Qo(t,x))}),k.on("response",x=>{let I=x.headers.location,P=x.statusCode;if(I&&s.followRedirects&&P>=300&&P<400){if(++t._redirects>s.maxRedirects){nt(t,k,"Maximum redirects exceeded");return}k.abort();let J;try{J=new jc(I,e)}catch{let b=new SyntaxError(`Invalid URL: ${I}`);Qo(t,b);return}qf(t,J,n,r)}else t.emit("unexpected-response",k,x)||nt(t,k,`Unexpected server response: ${x.statusCode}`)}),k.on("upgrade",(x,I,P)=>{if(t.emit("upgrade",x),t.readyState!==ge.CONNECTING)return;k=t._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){nt(t,I,"Invalid Upgrade header");return}let W=Gk("sha1").update(h+Yk).digest("base64");if(x.headers["sec-websocket-accept"]!==W){nt(t,I,"Invalid Sec-WebSocket-Accept header");return}let b=x.headers["sec-websocket-protocol"],C;if(b!==void 0?w.size?w.has(b)||(C="Server sent an invalid subprotocol"):C="Server sent a subprotocol but none was requested":w.size&&(C="Server sent no subprotocol"),C){nt(t,I,C);return}b&&(t._protocol=b);let H=x.headers["sec-websocket-extensions"];if(H!==void 0){if(!v){nt(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let $;try{$=r_(H)}catch{nt(t,I,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys($);if(q.length!==1||q[0]!==jn.extensionName){nt(t,I,"Server indicated an extension that was not requested");return}try{v.accept($[jn.extensionName])}catch{nt(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[jn.extensionName]=v}t.setSocket(I,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 Qo(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function o_(t){return t.path=t.socketPath,Df.connect(t)}function a_(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Df.isIP(t.host)?"":t.host),Hk.connect(t)}function nt(t,e,n){t._readyState=ge.CLOSING;let r=new Error(n);Error.captureStackTrace(r,nt),e.setHeader?(e[Uf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function zc(t,e,n){if(e){let r=Vk(e)?e.size:s_(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ln[t.readyState]})`);process.nextTick(n,r)}}function l_(t,e){let n=this[Re];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Re]!==void 0&&(n._socket.removeListener("data",ea),process.nextTick(Ff,n._socket),t===1005?n.close():n.close(t,e))}function c_(){let t=this[Re];t.isPaused||t._socket.resume()}function u_(t){let e=this[Re];e._socket[Re]!==void 0&&(e._socket.removeListener("data",ea),process.nextTick(Ff,e._socket),e.close(t[Qk])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function zf(){this[Re].emitClose()}function d_(t,e){this[Re].emit("message",t,e)}function h_(t){let e=this[Re];e._autoPong&&e.pong(t,!this._isServer,Lf),e.emit("ping",t)}function p_(t){this[Re].emit("pong",t)}function Ff(t){t.resume()}function f_(t){let e=this[Re];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,Bf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Bf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Hf(){let t=this[Re];if(this.removeListener("close",Hf),this.removeListener("data",ea),this.removeListener("end",Kf),t._readyState=ge.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[Re]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",zf),t._receiver.on("finish",zf))}function ea(t){this[Re]._receiver.write(t)||this.pause()}function Kf(){let t=this[Re];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function Gf(){let t=this[Re];this.removeListener("error",Gf),this.on("error",Lf),t&&(t._readyState=ge.CLOSING,this.destroy())}});var Yf=ce((Hx,Jf)=>{"use strict";var Bx=ta(),{Duplex:m_}=require("stream");function Wf(t){t.emit("close")}function g_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vf(t){this.removeListener("error",Vf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function y_(t,e){let n=!0,r=new m_({...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(Wf,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(Wf,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",g_),r.on("error",Vf),r}Jf.exports=y_});var Dc=ce((Kx,Xf)=>{"use strict";var{tokenChars:b_}=Cs();function w_(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&&b_[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}Xf.exports={parse:w_}});var im=ce((Zx,sm)=>{"use strict";var v_=require("events"),na=require("http"),{Duplex:Gx}=require("stream"),{createHash:k_}=require("crypto"),Qf=Yo(),qr=$s(),__=Dc(),S_=ta(),{CLOSE_TIMEOUT:T_,GUID:x_,kWebSocket:I_}=sn(),R_=/^[+/0-9A-Za-z]{22}==$/,em=0,tm=1,rm=2,Lc=class extends v_{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:T_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:S_,...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=na.createServer((r,s)=>{let i=na.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=E_(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=em}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===rm){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(yi,this);return}if(e&&this.once("close",e),this._state!==tm)if(this._state=tm,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(yi,this):process.nextTick(yi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{yi(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",nm);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Fr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Fr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!R_.test(i)){Fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Fr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){bi(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=__.parse(c)}catch{Fr(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 w=new qr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=Qf.parse(h);v[qr.extensionName]&&(w.accept(v[qr.extensionName]),f[qr.extensionName]=w)}catch{Fr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let w={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(w,(v,k,x,I)=>{if(!v)return bi(n,k||401,x,I);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(w))return bi(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[I_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>em)return bi(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${k_("sha1").update(n+x_).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[qr.extensionName]){let f=e[qr.extensionName].params,w=Qf.format({[qr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${w}`),h._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
|
|
371
371
|
`).join(`\r
|
|
372
372
|
`)),i.removeListener("error",nm),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(yi,this)})),l(h,s)}};sm.exports=Lc;function E_(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 yi(t){t._state=rm,t.emit("close")}function nm(){this.destroy()}function bi(t,e,n,r){n=n||na.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} ${na.STATUS_CODES[e]}\r
|
|
373
373
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
@@ -375,7 +375,7 @@ Reason from THIS. If it does not contain the answer, say what you would need to
|
|
|
375
375
|
\r
|
|
376
376
|
`+n)}function Fr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Fr),t.emit("wsClientError",o,n,e)}else bi(n,r,s,i)}});var fm={};hn(fm,{CATALOGUE:()=>Zc,catalogueForPrompt:()=>Wc,describeDiagnostic:()=>W_,runDiagnostic:()=>V_});function Wc(){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(`
|
|
377
377
|
`)}function W_(t){let e=Zc[t.command];return e?e.describe(t.args??{}):null}async function V_(t){let e=Zc[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,pm.execFile)(n[0],n.slice(1),{timeout:G_,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
|
|
378
|
-
${l}`:""}`.trim(),u=Gl(c).slice(0,Z_)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:u})})})}var pm,Gc,G_,Z_,dm,hm,
|
|
378
|
+
${l}`:""}`.trim(),u=Gl(c).slice(0,Z_)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:u})})})}var pm,Gc,G_,Z_,dm,hm,Kc,gt,aa,Zc,Vc=we(()=>{"use strict";pm=require("node:child_process"),Gc=E(require("node:fs"),1);Zl();G_=1e4,Z_=8e3,dm=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,hm=/^[a-zA-Z0-9@._-]{1,80}$/,Kc=/^\/[^\0\n]{1,300}$/,gt=t=>typeof t=="string"?t.trim():"",aa=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},Zc={service_status:{describe:t=>`systemctl status ${gt(t.unit)}`,build:t=>{let e=gt(t.unit);return hm.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${gt(t.unit)} -n ${aa(t.lines,200,50)}`,build:t=>{let e=gt(t.unit);return hm.test(e)?["journalctl","-u",e,"-n",String(aa(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 ${gt(t.path)}`,build:t=>{let e=gt(t.path);return Kc.test(e)?dm.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${aa(t.lines,200,100)} ${gt(t.path)}`,build:t=>{let e=gt(t.path);if(!Kc.test(e))return"refused: absolute path required";if(dm.test(e))return"refused: that path can hold credentials";try{if(Gc.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(aa(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${gt(t.url)}`,build:t=>{let e=gt(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 ${gt(t.path)} status + last 3 commits`,build:t=>{let e=gt(t.path);return Kc.test(e)?Gc.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Im={};hn(Im,{MANAGED_MARKER:()=>Ti,caddyBlock:()=>zs,checkoutOwner:()=>xm,detectApp:()=>ym,envPrepare:()=>X_,nginxBlock:()=>ki,nodeBinDir:()=>gm,ownsProxyFile:()=>Sm,pickPort:()=>wm,portsClaimedByUnits:()=>bm,resolveProxyChoice:()=>Tm,spliceCaddyBlock:()=>_m,spliceManagedBlock:()=>Yc,sudoersText:()=>km,unitSlug:()=>mm,unitText:()=>vm});function mm(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function gm(t){let e=n=>{try{let r=(0,Lt.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?Tt.default.dirname(r):null}catch{return null}};return t&&t!==Si.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function ym(t){let e=Tt.default.join(t,"package.json");if(!ye.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(ye.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 bm(){let t=new Set;try{for(let e of ye.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=ye.default.readFileSync(Tt.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 wm(t){let e=bm(),n=r=>new Promise(s=>{let i=Jc.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 vm(t){return`${Ti}
|
|
379
379
|
[Unit]
|
|
380
380
|
Description=${t.repoName} ${t.envName} (Allwright-prepared)
|
|
381
381
|
After=network-online.target
|
|
@@ -454,18 +454,18 @@ ${ki({slug:s,hostname:i,port:h})}
|
|
|
454
454
|
`)));let k=v?await eS(h,3e4):!1,x=_i(s);g.info(""),g.info(`${x?"\u2713":"\u2717"} service ${s}: ${x?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&g.info(`${k?"\u2713":"\u2717"} listening on 127.0.0.1:${h}${k?"":" - not yet; check the journal"}`),g.info("\u2713 deploys may restart it without a password (sudoers drop-in installed)"),g.info(""),g.info(`Deploy steps should end with: sudo systemctl restart ${s}`),i&&g.info(`Health checks should target: http://127.0.0.1:${h}/ (and later https://${i}/)`),g.info(`DNS stays yours: point ${i||"your hostname"} at this machine when you are ready.`)}function Q_(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 _i(t){try{return(0,Lt.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function eS(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=Jc.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 tS(t){let e="/etc/caddy/Caddyfile";if(!ye.default.existsSync(e)||!_i("caddy")){g.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
|
|
455
455
|
${zs(t)}`);return}let n;try{n=ye.default.readFileSync(e,"utf8")}catch{n=(0,Lt.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=_m(n,t.slug,zs(t));if(r===n){g.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=Tt.default.join(Si.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);ye.default.writeFileSync(s,r,{mode:420});try{(0,Lt.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),_e(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),_e(["cp",s,e]),_e(["systemctl","reload","caddy"]),g.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{ye.default.rmSync(s,{force:!0})}}function nS(t){let e=ki(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!ye.default.existsSync("/etc/nginx")||!_i("nginx")){g.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
|
|
456
456
|
${e}`),g.info(n);return}let r=ye.default.existsSync("/etc/nginx/sites-enabled"),s=r?`/etc/nginx/sites-available/allwright-${t.slug}.conf`:`/etc/nginx/conf.d/allwright-${t.slug}.conf`,i=r?`/etc/nginx/sites-enabled/allwright-${t.slug}.conf`:null,o=null;if(ye.default.existsSync(s)){try{o=ye.default.readFileSync(s,"utf8")}catch{o=(0,Lt.execFileSync)("sudo",["cat",s],{encoding:"utf8",timeout:1e4})}if(!Sm(o))throw new Error(`${s} exists and was not written by this command - refusing to overwrite a hand-written site. Delete it yourself if you want it replaced.`)}let l=Yc(o??"",t.slug,e).replace(/^\n+/,"");if(o!==null&&l===o){g.info(`nginx already routes ${t.hostname} - unchanged`);return}let c=i?ye.default.existsSync(i):!1;_e(["mkdir","-p",Tt.default.dirname(s)]),_e(["tee",s],l),_e(["chmod","644",s]),i&&!c&&_e(["ln","-s",s,i]);try{(0,Lt.execFileSync)("sudo",["nginx","-t"],{encoding:"utf8",timeout:3e4})}catch(u){o!==null?(_e(["tee",s],o),_e(["chmod","644",s])):(i&&!c&&_e(["rm","-f",i]),_e(["rm","-f",s]));let h=u&&typeof u=="object"&&"stderr"in u&&typeof u.stderr=="string"?u.stderr.trim():String(u);throw new Error(`nginx -t rejected the new config - ${s} was ${o!==null?"restored":"removed"} and nginx was NOT reloaded. nginx said:
|
|
457
|
-
${h}`)}_e(["systemctl","reload","nginx"]),g.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),g.info(n)}var Lt,ye,Jc,Si,Tt,Ti,Rm=we(()=>{"use strict";Lt=require("node:child_process"),ye=E(require("node:fs"),1),Jc=E(require("node:net"),1),Si=E(require("node:os"),1),Tt=E(require("node:path"),1);Qt();Ao();Ti="# managed by allwright env prepare"});var
|
|
458
|
-
`).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=le(),s;Qe.default.existsSync(r)&&Qe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Qe.default.renameSync(r,s)),Qe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Fi.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Qe.default.readdirSync(r)){let o=Bi.default.join(r,i);Qe.default.statSync(o).isFile()&&Qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var es=E(require("node:fs"),1),yn=E(require("node:path"),1),
|
|
457
|
+
${h}`)}_e(["systemctl","reload","nginx"]),g.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),g.info(n)}var Lt,ye,Jc,Si,Tt,Ti,Rm=we(()=>{"use strict";Lt=require("node:child_process"),ye=E(require("node:fs"),1),Jc=E(require("node:net"),1),Si=E(require("node:os"),1),Tt=E(require("node:path"),1);Qt();Ao();Ti="# managed by allwright env prepare"});var Nm={};hn(Nm,{buildSetupReport:()=>sS,claudeLoggedIn:()=>Pm,repoCurrentBranch:()=>$m,repoDefaultBranch:()=>Cm});function $m(t){try{let e=(0,Ii.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Cm(t){let e=(...s)=>{try{return(0,Ii.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 Pm(t=Em.default.homedir()){if(On.default.existsSync(Hr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(On.default.readFileSync(Hr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function sS(t,e,n){let r=!1,s="";if(xi&&Date.now()-xi.at<6e4)r=xi.installed,s=xi.version;else{try{let{stdout:l}=await rS(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}xi={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=On.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&On.default.existsSync(Hr.default.join(c.path,".git")),currentBranch:u?$m(c.path):"",claudeMd:u&&On.default.existsSync(Hr.default.join(c.path,"CLAUDE.md")),deployMd:u&&On.default.existsSync(Hr.default.join(c.path,"DEPLOY.md")),testMd:u&&On.default.existsSync(Hr.default.join(c.path,"TEST.md")),githubToken:!!ze(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?Cm(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:Pm()},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 Ii,On,Em,Hr,Am,rS,xi,jm=we(()=>{"use strict";Ii=require("node:child_process"),On=E(require("node:fs"),1),Em=E(require("node:os"),1),Hr=E(require("node:path"),1),Am=require("node:util");_r();rS=(0,Am.promisify)(Ii.execFile);xi=null});var rt=E(require("node:fs"),1),Ri=E(require("node:os"),1),cn=E(require("node:path"),1),dn=require("node:child_process"),Mn=require("node:crypto"),zn=E(require("node:readline/promises"),1);var fu=E(pu(),1),{program:fS,createCommand:mS,createArgument:gS,createOption:yS,CommanderError:bS,InvalidArgumentError:wS,InvalidOptionArgumentError:vS,Command:mu,Argument:kS,Option:_S,Help:SS}=fu.default;$e();var Fi=require("node:child_process"),Qe=E(require("node:fs"),1),Bi=E(require("node:path"),1);$e();var fy=new Set(["runner.log","runner.pid"]);function my(t){return Qe.default.readdirSync(t).filter(e=>!fy.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Cu(t){let e=le();if(!Qe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=my(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=Bi.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Qe.default.writeFileSync(s,"",{mode:384}),(0,Fi.execFileSync)("tar",["-czf",s,"-C",e,...n]),Qe.default.chmodSync(s,384),{file:s,entries:n}}function Pu(t){let e=Bi.default.resolve(t);if(!Qe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Fi.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
458
|
+
`).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=le(),s;Qe.default.existsSync(r)&&Qe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Qe.default.renameSync(r,s)),Qe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Fi.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Qe.default.readdirSync(r)){let o=Bi.default.join(r,i);Qe.default.statSync(o).isFile()&&Qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var es=E(require("node:fs"),1),yn=E(require("node:path"),1),Hi=".ticketpilot-attachments",gy=15*1024*1024,yy=50*1024*1024,Nu=20;function ju(t,e){let n=yn.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 ts(t,e,n,r){if(!e.length)return"";let s=yn.default.join(n,Hi);es.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=Nu){r("warn",`attachment cap reached (${Nu} files) - skipping the rest`);break}if(c.size>gy){r("warn",`skipping attachment "${c.filename}" - ${vy(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>yy){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),h=ju(c.filename,i);es.default.writeFileSync(yn.default.join(s,h),u),l+=u.length,o.push(`- ${Hi}/${h} (${c.mimeType||"unknown type"}, ${Pa(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${Pa(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
|
|
459
459
|
|
|
460
460
|
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:
|
|
461
461
|
${o.join(`
|
|
462
462
|
`)}
|
|
463
|
-
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(bn(n),"")}function bn(t){es.default.rmSync(yn.default.join(t,
|
|
463
|
+
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(bn(n),"")}function bn(t){es.default.rmSync(yn.default.join(t,Hi),{recursive:!0,force:!0})}var by=4*1024*1024,wy=16*1024*1024;function Ou(t,e,n){let r=yn.default.join(t,Hi,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};es.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=yn.default.relative(t,r);for(let u of n){let h=Buffer.from(u.contentBase64,"base64");if(h.length>by||o+h.length>wy){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=ju(u.name,s);es.default.writeFileSync(yn.default.join(r,f),h),o+=h.length,i.push(`- ${l}/${f} (${Pa(h.length)} KB)`)}return{section:`
|
|
464
464
|
|
|
465
465
|
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:
|
|
466
466
|
${i.join(`
|
|
467
467
|
`)}
|
|
468
|
-
Read them with the Read tool; images can be viewed directly.`,dir:r}}var Pa=t=>Math.max(1,Math.round(t/1024)),vy=t=>Math.round(t/(1024*1024)*10)/10;var
|
|
468
|
+
Read them with the Read tool; images can be viewed directly.`,dir:r}}var Pa=t=>Math.max(1,Math.round(t/1024)),vy=t=>Math.round(t/(1024*1024)*10)/10;var Ce=E(require("node:fs"),1),Gi=E(require("node:path"),1);$e();function ns(){return Gi.default.join(le(),"runner.pid")}function Ki(){return Gi.default.join(le(),"runner.log")}function Mu(){Ce.default.mkdirSync(le(),{recursive:!0,mode:448});let t=Ce.default.openSync(Ki(),"a",384);try{Ce.default.chmodSync(Ki(),384)}catch{}return t}function er(){let t=ns();if(!Ce.default.existsSync(t))return null;let e=Number(Ce.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function tr(t){try{return process.kill(t,0),!0}catch{return!1}}function zu(t){Ce.default.mkdirSync(le(),{recursive:!0,mode:448}),Ce.default.writeFileSync(ns(),String(t),{mode:384})}function Du(t){er()===t&&Ce.default.rmSync(ns(),{force:!0})}function Na(){return Gi.default.join(le(),"runner.lock")}function rs(){let t=Na();if(!Ce.default.existsSync(t))return null;let e=Number(Ce.default.readFileSync(t,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:tr(e)?e:null}function Lu(){let t=rs();return t?{ok:!1,pid:t}:(Ce.default.mkdirSync(le(),{recursive:!0,mode:448}),Ce.default.writeFileSync(Na(),String(process.pid),{mode:384}),{ok:!0})}function ja(){try{let t=Na();Ce.default.existsSync(t)&&Number(Ce.default.readFileSync(t,"utf8").trim())===process.pid&&Ce.default.rmSync(t,{force:!0})}catch{}}function Uu(t){try{let e=Ce.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var eo=E(require("node:fs"),1),Vs=E(require("node:path"),1),dd=E(Te(),1);$e();async function hd(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:to})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=dd.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return be(s),s}function Jb(){try{let t=process.argv[1]?eo.default.realpathSync(process.argv[1]):"";for(let e of[Vs.default.dirname(t),Vs.default.dirname(Vs.default.dirname(t))]){let n=Vs.default.join(e,"package.json");if(!eo.default.existsSync(n))continue;let r=JSON.parse(eo.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var to=Jb();Ct();var _d="Posted automatically by Allwright",Yb=["Posted automatically by TicketPilot"],Pt=t=>t.includes(_d)||Yb.some(e=>t.includes(e));function Xb(t){return t.length<=3e4?t:`${t.slice(0,3e4)}
|
|
469
469
|
|
|
470
470
|
[description truncated by Allwright at 30,000 characters - read the rest on the ticket]`}var il=200,Qb="no Jira credentials on this runner - add them with `allwright jira set-default`";function ol(){return new Me({baseUrl:"",email:"",apiToken:""},!1)}var Me=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(Qb)}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,issuetype`),r;try{r=await this.listAllComments(e)}catch{r=n.fields.comment?.comments??[]}let s=r.map(l=>({id:l.id??"",author:l.author?.displayName??"unknown",authorAccountId:l.author?.accountId??null,created:l.created,body:kd(l.body)})),i=(n.fields.attachment??[]).filter(l=>l.id&&l.filename&&l.content).map(l=>({id:l.id,filename:l.filename,mimeType:l.mimeType??"",size:l.size??0,contentUrl:l.content})),o=Xb(kd(n.fields.description));return{key:n.key,summary:n.fields.summary??"",description:o,labels:n.fields.labels??[],status:n.fields.status?.name??"",issueType:n.fields.issuetype?.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-il),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,il);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-il)}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:lo(r),...i?{parent:{key:i}}:{}}})).key}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:lo(n)}})}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:lo(n)})}async addComment(e,n){let r=`${n}
|
|
471
471
|
|
|
@@ -481,7 +481,7 @@ _${_d} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/is
|
|
|
481
481
|
|
|
482
482
|
allwright jira user-add ${s}
|
|
483
483
|
|
|
484
|
-
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 Td(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 xd(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}_r();var ew=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function Rd(t,e){let n=!1;return{text:t.replace(ew,(s,i)=>{let o=Number(i);return o<1||o>e.length?s:(n=!0,e[o-1])}),changed:n}}var An=require("node:child_process")
|
|
484
|
+
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 Td(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 xd(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}_r();var ew=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function Rd(t,e){let n=!1;return{text:t.replace(ew,(s,i)=>{let o=Number(i);return o<1||o>e.length?s:(n=!0,e[o-1])}),changed:n}}var An=require("node:child_process"),$n=E(require("node:fs"),1),uo=E(require("node:os"),1),fs=E(require("node:path"),1),Ad=E(Te(),1);var ps="allwright",Ed=`/etc/systemd/system/${ps}.service`,ho="ticketpilot-runner";function ll(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||uo.default.userInfo().username,n=t?fs.default.join("/home",t):uo.default.homedir();return{nodePath:process.execPath,scriptPath:$n.default.realpathSync(process.argv[1]),user:e,home:n}}function cl(t){let e=fs.default.dirname(t.nodePath);return`[Unit]
|
|
485
485
|
Description=Allwright runner
|
|
486
486
|
After=network-online.target
|
|
487
487
|
|
|
@@ -499,8 +499,8 @@ TimeoutStopSec=2h
|
|
|
499
499
|
|
|
500
500
|
[Install]
|
|
501
501
|
WantedBy=multi-user.target
|
|
502
|
-
`}function ul(){return process.platform==="linux"
|
|
503
|
-
`+n);return}try{(0,An.execFileSync)("systemctl",["disable","--now",ho]),t.info(`stopped the old ${ho} service - this one replaces it`)}catch{}let r=rs();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}
|
|
502
|
+
`}function ul(){return process.platform==="linux"&&$n.default.existsSync("/run/systemd/system")}function $d(t){if(!ul())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=ll(),n=cl(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 ${Ed}:`),t.info(`
|
|
503
|
+
`+n);return}try{(0,An.execFileSync)("systemctl",["disable","--now",ho]),t.info(`stopped the old ${ho} service - this one replaces it`)}catch{}let r=rs();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}$n.default.writeFileSync(Ed,n),(0,An.execFileSync)("systemctl",["daemon-reload"]),(0,An.execFileSync)("systemctl",["enable","--now",ps]),(0,An.execFileSync)("systemctl",["restart",ps]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${ps} -f`),t.info("Status: allwright service status")}function tw(t){if(t.override)return[fs.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=fs.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function nw(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[uo.default.homedir()];return t&&e.push(fs.default.join("/home",t)),tw({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function rw(){let t={removed:!1,paths:[],problems:[]};for(let e of nw())if($n.default.existsSync(e))try{$n.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 dl(){return typeof process.getuid!="function"||process.getuid()===0}function al(t){if(dl()){(0,An.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,An.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function sw(t){if(dl()){$n.default.rmSync(t);return}(0,An.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function iw(){if(!ul())return{removed:!1,absent:!0,error:""};let t=[ps,ho].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>$n.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{al(["disable",e.name])}catch{}sw(e.file)}return al(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:dl()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function hl(){if(ul())for(let t of[ps,ho])try{al(["stop",t])}catch{}}function pl(){let t=iw(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${Ad.RUNNER_UNINSTALL_COMMAND}`),e;let n=rw();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function Cd(t){let e=pl();e.serviceRemoved?(hl(),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 Pd=E(Te(),1);function Nd(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(Pd.NEEDS_INPUT_LABEL))}function jd(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
|
|
504
504
|
${i.replace(/\n+/g," ")}`:""}`}).join(`
|
|
505
505
|
`);return`You are looking at this repository to help sequence work on the Jira epic ${t} ("${e}"). These child tickets are still pending:
|
|
506
506
|
|
|
@@ -555,7 +555,7 @@ Explore the repository first - entry points, routes, storage, tests - then audit
|
|
|
555
555
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
556
556
|
\`\`\`
|
|
557
557
|
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 Dd(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=aw(l),u=c?fo.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 aw(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:"",...Md(i.line)?{line:Md(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:lw(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:fo.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 Md(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function lw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function cw(t){try{let e=fl.default.readFileSync(t,"utf8");return e?e.split(`
|
|
558
|
-
`).length:0}catch{return null}}function Ld(t,e){let n=po.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=po.default.resolve(n,u);if(h!==n&&!h.startsWith(n+po.default.sep))continue;let f;try{f=fl.default.statSync(h)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=cw(h);if(w!==null&&c.line>w){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 Ys=E(require("node:fs"),1),ml=E(require("node:path"),1),Ud=E(Te(),1)
|
|
558
|
+
`).length:0}catch{return null}}function Ld(t,e){let n=po.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=po.default.resolve(n,u);if(h!==n&&!h.startsWith(n+po.default.sep))continue;let f;try{f=fl.default.statSync(h)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=cw(h);if(w!==null&&c.line>w){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 Ys=E(require("node:fs"),1),ml=E(require("node:path"),1),Ud=E(Te(),1);$e();var uw=20;function qd(){return ml.default.join(le(),"audits.json")}function ms(){try{return{byProject:JSON.parse(Ys.default.readFileSync(qd(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Fd(t){let e=qd();Ys.default.mkdirSync(ml.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Ys.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Ys.default.renameSync(n,e)}function Bd(t,e){let n=ms(),r=n.byProject[t]??[];r.unshift(Ud.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,uw),Fd(n)}function Hd(t){return(ms().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 Kd(t,e){let n=ms(),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 gl(t,e,n){let r=ms(),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 Fd(r),i}function Gd(t,e){return(ms().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function yl(t,e){return(ms().byProject[t]??[]).find(n=>n.id===e)??null}Ct();var Be=E(require("node:fs"),1),Nt=E(require("node:path"),1),Yd=E(Te(),1);var De=E(require("node:fs"),1),vt=E(require("node:path"),1),dw=25e4,hw=2e5,Zd="/.ticketpilot/memory/";function pw(t){let e=vt.default.join(t,".git"),n;try{n=De.default.statSync(e)}catch{return null}if(n.isDirectory())return vt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(De.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=vt.default.resolve(t,r[1].trim());try{let i=De.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 fw(t){try{let e=pw(t);if(!e)return;let n=vt.default.join(e,"exclude"),r="";try{r=De.default.readFileSync(n,"utf8")}catch{}if(r.split(`
|
|
559
559
|
`).some(i=>i.trim()===Zd))return;De.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
|
|
560
560
|
`)?`
|
|
561
561
|
`:"";De.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
|
|
@@ -572,7 +572,7 @@ Newest entries are at the bottom.
|
|
|
572
572
|
`),mw(n)}catch{}}function Xs(t,e){try{return De.default.readFileSync(bl(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function mw(t){if(De.default.statSync(t).size<=dw)return;let r=De.default.readFileSync(t,"utf8").slice(-hw),s=r.indexOf(`
|
|
573
573
|
## `),i=s===-1?r:r.slice(s+1);De.default.writeFileSync(t,Wd+`*(older entries were rotated out)*
|
|
574
574
|
|
|
575
|
-
`+i)}function Vd(t){try{return De.default.readFileSync(bl(t),"utf8")}catch{return null}}
|
|
575
|
+
`+i)}function Vd(t){try{return De.default.readFileSync(bl(t),"utf8")}catch{return null}}$e();var gw=`# Security baseline - what to check in any repo
|
|
576
576
|
|
|
577
577
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
578
578
|
|
|
@@ -728,7 +728,7 @@ deviations.
|
|
|
728
728
|
|
|
729
729
|
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
730
730
|
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
731
|
-
`,Jd={security:[{name:"baseline.md",content:gw},{name:"gdpr.md",content:bw}],testing:[{name:"test-gaps.md",content:yw}],architecture:[{name:"architecture-health.md",content:ww}],functional:[],implement:[],compose:[]},vw=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function wl(t){return
|
|
731
|
+
`,Jd={security:[{name:"baseline.md",content:gw},{name:"gdpr.md",content:bw}],testing:[{name:"test-gaps.md",content:yw}],architecture:[{name:"architecture-health.md",content:ww}],functional:[],implement:[],compose:[]},vw=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function wl(t){return Nt.default.join(le(),"knowledge",t)}function Xd(t,e){return Nt.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function vl(t,e){return Nt.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Qd(t,e){let n=[],r=wl(t),s=[];if(Be.default.existsSync(r)){for(let c of Be.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=Nt.default.join(r,c),h=Be.default.readFileSync(u,"utf8");if(vw.some(f=>h.includes(f))&&Jd[t].map(w=>w.name).includes(c)&&!h.includes("SEC-0")&&!h.includes("TEST-0")&&!h.includes("GDPR-0")){Be.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Jd[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:Be.default.readFileSync(Nt.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Xd(e,t);Be.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:Be.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=vl(e,t);return Be.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:Be.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function gs(t,e){let n=Qd(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 kl(t,e,n,r="project"){let s=r==="org"?Nt.default.join(wl(e),"org-lessons.md"):vl(t,e);Be.default.mkdirSync(Nt.default.dirname(s),{recursive:!0});let i=Be.default.existsSync(s)?"":`# ${e} lessons (${r} level)
|
|
732
732
|
|
|
733
733
|
Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
|
|
734
734
|
|
|
@@ -739,7 +739,7 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
|
|
|
739
739
|
`)}function eh(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}
|
|
740
740
|
Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
|
|
741
741
|
`+(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 th(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
742
|
-
${t.trim()}`}function nh(t){let e=[];for(let r of Yd.KnowledgeRole.options)for(let s of Qd(r,t))e.push({role:r,...s});let n=Vd(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function rh(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"?
|
|
742
|
+
${t.trim()}`}function nh(t){let e=[];for(let r of Yd.KnowledgeRole.options)for(let s of Qd(r,t))e.push({role:r,...s});let n=Vd(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function rh(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"?Nt.default.join(wl(e),s):r==="lessons"?vl(t,e):Xd(t,e);Be.default.mkdirSync(Nt.default.dirname(o),{recursive:!0}),Be.default.writeFileSync(o,i,{mode:n==="org"?384:420})}Qt();var sh=require("node:child_process"),ih=E(require("node:fs"),1),oh=E(require("node:path"),1);function ys(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=oh.default.join(t,e);if(ih.default.existsSync(n))return n}return null}var kw=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function bs(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
|
|
743
743
|
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(kw.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function Sr(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(c=>{let u=(0,sh.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),h="",f=v=>{h+=v.toString(),h.length>2e5&&(h=h.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let w=setTimeout(()=>{u.kill("SIGKILL"),h+=`
|
|
744
744
|
[killed: timed out]`},s);u.on("close",v=>{clearTimeout(w),c({command:i,exitCode:v??-1,durationMs:Date.now()-o,tail:h.slice(-4e3)})}),u.on("error",v=>{clearTimeout(w),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(v)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function ws(t){let{packs:e,lessons:n}=gs(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:v,formatCrawlReport:k}=await Promise.resolve().then(()=>(uh(),ch));try{r=k(await v(t.baseUrl.trim()))}catch(x){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${x instanceof Error?x.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let v=t.scope.ref,k="";try{let I=await t.jira.getIssue(v);k=`Ticket ${v}: ${I.summary}
|
|
745
745
|
|
|
@@ -763,21 +763,21 @@ ${x.tail.slice(-2e3)}`).join(`
|
|
|
763
763
|
|
|
764
764
|
---
|
|
765
765
|
|
|
766
|
-
`))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:zd(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,Sl.randomUUID)(),model:l,onLog:(v,k)=>{v==="agent"&&g.info(`[audit:${t.role}] ${k.slice(0,160)}`)}}),h=Dd(u.resultText);if("error"in h)return{ok:!1,error:h.error};let f=Ld(t.repoPath,h.findings);for(let v of f.droppedFindings)g.warn(`[audit:${t.role}] dropped "${v.title}" - cited files do not exist: `+v.files.join(", "));let w={id:(0,Sl.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||l,summary:h.summary,packNames:e.map(v=>v.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return Bd(t.projectId,w),g.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:w}}var Pn=E(Te(),1)
|
|
766
|
+
`))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:zd(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,Sl.randomUUID)(),model:l,onLog:(v,k)=>{v==="agent"&&g.info(`[audit:${t.role}] ${k.slice(0,160)}`)}}),h=Dd(u.resultText);if("error"in h)return{ok:!1,error:h.error};let f=Ld(t.repoPath,h.findings);for(let v of f.droppedFindings)g.warn(`[audit:${t.role}] dropped "${v.title}" - cited files do not exist: `+v.files.join(", "));let w={id:(0,Sl.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||l,summary:h.summary,packNames:e.map(v=>v.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return Bd(t.projectId,w),g.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:w}}var Pn=E(Te(),1);$e();var zl=E(require("node:fs"),1),xo=E(require("node:path"),1),Io=require("node:crypto"),Se=E(Te(),1);$e();var Tr=E(Te(),1);var Tl=E(require("node:fs"),1),hh=E(require("node:os"),1),go=E(require("node:path"),1),ph=require("node:child_process"),fh=E(require("node:readline"),1),mh=E(Te(),1);function mo(t){return`
|
|
767
767
|
|
|
768
768
|
YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
|
|
769
769
|
- 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.
|
|
770
770
|
`+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
|
|
771
771
|
`:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
|
|
772
|
-
`)+'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 Tw=4e3,xw={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Iw(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??go.default.join(hh.default.homedir(),".claude");try{if(Tl.default.existsSync(go.default.join(e,".credentials.json"))||Tl.default.existsSync(go.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Rw(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",xw[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Iw(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,ph.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,w=()=>{if(!t.onUsage)return;let W=Date.now();W-f<Tw||(f=W,t.onUsage({inputTokens:c,outputTokens:u,cacheReadTokens:h,turns:o}))},v=!1,k=()=>{v||(v=!0,clearTimeout(I),t.signal?.removeEventListener("abort",x),r(i))},x=()=>{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",x,{once:!0});let I=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+mo(t.mode)),s.stdin.end(),fh.default.createInterface({input:s.stdout}).on("line",W=>{if(!W.trim())return;let b;try{b=JSON.parse(W)}catch{t.onLog("agent",W.slice(0,1e3));return}if(b.type==="system"&&b.subtype==="init")i.model=typeof b.model=="string"?b.model:void 0,t.onLog("info",`Claude Code session started (model: ${b.model??"default"})`);else if(b.type==="assistant"){o+=1,l=b.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
|
|
773
|
-
`).length>
|
|
774
|
-
`);if(o.length
|
|
772
|
+
`)+'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 Tw=4e3,xw={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Iw(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??go.default.join(hh.default.homedir(),".claude");try{if(Tl.default.existsSync(go.default.join(e,".credentials.json"))||Tl.default.existsSync(go.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Rw(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",xw[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Iw(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,ph.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,w=()=>{if(!t.onUsage)return;let W=Date.now();W-f<Tw||(f=W,t.onUsage({inputTokens:c,outputTokens:u,cacheReadTokens:h,turns:o}))},v=!1,k=()=>{v||(v=!0,clearTimeout(I),t.signal?.removeEventListener("abort",x),r(i))},x=()=>{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",x,{once:!0});let I=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+mo(t.mode)),s.stdin.end(),fh.default.createInterface({input:s.stdout}).on("line",W=>{if(!W.trim())return;let b;try{b=JSON.parse(W)}catch{t.onLog("agent",W.slice(0,1e3));return}if(b.type==="system"&&b.subtype==="init")i.model=typeof b.model=="string"?b.model:void 0,t.onLog("info",`Claude Code session started (model: ${b.model??"default"})`);else if(b.type==="assistant"){o+=1,l=b.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 C=b.message?.usage;if(C){c+=Number(C.input_tokens??0)+Number(C.cache_creation_input_tokens??0);let H=JSON.stringify(b.message?.content??[]).length;u+=Math.max(Number(C.output_tokens??0),Math.round(H/4)),h+=Number(C.cache_read_input_tokens??0),w()}for(let H of b.message?.content??[])if(H.type==="text"&&H.text?.trim())t.onLog("agent",H.text.trim().slice(0,4e3));else if(H.type==="tool_use"){let $=H.input??{},q=["file_path","path","pattern","command","description","url"].map(m=>typeof $[m]=="string"?`${m}=${$[m]}`:null).filter(Boolean).join(" "),d=JSON.stringify($).slice(0,400);t.onLog("info",`tool ${H.name} ${q?`${q} `:""}${d}`)}}else b.type==="result"&&(i.costUsd=Number(b.total_cost_usd??0),i.inputTokens=Number(b.usage?.input_tokens??0)+Number(b.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(b.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),u=Math.max(i.outputTokens,u),i.inputTokens=c,i.outputTokens=u,h=Number(b.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()),b.subtype==="success"&&!b.is_error?(i.ok=!0,i.resultText=String(b.result??""),i.outputTruncated=l):b.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=b.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String(b.result??b.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let J="";s.stderr.on("data",W=>{J=(J+W.toString()).slice(-2e3)}),s.on("error",W=>{i.error=`failed to start ${t.bin}: ${W.message}`,t.onLog("error",i.error),k()}),s.on("close",W=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${W}${J?`: ${J.slice(-500)}`:""}`),k()})})}var yo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:mh.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Rw};var gh=require("node:child_process"),yh=E(require("node:readline"),1),bh=E(Te(),1);async function Ew(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,gh.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+mo(t.mode)),r.stdin.end(),yh.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let w;try{w=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let v=w.item??w.msg??w,k=v?.type??w.type,x=v?.text??v?.message??"";k==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):k==="command_execution"||k==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):k==="error"&&typeof x=="string"&&x&&t.onLog("error",x.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 xl={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:bh.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Ew};var Aw={[yo.id]:yo,[xl.id]:xl};function Ye(t){return Aw[t||Tr.DEFAULT_AGENT_ID]??null}function Xe(t,e){return!e||e===yo.id?t.claudeBin:t.agents[e]?.bin??e}function Cn(t,e){let n=Ye(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${Tr.DEFAULT_AGENT_ID}"`;let r=(0,Tr.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 Le(t,e,n){let r=e.defaultAgent||Tr.DEFAULT_AGENT_ID,s=Ye(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,Tr.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:Xe(t,s.id)}}function en(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var Ts=E(Te(),1);var Il=E(require("node:fs"),1),bo=E(require("node:path"),1),$w=24,Cw=120,Pw=30,Nw=6e3,jw=new Set(["node_modules","dist","build","out","coverage","vendor","target"]);function Ow(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=Il.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of i){if(o.name.startsWith(".")||jw.has(o.name))continue;let l=bo.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 wo(t){let e=[],n=0;for(let r of Ow(t)){if(n>=$w||e.join(`
|
|
773
|
+
`).length>Nw)break;let s=bo.default.relative(t,r);if(bo.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=Il.default.readFileSync(r,"utf8")}catch{continue}let o=i.split(`
|
|
774
|
+
`);if(o.length<Cw)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>=Pw)){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?`
|
|
775
775
|
|
|
776
776
|
DOCUMENT INDEX - the repo's larger Markdown documents, with 1-based line numbers (generated; the files themselves are the truth):
|
|
777
777
|
${e.join(`
|
|
778
778
|
`)}
|
|
779
|
-
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 Qs=E(require("node:fs"),1),wh=E(require("node:path"),1)
|
|
780
|
-
`,{mode:384}),
|
|
779
|
+
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 Qs=E(require("node:fs"),1),wh=E(require("node:path"),1);$e();var Rl=2,vh=()=>wh.default.join(le(),"timeout-sessions.json");function kh(){try{return JSON.parse(Qs.default.readFileSync(vh(),"utf8"))}catch{return{}}}function _h(t){Qs.default.mkdirSync(le(),{recursive:!0,mode:448}),Qs.default.writeFileSync(vh(),JSON.stringify(t,null,2),{mode:384})}var Sh=(t,e)=>`${t}:${e}`;function Th(t,e,n){let r=kh();r[Sh(t,e)]={...n,at:new Date().toISOString()},_h(r)}function xh(t,e,n){let r=kh(),s=Sh(t,e),i=r[s];return!i||(delete r[s],_h(r),i.branch!==n)||!Qs.default.existsSync(i.worktreePath)?null:i}kt();_r();Ct();var He=E(require("node:fs"),1),vs=E(require("node:path"),1);Qr();$e();var zw=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),Dw=_.record(zw),Lw=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),Uw=_.record(Lw),qw=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional(),preflight:_.enum(["epic-confirm"]).optional(),ruleId:_.string().optional()}),Fw=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),Bw=_.record(Fw),Hw=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),Kw=_.record(Hw),Gw=_.record(qw);function Ih(){return vs.default.join(le(),"pending-runs.json")}function El(){return vs.default.join(le(),"pending-deploys.json")}function Al(){return vs.default.join(le(),"pending-inputs.json")}function $l(){return vs.default.join(le(),"merge-watch.json")}function Cl(){return vs.default.join(le(),"pending-pushes.json")}function Pl(){let t=Cl();if(!He.default.existsSync(t))return{};try{return Bw.parse(JSON.parse(He.default.readFileSync(t,"utf8")))}catch{return{}}}function vo(t){let e=Pl();e[t.runId]=t,tn(Cl(),e)}function ko(t){return Pl()[t]??null}function Nl(t){let e=Pl();t in e&&(delete e[t],tn(Cl(),e))}function _o(){let t=$l();if(!He.default.existsSync(t))return{};try{return Kw.parse(JSON.parse(He.default.readFileSync(t,"utf8")))}catch{return{}}}function Rh(t){let e=_o();e[t.runId]=t,tn($l(),e)}function ei(t){let e=_o();t in e&&(delete e[t],tn($l(),e))}function ti(){let t=Ih();if(!He.default.existsSync(t))return{};try{return Dw.parse(JSON.parse(He.default.readFileSync(t,"utf8")))}catch{return{}}}function tn(t,e){He.default.mkdirSync(le(),{recursive:!0,mode:448});let n=t+".tmp";He.default.writeFileSync(n,JSON.stringify(e,null,2)+`
|
|
780
|
+
`,{mode:384}),He.default.renameSync(n,t),He.default.chmodSync(t,384)}function Eh(t){tn(Ih(),t)}function _t(t){let e=ti();e[t.runId]=t,Eh(e)}function ks(t){return ti()[t]??null}function Ir(t){let e=ti();t in e&&(delete e[t],Eh(e))}function jl(){let t=El();if(!He.default.existsSync(t))return{};try{return Uw.parse(JSON.parse(He.default.readFileSync(t,"utf8")))}catch{return{}}}function Ah(t){let e=jl();e[t.runId]=t,tn(El(),e)}function So(t){return jl()[t]??null}function To(t){let e=jl();t in e&&(delete e[t],tn(El(),e))}function Rr(){let t=Al();if(!He.default.existsSync(t))return{};try{return Gw.parse(JSON.parse(He.default.readFileSync(t,"utf8")))}catch{return{}}}function $h(t){let e=Rr();e[t.runId]=t,tn(Al(),e)}function Ch(t){return Rr()[t]??null}function jt(t){let e=Rr();t in e&&(delete e[t],tn(Al(),e))}Qt();var Zw=`
|
|
781
781
|
|
|
782
782
|
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.`,Ww=`
|
|
783
783
|
|
|
@@ -807,10 +807,10 @@ This repository has working rules taught to Allwright - follow them:
|
|
|
807
807
|
Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
|
|
808
808
|
`+o}return r}catch{return""}}function Dl(t){return zl.default.existsSync(xo.default.join(t,"DESIGN.md"))?`
|
|
809
809
|
|
|
810
|
-
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 Mh=5,
|
|
810
|
+
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 Mh=5,Nh=2,Xw=8,jh=2,Ol="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.",Qw="Proceed - this epic's own description is the spec for this run",ev="Stop this run - the work lives in the child tickets",tv="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 si(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?Xw:Nh,h=!1;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(e.maxCostUsd&&o.costUsd>=e.maxCostUsd){c=`the run's cost cap ($${e.maxCostUsd.toFixed(2)}) is spent ($${o.costUsd.toFixed(2)} so far)`,h=!0;break}if(l>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=Nh){let w=await r().catch(()=>""),v=w!==""&&w!==i;if(i=w,!v){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*jh*1e3){c=`wall-clock budget (${jh}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 f=await t.run({...e,prompt:tv,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(h&&(o.costCapped=!0),o.error=h?`stopped by the rule's cost cap: $${o.costUsd.toFixed(2)} spent of the $${(e.maxCostUsd??0).toFixed(2)} allowed, with the work unfinished after ${l} resume(s). This is the circuit breaker doing its job - split the ticket into smaller ones, or raise the rule's max cost if the scope really warrants it.`:`${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 ni=new Map;function zh(t){let e=ni.get(t);return e?(e.abort(),!0):!1}function Dh(t){let e=new AbortController;return ni.set(t,e),e}function Lh(t){ni.delete(t)}async function xs(t,e,n,r,s){let i=new AbortController;ni.set(t,i);try{return await si(e,{...n,signal:i.signal},r,s)}finally{ni.delete(t)}}function Er(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"&&g.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 ii(t){return t.rule.action.type==="implement"?sv(t):t.rule.action.type==="respond"?rv(t):nv(t)}async function nv(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Er(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=Cn(o.agent,o.type);if(l){e("error",l),await _s(t,l),n("failed",{error:l});return}let c=(0,Io.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=en(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:Ss(u.comments)})+await ts(t.jira,u.attachments,t.repoPath,e)+Dl(t.repoPath)+wo(t.repoPath)+Ts.FOCUSED_READING_PROMPT+Se.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 xs(t.runId,Ye(o.agent),{repoPath:t.repoPath,prompt:h,timeoutSeconds:o.timeoutSeconds,bin:Xe(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(k,x)=>e(k,x),onUsage:r},e),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await _s(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ai(f.resultText);if(v){await ri({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},v,e,n,w);return}await Uh({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:w,emit:e,setStatus:n})}catch(u){let h=u instanceof Error?u.message:String(u);e("error",`Run failed: ${h}`),await _s(t,h),n("failed",{error:h})}finally{bn(t.repoPath)}}async function Ll(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Er(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=Jh(e)+await ts(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await xs(t.runId,Ye(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Xe(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(w,v)=>s(w,v),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 w=u.error??"Claude Code produced no output";s("error",`Run failed: ${w}`),await Ot(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),jt(t.runId),i(u.timedOut?"timed_out":"failed",{error:w,...u.cancelled?{errorKind:"guard"}:{},...h});return}let f=ai(u.resultText);if(f){if(t.rounds>=Mh){await Yh(r.jiraFor(t.repoName??""),t,s,i,h);return}await ri({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 Uh({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 Ot(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),jt(t.runId),i("failed",{error:u})}finally{bn(t.repoPath)}}async function Uh(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=`
|
|
811
811
|
|
|
812
812
|
---
|
|
813
|
-
_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:[Se.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 rv(t){let{emit:e,setStatus:n,sendUsage:r}=Er(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i
|
|
813
|
+
_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:[Se.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 rv(t){let{emit:e,setStatus:n,sendUsage:r}=Er(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Cn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
|
|
814
814
|
|
|
815
815
|
${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=en(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Ss(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await ts(t.jira,o.attachments,t.repoPath,e)+Dl(t.repoPath)+wo(t.repoPath)+Ts.FOCUSED_READING_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await xs(t.runId,Ye(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Xe(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Io.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.**
|
|
816
816
|
|
|
@@ -818,53 +818,53 @@ Error: ${h.slice(0,800)}
|
|
|
818
818
|
|
|
819
819
|
Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>g.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{bn(t.repoPath)}}async function qh(t,e,n,r){let s=`${e}-wip`;try{return bn(t),await wr(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Ba(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 Fh(t){return`
|
|
820
820
|
|
|
821
|
-
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 sv(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Er(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l
|
|
821
|
+
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 sv(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Er(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=Cn(o.agent,o.type);if(l){e("error",l),await _s(t,l),n("failed",{error:l});return}let c=en(o.branchTemplate,{issueKey:t.issueKey}),u=t.chain?null:xh(t.project.id,t.issueKey,c),h=t.chain?.worktreePath??u?.worktreePath??xo.default.join(Xt(),t.runId),f=t.chain?.sessionId??u?.sessionId??(0,Io.randomUUID)(),w=!1,v=!1,k=!1;try{if(!co(ke()??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(m){e("warn",`Jira start transition failed: ${m instanceof Error?m.message:m} - continuing anyway`)}let x=await kr(t.repoPath);if(e("info",`Repo origin: ${x}`),!wt(x))throw new Error(`origin "${x}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let I=await t.jira.getIssue(t.issueKey);if(/^epic$/i.test(I.issueType)&&!t.preflightAnswer&&!u&&!t.chain){k=!0;let m="```";await ri({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,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:I.summary,preflight:"epic-confirm",ruleId:t.rule.id},`This ticket is an **Epic** - usually a container whose child tickets hold the actual work. Implementing the container itself burns a full agent run on a description that was rarely written as a spec, and can contradict the children.
|
|
822
822
|
|
|
823
823
|
Should this run implement the epic ticket itself?
|
|
824
824
|
|
|
825
825
|
${m}${Se.NEEDS_INPUT_ASK_FENCE}
|
|
826
826
|
{"options": ["${Qw}", "${ev}"]}
|
|
827
|
-
${m}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let P=t.continueBranch?c:o.baseBranch;u?e("info",`Resuming the session that timed out on this ticket (timeout resume ${u.resumes}/${Rl}) - 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 In(t.repoPath,P),t.chain&&t.continueBranch||await
|
|
827
|
+
${m}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let P=t.continueBranch?c:o.baseBranch;u?e("info",`Resuming the session that timed out on this ticket (timeout resume ${u.resumes}/${Rl}) - 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 In(t.repoPath,P),t.chain&&t.continueBranch||await Ka(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 Ya(h,c,t.continueBranch?`origin/${c}`:`origin/${o.baseBranch}`)):await Ga(t.repoPath,h,c,P)),w=!0;let J=en(o.promptTemplate,{issueKey:I.key,summary:I.summary,description:I.description||"(no description)",comments:Ss(I.comments)}),W=[],b=(m,y)=>(y&&W.push({part:m,chars:y.length}),y),C=b("ticket: rule template + summary (rendered)",J)+b("attachments listing",await ts(t.jira,I.attachments,h,e))+b("design guideline pointer",Dl(h))+b("knowledge: packs + lessons",Yw(t.repoPath))+b("doc index",wo(h))+b("appendix: focused reading",Ts.FOCUSED_READING_PROMPT)+b("appendix: protected paths",Zw)+b("appendix: needs-input options",Se.NEEDS_INPUT_OPTIONS_PROMPT)+b("appendix: PR summary",Ww)+b("appendix: go-live",t.project.goLiveIssueKey?Vw:"")+b("appendix: write tests",o.writeTests?Ts.WRITE_TESTS_PROMPT:"")+b("appendix: update memory",o.updateMemory?Se.MEMORY_UPDATE_PROMPT:"")+b("epic confirmation answer",t.preflightAnswer?`
|
|
828
828
|
|
|
829
829
|
THIS TICKET IS AN EPIC, and a human was asked whether to implement the epic ticket itself. They said to proceed, in these words - treat any guidance in them as part of the ticket:
|
|
830
|
-
${t.preflightAnswer.slice(0,4e3)}`:"");I.description&&W.push({part:"\u21B3 of which ticket description",chars:I.description.length});let
|
|
830
|
+
${t.preflightAnswer.slice(0,4e3)}`:"");I.description&&W.push({part:"\u21B3 of which ticket description",chars:I.description.length});let H=Ss(I.comments).length;H&&W.push({part:"\u21B3 of which comment history",chars:H}),t.transport.sendRunContext({runId:t.runId,pieces:u?[{part:"continuation prompt (session resumed - original context already cached)",chars:Ol.length}]:W,totalChars:u?Ol.length:C.length,sessionMode:u?"timeout-resume":t.chain?"chained":t.preflightAnswer?"preflight-resume":"fresh"}),e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let $=await xs(t.runId,Ye(o.agent),{repoPath:h,prompt:u?Ol:C,timeoutSeconds:o.timeoutSeconds,bin:Xe(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,maxCostUsd:o.maxCostUsd,sessionId:f,resume:!!t.chain||!!u,onLog:(m,y)=>e(m,y),onUsage:r},e,()=>so(h)),q={costUsd:$.costUsd,inputTokens:$.inputTokens,outputTokens:$.outputTokens,billingMode:$.billingMode,model:$.model};if(!$.ok){let m=$.error??"Claude Code failed";e("error",`Run failed: ${m}`);let y=m,R=($.timedOut||$.costCapped)&&!$.cancelled&&Ye(o.agent)?.capabilities.sessionResume&&(u?.resumes??0)<Rl;if($.turnLimitHit&&!R){let N=await qh(h,c,t.runId,e);N&&(y+=Fh(N))}R&&(Th(t.project.id,t.issueKey,{sessionId:f,worktreePath:h,branch:c,resumes:(u?.resumes??0)+1}),v=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),y+=" - 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"),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:m.slice(0,500)}),await _s(t,y),n($.timedOut?"timed_out":"failed",{error:y,...$.cancelled||$.costCapped?{errorKind:"guard"}:{},...q});return}let d=ai($.resultText);if(d){k=!0,await ri({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:I.summary},d,e,n,q);return}bn(h),await Bh({runId:t.runId,issueKey:t.issueKey,issueSummary:I.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:$.resultText,costFields:q,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(x){let I=x instanceof Error?x.message:String(x);e("error",`Run failed: ${I}`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:I.slice(0,500)}),await _s(t,I),n("failed",{error:I})}finally{w&&!k&&!t.keepWorktree&&!v&&await $t(t.repoPath,h).catch(()=>{})}}async function Ul(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Er(t.runId,r.transport,t.nextLogSeq);if(t.preflight==="epic-confirm"){let h=e.trim();if(/stop this run/i.test(h)){s("info","Epic confirmed as a container - stopping before any agent spend"),i("failed",{error:"stopped by choice: this Epic's work lives in its child tickets - queue those instead. No agent ran and nothing was spent.",errorKind:"guard"});return}let f=r.findRule?.(t.ruleId??"")??null;if(!f){i("failed",{error:"the rule this run would use no longer exists on this runner (it was deleted or edited away while the question waited) - trigger the ticket again from a current rule"});return}s("info","Epic confirmed by a human - starting the implement run"),await ii({runId:t.runId,rule:f.rule,project:f.project,issueKey:t.issueKey,repoPath:f.repoPath,cfg:r.cfg,jira:r.jiraFor(f.project.repoName),transport:r.transport,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,preflightAnswer:e,startLogSeq:l()});return}let c=t.repoPath,u=!1;try{if(!co(ke()??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=Jh(e)+await ts(r.jiraFor(t.repoName??""),n,c,s),f=await xs(t.runId,Ye(t.agent),{repoPath:c,prompt:h,timeoutSeconds:t.timeoutSeconds,bin:Xe(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:(k,x)=>s(k,x),onUsage:o},s,()=>so(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let k=f.error??"Claude Code failed";s("error",`Run failed: ${k}`);let x=k;if(f.turnLimitHit&&t.branch){let I=await qh(c,t.branch,t.runId,s);I&&(x+=Fh(I))}await Ot(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),jt(t.runId),i(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ai(f.resultText);if(v){if(t.rounds>=Mh){await Yh(r.jiraFor(t.repoName??""),t,s,i,w);return}u=!0,await ri({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},v,s,i,w);return}bn(c),await Bh({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:w,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 Ot(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),jt(t.runId),i("failed",{error:f})}finally{u||await $t(t.baseRepoPath??c,c).catch(()=>{})}}async function Bh(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:w,repoName:v,jira:k,cfg:x,actorEmail:I,runTests:P,mergeOnApprove:J,mergeMethod:W,autoMerge:b,resultText:C,costFields:H,emit:$,setStatus:q}=t,d=await ds(s);d.deleted.length&&$("info",`Deleted ${d.deleted.length} file(s) listed in ${Yt}: `+d.deleted.slice(0,10).join(", ")+(d.deleted.length>10?", \u2026":""));for(let de of d.refused)$("warn",`${Yt} entry refused: ${de}`);$("info","Committing changes"),await wr(s,`${n}: ${r}
|
|
831
831
|
|
|
832
|
-
Allwright run ${e}`);let m=await Rn(s,l);if(!m.ok){let de=m.forbidden.length?`refusing to push: changes touch protected paths (${m.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 (${m.files} files, ${m.insertions+m.deletions} lines; limits ${Tn}/${xn})
|
|
833
|
-
${ie.tail.slice(-1500)}`));let
|
|
834
|
-
${xe.tail.slice(-1500)}`));
|
|
832
|
+
Allwright run ${e}`);let m=await Rn(s,l);if(!m.ok){let de=m.forbidden.length?`refusing to push: changes touch protected paths (${m.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 (${m.files} files, ${m.insertions+m.deletions} lines; limits ${Tn}/${xn})`;$("error",de),await Ot(k,n,e,w,de),q("failed",{error:de,errorKind:"guard",...H});return}$("info",`Diff: ${m.files} file(s), +${m.insertions}/-${m.deletions}`);let y={...H},R="",N="",G,L,Z;if(P){let de=ys(s);if(!de)$("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let qe=bs(zl.default.readFileSync(de,"utf8"));if(!qe.length)$("info",`${xo.default.basename(de)} lists no commands - nothing to run`);else{$("info",`Running ${qe.length} documented test command(s) - no tokens, plain shell`);let oe=await Sr(s,qe,{perCommandTimeoutMs:15*6e4}),Fe=oe.filter(ie=>ie.exitCode!==0),Pe=Fe.length;for(let ie of oe)$(ie.exitCode===0?"info":"warn",`${ie.exitCode===0?"PASS":"FAIL"} ${ie.command} (exit ${ie.exitCode})`+(ie.exitCode===0?"":`
|
|
833
|
+
${ie.tail.slice(-1500)}`));let Ne="";if(Fe.length&&t.fixSession){let ie=await ov({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Fe,emit:$,sendUsage:t.sendUsage,baseCost:y});if(y.costUsd+=ie.cost.costUsd,y.inputTokens+=ie.cost.inputTokens,y.outputTokens+=ie.cost.outputTokens,ie.outcome==="cancelled"){let xe="stopped by a person during the automatic test-fix attempt - nothing was pushed";$("warn",xe),vo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:J,mergeMethod:W,autoMerge:b,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Je(s),requireApproval:h,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:I,resultSummary:Oh(C),prSummary:Ml(C)??"",costUsd:y.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Ot(k,n,e,w,`${xe}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),q("failed",{error:xe,errorKind:"guard",retryAvailable:!0,...y});return}if(ie.outcome==="committed"){N=ie.resultText,$("info",`Re-running ${qe.length} documented test command(s) after the fix`),oe=await Sr(s,qe,{perCommandTimeoutMs:15*6e4}),Fe=oe.filter(xe=>xe.exitCode!==0);for(let xe of oe)$(xe.exitCode===0?"info":"warn",`${xe.exitCode===0?"PASS":"FAIL"} ${xe.command} (exit ${xe.exitCode})`+(xe.exitCode===0?"":`
|
|
834
|
+
${xe.tail.slice(-1500)}`));Ne=Fe.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${Pe} failure(s). ${ie.note}`:`The first pass had ${Pe} failure(s); one automatic same-session fix attempt resolved them. ${ie.note}`}else Ne=ie.note}G=Fe.slice(0,20).map(ie=>({command:ie.command.slice(0,500),exitCode:ie.exitCode,tail:ie.tail.slice(-4e3)})),L=oe.length-Fe.length,Z=oe.length,R=`
|
|
835
835
|
|
|
836
836
|
### Tests
|
|
837
|
-
`+
|
|
837
|
+
`+oe.map(ie=>`- ${ie.exitCode===0?"PASS":"FAIL"} \`${ie.command}\``).join(`
|
|
838
838
|
`)+(Fe.length?`
|
|
839
839
|
|
|
840
|
-
**${Fe.length} of ${
|
|
840
|
+
**${Fe.length} of ${oe.length} failed.** Output is in the run log.`:`
|
|
841
841
|
|
|
842
|
-
All ${
|
|
842
|
+
All ${oe.length} passed.`)+(Ne?`
|
|
843
843
|
|
|
844
|
-
${
|
|
845
|
-
`)+(
|
|
846
|
-
${
|
|
844
|
+
${Ne}`:""),Fe.length&&$("warn",`${Fe.length} test command(s) failed - the PR will say so; review before merging`),Pe>0&&dt(i,{issueKey:n,runId:e,title:Fe.length?`TEST.md commands failing at PR (${Fe.length} of ${oe.length})`:"TEST.md failures fixed by same-session retry",detail:oe.map(ie=>`${ie.exitCode===0?"PASS":"FAIL"} ${ie.command}`).join(`
|
|
845
|
+
`)+(Ne?`
|
|
846
|
+
${Ne}`:"")})}}}let U=await kr(s),z=wt(U);if(!z){let de=`origin "${U}" is not a GitHub remote - implement mode supports GitHub only`;$("error",de),await Ot(k,n,e,w,de),q("failed",{error:de,...H});return}let ee=await Je(s),V=Oh(C),fe=(N?Ml(N):null)??Ml(C);try{await Hh({gitDir:s,ownerRepo:z,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:h,doneLabel:f,failedLabel:w,repoName:v,jira:k,cfg:x,actorEmail:I,mergeOnApprove:J,mergeMethod:W,autoMerge:b,summary:V,prSummary:fe??void 0,cost:y,testReport:R,failedTests:G,testsPassed:L,testsTotal:Z,goLiveDraft:(N?Ph(N):null)??Ph(C)??void 0,emit:$,setStatus:q})}catch(de){let qe=de instanceof Error?de.message:String(de);vo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:J,mergeMethod:W,autoMerge:b,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:ee,requireApproval:h,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:I,resultSummary:V,prSummary:fe??"",costUsd:y.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),$("error",`Run failed: ${qe}`),$("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Ot(k,n,e,w,`${qe}
|
|
847
847
|
|
|
848
848
|
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),q("failed",{error:qe,retryAvailable:!0,...y})}}var iv={costUsd:0,inputTokens:0,outputTokens:0};async function ov(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:h}=t,f=Ye(i.agent);if(!f?.capabilities.sessionResume){let P=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",P),{outcome:"skipped",note:P,cost:iv}}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 w=await Je(r),v=await xs(e,f,{repoPath:r,prompt:Jw(l),timeoutSeconds:i.timeoutSeconds,bin:Xe(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:(P,J)=>c(P,J),onUsage:u?P=>u({...P,inputTokens:h.inputTokens+P.inputTokens,outputTokens:h.outputTokens+P.outputTokens,costUsd:P.costUsd===void 0?void 0:h.costUsd+P.costUsd}):void 0},c),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:k};if(!v.ok){let P=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return c("warn",P),{outcome:"agent_failed",note:P,cost:k}}if(ai(v.resultText)){let P="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",P),{outcome:"agent_failed",note:P,cost:k}}let x=await ds(r);for(let P of x.refused)c("warn",`${Yt} entry refused: ${P}`);try{await wr(r,`${n}: fix failing TEST.md commands
|
|
849
849
|
|
|
850
|
-
Allwright run ${e} (automatic test-fix attempt)`)}catch{let P=`An automatic fix attempt concluded no code change was warranted: ${Ar(v.resultText)}`;return c("info",P),{outcome:"no_changes",note:P,cost:k}}let I=await Rn(r,s);if(!I.ok){await hs(r,w);let P=I.forbidden.length?`An automatic fix attempt touched protected paths (${I.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",P),{outcome:"reverted",note:P,cost:k}}return{outcome:"committed",note:`Fix attempt: ${Ar(v.resultText)}`,resultText:v.resultText,cost:k}}async function
|
|
850
|
+
Allwright run ${e} (automatic test-fix attempt)`)}catch{let P=`An automatic fix attempt concluded no code change was warranted: ${Ar(v.resultText)}`;return c("info",P),{outcome:"no_changes",note:P,cost:k}}let I=await Rn(r,s);if(!I.ok){await hs(r,w);let P=I.forbidden.length?`An automatic fix attempt touched protected paths (${I.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",P),{outcome:"reverted",note:P,cost:k}}return{outcome:"committed",note:`Fix attempt: ${Ar(v.resultText)}`,resultText:v.resultText,cost:k}}async function Hh(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:w,requireApproval:v,doneLabel:k,failedLabel:x,repoName:I,jira:P,cfg:J,actorEmail:W,summary:b,prSummary:C,cost:H,testReport:$,emit:q,setStatus:d}=t;q("info",`Pushing ${u} to origin`),await vr(e,u);let m=await io(e,u),R=`${C?.trim()?`${C.trim()}
|
|
851
851
|
|
|
852
852
|
<details>
|
|
853
853
|
<summary>Technical details</summary>
|
|
854
854
|
|
|
855
855
|
${b}
|
|
856
856
|
|
|
857
|
-
</details>`:b}${
|
|
857
|
+
</details>`:b}${$??""}
|
|
858
858
|
|
|
859
859
|
---
|
|
860
860
|
Jira: ${new URL(`/browse/${s}`,J.jira?.baseUrl??"").toString()}
|
|
861
|
-
_Allwright implement run \`${r}\` \xB7 cost $${
|
|
861
|
+
_Allwright implement run \`${r}\` \xB7 cost $${H.costUsd.toFixed(4)}. `+($?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");q("info","Opening pull request");let N=co(ke()??J,I,W);N.source==="user"&&q("info",`PR will be authored with ${W}'s own GitHub token`);let L=await new Ue(N.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:h,body:R});q("info",`PR ready: ${L.url}`),Rh({runId:r,issueKey:s,repoName:I,owner:n.owner,repo:n.repo,prNumber:L.number,prUrl:L.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),d("posting",H);let Z={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:I,owner:n.owner,repo:n.repo,prNumber:L.number,prUrl:L.url,branch:u,headSha:m,doneLabel:k,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)_t(Z),await P.addComment(s,`**Allwright opened a pull request for review.**
|
|
862
862
|
|
|
863
863
|
PR: ${L.url}
|
|
864
864
|
|
|
865
|
-
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}\`)`),d("awaiting_approval",{...
|
|
865
|
+
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}\`)`),d("awaiting_approval",{...H,prUrl:L.url,headSha:m,resultSummary:Ar(C?.trim()||b),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}:{}}),q("info",`Awaiting approval on the dashboard \xB7 $${H.costUsd.toFixed(4)}`);else{if(c){q("info",`Auto-merging PR #${L.number} (${l})`);let z=ze(J,I),ee=z?await new Ue(z).mergePullRequest(n.owner,n.repo,L.number,l,{sha:m,title:`${s} (#${L.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};ee.merged?q("info",`PR #${L.number} merged`):(q("warn",`Auto-merge did not go through - ${ee.reason}. The PR stays open.`),await P.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${ee.reason}
|
|
866
866
|
|
|
867
|
-
PR: ${L.url}`))}let U=(ke()??J).repos[I]?.path;U&&Xs(U,s)&&dt(U,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${L.url} merged/opened straight-through.`}),await
|
|
867
|
+
PR: ${L.url}`))}let U=(ke()??J).repos[I]?.path;U&&Xs(U,s)&&dt(U,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${L.url} merged/opened straight-through.`}),await Kh({jira:P,issueKey:s},Z,q),d("succeeded",{...H,prUrl:L.url,headSha:m,resultSummary:Ar(C?.trim()||b),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}:{}}),q("info",`Run succeeded \xB7 ${L.url} \xB7 $${H.costUsd.toFixed(4)}`)}}async function Kh(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.**
|
|
868
868
|
|
|
869
869
|
PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
|
|
870
870
|
|
|
@@ -876,9 +876,9 @@ Note: ${r}`:"")+`
|
|
|
876
876
|
|
|
877
877
|
(run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Se.NEEDS_INPUT_LABEL]}),r}async function oi(t,e,n){let r=ks(e);if(!r){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Wh(t,e);try{let o=ze(ke()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new Ue(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}
|
|
878
878
|
|
|
879
|
-
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let h=(ke()??t.cfg).repos[r.repoName??""]?.path;h&&Xs(h,r.issueKey)&&dt(h,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await
|
|
879
|
+
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let h=(ke()??t.cfg).repos[r.repoName??""]?.path;h&&Xs(h,r.issueKey)&&dt(h,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await Kh({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.'),Ir(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await Vh(t,r,l),i("failed",{error:l}),Ir(e)}}async function Gh(t,e){let n=ks(e);if(!n){g.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Wh(t,e);try{let i=ze(ke()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Ue(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.**
|
|
880
880
|
|
|
881
|
-
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"),Ir(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Vh(t,n,o),s("failed",{error:o}),Ir(e)}}async function Zh(t,e){let n=ko(e);if(!n){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=Er(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}=Er(e,t.transport,n.nextLogSeq);try{let l=await io(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.`),
|
|
881
|
+
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"),Ir(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Vh(t,n,o),s("failed",{error:o}),Ir(e)}}async function Zh(t,e){let n=ko(e);if(!n){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=Er(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}=Er(e,t.transport,n.nextLogSeq);try{let l=await io(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.`),Nl(e),s("failed",{retryAvailable:!1});return}let c=await kr(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 Hh({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:ke()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Nl(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}`),vo({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function Wh(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"&&g.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{t.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Vh(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
882
882
|
|
|
883
883
|
Error: ${n.slice(0,800)}
|
|
884
884
|
|
|
@@ -896,23 +896,23 @@ Continue from where you left off now that you have this information. If you are
|
|
|
896
896
|
|
|
897
897
|
${i}
|
|
898
898
|
|
|
899
|
-
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:[Se.NEEDS_INPUT_LABEL]})
|
|
899
|
+
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:[Se.NEEDS_INPUT_LABEL]}),$h({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,preflight:t.preflight,ruleId:t.ruleId}),r("needs_input",{...s,resultSummary:Ar(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${Se.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function Yh(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 Ot(t,e.issueKey,e.runId,e.failedLabel,i),jt(e.runId),r("failed",{error:i,...s})}async function _s(t,e){await Ot(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Ot(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
|
|
900
900
|
|
|
901
901
|
Error: ${s.slice(0,800)}
|
|
902
902
|
|
|
903
903
|
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:[Se.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function Oh(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 Ml(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(`
|
|
904
|
-
`)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Is=E(require("node:fs"),1);var
|
|
904
|
+
`)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Is=E(require("node:fs"),1);var $r=E(require("node:fs"),1),ql=E(require("node:os"),1),Cr=E(require("node:path"),1);function lv(){try{return ql.default.userInfo().username}catch{return"the user the runner service runs as"}}function cv(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=$r.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=$r.default.readFileSync(Cr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Fl(t,e){let n=t.slice(-4e3),r=lv(),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?cv(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(ql.default.homedir(),".nvm","versions","node"),f=$r.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'
|
|
905
905
|
[Service]
|
|
906
906
|
Environment=PATH=${u||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
907
|
-
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=(
|
|
907
|
+
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=($r.default.existsSync("/etc/systemd/system")?$r.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let v=$r.default.readFileSync(Cr.default.join("/etc/systemd/system",w),"utf8");return e?.cwd?v.includes(e.cwd):!1}catch{return!1}}).map(w=>w.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 Xh(t){return t?`
|
|
908
908
|
|
|
909
909
|
What this means: ${t.cause}
|
|
910
910
|
Run these ON THE DEPLOY MACHINE:
|
|
911
911
|
`+t.commands.map(e=>` ${e}`).join(`
|
|
912
912
|
`)+`
|
|
913
|
-
${t.note}`:""}var Pr=E(require("node:path"),1)
|
|
913
|
+
${t.note}`:""}var Pr=E(require("node:path"),1),Co=require("node:child_process"),Vl=E(require("node:readline"),1),Jl=require("node:crypto"),Nr=E(Te(),1);Qr();$e();var Po=E(Te(),1);Ct();kt();_r();Ao();var ap="";function lp(t){ap=(t??"").trim()}function cp(){return ap}Zl();Qt();var mp=4e3,_v=4e3;function gp(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
|
|
914
914
|
`+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
|
|
915
|
-
`))}function Yl(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,_v)}),s!=="agent"&&g.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var Sv=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function Tv(t){let e=Sv.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
|
|
915
|
+
`))}function Yl(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,_v)}),s!=="agent"&&g.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var Sv=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function Tv(t){let e=Sv.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 No(t){let{emit:e,setStatus:n}=Yl(t),r=t.environment;try{let s=xv(t);if(s){e("error",s),await ht(t,`**Allwright could not deploy to \`${r.name}\`.**
|
|
916
916
|
|
|
917
917
|
${s}`),n("failed",{error:s});return}if(r.requireApproval){Ah({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 ht(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
|
|
918
918
|
|
|
@@ -920,27 +920,27 @@ ${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed y
|
|
|
920
920
|
|
|
921
921
|
${i.slice(0,800)}
|
|
922
922
|
|
|
923
|
-
(run \`${t.runId}\`)`),n("failed",{error:i})}}function xv(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=Zt(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&&g.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 vp(t,e,n){let r=t.environment,s=Zt(t.cfg,t.project.repoName,r.name),i=Xl(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 b=Le(t.cfg,t.project,"assist")
|
|
923
|
+
(run \`${t.runId}\`)`),n("failed",{error:i})}}function xv(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=Zt(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&&g.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 vp(t,e,n){let r=t.environment,s=Zt(t.cfg,t.project.repoName,r.name),i=Xl(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 b=Le(t.cfg,t.project,"assist"),C="error"in b?{ok:!1,error:b.error}:await ws({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:b,jira:t.jira});if(!C.ok)e("warn",`Pre-deploy audit could not run: ${C.error} - deploying anyway (advisory)`);else if(!C.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let H={};for(let $ of C.audit.findings)H[$.severity]=(H[$.severity]??0)+1;e("warn",`Pre-deploy audit: ${C.audit.findings.length} finding(s) (`+Object.entries(H).map(([$,q])=>`${q} ${$}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let $ of C.audit.findings.slice(0,5))e("warn",` [${$.severity}] ${$.title} - ${$.evidence[0]?.file??""}`)}}catch(b){e("warn",`Pre-deploy audit crashed: ${b instanceof Error?b.message:String(b)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let C=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",C),await ht(t,`**Allwright refused to deploy to \`${r.name}\`.**
|
|
924
924
|
|
|
925
|
-
${
|
|
925
|
+
${C}
|
|
926
926
|
|
|
927
|
-
(run \`${t.runId}\`)`),n("failed",{error
|
|
927
|
+
(run \`${t.runId}\`)`),n("failed",{error:C,errorKind:"guard"});return}let b=await Rv(t,e);if(b){await ht(t,b.comment),n("failed",{error:b.error,...b.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 Xa({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 b=en(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${b}" into "${r.branch}"`);let C=await Qa(c,b,`Deploy ${t.issueKey} to ${r.name}
|
|
928
928
|
|
|
929
|
-
Allwright run ${t.runId}`);if(
|
|
929
|
+
Allwright run ${t.runId}`);if(!C.ok){e("error",C.reason??"merge failed"),await ht(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
|
|
930
930
|
|
|
931
|
-
${
|
|
931
|
+
${C.reason}`),n("failed",{error:C.reason});return}C.alreadyMerged?e("info",`"${b}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await rl(c,r.branch))}let h=await Je(c).catch(()=>"");h&&e("info",`Deploying commit ${h.slice(0,10)}`);let f=Ev(c,r.workdir),w={...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},v=0,k=r.timeoutSeconds*1e3,x=Dh(t.runId),I=()=>x.signal.aborted;try{for(let[b,C]of r.steps.entries()){if(I()){let q=`stopped from the dashboard during step ${b+1} - nothing further ran`;e("error",q),n("failed",{error:q,errorKind:"guard",deployedRef:h});return}let H=k-(Date.now()-o);if(H<=0){let q=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${b+1}`;e("error",q),await ht(t,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
932
932
|
|
|
933
|
-
${q}`),n("timed_out",{error:q,deployedRef:h});return}e("info",`\u25B6 step ${b+1}/${r.steps.length}: ${
|
|
933
|
+
${q}`),n("timed_out",{error:q,deployedRef:h});return}e("info",`\u25B6 step ${b+1}/${r.steps.length}: ${C.name}`);let $=await Av({command:C.run,cwd:f,env:w,timeoutMs:H,signal:x.signal,onLine:(q,d)=>{v++;let m=Tv(d);m&&l.length<20&&l.push(m),v===mp&&e("warn","(output truncated - deploy log limit reached)"),!(v>=mp)&&e(q,i(d))}});if($.timedOut){let q=`step "${C.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",q),await ht(t,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
934
934
|
|
|
935
|
-
${q}`),n("timed_out",{error:q,deployedRef:h});return}if(
|
|
935
|
+
${q}`),n("timed_out",{error:q,deployedRef:h});return}if($.code!==0){if(C.continueOnError){e("warn",`step "${C.name}" exited ${$.code} - continuing (marked continue-on-error)`);continue}let q="";try{q=i(await Ha(c))}catch{}let d=Xh(Fl($.tail??"",{cwd:c})),m=`step ${b+1} "${C.name}" failed with exit code ${$.code}`+($.tail?`: ${i($.tail)}`:"")+d+(q?`
|
|
936
936
|
|
|
937
937
|
Checkout at failure:
|
|
938
938
|
${q}`:"");e("error",m),await ht(t,`**Allwright deploy to \`${r.name}\` failed.**
|
|
939
939
|
|
|
940
|
-
Step ${b+1} \`${
|
|
940
|
+
Step ${b+1} \`${C.name}\` exited ${$.code}.
|
|
941
941
|
|
|
942
|
-
`+(
|
|
943
|
-
${i(
|
|
942
|
+
`+($.tail?`\`\`\`
|
|
943
|
+
${i($.tail).slice(0,1200)}
|
|
944
944
|
\`\`\`
|
|
945
945
|
|
|
946
946
|
`:"")+(d?`${d.trim()}
|
|
@@ -954,10 +954,10 @@ ${q.slice(0,800)}
|
|
|
954
954
|
`+l.map(y=>`- \`${y.command}\`${y.why?` - ${y.why}`:""}`).join(`
|
|
955
955
|
`)+`
|
|
956
956
|
|
|
957
|
-
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${b+1} "${
|
|
958
|
-
${i(
|
|
957
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${b+1} "${C.name}" exit ${$.code}`+($.tail?`
|
|
958
|
+
${i($.tail).slice(0,500)}`:"")}),l.length&&gp(e,l),n("failed",{error:m.slice(0,1600),deployedRef:h,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${b+1}/${r.steps.length}: ${C.name}`)}}finally{Lh(t.runId)}if(h=await Je(c).catch(()=>"")||h,r.servePath?.trim()){let b=r.servePath.trim(),C=r.branch.trim(),H=await Je(b).catch(()=>"");if(!H)e("warn",`serving check: cannot read a git HEAD at ${b} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{h=H;let $=C?await Za(b,C):"";if(!$)e("warn",`serving check: ${b} is at ${H.slice(0,10)}, but `+(C?`origin/${C} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${C||"commit"} could not be verified`);else if(H!==$){let q=await Wa(b,H,$),d=`The steps all succeeded, but the live checkout at ${b} is at ${H.slice(0,10)} while origin/${C} is at ${$.slice(0,10)}`+(q?` - ${q} commit(s) behind`:"")+`. Users are NOT getting the latest ${C}. 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: ${d}`),await ht(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
|
|
959
959
|
|
|
960
|
-
${d}`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${
|
|
960
|
+
${d}`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${H.slice(0,10)}, origin/${C} at ${$.slice(0,10)} (${b})`}),n("failed",{error:d,deployedRef:h});return}else e("info",`serving check: ${b} is at ${H.slice(0,10)} = origin/${C} - users get this build`)}}n("posting");let P=Math.round((Date.now()-o)/1e3),J=null;r.publicUrl?.trim()&&(J=await Pv(r.publicUrl.trim()),e(J?"warn":"info",J??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Nr.BRANCH_DEPLOY_ISSUE_KEY&&await ht(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
|
|
961
961
|
|
|
962
962
|
`+(J?`> **Live where?** ${J}
|
|
963
963
|
|
|
@@ -977,20 +977,20 @@ ${l}
|
|
|
977
977
|
|
|
978
978
|
(run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await In(t.repoPath,r),await In(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 sl(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=ze(ke()??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 kr(t.repoPath),c=wt(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let h=await new Ue(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.
|
|
979
979
|
|
|
980
|
-
(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 Ev(t,e){if(!e.trim())return t;let n=Pr.default.resolve(t,e),r=Pr.default.relative(t,n);if(r.startsWith("..")||Pr.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
|
|
981
|
-
`)}))},c=setTimeout(()=>{o=!0
|
|
980
|
+
(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 Ev(t,e){if(!e.trim())return t;let n=Pr.default.resolve(t,e),r=Pr.default.relative(t,n);if(r.startsWith("..")||Pr.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,Co.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(`
|
|
981
|
+
`)}))},c=setTimeout(()=>{o=!0,$o(n.pid,"SIGTERM"),setTimeout(()=>$o(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),$o(n.pid,"SIGTERM"),setTimeout(()=>$o(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),Vl.default.createInterface({input:n.stdout}).on("line",h=>{s(h),t.onLine("info",h)}),Vl.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 $o(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function Xl(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 ht(t,e){if(t.issueKey!==Nr.BRANCH_DEPLOY_ISSUE_KEY)try{await t.jira.addComment(t.issueKey,e)}catch(n){g.error(`could not post deploy comment to ${t.issueKey}: ${n}`)}}function Ql(t){return So(t)!==null}async function kp(t,e){let n=So(e);if(!n)return;let{emit:r,setStatus:s}=Yl({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}),To(e);return}To(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 vp(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await ht(o,`**Allwright deploy failed.**
|
|
982
982
|
|
|
983
983
|
${c.slice(0,800)}`),s("failed",{error:c})}}async function _p(t,e){let n=So(e);if(!n)return;let{emit:r,setStatus:s}=Yl({runId:e,transport:t.transport});To(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.**
|
|
984
984
|
|
|
985
|
-
No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var
|
|
985
|
+
No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var $v=_.object({steps:_.array(Nr.DeployStep).max(50).default([]),requiredSecrets:_.array(_.string()).max(50).default([]),notes:_.string().default("")}),yp=24e3;function jo(t){for(let e of Po.DEPLOY_DOC_CANDIDATES){let n=Pr.default.join(t,e);try{if(!Is.default.existsSync(n))continue;let r=Is.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>yp?r.slice(0,yp)+`
|
|
986
986
|
|
|
987
|
-
[\u2026document truncated\u2026]`:r}}catch{continue}}return null}var bp=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Sp(t){return
|
|
987
|
+
[\u2026document truncated\u2026]`:r}}catch{continue}}return null}var bp=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Sp(t){return Cv("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function Cv(t,e){try{let n=(0,Co.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function Pv(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=cp();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 Nv(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 jv(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?`
|
|
988
988
|
- absolute paths the document mentions, checked on THIS machine:
|
|
989
989
|
${n.map(s=>` - ${s}: ${Is.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
|
|
990
990
|
`)}`:""}function Tp(t,e,n,r="",s="."){let i=bp.filter(c=>Sp(c)),o=bp.filter(c=>!i.includes(c)),l=Object.keys(Zt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
991
991
|
- available tools: ${i.join(", ")||"(none of the common ones)"}
|
|
992
992
|
- NOT installed: ${o.join(", ")||"(none missing)"}
|
|
993
|
-
- secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Bl()+
|
|
993
|
+
- secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Bl()+jv(r)+ci(s)}async function xp(t){let e=[];if(t.publicUrl?.trim()&&await Nv(t.publicUrl.trim(),e),e.push(Is.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=Pr.default.isAbsolute(t.workdir)?t.workdir:Pr.default.join(t.repoPath,t.workdir);e.push(Is.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=Eo(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=Zt(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=>!Sp(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 Ip(t){let e=Tp(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=en(Po.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((h,f)=>`${f+1}. [${h.name}]${h.continueOnError?" (continues on error)":""}
|
|
994
994
|
${h.run}`).join(`
|
|
995
995
|
`),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let h=Fl(t.errorText,{cwd:t.repoPath});return h?`
|
|
996
996
|
|
|
@@ -998,9 +998,9 @@ THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
|
|
|
998
998
|
- what it means: ${h.cause}
|
|
999
999
|
- what closes it: ${h.commands.join(" ; ")}
|
|
1000
1000
|
- ${h.note}
|
|
1001
|
-
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:fp(pp({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,Jl.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Ep(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?
|
|
1002
|
-
`+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 Ep(t){for(let e of Ov(t)){let n;try{n=JSON.parse(e)}catch{continue}let r
|
|
1003
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}
|
|
1001
|
+
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:fp(pp({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,Jl.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Ep(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?jo(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 Rp(t){let e=jo(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=Tp(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=en(Nr.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,Jl.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Ep(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
1002
|
+
`+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 Ep(t){for(let e of Ov(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=$v.safeParse(Mv(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function Ov(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 Mv(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:wp(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=Wl(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(Wl(c.name,c.title,c.description)??wp(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:Wl(e.notes,e.note,e.explanation)??""}}function Wl(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function wp(t,e){return(t.split(`
|
|
1003
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}Ct();kt();_r();function Oo(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}}}Qt();Lo();var $p=24*3600*1e3,Uo=14,Dv=Uo*24*3600*1e3,Lv=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),qo=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!!Ui(this.cfg,e)}get jiraless(){return qi(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,g.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),g.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),g.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.`}),g.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;g.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(g.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():g.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=Gd(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{g.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Le(this.cfg,n,"assist");if("error"in s){g.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ws({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;g.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else g.warn(`Scheduled audit failed: ${i.error}`)}catch(s){g.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){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){g.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){g.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let C=Date.parse(e.pausedUntil);Number.isFinite(C)&&(this.autopilotPausedUntil=C);return}let n=e.item;if(!n)return;let r=this.rules.find(C=>C.id===n.ruleId&&C.enabled),s=this.projects.find(C=>C.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=Oo(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;g.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(C){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${C instanceof Error?C.message:String(C)}`});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 w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let v=this.resolveClaudeProfile(f.runId,f.claudeProfile),k=!!(n.batchId&&n.branchOverride),x=n.batchId?nc(n.batchId):null,I=!n.continueBranch&&!k?rc(x,n.issueKey):null,P=I?Do(n.batchId,I,n.issueKey):null,J=k&&n.continueBranch?oc(n.batchId):null,W=P??J,b=uc(I,n.issueKey)||k&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await ii({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:v,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...W?{chain:{sessionId:W.sessionId,worktreePath:W.worktreePath}}:{},keepWorktree:b,onChainSession:I?C=>sc(n.batchId,I,n.issueKey,C):k&&b?C=>ac(n.batchId,n.issueKey,C,!!J):void 0}),I&&!Do(n.batchId,I,I[I.indexOf(n.issueKey)+1]??"")&&I.indexOf(n.issueKey)<I.length-1&&ic(n.batchId,I),k&&!lc(n.batchId,n.issueKey)&&cc(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(ti());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let o=ze(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new Ue(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(v){g.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!u)continue;let h={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(u.merged){g.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await oi(h,i.runId,u.headSha)}finally{this.inFlight.delete(l)}continue}if(u.state==="closed"){g.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let v=this.jiraFor(i.repoName),k=`PR #${i.prNumber} was closed on GitHub without merging`;await v.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
1004
1004
|
|
|
1005
1005
|
PR: ${i.prUrl}
|
|
1006
1006
|
|
|
@@ -1022,19 +1022,19 @@ Note: the "${l.jiraTransitionOnMerge}" transition failed: ${w instanceof Error?w
|
|
|
1022
1022
|
|
|
1023
1023
|
PR: ${l.prUrl} (merged at \`${u.headSha.slice(0,10)}\`)${f}
|
|
1024
1024
|
|
|
1025
|
-
(run \`${l.runId}\`)`)}catch(w){g.warn(`could not post merge comment to ${l.issueKey}: ${w instanceof Error?w.message:w}`);continue}g.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),ei(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${Pn.NEEDS_INPUT_LABEL}"`,10)}catch(s){g.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:[Pn.NEEDS_INPUT_LABEL]}).catch(()=>{}),g.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()>Dv){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(k){g.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let u=new Date(l.questionsPostedAt).getTime(),h=o.comments.filter(k=>!Pt(k.body)&&new Date(k.created).getTime()>u);if(!h.length)continue;let f=Ss(h),w=o.attachments;this.inFlight.add(c),g.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[Pn.NEEDS_INPUT_LABEL]}).catch(k=>{g.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:k=>this.findRuleForResume(k)};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Ul(l,f,w,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Ll(l,f,w,v)}finally{this.inFlight.delete(c)}})}}}findRuleForResume(e){let n=this.rules.find(i=>i.id===e),r=n&&this.projects.find(i=>i.id===n.projectId),s=r&&this.cfg.repos[r.repoName]?.path;return n&&r&&s?{rule:n,project:r,repoPath:s}:null}async answerPendingInput(e,n,r){let s
|
|
1025
|
+
(run \`${l.runId}\`)`)}catch(w){g.warn(`could not post merge comment to ${l.issueKey}: ${w instanceof Error?w.message:w}`);continue}g.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),ei(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${Pn.NEEDS_INPUT_LABEL}"`,10)}catch(s){g.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:[Pn.NEEDS_INPUT_LABEL]}).catch(()=>{}),g.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()>Dv){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(k){g.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let u=new Date(l.questionsPostedAt).getTime(),h=o.comments.filter(k=>!Pt(k.body)&&new Date(k.created).getTime()>u);if(!h.length)continue;let f=Ss(h),w=o.attachments;this.inFlight.add(c),g.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[Pn.NEEDS_INPUT_LABEL]}).catch(k=>{g.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:k=>this.findRuleForResume(k)};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Ul(l,f,w,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Ll(l,f,w,v)}finally{this.inFlight.delete(c)}})}}}findRuleForResume(e){let n=this.rules.find(i=>i.id===e),r=n&&this.projects.find(i=>i.id===n.projectId),s=r&&this.cfg.repos[r.repoName]?.path;return n&&r&&s?{rule:n,project:r,repoPath:s}:null}async answerPendingInput(e,n,r){let s=Ch(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}`:""}.**
|
|
1026
1026
|
|
|
1027
1027
|
${n}
|
|
1028
1028
|
|
|
1029
1029
|
This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[Pn.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let w=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${w}`}}g.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,findRule:f=>this.findRuleForResume(f)},h=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(h,async()=>{try{s.kind==="implement"?await Ul(s,c,l,u):await Ll(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){g.warn(`${e.issueKey}: needs-input unanswered for over ${Uo}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
1030
1030
|
|
|
1031
|
-
No reply arrived within ${Uo} 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:[Pn.NEEDS_INPUT_LABEL]})}catch(r){g.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await
|
|
1031
|
+
No reply arrived within ${Uo} 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:[Pn.NEEDS_INPUT_LABEL]})}catch(r){g.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await $t(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 ${Uo} 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=Oo(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"&&g.warn(`claim rejected for ${i.issueKey}: ${h.reason??"unknown"}`);continue}this.inFlight.add(o),g.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 ii({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()-$p;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)||Pt(h.body)||new Date(h.created).getTime()<l||!h.id)continue;let f=`respond:${h.id}`;if(this.inFlight.has(f))continue;let w=Oo(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let v=w.project,k=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!k){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${v.repoName}" but it has no local checkout - run: allwright repo add "${v.repoName}" /path/to/checkout`);continue}let x=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(!x.accepted||!x.runId){x.reason!=="duplicate"&&g.warn(`respond claim rejected for ${c.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(f),g.info(`claimed respond run ${x.runId}: ${c.key} (comment ${h.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let I={author:h.author,body:h.body},P=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(k,async()=>{try{await ii({runId:x.runId,rule:e,project:v,issueKey:c.key,repoPath:k,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:I,claudeConfigDir:P,actorEmail:x.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){g.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)Pt(h.body)&&(c=Math.max(c??0,new Date(h.created).getTime()));if(c===null||!l.comments.some(h=>!Pt(h.body)&&h.body.toLowerCase().includes(i)&&new Date(h.created).getTime()>c))continue;await this.jiraOf(n).editLabels(o.key,{remove:[r.doneLabel]}),g.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(l){g.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.**
|
|
1032
1032
|
|
|
1033
1033
|
${l.reason}`+(i.requestedByAccountId?`
|
|
1034
1034
|
|
|
1035
1035
|
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
1036
1036
|
|
|
1037
|
-
(run \`${l.runId}\`)`).catch(u=>g.warn(`could not post refusal to ${i.issueKey}: ${u}`)),g.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),g.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await
|
|
1037
|
+
(run \`${l.runId}\`)`).catch(u=>g.warn(`could not post refusal to ${i.issueKey}: ${u}`)),g.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),g.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await No({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()-$p,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 w=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&w.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let v of w.comments){if(!v.body.toLowerCase().includes(o)||Pt(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let k=s.envSelection==="fixed"?u:Uv(v.body,r.keyword,c);h.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(k?` \u2192 ${k}`:"")})}}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}", "${Pn.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}", "${Pn.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)&&!Pt(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=>{g.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(n,i)}};function Uv(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(!Lv.has(o.toLowerCase()))return o;return""}var Cp=E(require("node:fs"),1),Pp=E(require("node:path"),1),hc=require("node:crypto");Ct();var qv=`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.
|
|
1038
1038
|
|
|
1039
1039
|
Rules:
|
|
1040
1040
|
- Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
|
|
@@ -1043,10 +1043,10 @@ Rules:
|
|
|
1043
1043
|
- When you are done, every listed file must contain no conflict markers and must be syntactically valid.
|
|
1044
1044
|
|
|
1045
1045
|
Conflicted files:
|
|
1046
|
-
`;async function
|
|
1047
|
-
`),timeoutSeconds:t.timeoutSeconds,bin:Xe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,hc.randomUUID)(),onLog:(
|
|
1046
|
+
`;async function Np(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Pp.default.join(Xt(),`conflict-${(0,hc.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Js(n,l,r),c=!0;let u=await el(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 k=u.conflicts;o("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let x=Ye(t.agentId);if(!x)return await En(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let I=Cn(t.agentId,"edit_no_shell");if(I)return await En(l),{ok:!1,note:`${I} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let P=-1,J=setInterval(()=>{nl(l,k).then(C=>{let H=k.filter($=>!C.includes($));H.length!==P&&(P=H.length,o("info",`Conflict progress: ${H.length}/${k.length} resolved`+(H.length?` \xB7 clean: ${H.join(", ")}`:"")+(C.length?` \xB7 still conflicted: ${C.join(", ")}`:"")))}).catch(()=>{})},12e3),W=await si(x,{repoPath:l,prompt:qv+k.map(C=>`- ${C}`).join(`
|
|
1047
|
+
`),timeoutSeconds:t.timeoutSeconds,bin:Xe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,hc.randomUUID)(),onLog:(C,H)=>o(C,H)},(C,H)=>o(C==="warn"?"warn":C,H));if(clearInterval(J),h={costUsd:W.costUsd,inputTokens:W.inputTokens,outputTokens:W.outputTokens},!W.ok)return await En(l),{ok:!1,...h,note:`The agent could not do the resolution: ${W.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let b=await ao(l);if(b.length)return await En(l),{ok:!1,...h,note:`The agent left conflict markers in ${b.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 tl(l,`${i}: merge ${s}, conflicts resolved by the agent
|
|
1048
1048
|
|
|
1049
|
-
Resolved via Allwright`)}let w=await Rn(l,s);if(!w.ok){let k=w.forbidden.length?`the merged result touches protected paths (${w.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${w.files} files, ${w.insertions+w.deletions} lines; limits ${Tn}/${xn})`;return await En(l),{ok:!1,...h,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await vr(l,r);let v=await Je(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...h,freeOfCharge:!f,headSha:v,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 En(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await
|
|
1049
|
+
Resolved via Allwright`)}let w=await Rn(l,s);if(!w.ok){let k=w.forbidden.length?`the merged result touches protected paths (${w.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${w.files} files, ${w.insertions+w.deletions} lines; limits ${Tn}/${xn})`;return await En(l),{ok:!1,...h,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await vr(l,r);let v=await Je(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...h,freeOfCharge:!f,headSha:v,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 En(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await $t(n,l).catch(()=>{}),Cp.default.rmSync(l,{recursive:!0,force:!0}))}}var pc=E(require("node:fs"),1),jp=E(require("node:path"),1),fc=require("node:crypto");Ct();function Fv(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
|
|
1050
1050
|
${r.tail.slice(-2e3)}`).join(`
|
|
1051
1051
|
|
|
1052
1052
|
`);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:
|
|
@@ -1059,17 +1059,17 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
|
|
|
1059
1059
|
- 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.
|
|
1060
1060
|
- Do not ask questions; if you cannot fix something safely, say what you found and stop.
|
|
1061
1061
|
- You have no shell; the runner re-runs every documented command after you finish.
|
|
1062
|
-
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Op(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=
|
|
1062
|
+
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Op(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=jp.default.join(Xt(),`testfix-${(0,fc.randomUUID)().slice(0,8)}`),u=!1;try{let h=Ye(t.agentId);if(!h)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Cn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await In(n,r),await Js(n,c,r),u=!0,await hs(c,`origin/${r}`);let w=await Je(c);l("info",`Asking ${h.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await si(h,{repoPath:c,prompt:Fv(i,o),timeoutSeconds:t.timeoutSeconds,bin:Xe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,fc.randomUUID)(),onLog:($,q)=>l($,q)},($,q)=>l($==="warn"?"warn":$,q)),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,...k,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await ds(c);for(let $ of x.refused)l("warn",`${Yt} entry refused: ${$}`);let I=!0;try{await wr(c,`${i}: fix failing TEST.md commands
|
|
1063
1063
|
|
|
1064
|
-
Allwright test-fix run`)}catch{I=!1}if(!I){let
|
|
1065
|
-
${d.tail.slice(-1500)}`));J=q.filter(d=>d.exitCode!==0).slice(0,20).map(d=>({command:d.command.slice(0,500),exitCode:d.exitCode,tail:d.tail.slice(-4e3)})),b=q.length,W=q.length-J.length}}await vr(c,r);let
|
|
1066
|
-
`,{mode:384}),
|
|
1064
|
+
Allwright test-fix run`)}catch{I=!1}if(!I){let $=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",$),{ok:!0,...k,remaining:o,note:$}}let P=await Rn(c,s);if(!P.ok){await hs(c,w);let $=P.forbidden.length?`the fixed result touches protected paths (${P.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${P.files} files, ${P.insertions+P.deletions} lines; limits ${Tn}/${xn})`;return{ok:!1,...k,note:`Nothing was pushed: ${$}. The fix commit was discarded; the PR is unchanged.`}}let J=o,W,b,C=ys(c);if(C){let $=bs(pc.default.readFileSync(C,"utf8"));if($.length){l("info",`Re-running ${$.length} documented test command(s)`);let q=await Sr(c,$,{perCommandTimeoutMs:15*6e4});for(let d of q)l(d.exitCode===0?"info":"warn",`${d.exitCode===0?"PASS":"FAIL"} ${d.command} (exit ${d.exitCode})`+(d.exitCode===0?"":`
|
|
1065
|
+
${d.tail.slice(-1500)}`));J=q.filter(d=>d.exitCode!==0).slice(0,20).map(d=>({command:d.command.slice(0,500),exitCode:d.exitCode,tail:d.tail.slice(-4e3)})),b=q.length,W=q.length-J.length}}await vr(c,r);let H=await Je(c);return l("info",`Pushed the fix to ${r} (${H.slice(0,7)})`),{ok:!0,...k,headSha:H,remaining:J,testsPassed:W,testsTotal:b,note:J.length?`The fix was pushed, but ${J.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 $t(n,c).catch(()=>{}),pc.default.rmSync(c,{recursive:!0,force:!0}))}}kt();var jr=E(require("node:fs"),1),zp=E(require("node:path"),1);Qr();$e();var Bv=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([]),at:_.string().default(""),ms:_.number().int().nonnegative().default(0)}),Hv=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(Bv).default([])}),Kv=_.record(Hv),Gv=10,Zv=200,Mp=2e4,Wv=30,Vv=2e3,Jv=8,Yv=255;function Dp(){return zp.default.join(le(),"chat-sessions.json")}function mc(){let t=Dp();if(!jr.default.existsSync(t))return{};try{return Kv.parse(JSON.parse(jr.default.readFileSync(t,"utf8")))}catch{return{}}}function Xv(t){jr.default.mkdirSync(le(),{recursive:!0,mode:448});let e=Dp(),n=e+".tmp";jr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
1066
|
+
`,{mode:384}),jr.default.renameSync(n,e),jr.default.chmodSync(e,384)}function Lp(t,e,n,r,s=[],i=[],o={}){let l=mc(),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,Mp),steps:[],files:i.slice(0,Jv).map(f=>f.slice(0,Yv)),at:o.askedAt||new Date().toISOString(),ms:0},{role:"agent",text:r.slice(0,Mp),steps:s.slice(0,Wv).map(f=>f.slice(0,Vv)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0))}),u.messages=u.messages.slice(-Zv),u.updatedAt=new Date().toISOString(),l[e]=u;let h=Object.values(l).filter(f=>f.projectId===u.projectId).sort((f,w)=>w.updatedAt.localeCompare(f.updatedAt));for(let f of h.slice(Gv))delete l[f.sessionId];Xv(l)}function Up(t){return Object.values(mc()).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 di(t){return mc()[t]??null}Qt();var qp=36,Fp=60;function Bp(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 Qv=`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:
|
|
1067
1067
|
Goal: what the user is trying to achieve.
|
|
1068
1068
|
Decided: choices already made, including ones you talked them out of - each as one line.
|
|
1069
1069
|
Constraints: rules, preferences and corrections the user gave you.
|
|
1070
1070
|
Repo facts: what you learned about this codebase that is worth not re-reading.
|
|
1071
1071
|
Open: what is still unresolved right now.
|
|
1072
|
-
Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function
|
|
1072
|
+
Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function Hp(t,e,n){if(!di(e))return null;let s=Le(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:Qv,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 g.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var Kp=`
|
|
1073
1073
|
|
|
1074
1074
|
TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
|
|
1075
1075
|
1. When you ASK the user something and the sensible answers are countable, end with:
|
|
@@ -1082,12 +1082,12 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
|
|
|
1082
1082
|
["\u2026", "\u2026"]
|
|
1083
1083
|
\`\`\`
|
|
1084
1084
|
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.
|
|
1085
|
-
Never emit both blocks in one reply, and never let either replace the actual answer.`;var Or=E(require("node:fs"),1),pt=E(require("node:path"),1),gc=300,ek=4,Gp=512*1024,tk=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Zp=/\.mdx?$/i;function Wp(t){let e=pt.default.resolve(t),n=[],r=(s,i)=>{if(i>ek||n.length>=gc)return;let o;try{o=Or.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=gc)return;if(!l.isFile()||!Zp.test(l.name))continue;let c=pt.default.join(s,l.name);try{let u=Or.default.statSync(c);n.push({path:pt.default.relative(e,c).split(pt.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=gc)return;!l.isDirectory()||l.isSymbolicLink()||tk.has(l.name)||l.name.startsWith(".")||r(pt.default.join(s,l.name),i+1)}};return r(e,0),n}function Vp(t,e){let n=pt.default.resolve(t);if(!Zp.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=pt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+pt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Or.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Or.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+pt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Or.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=Or.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>Gp;return{ok:!0,path:pt.default.relative(i,s).split(pt.default.sep).join("/"),content:c?l.slice(0,Gp):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var
|
|
1086
|
-
`).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_=E(Yf(),1),C_=E(Yo(),1),$_=E(Cs(),1),P_=E(Ac(),1),j_=E(Pc(),1),N_=E(Dc(),1),om=E(ta(),1),O_=E(im(),1);var Uc=om.default;var wi=E(require("node:crypto"),1),Dt=E(Te(),1);Qt();function M_(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function qc(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 z_(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=Dt.ProjectConfig.safeParse(l);c.success?r.push(c.data):qc(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Dt.RuleConfig.safeParse(l);c.success?s.push(c.data):qc(n,"rule",M_(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Dt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):qc(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 D_=2e4,L_=6e4,U_=5e3,ra=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===Uc.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new Uc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Dt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let 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()})},D_)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){g.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Dt.parseServerMsg)(r)}catch(i){let o=z_(r);if(!o){g.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)g.warn(l);g.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)g.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){g.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);g.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,L_)}),e.on("error",n=>{g.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,g.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let 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>=U_){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=wi.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=wi.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:wi.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=wi.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})}sendRunContext(e){this.send({type:"run.context",runId:e.runId,pieces:e.pieces.slice(0,30),totalChars:e.totalChars,sessionMode:e.sessionMode})}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 sa=E(require("node:fs"),1),Ms=E(require("node:path"),1),Fc=require("node:child_process"),q_=/\.mdx?$/i,am=6,F_=/^[\w.\- ()]+$/;function B_(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ms.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!q_.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>am)return{ok:!1,error:`path deeper than ${am} levels`};for(let o of r)if(o==="."||o===".."||!F_.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ms.default.resolve(t),i=Ms.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ms.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Bc(t){let e=B_(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(sa.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};sa.default.mkdirSync(Ms.default.dirname(e.abs),{recursive:!0}),sa.default.writeFileSync(e.abs,t.content.endsWith(`
|
|
1085
|
+
Never emit both blocks in one reply, and never let either replace the actual answer.`;var Or=E(require("node:fs"),1),pt=E(require("node:path"),1),gc=300,ek=4,Gp=512*1024,tk=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Zp=/\.mdx?$/i;function Wp(t){let e=pt.default.resolve(t),n=[],r=(s,i)=>{if(i>ek||n.length>=gc)return;let o;try{o=Or.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=gc)return;if(!l.isFile()||!Zp.test(l.name))continue;let c=pt.default.join(s,l.name);try{let u=Or.default.statSync(c);n.push({path:pt.default.relative(e,c).split(pt.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=gc)return;!l.isDirectory()||l.isSymbolicLink()||tk.has(l.name)||l.name.startsWith(".")||r(pt.default.join(s,l.name),i+1)}};return r(e,0),n}function Vp(t,e){let n=pt.default.resolve(t);if(!Zp.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=pt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+pt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Or.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Or.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+pt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Or.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=Or.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>Gp;return{ok:!0,path:pt.default.relative(i,s).split(pt.default.sep).join("/"),content:c?l.slice(0,Gp):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Ke=E(Te(),1);var Fo=E(require("node:fs"),1),Jp=E(require("node:path"),1);Qr();$e();var nk=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),rk=_.array(nk);function Yp(){return Jp.default.join(le(),"synced-projects.json")}function Xp(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));Fo.default.mkdirSync(le(),{recursive:!0}),Fo.default.writeFileSync(Yp(),JSON.stringify(e,null,2),{mode:384})}catch{}}function sk(){try{let t=rk.safeParse(JSON.parse(Fo.default.readFileSync(Yp(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Qp(t){return sk().find(e=>e.repoName===t)??null}var bc=E(require("node:fs"),1),Mr=E(require("node:path"),1),ef=require("node:child_process"),zr=E(Te(),1);$e();var ik=15e4,yc=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function ok(t){let e=Mr.default.join(t,"node_modules",".bin","prisma");return bc.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function ak(t,e){if(!(0,zr.isSelfMigrationFilename)(e))return null;let n=Mr.default.join(t,zr.SELF_MIGRATION_DIR),r=Mr.default.resolve(n,e),s=Mr.default.relative(n,r);return s!==e||s.startsWith("..")||Mr.default.isAbsolute(s)?null:r}async function tf(t){let{file:e}=t,n=ak(t.repoPath,e);if(!n)return yc(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!bc.default.existsSync(n))return yc(e,{name:"file",ok:!1,detail:`${zr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${zr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Zt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return yc(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=Mr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=ok(i),c=Xl([s]),u=await lk(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:`${zr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:h,error:""}}function lk(t,e,n){return new Promise(r=>{(0,ef.execFile)(t,e,{cwd:n,timeout:ik,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
|
|
1086
|
+
`).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_=E(Yf(),1),$_=E(Yo(),1),C_=E($s(),1),P_=E(Ac(),1),N_=E(Pc(),1),j_=E(Dc(),1),om=E(ta(),1),O_=E(im(),1);var Uc=om.default;var wi=E(require("node:crypto"),1),Dt=E(Te(),1);Qt();function M_(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function qc(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 z_(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=Dt.ProjectConfig.safeParse(l);c.success?r.push(c.data):qc(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Dt.RuleConfig.safeParse(l);c.success?s.push(c.data):qc(n,"rule",M_(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Dt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):qc(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 D_=2e4,L_=6e4,U_=5e3,ra=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===Uc.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new Uc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Dt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let 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()})},D_)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){g.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Dt.parseServerMsg)(r)}catch(i){let o=z_(r);if(!o){g.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)g.warn(l);g.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)g.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){g.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);g.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,L_)}),e.on("error",n=>{g.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,g.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let 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>=U_){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=wi.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=wi.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:wi.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=wi.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,outputTruncated:n.outputTruncated??!1,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})}sendRunContext(e){this.send({type:"run.context",runId:e.runId,pieces:e.pieces.slice(0,30),totalChars:e.totalChars,sessionMode:e.sessionMode})}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 sa=E(require("node:fs"),1),Ms=E(require("node:path"),1),Fc=require("node:child_process"),q_=/\.mdx?$/i,am=6,F_=/^[\w.\- ()]+$/;function B_(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ms.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!q_.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>am)return{ok:!1,error:`path deeper than ${am} levels`};for(let o of r)if(o==="."||o===".."||!F_.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ms.default.resolve(t),i=Ms.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ms.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Bc(t){let e=B_(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(sa.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};sa.default.mkdirSync(Ms.default.dirname(e.abs),{recursive:!0}),sa.default.writeFileSync(e.abs,t.content.endsWith(`
|
|
1087
1087
|
`)?t.content:t.content+`
|
|
1088
|
-
`);let n=i=>new Promise((o,l)=>{(0,Fc.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,Fc.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 Br=E(require("node:fs"),1),Kc=E(require("node:path"),1),ia=require("node:child_process"),cm=require("node:util");Ce();_r();$t();var um=E(Te(),1),lm=(0,cm.promisify)(ia.execFile);function K_(t){try{return new URL(t).host}catch{return t}}function H_(t){try{return(0,ia.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function oa(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=K_(o.baseUrl),w=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 ${w} 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 v=new Me(o);try{let k=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${w})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${vi(x)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${vi(k)}`})}}}let c=t.repos[e.repoName];if(c&&Br.default.existsSync(c.path)){let f=Kc.default.join(c.path,"CLAUDE.md"),w=Br.default.existsSync(f)&&Br.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:w,detail:w?"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.",...w?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let v=No(c.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!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(!Br.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Br.default.existsSync(Kc.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 w=Xe(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await lm(w,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:v,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${vi(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 lm("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: ${vi(f)}`})}let h=ze(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 ${um.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(),xr)),w=new f(h),v=await w.whoami(),k=c&&Br.default.existsSync(c.path)?H_(c.path):null,x=k?wt(k):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let I=await w.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:I.ok&&I.canPush,detail:I.ok?I.canPush?`${v} has push access to ${x.owner}/${x.repo}`:`${v} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${x.owner}/${x.repo}: ${I.error}`,...I.ok&&I.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:vi(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 w=Zt(t,e.repoName,f.name),v=f.requiredSecrets.filter(k=>!w[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function vi(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Qt();Ao();Lo();Vc();var Ee=new mu;Ee.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(to);function Om(t){g.info(`Create the token at ${He.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of He.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(He.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${t}.`)}Ee.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",Ri.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=zn.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=Td(t),o=i==="skip";i==="offer-skip"&&(g.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=xd(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=$a.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new Me(c.jira).myself();g.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await hd(c,s),g.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),g.info(`Credentials saved to ${Gt()} (mode 600, this machine only)`),c.jira||g.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)."),g.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Xc=Ee.command("repo").description("Map control-plane repo names to local checkouts");Xc.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=ue(),s=cn.default.resolve(e.replace(/^~(?=\/|$)/,Ri.default.homedir()));if(!n.force){if(!rt.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(!rt.default.existsSync(cn.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},be(r),g.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>($t(),vd));g.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{g.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}un()||g.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.`)});Xc.command("list").description("Show configured repo mappings").action(()=>{let t=ue(),e=Object.entries(t.repos);if(!e.length)return g.info("no repos mapped yet");for(let[n,r]of e)g.info(`${n} -> ${r.path}`)});var Mm=Ee.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Mm.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=ue(),n=e.claudeProfiles[t]?.configDir??`${Gt().replace(/runner\.json$/,"")}claude-profiles/${t}`;rt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},be(e),g.info(`profile "${t}" -> ${n}`),g.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),g.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,dn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),g.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),un()});Mm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ue(),e=Object.entries(t.claudeProfiles);if(g.info("default: this OS user's own Claude login (no profile)"),!e.length)return g.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=rt.default.existsSync(r.configDir)&&rt.default.readdirSync(r.configDir).length>0;g.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Xc.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=ue();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),be(e),g.info(`Removed "${t}" (was ${n})`),r.length&&g.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&g.info("Also removed its audit schedule(s)"),g.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),g.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Qc=Ee.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Qc.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){g.info(`
|
|
1089
|
-
`+cl(ll()));return}Cd(g)});Qc.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(()=>$d(g));Qc.command("status").description("systemctl status for the runner service").action(()=>{(0,dn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Ee.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{g.info("Updating: npm install -g allwright@latest");let t=(0,dn.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)}),g.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Ds=Ee.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ds.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=ue();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=Qp(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 Me(l).myself();if(e.repos[t].jira=l,be(e),g.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 Me(l).search(`project = "${n.jiraProjectKey}"`,1),g.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{g.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.`)}un();return}catch{g.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=zn.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 w={baseUrl:c,email:h,apiToken:f},v=await new Me(w).myself();g.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=w,be(e),g.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),un()}finally{o.close()}});Ds.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=ue(),e=zn.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 Me(l).myself();t.jira=l,be(t),g.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),g.info(`Saved to ${Gt()} (mode 600, this machine only). Repo overrides are untouched.`),un()}finally{e.close()}});Ds.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ue();g.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))g.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Ds.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=zn.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 Me({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();g.info(`${u.baseUrl}: OK - authenticated as ${h.displayName}`),c=!0}catch{g.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},be(e),g.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Ds.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ue(),e=Object.entries(t.jiraUsers);if(!e.length)return g.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)g.info(`${n} -> posts to Jira as ${r.email}`)});Ds.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],be(e),g.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Ls=Ee.command("github").description("GitHub credential for implement-mode rules");Ls.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=zn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Om("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(),xr)),s=await new r(n).whoami(),i=ue();i.github={token:n,login:s},be(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${Gt()} (mode 600, this machine only)`)}finally{e.close()}});Ls.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=ue();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&&rt.default.existsSync(r))try{let i=(0,dn.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(),xr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let h=await c.whoami();g.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.`),g.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=zn.default.createInterface({input:process.stdin,output:process.stdout});try{Om(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){g.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(),xr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},be(e),g.info(`GitHub token OK - authenticated as ${l}`),g.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Ls.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=zn.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(),xr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},be(e),g.info(`GitHub token OK - authenticated as ${o}`),g.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});Ls.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ue(),e=Object.entries(t.githubUsers);if(!e.length)return g.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)g.info(`${n} -> own GitHub token stored`)});Ls.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],be(e),g.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Ls.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ue();g.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))g.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);g.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var eu=Ee.command("audit").description("Recurring specialist audits on this runner");eu.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=ue();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}],be(r),g.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});eu.command("schedules").description("List scheduled audits").action(()=>{let t=ue();if(!t.auditSchedules.length)return g.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)g.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});eu.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ue(),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");be(n),g.info("Removed. Restart the runner to apply.")});var tu=Ee.command("deploy").description("Deployment settings for this machine");tu.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=ue();t.deploy={enabled:!0},be(t),g.info("deployments ENABLED on this runner"),g.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),un()});tu.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ue();t.deploy={enabled:!1},be(t),g.info("deployments DISABLED on this runner"),un()});tu.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ue();g.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return g.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);g.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var la=Ee.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");la.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=ue(),s=Li(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,be(r),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${Gt()} (mode 600, this machine only)`),un()});la.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a proxy site block when --url is given - Caddy or nginx, whichever is RUNNING on this machine (it never installs a second proxy). 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 proxy").option("--proxy <proxy>","caddy | nginx | none (default: detect the running one; a flag that contradicts the running proxy is refused - two proxies cannot share :80/:443)").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=ue().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(()=>(Rm(),Im));await o({repoName:t,envName:e,dir:cn.default.resolve(i.replace(/^~(?=\/|$)/,Ri.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});la.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ue(),s=Li(t,e),i=r.environments[s];if(!i)return g.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,be(r),g.info(`removed ${n.join(", ")} from ${s}`)});la.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ue(),e=Object.entries(t.environments);if(!e.length)return g.info("no environment secrets stored");for(let[n,r]of e)g.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Ee.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=$u(t);g.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),g.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),g.info(`Restore on any machine with: allwright import ${cn.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Ee.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=er();if(e&&tr(e)){g.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=Pu(t);g.info(`Restored ${n.restored.length} entries into ${le()}`),n.previousDir&&g.info(`Previous config kept at ${n.previousDir}`),g.info("Start the runner and it will reconnect with the restored identity.")}catch(n){g.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Ee.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ue(),e=Object.keys(t.repos),n=qi(t);n&&g.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 oa(t,i),l=!Ui(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||g.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?g.info:g.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function un(){let t=er()??rs();if(t&&tr(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),g.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?Uu(t):null;return g.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 iS(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Lu();e.ok||(g.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Na);let n=t.jira?new Me(t.jira):ol(),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let y=r.get(d);return y||(y=new Me(m),r.set(d,y)),y},i=new Map,o=(d,m)=>{let y=Sd(ke()??t,d,m);switch(y.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:y.error};case"user":{let R=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,j=i.get(R);return j||(j=new Me(y.creds),i.set(R,j)),{jira:j,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],h=[],f,w=null,v={cfg:t,jiraFor:s,transport:null},k=new Set,x=async(d,m,y)=>{if(!(m.length<2))for(let R=0;R<m.length;R++){let{text:j,changed:G}=Rd(y[R]??"",m);G&&await d.updateDescription(m[R],j).then(()=>g.info(`Compose: rewrote sibling ticket refs in ${m[R]} to real keys`)).catch(L=>g.warn(`Compose: could not rewrite refs in ${m[R]}: ${L instanceof Error?L.message:L}`))}},I=d=>{let m=c.find(R=>R.id===d),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},P=d=>{let m=c.find(j=>j.id===d),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${y} 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`${y} 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`},J={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(d,m)=>{let y=I(d),R=h.find(j=>j.projectId===d&&j.name===m);return y&&R?{...y,environment:R}:null}},W=new Map,b=new ra(l.toString(),t.runnerToken,{runnerVersion:to},{onConfig:d=>{c=d.projects,Xp(d.projects),u=d.rules,h=d.environments,lp(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=I(d.projectId);if(!m){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let y=Le(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let R=await Ip({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});b.sendDeploySuggestResult(d.requestId,R)},onProjectTest:async d=>{let m=c.find(R=>R.id===d.projectId);if(!m){b.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}g.info(`running connection test for project "${m.name}"`);let y=await oa(ke()??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));b.sendProjectTestResult(d.requestId,y.every(R=>R.ok),y)},onRuleDiagnose:async d=>{let m=u.find(U=>U.id===d.ruleId),y=m&&c.find(U=>U.id===m.projectId);if(!m||!y){b.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}g.info(`diagnosing rule "${m.name}"`);let R=await oa(ke()??t,y,m.action.type==="deploy"?h.filter(U=>U.projectId===y.id):[]),j=m.action.type==="implement"?R:R.filter(U=>U.name!=="github-token"),{matchedCount:G,excludedCount:L,excludedSample:Z}=await f.diagnoseRule(m,y);b.sendRuleDiagnoseResult(d.requestId,{checks:j,matchedCount:G,excludedCount:L,excludedSample:Z})},onCancel:d=>{zh(d)?g.info(`run ${d} stopped from the dashboard`):g.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(Ql(d)){kp(J,d).catch(y=>g.error(`deploy approval crashed for ${d}: ${y instanceof Error?y.stack:y}`));return}oi(v,d,m).catch(y=>g.error(`approval handling crashed for ${d}: ${y instanceof Error?y.stack:y}`))},onRetryPush:d=>{let m=ko(d),y=()=>Zh(v,d).catch(R=>g.error(`retry push crashed for ${d}: ${R instanceof Error?R.stack:R}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:d=>{if(Ql(d)){_p(J,d).catch(m=>g.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Gh(v,d).catch(m=>g.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 y=I(d.projectId);if(!y){let R=P(d.projectId);g.error(`deploy ${d.runId}: ${R}`),b.send({type:"run.status",runId:d.runId,status:"failed",error:R});return}g.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>jo({runId:d.runId,project:y.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:b,requestedBy:d.requestedBy}).catch(R=>g.error(`deploy crashed for ${d.runId}: ${R instanceof Error?R.stack:R}`)))},onDeploySuggest:async d=>{let m=I(d.projectId);if(!m){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let y=Le(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`asking ${y.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let R=await Rp({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});b.sendDeploySuggestResult(d.requestId,R)},onEnvPreflight:async d=>{let m=I(d.projectId);if(!m){b.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await xp({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});b.sendEnvPreflightResult(d.requestId,y)},onSelfMigrationApply:async d=>{let m=I(d.projectId);if(!m){b.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:P(d.projectId)});return}g.info(`applying migration ${d.file} for "${d.environmentName}"`);let y=await tf({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});g.info(y.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${y.error}`),b.sendSelfMigrationApplyResult(d.requestId,y)},onAutopilotPlan:async d=>{try{let m=I(d.projectId);if(!m){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:P(d.projectId)});return}let y=s(m.project.repoName),R=[];for(let z of d.issueKeys)try{let ee=await y.getIssue(z);R.push(`${z}: ${ee.summary}
|
|
1090
|
-
${(ee.description||"").slice(0,500)}`)}catch{R.push(`${z}: (could not read from Jira)`)}let
|
|
1088
|
+
`);let n=i=>new Promise((o,l)=>{(0,Fc.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,Fc.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 Br=E(require("node:fs"),1),Hc=E(require("node:path"),1),ia=require("node:child_process"),cm=require("node:util");$e();_r();Ct();var um=E(Te(),1),lm=(0,cm.promisify)(ia.execFile);function H_(t){try{return new URL(t).host}catch{return t}}function K_(t){try{return(0,ia.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function oa(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),w=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 ${w} 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 v=new Me(o);try{let k=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${w})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${vi(x)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${vi(k)}`})}}}let c=t.repos[e.repoName];if(c&&Br.default.existsSync(c.path)){let f=Hc.default.join(c.path,"CLAUDE.md"),w=Br.default.existsSync(f)&&Br.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:w,detail:w?"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.",...w?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let v=jo(c.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!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(!Br.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Br.default.existsSync(Hc.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 w=Xe(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await lm(w,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:v,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${vi(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 lm("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: ${vi(f)}`})}let h=ze(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 ${um.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(),xr)),w=new f(h),v=await w.whoami(),k=c&&Br.default.existsSync(c.path)?K_(c.path):null,x=k?wt(k):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let I=await w.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:I.ok&&I.canPush,detail:I.ok?I.canPush?`${v} has push access to ${x.owner}/${x.repo}`:`${v} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${x.owner}/${x.repo}: ${I.error}`,...I.ok&&I.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:vi(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 w=Zt(t,e.repoName,f.name),v=f.requiredSecrets.filter(k=>!w[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function vi(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Qt();Ao();Lo();Vc();var Ee=new mu;Ee.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(to);function Om(t){g.info(`Create the token at ${Ke.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Ke.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(Ke.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${t}.`)}Ee.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",Ri.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=zn.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=Td(t),o=i==="skip";i==="offer-skip"&&(g.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=xd(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=Ca.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new Me(c.jira).myself();g.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await hd(c,s),g.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),g.info(`Credentials saved to ${Gt()} (mode 600, this machine only)`),c.jira||g.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)."),g.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Xc=Ee.command("repo").description("Map control-plane repo names to local checkouts");Xc.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=ue(),s=cn.default.resolve(e.replace(/^~(?=\/|$)/,Ri.default.homedir()));if(!n.force){if(!rt.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(!rt.default.existsSync(cn.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},be(r),g.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Ct(),vd));g.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{g.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}un()||g.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.`)});Xc.command("list").description("Show configured repo mappings").action(()=>{let t=ue(),e=Object.entries(t.repos);if(!e.length)return g.info("no repos mapped yet");for(let[n,r]of e)g.info(`${n} -> ${r.path}`)});var Mm=Ee.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Mm.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=ue(),n=e.claudeProfiles[t]?.configDir??`${Gt().replace(/runner\.json$/,"")}claude-profiles/${t}`;rt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},be(e),g.info(`profile "${t}" -> ${n}`),g.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),g.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,dn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),g.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),un()});Mm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ue(),e=Object.entries(t.claudeProfiles);if(g.info("default: this OS user's own Claude login (no profile)"),!e.length)return g.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=rt.default.existsSync(r.configDir)&&rt.default.readdirSync(r.configDir).length>0;g.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Xc.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=ue();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),be(e),g.info(`Removed "${t}" (was ${n})`),r.length&&g.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&g.info("Also removed its audit schedule(s)"),g.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),g.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Qc=Ee.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Qc.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){g.info(`
|
|
1089
|
+
`+cl(ll()));return}$d(g)});Qc.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(()=>Cd(g));Qc.command("status").description("systemctl status for the runner service").action(()=>{(0,dn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Ee.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{g.info("Updating: npm install -g allwright@latest");let t=(0,dn.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)}),g.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Ds=Ee.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ds.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=ue();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=Qp(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 Me(l).myself();if(e.repos[t].jira=l,be(e),g.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 Me(l).search(`project = "${n.jiraProjectKey}"`,1),g.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{g.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.`)}un();return}catch{g.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=zn.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 w={baseUrl:c,email:h,apiToken:f},v=await new Me(w).myself();g.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=w,be(e),g.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),un()}finally{o.close()}});Ds.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=ue(),e=zn.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 Me(l).myself();t.jira=l,be(t),g.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),g.info(`Saved to ${Gt()} (mode 600, this machine only). Repo overrides are untouched.`),un()}finally{e.close()}});Ds.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ue();g.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))g.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Ds.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=zn.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 Me({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();g.info(`${u.baseUrl}: OK - authenticated as ${h.displayName}`),c=!0}catch{g.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},be(e),g.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Ds.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ue(),e=Object.entries(t.jiraUsers);if(!e.length)return g.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)g.info(`${n} -> posts to Jira as ${r.email}`)});Ds.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],be(e),g.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Ls=Ee.command("github").description("GitHub credential for implement-mode rules");Ls.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=zn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Om("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(),xr)),s=await new r(n).whoami(),i=ue();i.github={token:n,login:s},be(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${Gt()} (mode 600, this machine only)`)}finally{e.close()}});Ls.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=ue();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&&rt.default.existsSync(r))try{let i=(0,dn.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(),xr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let h=await c.whoami();g.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.`),g.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=zn.default.createInterface({input:process.stdin,output:process.stdout});try{Om(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){g.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(),xr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},be(e),g.info(`GitHub token OK - authenticated as ${l}`),g.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Ls.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=zn.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(),xr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},be(e),g.info(`GitHub token OK - authenticated as ${o}`),g.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});Ls.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ue(),e=Object.entries(t.githubUsers);if(!e.length)return g.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)g.info(`${n} -> own GitHub token stored`)});Ls.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],be(e),g.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Ls.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ue();g.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))g.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);g.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var eu=Ee.command("audit").description("Recurring specialist audits on this runner");eu.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=ue();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}],be(r),g.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});eu.command("schedules").description("List scheduled audits").action(()=>{let t=ue();if(!t.auditSchedules.length)return g.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)g.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});eu.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ue(),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");be(n),g.info("Removed. Restart the runner to apply.")});var tu=Ee.command("deploy").description("Deployment settings for this machine");tu.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=ue();t.deploy={enabled:!0},be(t),g.info("deployments ENABLED on this runner"),g.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),un()});tu.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ue();t.deploy={enabled:!1},be(t),g.info("deployments DISABLED on this runner"),un()});tu.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ue();g.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return g.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);g.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var la=Ee.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");la.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=ue(),s=Li(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,be(r),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${Gt()} (mode 600, this machine only)`),un()});la.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a proxy site block when --url is given - Caddy or nginx, whichever is RUNNING on this machine (it never installs a second proxy). 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 proxy").option("--proxy <proxy>","caddy | nginx | none (default: detect the running one; a flag that contradicts the running proxy is refused - two proxies cannot share :80/:443)").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=ue().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(()=>(Rm(),Im));await o({repoName:t,envName:e,dir:cn.default.resolve(i.replace(/^~(?=\/|$)/,Ri.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});la.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ue(),s=Li(t,e),i=r.environments[s];if(!i)return g.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,be(r),g.info(`removed ${n.join(", ")} from ${s}`)});la.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ue(),e=Object.entries(t.environments);if(!e.length)return g.info("no environment secrets stored");for(let[n,r]of e)g.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Ee.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=Cu(t);g.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),g.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),g.info(`Restore on any machine with: allwright import ${cn.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Ee.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=er();if(e&&tr(e)){g.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=Pu(t);g.info(`Restored ${n.restored.length} entries into ${le()}`),n.previousDir&&g.info(`Previous config kept at ${n.previousDir}`),g.info("Start the runner and it will reconnect with the restored identity.")}catch(n){g.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Ee.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ue(),e=Object.keys(t.repos),n=qi(t);n&&g.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 oa(t,i),l=!Ui(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||g.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?g.info:g.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function un(){let t=er()??rs();if(t&&tr(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),g.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?Uu(t):null;return g.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 iS(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Lu();e.ok||(g.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",ja);let n=t.jira?new Me(t.jira):ol(),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let y=r.get(d);return y||(y=new Me(m),r.set(d,y)),y},i=new Map,o=(d,m)=>{let y=Sd(ke()??t,d,m);switch(y.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:y.error};case"user":{let R=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,N=i.get(R);return N||(N=new Me(y.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,w=null,v={cfg:t,jiraFor:s,transport:null},k=new Set,x=async(d,m,y)=>{if(!(m.length<2))for(let R=0;R<m.length;R++){let{text:N,changed:G}=Rd(y[R]??"",m);G&&await d.updateDescription(m[R],N).then(()=>g.info(`Compose: rewrote sibling ticket refs in ${m[R]} to real keys`)).catch(L=>g.warn(`Compose: could not rewrite refs in ${m[R]}: ${L instanceof Error?L.message:L}`))}},I=d=>{let m=c.find(R=>R.id===d),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},P=d=>{let m=c.find(N=>N.id===d),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${y} 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`${y} 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`},J={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(d,m)=>{let y=I(d),R=h.find(N=>N.projectId===d&&N.name===m);return y&&R?{...y,environment:R}:null}},W=new Map,b=new ra(l.toString(),t.runnerToken,{runnerVersion:to},{onConfig:d=>{c=d.projects,Xp(d.projects),u=d.rules,h=d.environments,lp(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=I(d.projectId);if(!m){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let y=Le(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let R=await Ip({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});b.sendDeploySuggestResult(d.requestId,R)},onProjectTest:async d=>{let m=c.find(R=>R.id===d.projectId);if(!m){b.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}g.info(`running connection test for project "${m.name}"`);let y=await oa(ke()??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));b.sendProjectTestResult(d.requestId,y.every(R=>R.ok),y)},onRuleDiagnose:async d=>{let m=u.find(U=>U.id===d.ruleId),y=m&&c.find(U=>U.id===m.projectId);if(!m||!y){b.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}g.info(`diagnosing rule "${m.name}"`);let R=await oa(ke()??t,y,m.action.type==="deploy"?h.filter(U=>U.projectId===y.id):[]),N=m.action.type==="implement"?R:R.filter(U=>U.name!=="github-token"),{matchedCount:G,excludedCount:L,excludedSample:Z}=await f.diagnoseRule(m,y);b.sendRuleDiagnoseResult(d.requestId,{checks:N,matchedCount:G,excludedCount:L,excludedSample:Z})},onCancel:d=>{zh(d)?g.info(`run ${d} stopped from the dashboard`):g.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(Ql(d)){kp(J,d).catch(y=>g.error(`deploy approval crashed for ${d}: ${y instanceof Error?y.stack:y}`));return}oi(v,d,m).catch(y=>g.error(`approval handling crashed for ${d}: ${y instanceof Error?y.stack:y}`))},onRetryPush:d=>{let m=ko(d),y=()=>Zh(v,d).catch(R=>g.error(`retry push crashed for ${d}: ${R instanceof Error?R.stack:R}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:d=>{if(Ql(d)){_p(J,d).catch(m=>g.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Gh(v,d).catch(m=>g.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 y=I(d.projectId);if(!y){let R=P(d.projectId);g.error(`deploy ${d.runId}: ${R}`),b.send({type:"run.status",runId:d.runId,status:"failed",error:R});return}g.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>No({runId:d.runId,project:y.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:b,requestedBy:d.requestedBy}).catch(R=>g.error(`deploy crashed for ${d.runId}: ${R instanceof Error?R.stack:R}`)))},onDeploySuggest:async d=>{let m=I(d.projectId);if(!m){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let y=Le(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`asking ${y.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let R=await Rp({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});b.sendDeploySuggestResult(d.requestId,R)},onEnvPreflight:async d=>{let m=I(d.projectId);if(!m){b.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await xp({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});b.sendEnvPreflightResult(d.requestId,y)},onSelfMigrationApply:async d=>{let m=I(d.projectId);if(!m){b.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:P(d.projectId)});return}g.info(`applying migration ${d.file} for "${d.environmentName}"`);let y=await tf({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});g.info(y.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${y.error}`),b.sendSelfMigrationApplyResult(d.requestId,y)},onAutopilotPlan:async d=>{try{let m=I(d.projectId);if(!m){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:P(d.projectId)});return}let y=s(m.project.repoName),R=[];for(let z of d.issueKeys)try{let ee=await y.getIssue(z);R.push(`${z}: ${ee.summary}
|
|
1090
|
+
${(ee.description||"").slice(0,500)}`)}catch{R.push(`${z}: (could not read from Jira)`)}let N=Le(t,m.project,"assist");if("error"in N){b.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.
|
|
1091
1091
|
|
|
1092
1092
|
`+R.join(`
|
|
1093
1093
|
|
|
@@ -1100,7 +1100,7 @@ Rules:
|
|
|
1100
1100
|
- "order": every key exactly once. Prerequisites before the work that needs them.
|
|
1101
1101
|
- "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.
|
|
1102
1102
|
- "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
|
|
1103
|
-
- "reasoning": 2-3 short lines a person can check your plan against.`,L=await
|
|
1103
|
+
- "reasoning": 2-3 short lines a person can check your plan against.`,L=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,Mn.randomUUID)(),onLog:()=>{}}),Z=dc(L.resultText,d.issueKeys);if(!Z){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:U}=await Promise.resolve().then(()=>(Lo(),Ap));U({batchId:d.batchId,projectId:d.projectId,order:Z.order,chains:Z.chains,dependencies:Z.dependencies,reasoning:Z.reasoning}),b.sendAutopilotPlanResult(d.requestId,{ok:!0,...Z})}catch(m){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async d=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(Vc(),fm)),y=await m({command:d.command,args:d.args});g.info(`chat diagnostic (user-approved): ${y.commandLine}`),b.sendChatDiagnosticResult(d.requestId,y)}catch(m){b.sendChatDiagnosticResult(d.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatCancel:d=>{let m=W.get(d.turnId);m&&(m.abort(),g.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let m=I(d.projectId);if(!m){b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:P(d.projectId)});return}let y=d.sessionId||(0,Mn.randomUUID)(),R=!d.sessionId,N=R?0:di(y)?.messages.length??0,G=!1,L=0,Z="";if(!R&&N>=qp){let Pe=await Hp(m,y,t);if(Pe)G=!0,L=N,Z=Pe,y=(0,Mn.randomUUID)(),R=!0,g.info(`chat compacted: ${N} message(s) summarized into a fresh session`);else if(N>=Fp){b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 U=d.files.length?Ou(m.repoPath,d.requestId,d.files):null,z=(0,Ke.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Ke.pendingMigrationsAppendix)(d.pendingMigrations)+(0,Ke.deployTargetsAppendix)(d.environments),ee="```",V=R?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
1104
1104
|
|
|
1105
1105
|
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.
|
|
1106
1106
|
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.
|
|
@@ -1128,33 +1128,43 @@ Acceptance Criteria: - testable bullet points a reviewer can check off one by on
|
|
|
1128
1128
|
Include a section only when it carries real content, and add extra sections (Out of Scope, Notes, \u2026) when the work genuinely needs them. Use as many bullets as the work needs - no artificial length cap, but no padding either. It must stay concrete enough that a developer (or an agent) can implement it without asking questions. NEVER paste the conversation into the description; distill it. Refine the draft over further turns if the user asks.
|
|
1129
1129
|
THE READER IS A COLD AGENT: whoever implements this sees the ticket alone, never this conversation. Anything that is obvious only from the chat must be written into the ticket; anything the repo already documents is referenced by path, not restated.
|
|
1130
1130
|
EXCEPTION - verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block - the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${ee}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ${ee} would end the outer block early and corrupt the draft.
|
|
1131
|
-
EXCEPTION -
|
|
1132
|
-
{"
|
|
1131
|
+
EXCEPTION - several tickets at once: when the user asks for more than one ticket, asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down and emit ONE \`\`\`ticket block of this shape:
|
|
1132
|
+
{"tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
|
|
1133
|
+
Add an "epic" key ONLY when the pieces genuinely belong under one parent goal:
|
|
1134
|
+
{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [ \u2026 ]}
|
|
1135
|
+
Never invent a parent to hold tickets that are simply independent - "make these three tickets" means three tickets, and the person chooses in the dashboard whether they become tasks, epics, or one epic with children. NEVER emit a second \`\`\`ticket block to add more tickets: only the last block in a reply is read, so a second one silently discards the first.
|
|
1133
1136
|
3-8 tickets, each sized for ONE short agent run and structured with the same section headings as above, ordered so foundations come first; the epic description is the overall goal in under 100 words. When one ticket needs another from the SAME batch, reference it as "Ticket #N" (its position in the list) - Allwright rewrites those into the real Jira keys at creation, and any other phrasing survives as a dangling reference nobody can follow.
|
|
1134
1137
|
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 ${ee}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.
|
|
1135
|
-
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.
|
|
1138
|
+
SIZE: a reply that outgrows the transport is cut off mid-block and creates NOTHING - and you cannot tell it happened, because your own memory holds the text you meant to send. So when several tickets will not fit, emit FEWER entries, complete, and say which ones you left out for a follow-up turn; never open a block you cannot finish, and never spend the budget on prose before it - the block comes last, so prose is what pushes it over the edge. 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.
|
|
1136
1139
|
|
|
1137
|
-
|
|
1140
|
+
A MACHINE ACTION IS NOT A TICKET. When the answer is an action ON A MACHINE rather than a change to this repository - installing a package, restarting or enabling a service, a DNS record, storing a credential, a permissions or sudoers change - do NOT propose a ticket for it. An implement run has NO SHELL and is path-jailed to this checkout, so no agent can carry a machine action out: such a ticket sits in the backlog forever or fails its run. What the person needs is the exact command and which machine to run it on, so end your reply with EXACTLY one fenced block:
|
|
1141
|
+
${ee}command
|
|
1142
|
+
{"server": "<machine name if known, else empty>", "why": "<one line: what this fixes>", "commands": ["<exact shell command>", "\u2026"]}
|
|
1143
|
+
${ee}
|
|
1144
|
+
Commands are EXACT and copy-pasteable - no placeholders, no prose, at most 5. NEVER include a secret VALUE: write $NAMES and let the person supply them.
|
|
1145
|
+
NEVER invent a server name - leave "server" empty when you are not sure which machine it is. When part of the fix is a code change and part is a machine action, emit BOTH blocks - the ${ee}ticket block for the code half, the ${ee}command block for the machine half - and say in ONE line which half is which.
|
|
1146
|
+
|
|
1147
|
+
`+(()=>{try{let{packs:Pe,lessons:Ne}=gs("compose",m.repoPath),ie=[Pe.map(xe=>`### ${xe.name}
|
|
1138
1148
|
${xe.content}`).join(`
|
|
1139
1149
|
|
|
1140
|
-
`).slice(0,4e3),
|
|
1150
|
+
`).slice(0,4e3),Ne.trim().slice(-4e3)].filter(Boolean).join(`
|
|
1141
1151
|
|
|
1142
1152
|
`).trim();return ie?`
|
|
1143
1153
|
HOUSE RULES FOR TICKETS here - taught by this team, follow them over the generic guidance above when they conflict:
|
|
1144
1154
|
${ie}
|
|
1145
|
-
`:""}catch{return""}})()+
|
|
1155
|
+
`:""}catch{return""}})()+Kp+(Z?`
|
|
1146
1156
|
|
|
1147
1157
|
This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
|
|
1148
1158
|
${Z}
|
|
1149
1159
|
`:"")+z+`
|
|
1150
|
-
${d.userName||"The user"} says: ${d.message}`+(U?.section??""):z+`${d.userName||"The user"} says: ${d.message}`+(U?.section??""),fe=0,de=new Date,qe=[],
|
|
1160
|
+
${d.userName||"The user"} says: ${d.message}`+(U?.section??""):z+`${d.userName||"The user"} says: ${d.message}`+(U?.section??""),fe=0,de=new Date,qe=[],oe;try{let Pe=Le(t,m.project,"chat");if("error"in Pe){b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:Pe.error});return}let Ne=new AbortController;W.set(d.requestId,Ne),oe=await Pe.adapter.run({repoPath:m.repoPath,prompt:V,signal:Ne.signal,timeoutSeconds:180,bin:Pe.bin,mode:"read_only",maxTurns:25,model:d.model||Pe.adapter.fastModel,sessionId:y,resume:!R,onLog:(ie,xe)=>{ie==="agent"&&(qe.push(xe.slice(0,4e3)),b.send({type:"chat.stream",requestId:d.requestId,seq:fe++,text:xe.slice(0,8e3)}))},onUsage:ie=>{b.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(ie.inputTokens),outputTokens:Math.round(ie.outputTokens),cacheReadTokens:ie.cacheReadTokens===void 0?void 0:Math.round(ie.cacheReadTokens),turns:ie.turns})}})}finally{W.delete(d.requestId),U&&rt.default.rmSync(U.dir,{recursive:!0,force:!0})}if(oe.cancelled){b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 Pe=qe.filter(Ne=>Ne.trim()&&!oe.resultText.trim().startsWith(Ne.trim()));Lp(d.projectId,y,d.message,oe.resultText,Pe,d.files.map(Ne=>Ne.name),{askedAt:de.toISOString(),ms:Date.now()-de.getTime()})}let Fe=(oe.inputTokens??0)+(oe.cacheReadTokens??0);b.sendChatTurnResult(d.requestId,{contextTokens:Fe,contextLimit:Bp(oe.model||d.model||""),compacted:G,compactedMessages:L,ok:oe.ok,sessionId:y,reply:oe.resultText,outputTruncated:!!oe.outputTruncated,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=>{b.sendChatListResult(d.requestId,Up(d.projectId))},onRepoDocs:d=>{let m=I(d.projectId);if(!m){b.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:P(d.projectId)});return}b.sendRepoDocsResult(d.requestId,{ok:!0,docs:Wp(m.repoPath)})},onRepoDocRead:d=>{let m=I(d.projectId);if(!m){b.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:P(d.projectId)});return}let y=Vp(m.repoPath,d.path);b.sendRepoDocReadResult(d.requestId,{ok:y.ok,path:y.ok?y.path:d.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:d=>{let m=di(d.sessionId);b.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=I(d.projectId);if(!m){b.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:P(d.projectId)});return}try{let y=s(m.project.repoName),R;try{R=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{R=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await y.boardColumns(m.project.jiraProjectKey),G;if(N){G=N.map(U=>({name:U.name,issues:[]}));let Z=new Map;for(let U of R){let z=N.findIndex(V=>V.statusIds.includes(U.statusId)),ee={key:U.key,summary:U.summary,labels:U.labels};if(z>=0)G[z].issues.push(ee);else{let V=Z.get(U.status)??[];V.push(ee),Z.set(U.status,V)}}for(let[U,z]of Z)G.push({name:U,issues:z})}else{let Z=fe=>fe.trim().toLowerCase(),U=new Map,z=new Map;for(let fe of R){let de=Z(fe.status);U.has(de)||U.set(de,fe.status.trim());let qe=z.get(de)??[];qe.push({key:fe.key,summary:fe.summary,labels:fe.labels}),z.set(de,qe)}let ee=[];try{ee=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let V=[];for(let fe of ee){let de=Z(fe);!V.includes(de)&&z.has(de)&&V.push(de)}for(let fe of z.keys())V.includes(fe)||V.push(fe);G=V.map(fe=>({name:U.get(fe)??fe,issues:z.get(fe)??[]}))}let L=t.repos[m.project.repoName]?.jira??t.jira;b.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(L?.baseUrl??"").replace(/\/+$/,""),columns:G})}catch(y){b.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async d=>{let m=I(d.projectId);if(!m){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let y=s(m.project.repoName),R=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:y,authored:!1};if(R.error!==void 0){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:R.error});return}if(d.reimplement){let N=await y.getIssue(d.issueKey),G=N.comments.filter(U=>Pt(U.body)),L=G.length?Math.max(...G.map(U=>new Date(U.created).getTime())):0;if(!N.comments.some(U=>!Pt(U.body)&&new Date(U.created).getTime()>L)){b.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 y.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await y.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await R.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!R.authored&&d.requestedBy?`
|
|
1151
1161
|
|
|
1152
1162
|
_(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),b.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(y){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async d=>{let m=I(d.projectId);if(!m){b.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:P(d.projectId)});return}try{let y=o(m.project.repoName,d.requestedByEmail);if(y.error!==void 0){b.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:y.error});return}let R=`
|
|
1153
1163
|
|
|
1154
1164
|
---
|
|
1155
|
-
_Created via Allwright Compose`+(!y.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let L=d.createAs==="separate_epics"?"Epic":"Task",Z=[],U=[];for(let z of d.children){let ee=(z.description||"(no description)")+R,V=await y.jira.createIssue(m.project.jiraProjectKey,z.summary,ee,L);Z.push(V.key),U.push(ee)}await x(y.jira,Z,U),g.info(`Compose created ${Z.length} standalone ${L.toLowerCase()}(s)`),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:Z[0]??"",childKeys:Z});return}let{key:
|
|
1165
|
+
_Created via Allwright Compose`+(!y.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let L=d.createAs==="separate_epics"?"Epic":"Task",Z=[],U=[];for(let z of d.children){let ee=(z.description||"(no description)")+R,V=await y.jira.createIssue(m.project.jiraProjectKey,z.summary,ee,L);Z.push(V.key),U.push(ee)}await x(y.jira,Z,U),g.info(`Compose created ${Z.length} standalone ${L.toLowerCase()}(s)`),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:Z[0]??"",childKeys:Z});return}let{key:N}=await y.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+R,d.asEpic?"Epic":"Task");d.files.length&&await y.jira.addAttachments(N,d.files.map(L=>({name:L.name,content:Buffer.from(L.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${d.files.length} file(s) to ${N}`)).catch(L=>g.warn(`Compose could not attach files to ${N}: ${L instanceof Error?L.message:L}`));let G=[];if(d.asEpic){let L=[];for(let Z of d.children){let U=(Z.description||"(no description)")+R,z=await y.jira.createIssue(m.project.jiraProjectKey,Z.summary,U,"Task",N);G.push(z.key),L.push(U)}await x(y.jira,G,L),g.info(`Compose created epic ${N} with ${G.length} child ticket(s)`),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N,childKeys:G});return}d.triggerComment.trim()&&await y.jira.addTriggerComment(N,`${d.triggerComment.trim()}`+(!y.authored&&d.requestedBy?`
|
|
1156
1166
|
|
|
1157
|
-
_(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${
|
|
1167
|
+
_(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${N}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N})}catch(y){b.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:y instanceof Error?y.message:String(y)})}},onAuditStart:async d=>{let m=I(d.projectId);if(!m){b.sendAuditStartResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{g.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let y=Le(t,m.project,"assist");if("error"in y){b.sendAuditStartResult(d.requestId,{ok:!1,error:y.error});return}let R=await ws({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:y,jira:s(m.project.repoName),baseUrl:d.baseUrl});if(!R.ok){b.sendAuditStartResult(d.requestId,{ok:!1,error:R.error});return}b.sendAuditStartResult(d.requestId,{ok:!0,audit:R.audit})}catch(y){b.sendAuditStartResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async d=>{try{b.sendAuditListResult(d.requestId,{ok:!0,audits:Hd(d.projectId)})}catch(m){b.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async d=>{try{let m=yl(d.projectId,d.auditId),y=m?.findings.find(U=>U.id===d.findingId);if(!m||!y){b.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let R=I(d.projectId);if(!R){b.sendAuditExplainResult(d.requestId,{ok:!1,error:P(d.projectId)});return}let N=Le(t,R.project,"assist");if("error"in N){b.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.
|
|
1158
1168
|
|
|
1159
1169
|
FINDING (${y.severity}${y.ruleId?`, rule ${y.ruleId}`:""}):
|
|
1160
1170
|
${y.title}
|
|
@@ -1169,7 +1179,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
|
|
|
1169
1179
|
**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.
|
|
1170
1180
|
**How urgent:** now / before the next release / when convenient - and why.
|
|
1171
1181
|
**What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
|
|
1172
|
-
Nothing else - no preamble, no code.`,L=await
|
|
1182
|
+
Nothing else - no preamble, no code.`,L=await N.adapter.run({repoPath:R.repoPath,prompt:G,timeoutSeconds:120,bin:N.bin,mode:"read_only",maxTurns:8,sessionId:(0,Mn.randomUUID)(),onLog:()=>{}}),Z=L.resultText.trim();if(!L.ok||!Z){b.sendAuditExplainResult(d.requestId,{ok:!1,error:L.error??"the agent returned nothing - try again"});return}b.sendAuditExplainResult(d.requestId,{ok:!0,explanation:Z})}catch(m){b.sendAuditExplainResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=yl(d.projectId,d.auditId);if(!m){b.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}b.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=gl(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){b.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=I(d.projectId);if(y&&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(L=>L.id===N.findingId);G&&(kl(y.repoPath,m.role,eh(G,N.verdict,N.note,d.verdictBy)),R.push(N.findingId),g.info(`Lesson written (${m.role}): ${N.verdict} - ${G.title.slice(0,60)}`))}R.length&&(m=gl(d.projectId,d.auditId,{markLessonsWritten:R})??m)}b.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=I(d.projectId);if(!m){b.sendKnowledgeListResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{b.sendKnowledgeListResult(d.requestId,{ok:!0,files:nh(m.repoPath)})}catch(y){b.sendKnowledgeListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async d=>{let m=I(d.projectId);if(!m){b.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{d.append?kl(m.repoPath,d.role,th(d.content,d.by),d.level):rh(m.repoPath,d.role,d.level,d.source,d.name,d.content),g.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),b.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(y){b.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async d=>{let m=I(d.projectId);if(!m){b.sendEpicListResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let y=s(m.project.repoName);if(d.epicKey){let R=await y.epicChildren(d.epicKey);b.sendEpicListResult(d.requestId,{ok:!0,children:R})}else{let R=await y.searchEpics(m.project.jiraProjectKey);b.sendEpicListResult(d.requestId,{ok:!0,epics:R})}}catch(y){b.sendEpicListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async d=>{let m=I(d.projectId);if(!m){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let y=s(m.project.repoName),R=await y.epicChildren(d.epicKey),N=Nd(R);if(!N.length){b.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){b.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 ee=>{try{let V=await y.getIssue(ee.key);return{...ee,description:V.description}}catch{return{...ee,description:""}}})),L=(await y.getIssue(d.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${G.length} pending children of ${d.epicKey}`);let Z=Le(t,m.project,"assist");if("error"in Z){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:Z.error});return}let U=await Z.adapter.run({repoPath:m.repoPath,prompt:jd(d.epicKey,L,G),timeoutSeconds:150,bin:Z.bin,mode:"read_only",maxTurns:20,sessionId:(0,Mn.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),z=Od(U.resultText,G.map(ee=>ee.key));if("error"in z){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:z.error});return}g.info(`Epic suggest: ${d.epicKey} -> do ${z.issueKey} first`),b.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:G.length})}catch(y){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async d=>{try{let m=ke()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:R}=await Promise.resolve().then(()=>(kt(),xr));m.github.login=await new R(m.github.token).whoami(),be(m)}catch{}let y=Id(m,d.emails);b.sendTeamCredsResult(d.requestId,{ok:!0,...y})}catch(m){b.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=ke();if(!m){b.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let y=m.repos[d.repoName];if(!y){b.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let R=y.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),be(m),un(),g.info(`Unmapped "${d.repoName}" (was ${R}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),b.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:R})}catch(m){b.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=I(d.projectId);if(!m){b.sendSetupRecheckResult(d.requestId,{ok:!1,error:P(d.projectId)});return}b.sendSetupRecheckResult(d.requestId,{ok:!0,checks:op({repoPath:m.repoPath,environments:d.environments})})}catch(m){b.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ke()??t,{buildSetupReport:y}=await Promise.resolve().then(()=>(jm(),Nm)),R=await y(m,d.repoNames,t);b.sendSetupStatusResult(d.requestId,{ok:!0,...R})}catch(m){b.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=I(d.projectId);if(!m){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";g.info(`Setup: drafting ${y} 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.
|
|
1173
1183
|
|
|
1174
1184
|
Ten things decide whether this document can actually be run:
|
|
1175
1185
|
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.
|
|
@@ -1188,7 +1198,7 @@ Reply with ONLY the file content - no preamble, no fences around the whole thing
|
|
|
1188
1198
|
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:
|
|
1189
1199
|
`+d.environments.map(V=>`- ${V.name}`+(V.branch?` (branch ${V.branch})`:"")+(V.publicUrl?` serves ${V.publicUrl}`:" - no URL given")+(V.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(V.workdir?`${V.workdir}`:V.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(`
|
|
1190
1200
|
`)+`
|
|
1191
|
-
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"?
|
|
1201
|
+
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"?Hl({repoPath:m.repoPath,urls:d.environments.map(V=>V.publicUrl).filter(Boolean)})+ci(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.`,L=`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.
|
|
1192
1202
|
|
|
1193
1203
|
BLOCKERS AS REPORTED:
|
|
1194
1204
|
`+d.blockers.map((V,fe)=>`${fe+1}. ${V}`).join(`
|
|
@@ -1228,7 +1238,7 @@ Reply with ONLY the guide - no preamble.`+(d.environments.length?`
|
|
|
1228
1238
|
|
|
1229
1239
|
THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
|
|
1230
1240
|
`+d.environments.map(V=>`- ${V.name}`+(V.branch?` (branch ${V.branch})`:"")+(V.publicUrl?` serves ${V.publicUrl}`:"")+(V.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(V.workdir?V.workdir:V.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(`
|
|
1231
|
-
`):"")+
|
|
1241
|
+
`):"")+Hl({repoPath:m.repoPath,urls:d.environments.map(V=>V.publicUrl).filter(Boolean)})+ci(m.repoPath),Z=Le(t,m.project,"assist");if("error"in Z){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:Z.error});return}let U=0,z=await Z.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?N:d.kind==="design"?G:d.kind==="unblock"?L:R,timeoutSeconds:600,bin:Z.bin,mode:"read_only",maxTurns:40,sessionId:(0,Mn.randomUUID)(),onLog:(V,fe)=>{V==="agent"&&d.streamId&&b.send({type:"chat.stream",requestId:d.streamId,seq:U++,text:fe.slice(0,8e3)})}}),ee=z.resultText.trim();if(!ee){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}z.outputTruncated&&g.warn(`Setup: the ${y} draft was cut off at the agent's output limit - ${ee.length} chars, incomplete`),b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:ee,truncated:!!z.outputTruncated})}catch(m){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async d=>{try{let m=I(d.projectId);if(!m){b.sendSetupAskResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=Le(t,m.project,"assist");if("error"in y){b.sendSetupAskResult(d.requestId,{ok:!1,error:y.error});return}g.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?`
|
|
1232
1242
|
|
|
1233
1243
|
WHAT THEY ARE WORKING ON:
|
|
1234
1244
|
${d.subject}`:"")+(d.command?`
|
|
@@ -1250,4 +1260,4 @@ ${d.question}
|
|
|
1250
1260
|
|
|
1251
1261
|
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.
|
|
1252
1262
|
|
|
1253
|
-
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 y.adapter.run({repoPath:m.repoPath,prompt:R,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Mn.randomUUID)(),onLog:()=>{}})).resultText.trim();b.sendSetupAskResult(d.requestId,G?{ok:!0,answer:G}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){b.sendSetupAskResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=I(d.projectId);if(!m){b.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",R=await Bc({repoPath:m.repoPath,relPath:y,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});R.ok&&g.info(`Setup: wrote human-approved ${y} to ${m.repoPath} - ${R.note}`),b.sendSetupClaudeMdSaveResult(d.requestId,R)}catch(m){b.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=I(d.projectId);if(!m){b.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Bc({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&g.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),b.sendRepoDocSaveResult(d.requestId,y)}catch(m){b.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{b.sendAuditStatsResult(d.requestId,{ok:!0,byProject:Hd(d.projectIds,d.since)})}catch(m){b.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){b.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=()=>{g.info("Installing allwright@latest");let R=cn.default.dirname(process.execPath),j=rt.default.existsSync(cn.default.join(R,"npm"))?cn.default.join(R,"npm"):"npm";(0,dn.execFile)(j,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${R}:${process.env.PATH??""}`}},(G,L,Z)=>{if(G){b.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(Z||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}b.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),g.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(w){b.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;b.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),g.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s)/chat turn(s) to finish`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){b.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=pl()}catch(R){b.sendRunnerUninstallResult(d.requestId,{ok:!1,error:R instanceof Error?R.message:String(R)});return}let y=m.problems.length===0;if(b.sendRunnerUninstallResult(d.requestId,{ok:y,error:y?void 0:m.problems.join("; "),note:y?[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}),!y){g.info("Uninstall requested from the dashboard, but it could not complete here");return}g.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{hl(),process.exit(0)},1500)},onTestFix:async d=>{let m=y=>b.sendTestFixResult(d.requestId,{ok:!1,note:y});try{let y=ks(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[y.repoName];if(!R){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let j=ze(t,y.repoName);if(!j){m("no GitHub token on this runner for that repo");return}let G=await new Ue(j).getPullRequest(y.owner,y.repo,y.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 L=c.find(ee=>ee.repoName===y.repoName),Z=y.nextDecisionSeq??1e5,U=(ee,V)=>{b.send({type:"run.log",runId:d.runId,seq:Z++,ts:new Date().toISOString(),level:ee,message:V}),y.nextDecisionSeq=Z,_t(y)},z=await Op({cfg:t,repoPath:R.path,branch:y.branch,baseBranch:G.baseRef||"main",issueKey:y.issueKey,agentId:L?.defaultAgent||He.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:U});z.ok&&z.headSha&&(y.headSha=z.headSha,_t(y),b.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:z.headSha,failedTests:z.remaining??[],...z.testsPassed!==void 0?{testsPassed:z.testsPassed}:{},...z.testsTotal!==void 0?{testsTotal:z.testsTotal}:{},...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),dt(R.path,{issueKey:y.issueKey,runId:d.runId,title:z.ok?z.headSha?(z.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:z.note.slice(0,500)}),b.sendTestFixResult(d.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);b.sendRunAnswerResult(d.requestId,m)}catch(m){b.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=y=>b.sendResolveConflictResult(d.requestId,{ok:!1,note:y});try{let y=ks(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[y.repoName];if(!R){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let j=ze(t,y.repoName);if(!j){m("no GitHub token on this runner for that repo");return}let G=await new Ue(j).getPullRequest(y.owner,y.repo,y.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 L=c.find(ee=>ee.repoName===y.repoName),Z=y.nextDecisionSeq??1e5,U=(ee,V)=>{b.send({type:"run.log",runId:d.runId,seq:Z++,ts:new Date().toISOString(),level:ee,message:V}),y.nextDecisionSeq=Z,_t(y)},z=await jp({cfg:t,repoPath:R.path,branch:y.branch,baseBranch:G.baseRef,issueKey:y.issueKey,agentId:L?.defaultAgent||He.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:U});z.ok&&z.headSha&&(y.headSha=z.headSha,y.conflictNotified=!1,_t(y),b.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),b.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:z.headSha,...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),b.sendResolveConflictResult(d.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:d=>{try{let m=R=>{try{return rt.default.existsSync(R)&&rt.default.readdirSync(R).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([R,j])=>({agent:"claude-code",name:R,loggedIn:m(j.configDir)}));b.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(cn.default.join(Ri.default.homedir(),".claude")),agentsWithoutProfiles:He.REGISTERED_AGENTS.filter(R=>!R.capabilities.loginProfiles).map(R=>R.id)})}catch(m){b.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);b.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){b.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=b,f=new qo(t,s,b),f.setExternalBusy(()=>W.size);let $=Object.values(Rr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Va(Object.values(t.repos).map(d=>d.path),$).catch(()=>{}),b.start(),f.start();let K=()=>{g.info("shutting down"),w&&clearInterval(w),b.stop(),Du(process.pid),Na(),process.exit(0)},C=!1,q=()=>{if(C){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),K();return}if(C=!0,f.stop(),f.idle){K();return}g.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),K())},3e3)};process.on("SIGINT",q),process.on("SIGTERM",q),process.on("SIGHUP",()=>{try{let d=ue();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new Me(d.jira):ol(),r.clear(),g.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){g.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Ee.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=ue();if(t.foreground){iS(e);return}let n=er();if(n&&tr(n)){g.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=rs();if(r){g.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=Mu(),i=(0,dn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),zu(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${Hi()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Ee.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=er();if(!e||!tr(e)){g.info("no background runner is running"),e&&rt.default.rmSync(ns(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),rt.default.rmSync(ns(),{force:!0}),g.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),g.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Ee.command("status").description("Check whether the background runner is running").action(()=>{let t=er();t&&tr(t)?g.info(`running in the background (pid ${t})`):g.info("not running")});Ee.parseAsync().catch(t=>{g.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|
|
1263
|
+
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 y.adapter.run({repoPath:m.repoPath,prompt:R,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Mn.randomUUID)(),onLog:()=>{}})).resultText.trim();b.sendSetupAskResult(d.requestId,G?{ok:!0,answer:G}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){b.sendSetupAskResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=I(d.projectId);if(!m){b.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",R=await Bc({repoPath:m.repoPath,relPath:y,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});R.ok&&g.info(`Setup: wrote human-approved ${y} to ${m.repoPath} - ${R.note}`),b.sendSetupClaudeMdSaveResult(d.requestId,R)}catch(m){b.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=I(d.projectId);if(!m){b.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Bc({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&g.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),b.sendRepoDocSaveResult(d.requestId,y)}catch(m){b.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{b.sendAuditStatsResult(d.requestId,{ok:!0,byProject:Kd(d.projectIds,d.since)})}catch(m){b.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){b.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=()=>{g.info("Installing allwright@latest");let R=cn.default.dirname(process.execPath),N=rt.default.existsSync(cn.default.join(R,"npm"))?cn.default.join(R,"npm"):"npm";(0,dn.execFile)(N,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${R}:${process.env.PATH??""}`}},(G,L,Z)=>{if(G){b.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(Z||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}b.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),g.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(w){b.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;b.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),g.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s)/chat turn(s) to finish`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){b.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=pl()}catch(R){b.sendRunnerUninstallResult(d.requestId,{ok:!1,error:R instanceof Error?R.message:String(R)});return}let y=m.problems.length===0;if(b.sendRunnerUninstallResult(d.requestId,{ok:y,error:y?void 0:m.problems.join("; "),note:y?[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}),!y){g.info("Uninstall requested from the dashboard, but it could not complete here");return}g.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{hl(),process.exit(0)},1500)},onTestFix:async d=>{let m=y=>b.sendTestFixResult(d.requestId,{ok:!1,note:y});try{let y=ks(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[y.repoName];if(!R){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let N=ze(t,y.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Ue(N).getPullRequest(y.owner,y.repo,y.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 L=c.find(ee=>ee.repoName===y.repoName),Z=y.nextDecisionSeq??1e5,U=(ee,V)=>{b.send({type:"run.log",runId:d.runId,seq:Z++,ts:new Date().toISOString(),level:ee,message:V}),y.nextDecisionSeq=Z,_t(y)},z=await Op({cfg:t,repoPath:R.path,branch:y.branch,baseBranch:G.baseRef||"main",issueKey:y.issueKey,agentId:L?.defaultAgent||Ke.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:U});z.ok&&z.headSha&&(y.headSha=z.headSha,_t(y),b.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:z.headSha,failedTests:z.remaining??[],...z.testsPassed!==void 0?{testsPassed:z.testsPassed}:{},...z.testsTotal!==void 0?{testsTotal:z.testsTotal}:{},...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),dt(R.path,{issueKey:y.issueKey,runId:d.runId,title:z.ok?z.headSha?(z.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:z.note.slice(0,500)}),b.sendTestFixResult(d.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);b.sendRunAnswerResult(d.requestId,m)}catch(m){b.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=y=>b.sendResolveConflictResult(d.requestId,{ok:!1,note:y});try{let y=ks(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[y.repoName];if(!R){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let N=ze(t,y.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Ue(N).getPullRequest(y.owner,y.repo,y.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 L=c.find(ee=>ee.repoName===y.repoName),Z=y.nextDecisionSeq??1e5,U=(ee,V)=>{b.send({type:"run.log",runId:d.runId,seq:Z++,ts:new Date().toISOString(),level:ee,message:V}),y.nextDecisionSeq=Z,_t(y)},z=await Np({cfg:t,repoPath:R.path,branch:y.branch,baseBranch:G.baseRef,issueKey:y.issueKey,agentId:L?.defaultAgent||Ke.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:U});z.ok&&z.headSha&&(y.headSha=z.headSha,y.conflictNotified=!1,_t(y),b.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),b.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:z.headSha,...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),b.sendResolveConflictResult(d.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:d=>{try{let m=R=>{try{return rt.default.existsSync(R)&&rt.default.readdirSync(R).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([R,N])=>({agent:"claude-code",name:R,loggedIn:m(N.configDir)}));b.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(cn.default.join(Ri.default.homedir(),".claude")),agentsWithoutProfiles:Ke.REGISTERED_AGENTS.filter(R=>!R.capabilities.loginProfiles).map(R=>R.id)})}catch(m){b.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);b.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){b.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=b,f=new qo(t,s,b),f.setExternalBusy(()=>W.size);let C=Object.values(Rr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Va(Object.values(t.repos).map(d=>d.path),C).catch(()=>{}),b.start(),f.start();let H=()=>{g.info("shutting down"),w&&clearInterval(w),b.stop(),Du(process.pid),ja(),process.exit(0)},$=!1,q=()=>{if($){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),H();return}if($=!0,f.stop(),f.idle){H();return}g.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),H())},3e3)};process.on("SIGINT",q),process.on("SIGTERM",q),process.on("SIGHUP",()=>{try{let d=ue();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new Me(d.jira):ol(),r.clear(),g.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){g.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Ee.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=ue();if(t.foreground){iS(e);return}let n=er();if(n&&tr(n)){g.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=rs();if(r){g.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=Mu(),i=(0,dn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),zu(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${Ki()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Ee.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=er();if(!e||!tr(e)){g.info("no background runner is running"),e&&rt.default.rmSync(ns(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),rt.default.rmSync(ns(),{force:!0}),g.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),g.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Ee.command("status").description("Check whether the background runner is running").action(()=>{let t=er();t&&tr(t)?g.info(`running in the background (pid ${t})`):g.info("not running")});Ee.parseAsync().catch(t=>{g.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|