allwright 1.85.0 → 1.86.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 +49 -49
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -20,7 +20,7 @@ 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 _e.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()}`,_e.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new yb(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),d=this.options.find(f=>f.negate&&l===f.attributeName()),p=this.options.find(f=>!f.negate&&l===f.attributeName());return d&&(d.presetArg===void 0&&c===!1||d.presetArg!==void 0&&c===d.presetArg)?d:p||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=hd(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=hd(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=>mb(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=Xt.basename(e,Xt.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=_e.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 pd(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})}fd.Command=hl});var wd=he(lt=>{var{Argument:gd}=no(),{Command:pl}=md(),{CommanderError:bb,InvalidArgumentError:yd}=ni(),{Help:wb}=sl(),{Option:bd}=ll();lt.program=new pl;lt.createCommand=t=>new pl(t);lt.createOption=(t,e)=>new bd(t,e);lt.createArgument=(t,e)=>new gd(t,e);lt.Command=pl;lt.Option=bd;lt.Argument=gd;lt.Help=wb;lt.CommanderError=bb;lt.InvalidArgumentError=yd;lt.InvalidOptionArgumentError=yd});var ue,fl,q,Ot,ri=Q(()=>{(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})(ue||(ue={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(fl||(fl={}));q=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ot=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}}});var P,vb,Ye,ro=Q(()=>{ri();P=ue.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"]),vb=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ye=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 d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],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,ue.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()}};Ye.create=t=>new Ye(t)});var kb,Qt,ml=Q(()=>{ro();ri();kb=(t,e)=>{let n;switch(t.code){case P.invalid_type:t.received===q.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case P.invalid_union:n="Invalid input";break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${ue.joinValues(t.options)}, received '${t.received}'`;break;case P.invalid_arguments:n="Invalid function arguments";break;case P.invalid_return_type:n="Invalid function return type";break;case P.invalid_date:n="Invalid date";break;case P.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}"`:ue.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case P.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 P.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 P.custom:n="Invalid input";break;case P.invalid_intersection_types:n="Intersection results could not be merged";break;case P.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case P.not_finite:n="Number must be finite";break;default:n=e.defaultError,ue.assertNever(t)}return{message:n}},Qt=kb});function _b(t){_d=t}function ss(){return _d}var _d,so=Q(()=>{ml();_d=Qt});function D(t,e){let n=ss(),r=si({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 si,Sb,Me,X,Yn,De,io,oo,_n,is,gl=Q(()=>{so();ml();si=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(d=>!!d).slice().reverse();for(let d of c)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Sb=[];Me=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 X;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 X;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}}},X=Object.freeze({status:"aborted"}),Yn=t=>({status:"dirty",value:t}),De=t=>({status:"valid",value:t}),io=t=>t.status==="aborted",oo=t=>t.status==="dirty",_n=t=>t.status==="valid",is=t=>typeof Promise<"u"&&t instanceof Promise});var Sd=Q(()=>{});var W,Td=Q(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}))});function ie(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 Ed(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 Ub(t){return new RegExp(`^${Ed(t)}$`)}function Ad(t){let e=`${Rd}T${Ed(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 qb(t,e){return!!((e==="v4"||!e)&&Nb.test(t)||(e==="v6"||!e)&&Ob.test(t))}function Fb(t,e){if(!Ab.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 Bb(t,e){return!!((e==="v4"||!e)&&jb.test(t)||(e==="v6"||!e)&&Mb.test(t))}function Hb(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 os(t){if(t instanceof Xe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ct.create(os(r))}return new Xe({...t._def,shape:()=>e})}else return t instanceof nn?new nn({...t._def,type:os(t.element)}):t instanceof ct?ct.create(os(t.unwrap())):t instanceof zt?zt.create(os(t.unwrap())):t instanceof Mt?Mt.create(t.items.map(e=>os(e))):t}function bl(t,e){let n=Ot(t),r=Ot(e);if(t===e)return{valid:!0,data:t};if(n===q.object&&r===q.object){let s=ue.objectKeys(e),i=ue.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=bl(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===q.array&&r===q.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=bl(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===q.date&&r===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Cd(t,e){return new lr({values:t,typeName:ee.ZodEnum,...ie(e)})}function Id(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function $d(t,e={},n){return t?Tn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Id(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Id(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Tn.create()}var ut,xd,le,Tb,xb,Ib,Rb,Eb,Ab,Cb,$b,Pb,yl,Nb,jb,Ob,Mb,zb,Db,Rd,Lb,Sn,Xn,Qn,er,tr,as,nr,rr,Tn,tn,xt,ls,nn,Xe,sr,en,ao,ir,Mt,lo,cs,us,co,or,ar,lr,cr,xn,dt,ct,zt,ur,dr,ds,Kb,ii,oi,hr,Gb,ee,Wb,Pd,Nd,Zb,Vb,jd,Jb,Yb,Xb,Qb,ew,tw,nw,rw,sw,iw,ow,aw,lw,cw,uw,dw,hw,pw,fw,mw,gw,yw,bw,ww,vw,kw,_w,Sw,Tw,xw,Iw,Rw,Ew,Aw,Od=Q(()=>{ro();so();Td();gl();ri();ut=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}},xd=(t,e)=>{if(_n(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 Ye(t.common.issues);return this._error=n,this._error}}};le=class{get description(){return this._def.description}_getType(e){return Ot(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Me,ctx:{common:e.parent.common,data:e.data,parsedType:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(is(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:Ot(e)},s=this._parseSync({data:e,path:r.path,parent:r});return xd(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ot(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return _n(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=>_n(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:Ot(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(is(s)?s:Promise.resolve(s));return xd(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:P.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 dt({schema:this,typeName:ee.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 ct.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nn.create(this)}promise(){return xn.create(this,this._def)}or(e){return sr.create([this,e],this._def)}and(e){return ir.create(this,e,this._def)}transform(e){return new dt({...ie(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new ur({...ie(this._def),innerType:this,defaultValue:n,typeName:ee.ZodDefault})}brand(){return new ii({typeName:ee.ZodBranded,type:this,...ie(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new dr({...ie(this._def),innerType:this,catchValue:n,typeName:ee.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return oi.create(this,e)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tb=/^c[^\s-]{8,}$/i,xb=/^[0-9a-z]+$/,Ib=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rb=/^[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,Eb=/^[a-z0-9_-]{21}$/i,Ab=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cb=/^[-+]?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)?)??$/,$b=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Nb=/^(?:(?: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])$/,jb=/^(?:(?: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])$/,Ob=/^(([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]))$/,Mb=/^(([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])$/,zb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Db=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rd="((\\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])))",Lb=new RegExp(`^${Rd}$`);Sn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_type,expected:q.string,received:i.parsedType}),X}let r=new Me,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:P.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),D(s,{code:P.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?D(s,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&D(s,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$b.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"email",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")yl||(yl=new RegExp(Pb,"u")),yl.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"emoji",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Rb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"uuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Eb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"nanoid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")xb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid2",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ib.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ulid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),D(s,{validation:"url",code:P.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),D(s,{validation:"regex",code:P.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),D(s,{code:P.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),D(s,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Ad(i).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Lb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ub(i).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Cb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"duration",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ip",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Fb(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"jwt",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cidr",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?zb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Db.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64url",code:P.invalid_string,message:i.message}),r.dirty()):ue.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:P.invalid_string,...W.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...W.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...W.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...W.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...W.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...W.errToObj(n)})}nonempty(e){return this.min(1,W.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}};Sn.create=t=>new Sn({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...ie(t)});Xn=class t extends le{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)!==q.number){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_type,expected:q.number,received:i.parsedType}),X}let r,s=new Me;for(let i of this._def.checks)i.kind==="int"?ue.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:P.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),D(r,{code:P.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),D(r,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Hb(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_finite,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&ue.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)}};Xn.create=t=>new Xn({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...ie(t)});Qn=class t extends le{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)!==q.bigint)return this._getInvalidInput(e);let r,s=new Me;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),D(r,{code:P.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),D(r,{code:P.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),D(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return D(n,{code:P.invalid_type,expected:q.bigint,received:n.parsedType}),X}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.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:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.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}};Qn.create=t=>new Qn({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...ie(t)});er=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:q.boolean,received:r.parsedType}),X}return De(e.data)}};er.create=t=>new er({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...ie(t)});tr=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_type,expected:q.date,received:i.parsedType}),X}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_date}),X}let r=new Me,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:P.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),D(s,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ue.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:W.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:W.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}};tr.create=t=>new tr({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...ie(t)});as=class extends le{_parse(e){if(this._getType(e)!==q.symbol){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:q.symbol,received:r.parsedType}),X}return De(e.data)}};as.create=t=>new as({typeName:ee.ZodSymbol,...ie(t)});nr=class extends le{_parse(e){if(this._getType(e)!==q.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:q.undefined,received:r.parsedType}),X}return De(e.data)}};nr.create=t=>new nr({typeName:ee.ZodUndefined,...ie(t)});rr=class extends le{_parse(e){if(this._getType(e)!==q.null){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:q.null,received:r.parsedType}),X}return De(e.data)}};rr.create=t=>new rr({typeName:ee.ZodNull,...ie(t)});Tn=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return De(e.data)}};Tn.create=t=>new Tn({typeName:ee.ZodAny,...ie(t)});tn=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return De(e.data)}};tn.create=t=>new tn({typeName:ee.ZodUnknown,...ie(t)});xt=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return D(n,{code:P.invalid_type,expected:q.never,received:n.parsedType}),X}};xt.create=t=>new xt({typeName:ee.ZodNever,...ie(t)});ls=class extends le{_parse(e){if(this._getType(e)!==q.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:q.void,received:r.parsedType}),X}return De(e.data)}};ls.create=t=>new ls({typeName:ee.ZodVoid,...ie(t)});nn=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==q.array)return D(n,{code:P.invalid_type,expected:q.array,received:n.parsedType}),X;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(D(n,{code:o?P.too_big:P.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&&(D(n,{code:P.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&&(D(n,{code:P.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 ut(n,o,n.path,l)))).then(o=>Me.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ut(n,o,n.path,l)));return Me.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:W.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:W.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:W.toString(n)}})}nonempty(e){return this.min(1,e)}};nn.create=(t,e)=>new nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...ie(e)});Xe=class t extends le{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=ue.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==q.object){let d=this._getOrReturnCtx(e);return D(d,{code:P.invalid_type,expected:q.object,received:d.parsedType}),X}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof xt&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||l.push(d);let c=[];for(let d of o){let p=i[d],f=s.data[d];c.push({key:{status:"valid",value:d},value:p._parse(new ut(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof xt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&(D(s,{code:P.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:d._parse(new ut(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of c){let f=await p.key,b=await p.value;d.push({key:f,value:b,alwaysSet:p.alwaysSet})}return d}).then(d=>Me.mergeObjectSync(r,d)):Me.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return W.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:W.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:ee.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 ue.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 ue.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return os(this)}partial(e){let n={};for(let r of ue.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 ue.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ct;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Cd(ue.objectKeys(this.shape))}};Xe.create=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strip",catchall:xt.create(),typeName:ee.ZodObject,...ie(e)});Xe.strictCreate=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strict",catchall:xt.create(),typeName:ee.ZodObject,...ie(e)});Xe.lazycreate=(t,e)=>new Xe({shape:t,unknownKeys:"strip",catchall:xt.create(),typeName:ee.ZodObject,...ie(e)});sr=class extends le{_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 Ye(l.ctx.common.issues));return D(n,{code:P.invalid_union,unionErrors:o}),X}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 d={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Ye(c));return D(n,{code:P.invalid_union,unionErrors:l}),X}}get options(){return this._def.options}};sr.create=(t,e)=>new sr({options:t,typeName:ee.ZodUnion,...ie(e)});en=t=>t instanceof or?en(t.schema):t instanceof dt?en(t.innerType()):t instanceof ar?[t.value]:t instanceof lr?t.options:t instanceof cr?ue.objectValues(t.enum):t instanceof ur?en(t._def.innerType):t instanceof nr?[void 0]:t instanceof rr?[null]:t instanceof ct?[void 0,...en(t.unwrap())]:t instanceof zt?[null,...en(t.unwrap())]:t instanceof ii||t instanceof hr?en(t.unwrap()):t instanceof dr?en(t._def.innerType):[],ao=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return D(n,{code:P.invalid_type,expected:q.object,received:n.parsedType}),X;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}):(D(n,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),X)}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=en(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:ee.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ie(r)})}};ir=class extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(io(i)||io(o))return X;let l=bl(i.value,o.value);return l.valid?((oo(i)||oo(o))&&n.dirty(),{status:n.value,value:l.data}):(D(r,{code:P.invalid_intersection_types}),X)};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}))}};ir.create=(t,e,n)=>new ir({left:t,right:e,typeName:ee.ZodIntersection,...ie(n)});Mt=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==q.array)return D(r,{code:P.invalid_type,expected:q.array,received:r.parsedType}),X;if(r.data.length<this._def.items.length)return D(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&r.data.length>this._def.items.length&&(D(r,{code:P.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 ut(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Me.mergeArray(n,o)):Me.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Mt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mt({items:t,typeName:ee.ZodTuple,rest:null,...ie(e)})};lo=class t extends le{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!==q.object)return D(r,{code:P.invalid_type,expected:q.object,received:r.parsedType}),X;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ut(r,l,r.path,l)),value:o._parse(new ut(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Me.mergeObjectAsync(n,s):Me.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof le?new t({keyType:e,valueType:n,typeName:ee.ZodRecord,...ie(r)}):new t({keyType:Sn.create(),valueType:e,typeName:ee.ZodRecord,...ie(n)})}},cs=class extends le{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!==q.map)return D(r,{code:P.invalid_type,expected:q.map,received:r.parsedType}),X;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new ut(r,l,r.path,[d,"key"])),value:i._parse(new ut(r,c,r.path,[d,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let d=await c.key,p=await c.value;if(d.status==="aborted"||p.status==="aborted")return X;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let d=c.key,p=c.value;if(d.status==="aborted"||p.status==="aborted")return X;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};cs.create=(t,e,n)=>new cs({valueType:e,keyType:t,typeName:ee.ZodMap,...ie(n)});us=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==q.set)return D(r,{code:P.invalid_type,expected:q.set,received:r.parsedType}),X;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(D(r,{code:P.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&&(D(r,{code:P.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 d=new Set;for(let p of c){if(p.status==="aborted")return X;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let l=[...r.data.values()].map((c,d)=>i._parse(new ut(r,c,r.path,d)));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:W.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:W.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};us.create=(t,e)=>new us({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...ie(e)});co=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==q.function)return D(n,{code:P.invalid_type,expected:q.function,received:n.parsedType}),X;function r(l,c){return si({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ss(),Qt].filter(d=>!!d),issueData:{code:P.invalid_arguments,argumentsError:c}})}function s(l,c){return si({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ss(),Qt].filter(d=>!!d),issueData:{code:P.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof xn){let l=this;return De(async function(...c){let d=new Ye([]),p=await l._def.args.parseAsync(c,i).catch(w=>{throw d.addIssue(r(c,w)),d}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(w=>{throw d.addIssue(s(f,w)),d})})}else{let l=this;return De(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new Ye([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Ye([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Mt.create(e).rest(tn.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||Mt.create([]).rest(tn.create()),returns:n||tn.create(),typeName:ee.ZodFunction,...ie(r)})}},or=class extends le{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})}};or.create=(t,e)=>new or({getter:t,typeName:ee.ZodLazy,...ie(e)});ar=class extends le{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return D(n,{received:n.data,code:P.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}};ar.create=(t,e)=>new ar({value:t,typeName:ee.ZodLiteral,...ie(e)});lr=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{expected:ue.joinValues(r),received:n.parsedType,code:P.invalid_type}),X}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 D(n,{received:n.data,code:P.invalid_enum_value,options:r}),X}return De(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})}};lr.create=Cd;cr=class extends le{_parse(e){let n=ue.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==q.string&&r.parsedType!==q.number){let s=ue.objectValues(n);return D(r,{expected:ue.joinValues(s),received:r.parsedType,code:P.invalid_type}),X}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ue.objectValues(n);return D(r,{received:r.data,code:P.invalid_enum_value,options:s}),X}return De(e.data)}get enum(){return this._def.values}};cr.create=(t,e)=>new cr({values:t,typeName:ee.ZodNativeEnum,...ie(e)});xn=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==q.promise&&n.common.async===!1)return D(n,{code:P.invalid_type,expected:q.promise,received:n.parsedType}),X;let r=n.parsedType===q.promise?n.data:Promise.resolve(n.data);return De(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};xn.create=(t,e)=>new xn({type:t,typeName:ee.ZodPromise,...ie(e)});dt=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.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=>{D(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return X;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?X:c.status==="dirty"?Yn(c.value):n.value==="dirty"?Yn(c.value):c});{if(n.value==="aborted")return X;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?X:l.status==="dirty"?Yn(l.value):n.value==="dirty"?Yn(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?X:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?X:(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(!_n(o))return X;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=>_n(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):X);ue.assertNever(s)}};dt.create=(t,e,n)=>new dt({schema:t,typeName:ee.ZodEffects,effect:e,...ie(n)});dt.createWithPreprocess=(t,e,n)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...ie(n)});ct=class extends le{_parse(e){return this._getType(e)===q.undefined?De(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(t,e)=>new ct({innerType:t,typeName:ee.ZodOptional,...ie(e)});zt=class extends le{_parse(e){return this._getType(e)===q.null?De(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:ee.ZodNullable,...ie(e)});ur=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===q.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};ur.create=(t,e)=>new ur({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ie(e)});dr=class extends le{_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 is(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};dr.create=(t,e)=>new dr({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ie(e)});ds=class extends le{_parse(e){if(this._getType(e)!==q.nan){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:q.nan,received:r.parsedType}),X}return{status:"valid",value:e.data}}};ds.create=t=>new ds({typeName:ee.ZodNaN,...ie(t)});Kb=Symbol("zod_brand"),ii=class extends le{_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}},oi=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?X:i.status==="dirty"?(n.dirty(),Yn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?X: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:ee.ZodPipeline})}},hr=class extends le{_parse(e){let n=this._def.innerType._parse(e),r=s=>(_n(s)&&(s.value=Object.freeze(s.value)),s);return is(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:ee.ZodReadonly,...ie(e)});Gb={object:Xe.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"})(ee||(ee={}));Wb=(t,e={message:`Input not instance of ${t.name}`})=>$d(n=>n instanceof t,e),Pd=Sn.create,Nd=Xn.create,Zb=ds.create,Vb=Qn.create,jd=er.create,Jb=tr.create,Yb=as.create,Xb=nr.create,Qb=rr.create,ew=Tn.create,tw=tn.create,nw=xt.create,rw=ls.create,sw=nn.create,iw=Xe.create,ow=Xe.strictCreate,aw=sr.create,lw=ao.create,cw=ir.create,uw=Mt.create,dw=lo.create,hw=cs.create,pw=us.create,fw=co.create,mw=or.create,gw=ar.create,yw=lr.create,bw=cr.create,ww=xn.create,vw=dt.create,kw=ct.create,_w=zt.create,Sw=dt.createWithPreprocess,Tw=oi.create,xw=()=>Pd().optional(),Iw=()=>Nd().optional(),Rw=()=>jd().optional(),Ew={string:(t=>Sn.create({...t,coerce:!0})),number:(t=>Xn.create({...t,coerce:!0})),boolean:(t=>er.create({...t,coerce:!0})),bigint:(t=>Qn.create({...t,coerce:!0})),date:(t=>tr.create({...t,coerce:!0}))},Aw=X});var k={};at(k,{BRAND:()=>Kb,DIRTY:()=>Yn,EMPTY_PATH:()=>Sb,INVALID:()=>X,NEVER:()=>Aw,OK:()=>De,ParseStatus:()=>Me,Schema:()=>le,ZodAny:()=>Tn,ZodArray:()=>nn,ZodBigInt:()=>Qn,ZodBoolean:()=>er,ZodBranded:()=>ii,ZodCatch:()=>dr,ZodDate:()=>tr,ZodDefault:()=>ur,ZodDiscriminatedUnion:()=>ao,ZodEffects:()=>dt,ZodEnum:()=>lr,ZodError:()=>Ye,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>co,ZodIntersection:()=>ir,ZodIssueCode:()=>P,ZodLazy:()=>or,ZodLiteral:()=>ar,ZodMap:()=>cs,ZodNaN:()=>ds,ZodNativeEnum:()=>cr,ZodNever:()=>xt,ZodNull:()=>rr,ZodNullable:()=>zt,ZodNumber:()=>Xn,ZodObject:()=>Xe,ZodOptional:()=>ct,ZodParsedType:()=>q,ZodPipeline:()=>oi,ZodPromise:()=>xn,ZodReadonly:()=>hr,ZodRecord:()=>lo,ZodSchema:()=>le,ZodSet:()=>us,ZodString:()=>Sn,ZodSymbol:()=>as,ZodTransformer:()=>dt,ZodTuple:()=>Mt,ZodType:()=>le,ZodUndefined:()=>nr,ZodUnion:()=>sr,ZodUnknown:()=>tn,ZodVoid:()=>ls,addIssueToContext:()=>D,any:()=>ew,array:()=>sw,bigint:()=>Vb,boolean:()=>jd,coerce:()=>Ew,custom:()=>$d,date:()=>Jb,datetimeRegex:()=>Ad,defaultErrorMap:()=>Qt,discriminatedUnion:()=>lw,effect:()=>vw,enum:()=>yw,function:()=>fw,getErrorMap:()=>ss,getParsedType:()=>Ot,instanceof:()=>Wb,intersection:()=>cw,isAborted:()=>io,isAsync:()=>is,isDirty:()=>oo,isValid:()=>_n,late:()=>Gb,lazy:()=>mw,literal:()=>gw,makeIssue:()=>si,map:()=>hw,nan:()=>Zb,nativeEnum:()=>bw,never:()=>nw,null:()=>Qb,nullable:()=>_w,number:()=>Nd,object:()=>iw,objectUtil:()=>fl,oboolean:()=>Rw,onumber:()=>Iw,optional:()=>kw,ostring:()=>xw,pipeline:()=>Tw,preprocess:()=>Sw,promise:()=>ww,quotelessJson:()=>vb,record:()=>dw,set:()=>pw,setErrorMap:()=>_b,strictObject:()=>ow,string:()=>Pd,symbol:()=>Yb,transformer:()=>vw,tuple:()=>uw,undefined:()=>Xb,union:()=>aw,unknown:()=>tw,util:()=>ue,void:()=>rw});var wl=Q(()=>{so();gl();Sd();ri();Od();ro()});var In=Q(()=>{wl();wl()});function ne(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ho.default.join(uo.default.homedir(),".config","allwright"),n=ho.default.join(uo.default.homedir(),".config","ticketpilot");return!rn.default.existsSync(e)&&rn.default.existsSync(n)?n:e}function sn(){return ho.default.join(ne(),"runner.json")}function ke(){let t=sn();if(!rn.default.existsSync(t))return null;let e=JSON.parse(rn.default.readFileSync(t,"utf8"));return vl.parse(e)}function me(t){let e=ne();rn.default.mkdirSync(e,{recursive:!0,mode:448});let n=sn(),r=n+".tmp";rn.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function pd(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})}fd.Command=hl});var wd=he(lt=>{var{Argument:gd}=no(),{Command:pl}=md(),{CommanderError:bb,InvalidArgumentError:yd}=ni(),{Help:wb}=sl(),{Option:bd}=ll();lt.program=new pl;lt.createCommand=t=>new pl(t);lt.createOption=(t,e)=>new bd(t,e);lt.createArgument=(t,e)=>new gd(t,e);lt.Command=pl;lt.Option=bd;lt.Argument=gd;lt.Help=wb;lt.CommanderError=bb;lt.InvalidArgumentError=yd;lt.InvalidOptionArgumentError=yd});var ue,fl,F,Ot,ri=Q(()=>{(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})(ue||(ue={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(fl||(fl={}));F=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ot=t=>{switch(typeof t){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(t)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(t)?F.array:t===null?F.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?F.promise:typeof Map<"u"&&t instanceof Map?F.map:typeof Set<"u"&&t instanceof Set?F.set:typeof Date<"u"&&t instanceof Date?F.date:F.object;default:return F.unknown}}});var P,vb,Ye,ro=Q(()=>{ri();P=ue.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"]),vb=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ye=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 d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],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,ue.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()}};Ye.create=t=>new Ye(t)});var kb,Qt,ml=Q(()=>{ro();ri();kb=(t,e)=>{let n;switch(t.code){case P.invalid_type:t.received===F.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case P.invalid_union:n="Invalid input";break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${ue.joinValues(t.options)}, received '${t.received}'`;break;case P.invalid_arguments:n="Invalid function arguments";break;case P.invalid_return_type:n="Invalid function return type";break;case P.invalid_date:n="Invalid date";break;case P.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}"`:ue.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case P.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 P.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 P.custom:n="Invalid input";break;case P.invalid_intersection_types:n="Intersection results could not be merged";break;case P.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case P.not_finite:n="Number must be finite";break;default:n=e.defaultError,ue.assertNever(t)}return{message:n}},Qt=kb});function _b(t){_d=t}function ss(){return _d}var _d,so=Q(()=>{ml();_d=Qt});function D(t,e){let n=ss(),r=si({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 si,Sb,Me,X,Yn,De,io,oo,_n,is,gl=Q(()=>{so();ml();si=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(d=>!!d).slice().reverse();for(let d of c)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Sb=[];Me=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 X;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 X;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}}},X=Object.freeze({status:"aborted"}),Yn=t=>({status:"dirty",value:t}),De=t=>({status:"valid",value:t}),io=t=>t.status==="aborted",oo=t=>t.status==="dirty",_n=t=>t.status==="valid",is=t=>typeof Promise<"u"&&t instanceof Promise});var Sd=Q(()=>{});var W,Td=Q(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}))});function ie(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 Ed(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 Ub(t){return new RegExp(`^${Ed(t)}$`)}function Ad(t){let e=`${Rd}T${Ed(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 qb(t,e){return!!((e==="v4"||!e)&&Nb.test(t)||(e==="v6"||!e)&&Ob.test(t))}function Fb(t,e){if(!Ab.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 Bb(t,e){return!!((e==="v4"||!e)&&jb.test(t)||(e==="v6"||!e)&&Mb.test(t))}function Hb(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 os(t){if(t instanceof Xe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ct.create(os(r))}return new Xe({...t._def,shape:()=>e})}else return t instanceof nn?new nn({...t._def,type:os(t.element)}):t instanceof ct?ct.create(os(t.unwrap())):t instanceof zt?zt.create(os(t.unwrap())):t instanceof Mt?Mt.create(t.items.map(e=>os(e))):t}function bl(t,e){let n=Ot(t),r=Ot(e);if(t===e)return{valid:!0,data:t};if(n===F.object&&r===F.object){let s=ue.objectKeys(e),i=ue.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=bl(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===F.array&&r===F.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=bl(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===F.date&&r===F.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Cd(t,e){return new lr({values:t,typeName:ee.ZodEnum,...ie(e)})}function Id(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function $d(t,e={},n){return t?Tn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Id(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Id(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Tn.create()}var ut,xd,le,Tb,xb,Ib,Rb,Eb,Ab,Cb,$b,Pb,yl,Nb,jb,Ob,Mb,zb,Db,Rd,Lb,Sn,Xn,Qn,er,tr,as,nr,rr,Tn,tn,xt,ls,nn,Xe,sr,en,ao,ir,Mt,lo,cs,us,co,or,ar,lr,cr,xn,dt,ct,zt,ur,dr,ds,Kb,ii,oi,hr,Gb,ee,Wb,Pd,Nd,Zb,Vb,jd,Jb,Yb,Xb,Qb,ew,tw,nw,rw,sw,iw,ow,aw,lw,cw,uw,dw,hw,pw,fw,mw,gw,yw,bw,ww,vw,kw,_w,Sw,Tw,xw,Iw,Rw,Ew,Aw,Od=Q(()=>{ro();so();Td();gl();ri();ut=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}},xd=(t,e)=>{if(_n(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 Ye(t.common.issues);return this._error=n,this._error}}};le=class{get description(){return this._def.description}_getType(e){return Ot(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Me,ctx:{common:e.parent.common,data:e.data,parsedType:Ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(is(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:Ot(e)},s=this._parseSync({data:e,path:r.path,parent:r});return xd(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ot(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return _n(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=>_n(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:Ot(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(is(s)?s:Promise.resolve(s));return xd(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:P.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 dt({schema:this,typeName:ee.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 ct.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nn.create(this)}promise(){return xn.create(this,this._def)}or(e){return sr.create([this,e],this._def)}and(e){return ir.create(this,e,this._def)}transform(e){return new dt({...ie(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new ur({...ie(this._def),innerType:this,defaultValue:n,typeName:ee.ZodDefault})}brand(){return new ii({typeName:ee.ZodBranded,type:this,...ie(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new dr({...ie(this._def),innerType:this,catchValue:n,typeName:ee.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return oi.create(this,e)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tb=/^c[^\s-]{8,}$/i,xb=/^[0-9a-z]+$/,Ib=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rb=/^[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,Eb=/^[a-z0-9_-]{21}$/i,Ab=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cb=/^[-+]?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)?)??$/,$b=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Nb=/^(?:(?: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])$/,jb=/^(?:(?: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])$/,Ob=/^(([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]))$/,Mb=/^(([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])$/,zb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Db=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rd="((\\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])))",Lb=new RegExp(`^${Rd}$`);Sn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_type,expected:F.string,received:i.parsedType}),X}let r=new Me,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:P.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),D(s,{code:P.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?D(s,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&D(s,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$b.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"email",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")yl||(yl=new RegExp(Pb,"u")),yl.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"emoji",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Rb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"uuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Eb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"nanoid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")xb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid2",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ib.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ulid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),D(s,{validation:"url",code:P.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),D(s,{validation:"regex",code:P.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),D(s,{code:P.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),D(s,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Ad(i).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Lb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ub(i).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:P.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Cb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"duration",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ip",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Fb(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"jwt",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cidr",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?zb.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Db.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64url",code:P.invalid_string,message:i.message}),r.dirty()):ue.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:P.invalid_string,...W.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...W.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...W.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...W.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...W.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...W.errToObj(n)})}nonempty(e){return this.min(1,W.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}};Sn.create=t=>new Sn({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...ie(t)});Xn=class t extends le{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)!==F.number){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_type,expected:F.number,received:i.parsedType}),X}let r,s=new Me;for(let i of this._def.checks)i.kind==="int"?ue.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:P.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),D(r,{code:P.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),D(r,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Hb(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),D(r,{code:P.not_finite,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&ue.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)}};Xn.create=t=>new Xn({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...ie(t)});Qn=class t extends le{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)!==F.bigint)return this._getInvalidInput(e);let r,s=new Me;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),D(r,{code:P.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),D(r,{code:P.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),D(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return D(n,{code:P.invalid_type,expected:F.bigint,received:n.parsedType}),X}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.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:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.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}};Qn.create=t=>new Qn({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...ie(t)});er=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:F.boolean,received:r.parsedType}),X}return De(e.data)}};er.create=t=>new er({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...ie(t)});tr=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_type,expected:F.date,received:i.parsedType}),X}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return D(i,{code:P.invalid_date}),X}let r=new Me,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:P.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),D(s,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ue.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:W.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:W.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}};tr.create=t=>new tr({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...ie(t)});as=class extends le{_parse(e){if(this._getType(e)!==F.symbol){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:F.symbol,received:r.parsedType}),X}return De(e.data)}};as.create=t=>new as({typeName:ee.ZodSymbol,...ie(t)});nr=class extends le{_parse(e){if(this._getType(e)!==F.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:F.undefined,received:r.parsedType}),X}return De(e.data)}};nr.create=t=>new nr({typeName:ee.ZodUndefined,...ie(t)});rr=class extends le{_parse(e){if(this._getType(e)!==F.null){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:F.null,received:r.parsedType}),X}return De(e.data)}};rr.create=t=>new rr({typeName:ee.ZodNull,...ie(t)});Tn=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return De(e.data)}};Tn.create=t=>new Tn({typeName:ee.ZodAny,...ie(t)});tn=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return De(e.data)}};tn.create=t=>new tn({typeName:ee.ZodUnknown,...ie(t)});xt=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return D(n,{code:P.invalid_type,expected:F.never,received:n.parsedType}),X}};xt.create=t=>new xt({typeName:ee.ZodNever,...ie(t)});ls=class extends le{_parse(e){if(this._getType(e)!==F.undefined){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:F.void,received:r.parsedType}),X}return De(e.data)}};ls.create=t=>new ls({typeName:ee.ZodVoid,...ie(t)});nn=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==F.array)return D(n,{code:P.invalid_type,expected:F.array,received:n.parsedType}),X;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(D(n,{code:o?P.too_big:P.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&&(D(n,{code:P.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&&(D(n,{code:P.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 ut(n,o,n.path,l)))).then(o=>Me.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ut(n,o,n.path,l)));return Me.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:W.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:W.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:W.toString(n)}})}nonempty(e){return this.min(1,e)}};nn.create=(t,e)=>new nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...ie(e)});Xe=class t extends le{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=ue.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==F.object){let d=this._getOrReturnCtx(e);return D(d,{code:P.invalid_type,expected:F.object,received:d.parsedType}),X}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof xt&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||l.push(d);let c=[];for(let d of o){let p=i[d],f=s.data[d];c.push({key:{status:"valid",value:d},value:p._parse(new ut(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof xt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&(D(s,{code:P.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:d._parse(new ut(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of c){let f=await p.key,b=await p.value;d.push({key:f,value:b,alwaysSet:p.alwaysSet})}return d}).then(d=>Me.mergeObjectSync(r,d)):Me.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return W.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:W.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:ee.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 ue.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 ue.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return os(this)}partial(e){let n={};for(let r of ue.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 ue.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ct;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Cd(ue.objectKeys(this.shape))}};Xe.create=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strip",catchall:xt.create(),typeName:ee.ZodObject,...ie(e)});Xe.strictCreate=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strict",catchall:xt.create(),typeName:ee.ZodObject,...ie(e)});Xe.lazycreate=(t,e)=>new Xe({shape:t,unknownKeys:"strip",catchall:xt.create(),typeName:ee.ZodObject,...ie(e)});sr=class extends le{_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 Ye(l.ctx.common.issues));return D(n,{code:P.invalid_union,unionErrors:o}),X}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 d={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Ye(c));return D(n,{code:P.invalid_union,unionErrors:l}),X}}get options(){return this._def.options}};sr.create=(t,e)=>new sr({options:t,typeName:ee.ZodUnion,...ie(e)});en=t=>t instanceof or?en(t.schema):t instanceof dt?en(t.innerType()):t instanceof ar?[t.value]:t instanceof lr?t.options:t instanceof cr?ue.objectValues(t.enum):t instanceof ur?en(t._def.innerType):t instanceof nr?[void 0]:t instanceof rr?[null]:t instanceof ct?[void 0,...en(t.unwrap())]:t instanceof zt?[null,...en(t.unwrap())]:t instanceof ii||t instanceof hr?en(t.unwrap()):t instanceof dr?en(t._def.innerType):[],ao=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==F.object)return D(n,{code:P.invalid_type,expected:F.object,received:n.parsedType}),X;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}):(D(n,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),X)}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=en(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:ee.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ie(r)})}};ir=class extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(io(i)||io(o))return X;let l=bl(i.value,o.value);return l.valid?((oo(i)||oo(o))&&n.dirty(),{status:n.value,value:l.data}):(D(r,{code:P.invalid_intersection_types}),X)};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}))}};ir.create=(t,e,n)=>new ir({left:t,right:e,typeName:ee.ZodIntersection,...ie(n)});Mt=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==F.array)return D(r,{code:P.invalid_type,expected:F.array,received:r.parsedType}),X;if(r.data.length<this._def.items.length)return D(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&r.data.length>this._def.items.length&&(D(r,{code:P.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 ut(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Me.mergeArray(n,o)):Me.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Mt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mt({items:t,typeName:ee.ZodTuple,rest:null,...ie(e)})};lo=class t extends le{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!==F.object)return D(r,{code:P.invalid_type,expected:F.object,received:r.parsedType}),X;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ut(r,l,r.path,l)),value:o._parse(new ut(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Me.mergeObjectAsync(n,s):Me.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof le?new t({keyType:e,valueType:n,typeName:ee.ZodRecord,...ie(r)}):new t({keyType:Sn.create(),valueType:e,typeName:ee.ZodRecord,...ie(n)})}},cs=class extends le{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!==F.map)return D(r,{code:P.invalid_type,expected:F.map,received:r.parsedType}),X;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new ut(r,l,r.path,[d,"key"])),value:i._parse(new ut(r,c,r.path,[d,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let d=await c.key,p=await c.value;if(d.status==="aborted"||p.status==="aborted")return X;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let d=c.key,p=c.value;if(d.status==="aborted"||p.status==="aborted")return X;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};cs.create=(t,e,n)=>new cs({valueType:e,keyType:t,typeName:ee.ZodMap,...ie(n)});us=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==F.set)return D(r,{code:P.invalid_type,expected:F.set,received:r.parsedType}),X;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(D(r,{code:P.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&&(D(r,{code:P.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 d=new Set;for(let p of c){if(p.status==="aborted")return X;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let l=[...r.data.values()].map((c,d)=>i._parse(new ut(r,c,r.path,d)));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:W.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:W.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};us.create=(t,e)=>new us({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...ie(e)});co=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==F.function)return D(n,{code:P.invalid_type,expected:F.function,received:n.parsedType}),X;function r(l,c){return si({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ss(),Qt].filter(d=>!!d),issueData:{code:P.invalid_arguments,argumentsError:c}})}function s(l,c){return si({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ss(),Qt].filter(d=>!!d),issueData:{code:P.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof xn){let l=this;return De(async function(...c){let d=new Ye([]),p=await l._def.args.parseAsync(c,i).catch(w=>{throw d.addIssue(r(c,w)),d}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(w=>{throw d.addIssue(s(f,w)),d})})}else{let l=this;return De(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new Ye([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Ye([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Mt.create(e).rest(tn.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||Mt.create([]).rest(tn.create()),returns:n||tn.create(),typeName:ee.ZodFunction,...ie(r)})}},or=class extends le{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})}};or.create=(t,e)=>new or({getter:t,typeName:ee.ZodLazy,...ie(e)});ar=class extends le{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return D(n,{received:n.data,code:P.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}};ar.create=(t,e)=>new ar({value:t,typeName:ee.ZodLiteral,...ie(e)});lr=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return D(n,{expected:ue.joinValues(r),received:n.parsedType,code:P.invalid_type}),X}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 D(n,{received:n.data,code:P.invalid_enum_value,options:r}),X}return De(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})}};lr.create=Cd;cr=class extends le{_parse(e){let n=ue.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==F.string&&r.parsedType!==F.number){let s=ue.objectValues(n);return D(r,{expected:ue.joinValues(s),received:r.parsedType,code:P.invalid_type}),X}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ue.objectValues(n);return D(r,{received:r.data,code:P.invalid_enum_value,options:s}),X}return De(e.data)}get enum(){return this._def.values}};cr.create=(t,e)=>new cr({values:t,typeName:ee.ZodNativeEnum,...ie(e)});xn=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==F.promise&&n.common.async===!1)return D(n,{code:P.invalid_type,expected:F.promise,received:n.parsedType}),X;let r=n.parsedType===F.promise?n.data:Promise.resolve(n.data);return De(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};xn.create=(t,e)=>new xn({type:t,typeName:ee.ZodPromise,...ie(e)});dt=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.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=>{D(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return X;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?X:c.status==="dirty"?Yn(c.value):n.value==="dirty"?Yn(c.value):c});{if(n.value==="aborted")return X;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?X:l.status==="dirty"?Yn(l.value):n.value==="dirty"?Yn(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?X:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?X:(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(!_n(o))return X;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=>_n(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):X);ue.assertNever(s)}};dt.create=(t,e,n)=>new dt({schema:t,typeName:ee.ZodEffects,effect:e,...ie(n)});dt.createWithPreprocess=(t,e,n)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...ie(n)});ct=class extends le{_parse(e){return this._getType(e)===F.undefined?De(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(t,e)=>new ct({innerType:t,typeName:ee.ZodOptional,...ie(e)});zt=class extends le{_parse(e){return this._getType(e)===F.null?De(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:ee.ZodNullable,...ie(e)});ur=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===F.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};ur.create=(t,e)=>new ur({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ie(e)});dr=class extends le{_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 is(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};dr.create=(t,e)=>new dr({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ie(e)});ds=class extends le{_parse(e){if(this._getType(e)!==F.nan){let r=this._getOrReturnCtx(e);return D(r,{code:P.invalid_type,expected:F.nan,received:r.parsedType}),X}return{status:"valid",value:e.data}}};ds.create=t=>new ds({typeName:ee.ZodNaN,...ie(t)});Kb=Symbol("zod_brand"),ii=class extends le{_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}},oi=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?X:i.status==="dirty"?(n.dirty(),Yn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?X: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:ee.ZodPipeline})}},hr=class extends le{_parse(e){let n=this._def.innerType._parse(e),r=s=>(_n(s)&&(s.value=Object.freeze(s.value)),s);return is(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:ee.ZodReadonly,...ie(e)});Gb={object:Xe.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"})(ee||(ee={}));Wb=(t,e={message:`Input not instance of ${t.name}`})=>$d(n=>n instanceof t,e),Pd=Sn.create,Nd=Xn.create,Zb=ds.create,Vb=Qn.create,jd=er.create,Jb=tr.create,Yb=as.create,Xb=nr.create,Qb=rr.create,ew=Tn.create,tw=tn.create,nw=xt.create,rw=ls.create,sw=nn.create,iw=Xe.create,ow=Xe.strictCreate,aw=sr.create,lw=ao.create,cw=ir.create,uw=Mt.create,dw=lo.create,hw=cs.create,pw=us.create,fw=co.create,mw=or.create,gw=ar.create,yw=lr.create,bw=cr.create,ww=xn.create,vw=dt.create,kw=ct.create,_w=zt.create,Sw=dt.createWithPreprocess,Tw=oi.create,xw=()=>Pd().optional(),Iw=()=>Nd().optional(),Rw=()=>jd().optional(),Ew={string:(t=>Sn.create({...t,coerce:!0})),number:(t=>Xn.create({...t,coerce:!0})),boolean:(t=>er.create({...t,coerce:!0})),bigint:(t=>Qn.create({...t,coerce:!0})),date:(t=>tr.create({...t,coerce:!0}))},Aw=X});var k={};at(k,{BRAND:()=>Kb,DIRTY:()=>Yn,EMPTY_PATH:()=>Sb,INVALID:()=>X,NEVER:()=>Aw,OK:()=>De,ParseStatus:()=>Me,Schema:()=>le,ZodAny:()=>Tn,ZodArray:()=>nn,ZodBigInt:()=>Qn,ZodBoolean:()=>er,ZodBranded:()=>ii,ZodCatch:()=>dr,ZodDate:()=>tr,ZodDefault:()=>ur,ZodDiscriminatedUnion:()=>ao,ZodEffects:()=>dt,ZodEnum:()=>lr,ZodError:()=>Ye,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>co,ZodIntersection:()=>ir,ZodIssueCode:()=>P,ZodLazy:()=>or,ZodLiteral:()=>ar,ZodMap:()=>cs,ZodNaN:()=>ds,ZodNativeEnum:()=>cr,ZodNever:()=>xt,ZodNull:()=>rr,ZodNullable:()=>zt,ZodNumber:()=>Xn,ZodObject:()=>Xe,ZodOptional:()=>ct,ZodParsedType:()=>F,ZodPipeline:()=>oi,ZodPromise:()=>xn,ZodReadonly:()=>hr,ZodRecord:()=>lo,ZodSchema:()=>le,ZodSet:()=>us,ZodString:()=>Sn,ZodSymbol:()=>as,ZodTransformer:()=>dt,ZodTuple:()=>Mt,ZodType:()=>le,ZodUndefined:()=>nr,ZodUnion:()=>sr,ZodUnknown:()=>tn,ZodVoid:()=>ls,addIssueToContext:()=>D,any:()=>ew,array:()=>sw,bigint:()=>Vb,boolean:()=>jd,coerce:()=>Ew,custom:()=>$d,date:()=>Jb,datetimeRegex:()=>Ad,defaultErrorMap:()=>Qt,discriminatedUnion:()=>lw,effect:()=>vw,enum:()=>yw,function:()=>fw,getErrorMap:()=>ss,getParsedType:()=>Ot,instanceof:()=>Wb,intersection:()=>cw,isAborted:()=>io,isAsync:()=>is,isDirty:()=>oo,isValid:()=>_n,late:()=>Gb,lazy:()=>mw,literal:()=>gw,makeIssue:()=>si,map:()=>hw,nan:()=>Zb,nativeEnum:()=>bw,never:()=>nw,null:()=>Qb,nullable:()=>_w,number:()=>Nd,object:()=>iw,objectUtil:()=>fl,oboolean:()=>Rw,onumber:()=>Iw,optional:()=>kw,ostring:()=>xw,pipeline:()=>Tw,preprocess:()=>Sw,promise:()=>ww,quotelessJson:()=>vb,record:()=>dw,set:()=>pw,setErrorMap:()=>_b,strictObject:()=>ow,string:()=>Pd,symbol:()=>Yb,transformer:()=>vw,tuple:()=>uw,undefined:()=>Xb,union:()=>aw,unknown:()=>tw,util:()=>ue,void:()=>rw});var wl=Q(()=>{so();gl();Sd();ri();Od();ro()});var In=Q(()=>{wl();wl()});function ne(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ho.default.join(uo.default.homedir(),".config","allwright"),n=ho.default.join(uo.default.homedir(),".config","ticketpilot");return!rn.default.existsSync(e)&&rn.default.existsSync(n)?n:e}function sn(){return ho.default.join(ne(),"runner.json")}function ke(){let t=sn();if(!rn.default.existsSync(t))return null;let e=JSON.parse(rn.default.readFileSync(t,"utf8"));return vl.parse(e)}function me(t){let e=ne();rn.default.mkdirSync(e,{recursive:!0,mode:448});let n=sn(),r=n+".tmp";rn.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
24
24
|
`,{mode:384}),rn.default.renameSync(r,n),rn.default.chmodSync(n,384)}function po(t,e){return`${t}:${e}`}function Dt(t,e,n){return t.environments[po(e,n)]?.secrets??{}}function fo(t,e){return t.repos[e]?.jira??t.jira}function ai(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function de(){let t=ke();if(!t)throw new Error(`No runner config found at ${sn()}. Run \`allwright init\` first.`);return t}var rn,uo,ho,Md,vl,Ae=Q(()=>{"use strict";rn=E(require("node:fs"),1),uo=E(require("node:os"),1),ho=E(require("node:path"),1);In();Md=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),vl=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(uo.default.hostname()),jira:Md.optional(),repos:k.record(k.object({path:k.string(),jira:Md.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30),operatorEnabled:k.boolean().default(!1)})});function Ud(t,e){let n=Rn.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 ps(t,e,n,r){if(!e.length)return"";let s=Rn.default.join(n,yo);hs.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=Ld){r("warn",`attachment cap reached (${Ld} files) - skipping the rest`);break}if(c.size>Pw){r("warn",`skipping attachment "${c.filename}" - ${Mw(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Nw){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let d=await t.downloadAttachment(c.contentUrl),p=Ud(c.filename,i);hs.default.writeFileSync(Rn.default.join(s,p),d),l+=d.length,o.push(`- ${yo}/${p} (${c.mimeType||"unknown type"}, ${kl(d.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${kl(d.length)} KB)`)}catch(d){r("warn",`could not download attachment "${c.filename}": ${d instanceof Error?d.message:d}`)}}return o.length?`
|
|
25
25
|
|
|
26
26
|
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:
|
|
@@ -661,8 +661,8 @@ YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
|
|
|
661
661
|
`,n=t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
|
|
662
662
|
`:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
|
|
663
663
|
`,r=t==="read_only_web"||t==="edit_no_shell_web"?`- You CAN search the public web (WebSearch) and fetch public pages (WebFetch) - use them for current documentation, error messages, versions and comparisons. Never put code from this repository, file paths, or anything secret into a query or URL, and never fetch private/internal addresses.
|
|
664
|
-
`:"";return e+n+r+'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 Go=Q(()=>{"use strict"});function n_(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Wo.default.join(Tp.default.homedir(),".claude");try{if(gc.default.existsSync(Wo.default.join(e,".credentials.json"))||gc.default.existsSync(Wo.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function r_(t,e,n){let r=o=>typeof e[o]=="string"?e[o]:"",i=(o=>o.startsWith(n+"/")?o.slice(n.length+1):o)(r("file_path")||r("path")||r("notebook_path"));switch(t){case"Read":return{verb:"Read",target:i};case"Glob":return{verb:"Looked for files",target:r("pattern")};case"Grep":return{verb:"Searched for",target:r("pattern")};case"Bash":return{verb:"Ran",target:r("description")||r("command")};case"Edit":case"MultiEdit":return{verb:"Edited",target:i};case"Write":return{verb:"Wrote",target:i};case"NotebookEdit":return{verb:"Edited",target:i};case"WebFetch":return{verb:"Fetched",target:r("url")};case"WebSearch":return{verb:"Searched the web for",target:r("query")};case"Task":return{verb:"Started a sub-agent",target:r("description")};case"TodoWrite":return{verb:"Updated its plan",target:""};default:return{verb:`Used ${t}`,target:r("description")}}}async function s_(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",t_[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=n_(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,xp.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,d=0,p=0,f=0,b=()=>{if(!t.onUsage)return;let Y=Date.now();Y-f<e_||(f=Y,t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,turns:o}))},w=!1,_=()=>{w||(w=!0,clearTimeout(R),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 R=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+Ps(t.mode)),s.stdin.end(),Ip.default.createInterface({input:s.stdout}).on("line",Y=>{if(!Y.trim())return;let C;try{C=JSON.parse(Y)}catch{t.onLog("agent",Y.slice(0,1e3));return}if(C.type==="system"&&C.subtype==="init")i.model=typeof C.model=="string"?C.model:void 0,t.onLog("info",`Claude Code session started (model: ${C.model??"default"})`);else if(C.type==="assistant"){o+=1,l=C.message?.stop_reason==="max_tokens",l&&t.onLog("error","the agent hit its output limit mid-message - this reply is cut off, not finished");let v=C.message?.usage;if(v){c+=Number(v.input_tokens??0)+Number(v.cache_creation_input_tokens??0);let N=JSON.stringify(C.message?.content??[]).length;d+=Math.max(Number(v.output_tokens??0),Math.round(N/4)),p+=Number(v.cache_read_input_tokens??0),b()}for(let N of C.message?.content??[])if(N.type==="text"&&N.text?.trim())t.onLog("agent",N.text.trim().slice(0,4e3));else if(N.type==="tool_use"){let O=N.input??{},B=["file_path","path","pattern","command","description","url"].map(u=>typeof O[u]=="string"?`${u}=${O[u]}`:null).filter(Boolean).join(" "),F=JSON.stringify(O).slice(0,400);if(t.onLog("info",`tool ${N.name} ${B?`${B} `:""}${F}`),t.onTool){let u=r_(String(N.name??""),O,t.repoPath);t.onTool(u.verb,u.target.slice(0,200))}}}else C.type==="result"&&(i.costUsd=Number(C.total_cost_usd??0),i.inputTokens=Number(C.usage?.input_tokens??0)+Number(C.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(C.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),d=Math.max(i.outputTokens,d),i.inputTokens=c,i.outputTokens=d,p=Number(C.usage?.cache_read_input_tokens??p),i.cacheReadTokens=p,t.onUsage&&(t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,costUsd:i.costUsd,turns:o}),f=Date.now()),C.subtype==="success"&&!C.is_error?(i.ok=!0,i.resultText=String(C.result??""),i.outputTruncated=l):C.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=C.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String(C.result??C.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let J="";s.stderr.on("data",Y=>{J=(J+Y.toString()).slice(-2e3)}),s.on("error",Y=>{i.error=`failed to start ${t.bin}: ${Y.message}`,t.onLog("error",i.error),_()}),s.on("close",Y=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${Y}${J?`: ${J.slice(-500)}`:""}`),_()})})}var gc,Tp,Wo,xp,Ip,Rp,e_,t_,Zo,Ep=Q(()=>{"use strict";gc=E(require("node:fs"),1),Tp=E(require("node:os"),1),Wo=E(require("node:path"),1),xp=require("node:child_process"),Ip=E(require("node:readline"),1),Rp=E(Ee(),1);Go();e_=4e3,t_={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"],read_only_web:["Read(./**)","Glob(./**)","Grep(./**)","WebSearch","WebFetch"],edit_no_shell_web:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)","WebSearch","WebFetch"],operator:["Bash","Read","Glob","Grep","Edit","Write"]};Zo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Rp.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:s_}});async function i_(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,Ap.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+Ps(t.mode)),r.stdin.end(),Cp.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let b;try{b=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let w=b.item??b.msg??b,_=w?.type??b.type,x=w?.text??w?.message??"";_==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):_==="command_execution"||_==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):_==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let p="";r.stderr.on("data",f=>{p=(p+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")+(p?`: ${p.slice(-500)}`:"")),l()})})}var Ap,Cp,$p,yc,Pp=Q(()=>{"use strict";Ap=require("node:child_process"),Cp=E(require("node:readline"),1),$p=E(Ee(),1);Go();yc={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:$p.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:i_}});function u_(t){return t.resume?t.sessionId?["--session",t.sessionId]:["--continue"]:t.sessionId?["--session",t.sessionId]:[]}function h_(t,e,n){let r=c=>typeof e[c]=="string"?e[c]:"",s=(...c)=>c.map(r).find(d=>d)??"",o=(c=>c.startsWith(n+"/")?c.slice(n.length+1):c)(s("file_path","path","file","filename","dir","directory")),l=t.toLowerCase();if(l.includes("web")||l.includes("fetch")||l.includes("url")){let c=r("url");return c?{verb:"Fetched",target:c}:{verb:"Searched the web for",target:s("query","q")}}return l.includes("read")||l.includes("view")||l.includes("open")?{verb:"Read",target:o}:l.includes("glob")||l.includes("list")||l==="ls"?{verb:"Looked for files",target:s("pattern","glob")||o}:l.includes("grep")||l.includes("search")||l.includes("find")?{verb:"Searched for",target:s("pattern","query","regex")||o}:l.includes("write")||l.includes("create")?{verb:"Wrote",target:o}:l.includes("edit")||l.includes("replace")||l.includes("patch")?{verb:"Edited",target:o}:l.includes("shell")||l.includes("bash")||l.includes("exec")||l.includes("command")?{verb:"Ran",target:s("command","cmd","script")}:{verb:`Used ${t||"a tool"}`,target:s("description","command","query","pattern")||o}}function bc(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"?String(e.text??""):"").filter(Boolean).join(`
|
|
665
|
-
`):""}function p_(t){let e=[];for(let n of Array.isArray(t?.tool_calls)?t.tool_calls:[]){let r=n?.function??n,s={},i=r?.arguments??n?.arguments??n?.input;if(i&&typeof i=="object")s=i;else if(typeof i=="string")try{let o=JSON.parse(i);o&&typeof o=="object"?s=o:s={description:i}}catch{s={description:i}}e.push({name:String(r?.name??n?.name??""),input:s})}for(let n of Array.isArray(t?.content)?t.content:[])n?.type==="tool_use"&&e.push({name:String(n.name??""),input:n.input??{}});return e}async function f_(t){let e=r=>({ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:r});if(!a_.includes(t.mode))return e("the kimi adapter only supports read-only runs - it has no verified way to allow edits while refusing a shell, and Allwright never weakens a guarantee silently");let n=["--prompt",t.prompt+Ps(t.mode)+c_,"--output-format","stream-json",...t.model?["--model",t.model]:[],...u_(t)];return t.onLog("info",l_),new Promise(r=>{let s=(0,Np.spawn)(t.bin,n,{cwd:t.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]});s.stdin.end();let i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},o="",l="",c=0,d=0,p=0,f=0,b=0,w=!1,_=new Set,x=(u=!1)=>{if(!t.onUsage||!w)return;let m=Date.now();if(!u&&m-b<o_)return;b=m;let g={inputTokens:d,outputTokens:p,cacheReadTokens:f,turns:c};t.onUsage(g)},R=!1,A=()=>{R||(R=!0,clearTimeout(Y),t.signal?.removeEventListener("abort",J),r(i))},J=()=>{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",J,{once:!0});let Y=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),C=jp.default.createInterface({input:s.stdout});C.on("line",u=>{if(!u.trim())return;let m;try{m=JSON.parse(u)}catch{t.onLog("agent",u.slice(0,1e3));return}let g=m.message??m,S=String(g?.role??m.type??"");if(m.type==="system"&&m.subtype==="init"){typeof m.model=="string"&&(i.model=m.model),t.onLog("info",`Kimi session started (model: ${m.model??"default"})`);return}if(S==="assistant"){c+=1;let $=g?.usage??m.usage;$&&(w=!0,d+=Number($.input_tokens??$.prompt_tokens??0),p+=Number($.output_tokens??$.completion_tokens??0),f+=Number($.cache_read_input_tokens??$.cached_tokens??0),x());let
|
|
664
|
+
`:"";return e+n+r+'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 Go=Q(()=>{"use strict"});function n_(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Wo.default.join(Tp.default.homedir(),".claude");try{if(gc.default.existsSync(Wo.default.join(e,".credentials.json"))||gc.default.existsSync(Wo.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function r_(t,e,n){let r=o=>typeof e[o]=="string"?e[o]:"",i=(o=>o.startsWith(n+"/")?o.slice(n.length+1):o)(r("file_path")||r("path")||r("notebook_path"));switch(t){case"Read":return{verb:"Read",target:i};case"Glob":return{verb:"Looked for files",target:r("pattern")};case"Grep":return{verb:"Searched for",target:r("pattern")};case"Bash":return{verb:"Ran",target:r("description")||r("command")};case"Edit":case"MultiEdit":return{verb:"Edited",target:i};case"Write":return{verb:"Wrote",target:i};case"NotebookEdit":return{verb:"Edited",target:i};case"WebFetch":return{verb:"Fetched",target:r("url")};case"WebSearch":return{verb:"Searched the web for",target:r("query")};case"Task":return{verb:"Started a sub-agent",target:r("description")};case"TodoWrite":return{verb:"Updated its plan",target:""};default:return{verb:`Used ${t}`,target:r("description")}}}async function s_(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",t_[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=n_(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,xp.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,d=0,p=0,f=0,b=()=>{if(!t.onUsage)return;let Y=Date.now();Y-f<e_||(f=Y,t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,turns:o}))},w=!1,_=()=>{w||(w=!0,clearTimeout(R),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 R=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+Ps(t.mode)),s.stdin.end(),Ip.default.createInterface({input:s.stdout}).on("line",Y=>{if(!Y.trim())return;let C;try{C=JSON.parse(Y)}catch{t.onLog("agent",Y.slice(0,1e3));return}if(C.type==="system"&&C.subtype==="init")i.model=typeof C.model=="string"?C.model:void 0,t.onLog("info",`Claude Code session started (model: ${C.model??"default"})`);else if(C.type==="assistant"){o+=1,l=C.message?.stop_reason==="max_tokens",l&&t.onLog("error","the agent hit its output limit mid-message - this reply is cut off, not finished");let v=C.message?.usage;if(v){c+=Number(v.input_tokens??0)+Number(v.cache_creation_input_tokens??0);let j=JSON.stringify(C.message?.content??[]).length;d+=Math.max(Number(v.output_tokens??0),Math.round(j/4)),p+=Number(v.cache_read_input_tokens??0),b()}for(let j of C.message?.content??[])if(j.type==="text"&&j.text?.trim())t.onLog("agent",j.text.trim().slice(0,4e3));else if(j.type==="tool_use"){let O=j.input??{},H=["file_path","path","pattern","command","description","url"].map(u=>typeof O[u]=="string"?`${u}=${O[u]}`:null).filter(Boolean).join(" "),B=JSON.stringify(O).slice(0,400);if(t.onLog("info",`tool ${j.name} ${H?`${H} `:""}${B}`),t.onTool){let u=r_(String(j.name??""),O,t.repoPath);t.onTool(u.verb,u.target.slice(0,200))}}}else C.type==="result"&&(i.costUsd=Number(C.total_cost_usd??0),i.inputTokens=Number(C.usage?.input_tokens??0)+Number(C.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(C.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),d=Math.max(i.outputTokens,d),i.inputTokens=c,i.outputTokens=d,p=Number(C.usage?.cache_read_input_tokens??p),i.cacheReadTokens=p,t.onUsage&&(t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,costUsd:i.costUsd,turns:o}),f=Date.now()),C.subtype==="success"&&!C.is_error?(i.ok=!0,i.resultText=String(C.result??""),i.outputTruncated=l):C.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=C.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String(C.result??C.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let J="";s.stderr.on("data",Y=>{J=(J+Y.toString()).slice(-2e3)}),s.on("error",Y=>{i.error=`failed to start ${t.bin}: ${Y.message}`,t.onLog("error",i.error),_()}),s.on("close",Y=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${Y}${J?`: ${J.slice(-500)}`:""}`),_()})})}var gc,Tp,Wo,xp,Ip,Rp,e_,t_,Zo,Ep=Q(()=>{"use strict";gc=E(require("node:fs"),1),Tp=E(require("node:os"),1),Wo=E(require("node:path"),1),xp=require("node:child_process"),Ip=E(require("node:readline"),1),Rp=E(Ee(),1);Go();e_=4e3,t_={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"],read_only_web:["Read(./**)","Glob(./**)","Grep(./**)","WebSearch","WebFetch"],edit_no_shell_web:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)","WebSearch","WebFetch"],operator:["Bash","Read","Glob","Grep","Edit","Write"]};Zo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Rp.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:s_}});async function i_(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,Ap.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+Ps(t.mode)),r.stdin.end(),Cp.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let b;try{b=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let w=b.item??b.msg??b,_=w?.type??b.type,x=w?.text??w?.message??"";_==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):_==="command_execution"||_==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):_==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let p="";r.stderr.on("data",f=>{p=(p+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")+(p?`: ${p.slice(-500)}`:"")),l()})})}var Ap,Cp,$p,yc,Pp=Q(()=>{"use strict";Ap=require("node:child_process"),Cp=E(require("node:readline"),1),$p=E(Ee(),1);Go();yc={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:$p.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:i_}});function u_(t){return t.resume?t.sessionId?["--session",t.sessionId]:["--continue"]:t.sessionId?["--session",t.sessionId]:[]}function h_(t,e,n){let r=c=>typeof e[c]=="string"?e[c]:"",s=(...c)=>c.map(r).find(d=>d)??"",o=(c=>c.startsWith(n+"/")?c.slice(n.length+1):c)(s("file_path","path","file","filename","dir","directory")),l=t.toLowerCase();if(l.includes("web")||l.includes("fetch")||l.includes("url")){let c=r("url");return c?{verb:"Fetched",target:c}:{verb:"Searched the web for",target:s("query","q")}}return l.includes("read")||l.includes("view")||l.includes("open")?{verb:"Read",target:o}:l.includes("glob")||l.includes("list")||l==="ls"?{verb:"Looked for files",target:s("pattern","glob")||o}:l.includes("grep")||l.includes("search")||l.includes("find")?{verb:"Searched for",target:s("pattern","query","regex")||o}:l.includes("write")||l.includes("create")?{verb:"Wrote",target:o}:l.includes("edit")||l.includes("replace")||l.includes("patch")?{verb:"Edited",target:o}:l.includes("shell")||l.includes("bash")||l.includes("exec")||l.includes("command")?{verb:"Ran",target:s("command","cmd","script")}:{verb:`Used ${t||"a tool"}`,target:s("description","command","query","pattern")||o}}function bc(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"?String(e.text??""):"").filter(Boolean).join(`
|
|
665
|
+
`):""}function p_(t){let e=[];for(let n of Array.isArray(t?.tool_calls)?t.tool_calls:[]){let r=n?.function??n,s={},i=r?.arguments??n?.arguments??n?.input;if(i&&typeof i=="object")s=i;else if(typeof i=="string")try{let o=JSON.parse(i);o&&typeof o=="object"?s=o:s={description:i}}catch{s={description:i}}e.push({name:String(r?.name??n?.name??""),input:s})}for(let n of Array.isArray(t?.content)?t.content:[])n?.type==="tool_use"&&e.push({name:String(n.name??""),input:n.input??{}});return e}async function f_(t){let e=r=>({ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:r});if(!a_.includes(t.mode))return e("the kimi adapter only supports read-only runs - it has no verified way to allow edits while refusing a shell, and Allwright never weakens a guarantee silently");let n=["--prompt",t.prompt+Ps(t.mode)+c_,"--output-format","stream-json",...t.model?["--model",t.model]:[],...u_(t)];return t.onLog("info",l_),new Promise(r=>{let s=(0,Np.spawn)(t.bin,n,{cwd:t.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]});s.stdin.end();let i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},o="",l="",c=0,d=0,p=0,f=0,b=0,w=!1,_=new Set,x=(u=!1)=>{if(!t.onUsage||!w)return;let m=Date.now();if(!u&&m-b<o_)return;b=m;let g={inputTokens:d,outputTokens:p,cacheReadTokens:f,turns:c};t.onUsage(g)},R=!1,A=()=>{R||(R=!0,clearTimeout(Y),t.signal?.removeEventListener("abort",J),r(i))},J=()=>{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",J,{once:!0});let Y=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),C=jp.default.createInterface({input:s.stdout});C.on("line",u=>{if(!u.trim())return;let m;try{m=JSON.parse(u)}catch{t.onLog("agent",u.slice(0,1e3));return}let g=m.message??m,S=String(g?.role??m.type??"");if(m.type==="system"&&m.subtype==="init"){typeof m.model=="string"&&(i.model=m.model),t.onLog("info",`Kimi session started (model: ${m.model??"default"})`);return}if(S==="assistant"){c+=1;let $=g?.usage??m.usage;$&&(w=!0,d+=Number($.input_tokens??$.prompt_tokens??0),p+=Number($.output_tokens??$.completion_tokens??0),f+=Number($.cache_read_input_tokens??$.cached_tokens??0),x());let N=bc(g?.content).trim();N&&(o=N,t.onLog("agent",N.slice(0,4e3)));for(let G of p_(g)){let U=JSON.stringify(G.input).slice(0,400);if(t.onLog("info",`tool ${G.name} ${U}`),d_.test(G.name)&&!_.has(G.name)&&(_.add(G.name),t.onLog("error",`Kimi used "${G.name}" in a read-only run - this agent's read-only mode is an instruction, not a sandbox, so treat anything this run touched as changed.`)),t.onTool){let q=h_(G.name,G.input,t.repoPath);t.onTool(q.verb,q.target.slice(0,200))}}return}if(S==="tool"){let $=bc(g?.content).trim();$&&t.onLog("info",`tool result ${$.slice(0,300)}`);return}if(m.type==="result"){let $=m.usage;$&&(w=!0,d=Math.max(d,Number($.input_tokens??$.prompt_tokens??0)),p=Math.max(p,Number($.output_tokens??$.completion_tokens??0)),f=Math.max(f,Number($.cache_read_input_tokens??0))),m.is_error||m.subtype&&m.subtype!=="success"?i.error||(i.error=String(m.result??m.error??m.subtype??"unknown Kimi error")):l=String(m.result??"");return}if(S==="error"||m.type==="error"){let $=bc(g?.content)||String(m.error??m.message??"");$&&t.onLog("error",$.slice(0,1e3))}});let v="";s.stderr.on("data",u=>{v=(v+u.toString()).slice(-2e3)}),s.on("error",u=>{i.error=`failed to start ${t.bin}: ${u.message} - is the Kimi CLI installed and logged in?`,t.onLog("error",i.error),A()});let j=!1,O=!1,H=null,B=()=>{if(!j||!O||R)return;let u=(l||o).trim();H===0&&u&&!i.error?(i.ok=!0,i.resultText=u):i.error||(i.error=`kimi exited with code ${H}`+(u?"":" and produced no answer")+(v?`: ${v.slice(-500)}`:"")),i.inputTokens=d,i.outputTokens=p,i.cacheReadTokens=f,x(!0),A()};C.on("close",()=>{j=!0,B()}),s.on("close",u=>{O=!0,H=u,B()})})}var Np,jp,Op,o_,a_,l_,c_,d_,wc,Mp=Q(()=>{"use strict";Np=require("node:child_process"),jp=E(require("node:readline"),1),Op=E(Ee(),1);Go();o_=4e3,a_=["read_only","read_only_web"],l_="Kimi's read-only mode is PROMPT-LEVEL ONLY - this CLI has no sandbox switch to enforce it. Use it for repositories and tickets you already trust; every other agent here is jailed in code.",c_=`
|
|
666
666
|
|
|
667
667
|
READ-ONLY RUN - and on this agent that is an INSTRUCTION YOU MUST KEEP, not a sandbox that will stop you. Even if the tools are there:
|
|
668
668
|
- Do NOT create, edit, move or delete any file, and do NOT run any shell command.
|
|
@@ -728,12 +728,12 @@ Should this run implement the epic ticket itself?
|
|
|
728
728
|
${g}${Ce.NEEDS_INPUT_ASK_FENCE}
|
|
729
729
|
{"options": ["${K_}", "${G_}"]}
|
|
730
730
|
${g}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let A=t.continueBranch;A&&!d&&await Ml(t.repoPath,c)===!1&&(e("info",`Batch branch "${c}" is not on origin - an earlier ticket in this batch finished without pushing one. Starting it from origin/${o.baseBranch}.`),A=!1);let J=A?c:o.baseBranch;d?e("info",`Resuming the session that timed out on this ticket (timeout resume ${d.resumes}/${xc}) - same worktree, uncommitted work intact, repo context cached`):(e("info",A?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await Mn(t.repoPath,J),t.chain&&A||await zl(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 Bl(p,c,A?`origin/${c}`:`origin/${o.baseBranch}`)):await Dl(t.repoPath,p,c,J)),b=!0;let Y=hn(o.promptTemplate,{issueKey:R.key,summary:R.summary,description:R.description||"(no description)",comments:Ur(R.comments)});!d&&!eS(`${R.summary}
|
|
731
|
-
${R.description??""}`)&&e("info","This ticket names no files or symbols - the agent has to discover them, which costs extra reads. Tickets that name paths run cheaper.");let C=d?null:await Ol(p,o.baseBranch,R.key).catch(()=>null),v=[],
|
|
731
|
+
${R.description??""}`)&&e("info","This ticket names no files or symbols - the agent has to discover them, which costs extra reads. Tickets that name paths run cheaper.");let C=d?null:await Ol(p,o.baseBranch,R.key).catch(()=>null),v=[],j=(g,S)=>(S&&v.push({part:g,chars:S.length}),S),O=j("ticket: rule template + summary (rendered)",Y)+j("attachments listing",await ps(t.jira,R.attachments,p,e))+j("design guideline pointer",Oc(p))+j("knowledge: rules",B_(t.repoPath))+j("memory: retrieved history",qn("implement",t.repoPath,{issueKey:R.key,summary:R.summary,description:R.description,ruleName:t.rule.name}))+j("doc index",Jo(p))+j("repo brief (machine-generated)",t.chain?"":vi(t.project.repoName))+j("revision: previous delivery + what is new",C?Q_(C,R.comments,mt):"")+j("appendix: focused reading",Kn.FOCUSED_READING_PROMPT)+j("appendix: protected paths",L_)+j("appendix: needs-input options",Ce.NEEDS_INPUT_OPTIONS_PROMPT)+j("appendix: PR summary",U_)+j("appendix: go-live",t.project.goLiveIssueKey?q_:"")+j("appendix: write tests",o.writeTests?Kn.WRITE_TESTS_PROMPT:"")+j("appendix: update memory",o.updateMemory?Ce.MEMORY_UPDATE_PROMPT:"")+j("epic confirmation answer",t.preflightAnswer?`
|
|
732
732
|
|
|
733
733
|
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:
|
|
734
|
-
${t.preflightAnswer.slice(0,4e3)}`:"");R.description&&v.push({part:"\u21B3 of which ticket description",chars:R.description.length});let
|
|
734
|
+
${t.preflightAnswer.slice(0,4e3)}`:"");R.description&&v.push({part:"\u21B3 of which ticket description",chars:R.description.length});let H=Ur(R.comments).length;H&&v.push({part:"\u21B3 of which comment history",chars:H}),t.transport.sendRunContext({runId:t.runId,pieces:d?[{part:"continuation prompt (session resumed - original context already cached)",chars:Nc.length}]:v,totalChars:d?Nc.length:O.length,sessionMode:d?"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 B=await Ms(t.runId,Ze(o.agent),{repoPath:p,prompt:d?Nc:O,timeoutSeconds:o.timeoutSeconds,bin:je(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:o.allowWeb?"edit_no_shell_web":"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,maxCostUsd:o.maxCostUsd,sessionId:f,resume:!!t.chain||!!d,onLog:(g,S)=>e(g,S),onUsage:r},e,()=>$o(p)),u={costUsd:B.costUsd,inputTokens:B.inputTokens,outputTokens:B.outputTokens,billingMode:B.billingMode,model:B.model};if(!B.ok){let g=B.error??"Claude Code failed";e("error",`Run failed: ${g}`);let S=g,$=(B.timedOut||B.costCapped)&&!B.cancelled&&Ze(o.agent)?.capabilities.sessionResume&&(d?.resumes??0)<xc;if(B.turnLimitHit&&!$){let N=await ff(p,c,t.runId,e);N&&(S+=mf(N))}$&&(Wp(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:c,resumes:(d?.resumes??0)+1}),w=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),S+=" - 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"),gt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:g.slice(0,500)}),await Os(t,S),n(B.timedOut?"timed_out":"failed",{error:S,...B.cancelled||B.costCapped?{errorKind:"guard"}:{},...u});return}let m=Ci(B.resultText);if(m){_=!0,await Ii({kind:"implement",allowWeb:o.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:p,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:R.summary},m,e,n,u);return}En(p),await gf({runId:t.runId,issueKey:t.issueKey,issueSummary:R.summary,worktreePath:p,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:B.resultText,costFields:u,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns,allowWeb:o.allowWeb},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:n}),t.onChainSession?.({sessionId:f,worktreePath:p})}catch(x){let R=x instanceof Error?x.message:String(x);e("error",`Run failed: ${R}`),gt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:R.slice(0,500)}),await Os(t,R),n("failed",{error:R})}finally{b&&!_&&!t.keepWorktree&&!w&&await qt(t.repoPath,p).catch(()=>{})}}async function zc(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Lr(t.runId,r.transport,t.nextLogSeq);if(t.preflight==="epic-confirm"){let p=e.trim();if(/stop this run/i.test(p)){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 Ei({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,d=!1;if(!ra.default.existsSync(c)){i("failed",{error:`the workspace this run was parked in (${c}) no longer exists - it was cleaned up while the question waited (an autopilot batch that moved on, or a runner restart). The answer was still posted to ${t.issueKey}; re-trigger the ticket and the fresh run will read it there.`,errorKind:"guard"});return}try{if(!Mo(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 p=Sf(e)+await ps(r.jiraFor(t.repoName??""),n,c,s),f=await Ms(t.runId,Ze(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:je(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:t.allowWeb?"edit_no_shell_web":"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(_,x)=>s(_,x),onUsage:o},s,()=>$o(c)),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let _=f.error??"Claude Code failed";s("error",`Run failed: ${_}`);let x=_;if(f.turnLimitHit&&t.branch){let R=await ff(c,t.branch,t.runId,s);R&&(x+=mf(R))}await Kt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),Ht(t.runId),i(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...b});return}let w=Ci(f.resultText);if(w){if(t.rounds>=lf){await Tf(r.jiraFor(t.repoName??""),t,s,i,b);return}d=!0,await Ii({kind:"implement",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},w,s,i,b);return}En(c),await gf({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:c,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??c,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,requireApproval:t.requireApproval??!0,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:r.jiraFor(t.repoName??""),cfg:r.cfg,actorEmail:t.actorEmail,resultText:f.resultText,costFields:b,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns,allowWeb:t.allowWeb},sendUsage:o,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),Ht(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Kt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),Ht(t.runId),i("failed",{error:f})}finally{d||await qt(t.baseRepoPath??c,c).catch(()=>{})}}async function gf(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:b,repoName:w,jira:_,cfg:x,actorEmail:R,runTests:A,mergeOnApprove:J,mergeMethod:Y,autoMerge:C,resultText:v,costFields:j,emit:O,setStatus:H}=t,B=await Ss(s);B.deleted.length&&O("info",`Deleted ${B.deleted.length} file(s) listed in ${cn}: `+B.deleted.slice(0,10).join(", ")+(B.deleted.length>10?", \u2026":""));for(let re of B.refused)O("warn",`${cn} entry refused: ${re}`);O("info","Committing changes"),await Pr(s,`${n}: ${r}
|
|
735
735
|
|
|
736
|
-
Allwright run ${e}`);let u=await zn(s,l);if(!u.ok){let re=u.forbidden.length?`refusing to push: changes touch protected paths (${u.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 (${u.files} files, ${u.insertions+u.deletions} lines; limits ${jn}/${On})`;O("error",re),await Kt(_,n,e,b,re),
|
|
736
|
+
Allwright run ${e}`);let u=await zn(s,l);if(!u.ok){let re=u.forbidden.length?`refusing to push: changes touch protected paths (${u.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 (${u.files} files, ${u.insertions+u.deletions} lines; limits ${jn}/${On})`;O("error",re),await Kt(_,n,e,b,re),H("failed",{error:re,errorKind:"guard",...j});return}O("info",`Diff: ${u.files} file(s), +${u.insertions}/-${u.deletions}`);let m={...j},g="",S="",$,N,G;if(A){let re=Cs(s);if(!re)O("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let Ie=Fn(ra.default.readFileSync(re,"utf8"));if(!Ie.length)O("info",`${sa.default.basename(re)} lists no commands - nothing to run`);else{O("info",`Running ${Ie.length} documented test command(s) - no tokens, plain shell`);let Pe=await dn(s,Ie,{perCommandTimeoutMs:15*6e4}),Ge=Pe.filter(fe=>fe.exitCode!==0),ti=Ge.length;for(let fe of Pe)O(fe.exitCode===0?"info":"warn",rf(fe));let kn="";if(Ge.length&&t.fixSession){let fe=await X_({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Ge,emit:O,sendUsage:t.sendUsage,baseCost:m});if(m.costUsd+=fe.cost.costUsd,m.inputTokens+=fe.cost.inputTokens,m.outputTokens+=fe.cost.outputTokens,fe.outcome==="cancelled"){let Je="stopped by a person during the automatic test-fix attempt - nothing was pushed";O("warn",Je),Xo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:J,mergeMethod:Y,autoMerge:C,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:await tt(s),requireApproval:p,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:R,resultSummary:af(v),prSummary:jc(v)??"",costUsd:m.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Kt(_,n,e,b,`${Je}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),H("failed",{error:Je,errorKind:"guard",retryAvailable:!0,...m});return}if(fe.outcome==="committed"){S=fe.resultText,O("info",`Re-running ${Ie.length} documented test command(s) after the fix`),Pe=await dn(s,Ie,{perCommandTimeoutMs:15*6e4}),Ge=Pe.filter(Je=>Je.exitCode!==0);for(let Je of Pe)O(Je.exitCode===0?"info":"warn",rf(Je));kn=Ge.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${ti} failure(s). ${fe.note}`:`The first pass had ${ti} failure(s); one automatic same-session fix attempt resolved them. ${fe.note}`}else kn=fe.note}$=Ge.slice(0,20).map(fe=>({command:fe.command.slice(0,500),exitCode:fe.exitCode,tail:fe.tail.slice(-4e3)})),N=Pe.length-Ge.length,G=Pe.length,g=`
|
|
737
737
|
|
|
738
738
|
### Tests
|
|
739
739
|
`+Pe.map(fe=>`- ${fe.exitCode===0?"PASS":"FAIL"} \`${fe.command}\``).join(`
|
|
@@ -745,11 +745,11 @@ All ${Pe.length} passed.`)+(kn?`
|
|
|
745
745
|
|
|
746
746
|
${kn}`:""),Ge.length&&O("warn",`${Ge.length} test command(s) failed - the PR will say so; review before merging`),ti>0&>(i,{issueKey:n,runId:e,title:Ge.length?`TEST.md commands failing at PR (${Ge.length} of ${Pe.length})`:"TEST.md failures fixed by same-session retry",detail:Pe.map(fe=>`${fe.exitCode===0?"PASS":"FAIL"} ${fe.command}`).join(`
|
|
747
747
|
`)+(kn?`
|
|
748
|
-
${kn}`:"")})}}}let
|
|
748
|
+
${kn}`:"")})}}}let U=await jr(s),q=Rt(U);if(!q){let re=`origin "${U}" is not a GitHub remote - implement mode supports GitHub only`;O("error",re),await Kt(_,n,e,b,re),H("failed",{error:re,...j});return}let L=await tt(s),ce=af(v),V=(S?jc(S):null)??jc(v);try{await yf({gitDir:s,ownerRepo:q,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:b,repoName:w,jira:_,cfg:x,actorEmail:R,mergeOnApprove:J,mergeMethod:Y,autoMerge:C,summary:ce,prSummary:V??void 0,cost:m,testReport:g,failedTests:$,testsPassed:N,testsTotal:G,goLiveDraft:(S?nf(S):null)??nf(v)??void 0,emit:O,setStatus:H})}catch(re){let Ie=re instanceof Error?re.message:String(re);Xo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:J,mergeMethod:Y,autoMerge:C,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:L,requireApproval:p,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:R,resultSummary:ce,prSummary:V??"",costUsd:m.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),O("error",`Run failed: ${Ie}`),O("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Kt(_,n,e,b,`${Ie}
|
|
749
749
|
|
|
750
|
-
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),
|
|
750
|
+
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),H("failed",{error:Ie,retryAvailable:!0,...m})}}async function X_(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:d,baseCost:p}=t,f=Ze(i.agent);if(!f?.capabilities.sessionResume){let A=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",A),{outcome:"skipped",note:A,cost:Y_}}c("info",`${l.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let b=await tt(r),w=await Ms(e,f,{repoPath:r,prompt:F_(l),timeoutSeconds:i.timeoutSeconds,bin:je(o,i.agent),configDir:t.agentConfigDir,mode:i.allowWeb?"edit_no_shell_web":"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(A,J)=>c(A,J),onUsage:d?A=>d({...A,inputTokens:p.inputTokens+A.inputTokens,outputTokens:p.outputTokens+A.outputTokens,costUsd:A.costUsd===void 0?void 0:p.costUsd+A.costUsd}):void 0},c),_={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:_};if(!w.ok){let A=`One automatic fix attempt did not complete (${w.error??"agent error"}) - the results above are from the original work.`;return c("warn",A),{outcome:"agent_failed",note:A,cost:_}}if(Ci(w.resultText)){let A="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",A),{outcome:"agent_failed",note:A,cost:_}}let x=await Ss(r);for(let A of x.refused)c("warn",`${cn} entry refused: ${A}`);try{await Pr(r,`${n}: fix failing TEST.md commands
|
|
751
751
|
|
|
752
|
-
Allwright run ${e} (automatic test-fix attempt)`)}catch{let A=`An automatic fix attempt concluded no code change was warranted: ${qr(w.resultText)}`;return c("info",A),{outcome:"no_changes",note:A,cost:_}}let R=await zn(r,s);if(!R.ok){await Ts(r,b);let A=R.forbidden.length?`An automatic fix attempt touched protected paths (${R.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",A),{outcome:"reverted",note:A,cost:_}}return{outcome:"committed",note:`Fix attempt: ${qr(w.resultText)}`,resultText:w.resultText,cost:_}}async function yf(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:d,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:b,requireApproval:w,doneLabel:_,failedLabel:x,repoName:R,jira:A,cfg:J,actorEmail:Y,summary:C,prSummary:v,cost:
|
|
752
|
+
Allwright run ${e} (automatic test-fix attempt)`)}catch{let A=`An automatic fix attempt concluded no code change was warranted: ${qr(w.resultText)}`;return c("info",A),{outcome:"no_changes",note:A,cost:_}}let R=await zn(r,s);if(!R.ok){await Ts(r,b);let A=R.forbidden.length?`An automatic fix attempt touched protected paths (${R.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",A),{outcome:"reverted",note:A,cost:_}}return{outcome:"committed",note:`Fix attempt: ${qr(w.resultText)}`,resultText:w.resultText,cost:_}}async function yf(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:d,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:b,requireApproval:w,doneLabel:_,failedLabel:x,repoName:R,jira:A,cfg:J,actorEmail:Y,summary:C,prSummary:v,cost:j,testReport:O,emit:H,setStatus:B}=t;H("info",`Pushing ${d} to origin`),await Nr(e,d);let u=await Po(e,d),g=`${v?.trim()?`${v.trim()}
|
|
753
753
|
|
|
754
754
|
<details>
|
|
755
755
|
<summary>Technical details</summary>
|
|
@@ -760,13 +760,13 @@ ${C}
|
|
|
760
760
|
|
|
761
761
|
---
|
|
762
762
|
Jira: ${new URL(`/browse/${s}`,J.jira?.baseUrl??"").toString()}
|
|
763
|
-
_Allwright implement run \`${r}\` \xB7 cost $${
|
|
763
|
+
_Allwright implement run \`${r}\` \xB7 cost $${j.costUsd.toFixed(4)}. `+(O?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");H("info","Opening pull request");let S=Mo(ke()??J,R,Y);S.source==="user"&&H("info",`PR will be authored with ${Y}'s own GitHub token`);let N=await new He(S.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:d,base:p,body:g});H("info",`PR ready: ${N.url}`),Yp({runId:r,issueKey:s,repoName:R,owner:n.owner,repo:n.repo,prNumber:N.number,prUrl:N.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),B("posting",j);let G={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:R,owner:n.owner,repo:n.repo,prNumber:N.number,prUrl:N.url,branch:d,headSha:u,doneLabel:_,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(w)bt(G),await A.addComment(s,`**Allwright opened a pull request for review.**
|
|
764
764
|
|
|
765
|
-
PR: ${
|
|
765
|
+
PR: ${N.url}
|
|
766
766
|
|
|
767
|
-
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}\`)`),
|
|
767
|
+
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}\`)`),B("awaiting_approval",{...j,prUrl:N.url,headSha:u,resultSummary:qr(v?.trim()||C),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),H("info",`Awaiting approval on the dashboard \xB7 $${j.costUsd.toFixed(4)}`);else{if(c){H("info",`Auto-merging PR #${N.number} (${l})`);let q=Fe(J,R),L=q?await new He(q).mergePullRequest(n.owner,n.repo,N.number,l,{sha:u,title:`${s} (#${N.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};L.merged?H("info",`PR #${N.number} merged`):(H("warn",`Auto-merge did not go through - ${L.reason}. The PR stays open.`),await A.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${L.reason}
|
|
768
768
|
|
|
769
|
-
PR: ${
|
|
769
|
+
PR: ${N.url}`))}let U=(ke()??J).repos[R]?.path;U&&gi(U,s)&>(U,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${N.url} merged/opened straight-through.`}),await bf({jira:A,issueKey:s},G,H),B("succeeded",{...j,prUrl:N.url,headSha:u,resultSummary:qr(v?.trim()||C),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),H("info",`Run succeeded \xB7 ${N.url} \xB7 $${j.costUsd.toFixed(4)}`)}}async function bf(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.**
|
|
770
770
|
|
|
771
771
|
PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
|
|
772
772
|
|
|
@@ -874,7 +874,7 @@ ${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed y
|
|
|
874
874
|
|
|
875
875
|
${i.slice(0,800)}
|
|
876
876
|
|
|
877
|
-
(run \`${t.runId}\`)`),n("failed",{error:i})}}function _S(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=Dt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&y.warn(`environment "${e.name}" lists ${i.join(", ")} under required secrets, but no step uses ${i.length===1?"it":"them"} - ignoring. Remove ${i.length===1?"it":"them"} from "Needs secrets" on the environment to silence this.`);let o=e.requiredSecrets.filter(l=>s.has(l)&&!r.has(l)&&!n[l]&&!process.env[l]);return o.length?`missing deploy secret(s) on this runner: ${o.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${o[0]}=...`:null}async function Yf(t,e,n){let r=t.environment,s=Dt(t.cfg,t.project.repoName,r.name),i=ji(Object.values(s)),o=Date.now(),l=[];if(n("running"),e("info",`Deploying ${t.issueKey} to "${r.name}"`+(t.requestedBy?` (requested by ${t.requestedBy})`:"")+` - ${r.steps.length} step(s), ${r.timeoutSeconds}s budget`),r.auditBeforeDeploy){e("info",`Pre-deploy ${r.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let C=Se(t.cfg,t.project,"assist"),v="error"in C?{ok:!1,error:C.error}:await $s({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:C,jira:t.jira});if(!v.ok)e("warn",`Pre-deploy audit could not run: ${v.error} - deploying anyway (advisory)`);else if(!v.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let
|
|
877
|
+
(run \`${t.runId}\`)`),n("failed",{error:i})}}function _S(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=Dt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&y.warn(`environment "${e.name}" lists ${i.join(", ")} under required secrets, but no step uses ${i.length===1?"it":"them"} - ignoring. Remove ${i.length===1?"it":"them"} from "Needs secrets" on the environment to silence this.`);let o=e.requiredSecrets.filter(l=>s.has(l)&&!r.has(l)&&!n[l]&&!process.env[l]);return o.length?`missing deploy secret(s) on this runner: ${o.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${o[0]}=...`:null}async function Yf(t,e,n){let r=t.environment,s=Dt(t.cfg,t.project.repoName,r.name),i=ji(Object.values(s)),o=Date.now(),l=[];if(n("running"),e("info",`Deploying ${t.issueKey} to "${r.name}"`+(t.requestedBy?` (requested by ${t.requestedBy})`:"")+` - ${r.steps.length} step(s), ${r.timeoutSeconds}s budget`),r.auditBeforeDeploy){e("info",`Pre-deploy ${r.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let C=Se(t.cfg,t.project,"assist"),v="error"in C?{ok:!1,error:C.error}:await $s({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:C,jira:t.jira});if(!v.ok)e("warn",`Pre-deploy audit could not run: ${v.error} - deploying anyway (advisory)`);else if(!v.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let j={};for(let O of v.audit.findings)j[O.severity]=(j[O.severity]??0)+1;e("warn",`Pre-deploy audit: ${v.audit.findings.length} finding(s) (`+Object.entries(j).map(([O,H])=>`${H} ${O}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let O of v.audit.findings.slice(0,5))e("warn",` [${O.severity}] ${O.title} - ${O.evidence[0]?.file??""}`)}}catch(C){e("warn",`Pre-deploy audit crashed: ${C instanceof Error?C.message:String(C)} - deploying anyway`)}}if(t.project.goLiveIssueKey)try{let{runGoLiveChecklist:C,describeGoLive:v}=await Promise.resolve().then(()=>(Kf(),Hf));e("info",`Go-live checklist: running what can be run from ${t.project.goLiveIssueKey}`);let j=await C({jira:t.jira,issueKey:t.project.goLiveIssueKey,repoPath:t.repoPath,onProgress:O=>e("info",` ${O}`)});for(let O of v(j,t.project.goLiveIssueKey))e(j.results.some(H=>H.exitCode!==0)?"warn":"info",O)}catch(C){e("warn",`Go-live checklist could not run: ${C instanceof Error?C.message:String(C)} - deploying anyway`)}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let v=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",v),await wt(t,`**Allwright refused to deploy to \`${r.name}\`.**
|
|
878
878
|
|
|
879
879
|
${v}
|
|
880
880
|
|
|
@@ -882,46 +882,46 @@ ${v}
|
|
|
882
882
|
|
|
883
883
|
Allwright run ${t.runId}`);if(!v.ok){e("error",v.reason??"merge failed"),await wt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
|
|
884
884
|
|
|
885
|
-
${v.reason}`),n("failed",{error:v.reason});return}v.alreadyMerged?e("info",`"${C}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Vl(c,r.branch))}let p=await tt(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Jc(c,r.workdir),b={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:t.issueKey,ALLWRIGHT_RUN_ID:t.runId,ALLWRIGHT_DEPLOY_REF:p,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:t.issueKey,TICKETPILOT_RUN_ID:t.runId,TICKETPILOT_DEPLOY_REF:p,TICKETPILOT_BRANCH:r.branch},w=0,_=r.timeoutSeconds*1e3,x=df(t.runId),R=()=>x.signal.aborted;try{for(let[C,v]of r.steps.entries()){if(R()){let
|
|
885
|
+
${v.reason}`),n("failed",{error:v.reason});return}v.alreadyMerged?e("info",`"${C}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Vl(c,r.branch))}let p=await tt(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Jc(c,r.workdir),b={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:t.issueKey,ALLWRIGHT_RUN_ID:t.runId,ALLWRIGHT_DEPLOY_REF:p,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:t.issueKey,TICKETPILOT_RUN_ID:t.runId,TICKETPILOT_DEPLOY_REF:p,TICKETPILOT_BRANCH:r.branch},w=0,_=r.timeoutSeconds*1e3,x=df(t.runId),R=()=>x.signal.aborted;try{for(let[C,v]of r.steps.entries()){if(R()){let H=`stopped from the dashboard during step ${C+1} - nothing further ran`;e("error",H),n("failed",{error:H,errorKind:"guard",deployedRef:p});return}let j=_-(Date.now()-o);if(j<=0){let H=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${C+1}`;e("error",H),await wt(t,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
886
886
|
|
|
887
|
-
${
|
|
887
|
+
${H}`),n("timed_out",{error:H,deployedRef:p});return}e("info",`\u25B6 step ${C+1}/${r.steps.length}: ${v.name}`);let O=await Xf({command:v.run,cwd:f,env:b,timeoutMs:j,signal:x.signal,onLine:(H,B)=>{w++;let u=kS(B);u&&l.length<20&&l.push(u),w===Gf&&e("warn","(output truncated - deploy log limit reached)"),!(w>=Gf)&&e(H,i(B))}});if(O.timedOut){let H=`step "${v.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",H),await wt(t,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
888
888
|
|
|
889
|
-
${
|
|
890
|
-
${u}`.trim(),{cwd:c})),g=`step ${C+1} "${v.name}" failed with exit code ${O.code}`+(
|
|
891
|
-
${
|
|
889
|
+
${H}`),n("timed_out",{error:H,deployedRef:p});return}if(O.code!==0){if(v.continueOnError){e("warn",`step "${v.name}" exited ${O.code} - continuing (marked continue-on-error)`);continue}let H="";try{H=i(await jl(c))}catch{}let B=O.failures?i(O.failures):"",u=O.tail?i(O.tail):"",m=xf(Lc(`${B}
|
|
890
|
+
${u}`.trim(),{cwd:c})),g=`step ${C+1} "${v.name}" failed with exit code ${O.code}`+(B?`:
|
|
891
|
+
${B}`:"")+(u?`${B?`
|
|
892
892
|
|
|
893
893
|
how the output ended:
|
|
894
|
-
`:": "}${u}`:"")+m+(
|
|
894
|
+
`:": "}${u}`:"")+m+(H?`
|
|
895
895
|
|
|
896
896
|
Checkout at failure:
|
|
897
|
-
${
|
|
897
|
+
${H}`:"");e("error",g),await wt(t,`**Allwright deploy to \`${r.name}\` failed.**
|
|
898
898
|
|
|
899
899
|
Step ${C+1} \`${v.name}\` exited ${O.code}.
|
|
900
900
|
|
|
901
|
-
`+(
|
|
902
|
-
${
|
|
901
|
+
`+(B?`\`\`\`
|
|
902
|
+
${B}
|
|
903
903
|
\`\`\`
|
|
904
904
|
|
|
905
|
-
`:"")+(u?`${
|
|
905
|
+
`:"")+(u?`${B?`How the output ended:
|
|
906
906
|
`:""}\`\`\`
|
|
907
907
|
${u.slice(0,1200)}
|
|
908
908
|
\`\`\`
|
|
909
909
|
|
|
910
910
|
`:"")+(m?`${m.trim()}
|
|
911
911
|
|
|
912
|
-
`:"")+(
|
|
912
|
+
`:"")+(H?`Checkout at failure:
|
|
913
913
|
\`\`\`
|
|
914
|
-
${
|
|
914
|
+
${H.slice(0,800)}
|
|
915
915
|
\`\`\`
|
|
916
916
|
|
|
917
917
|
`:"")+(l.length?`**Before retrying, these still need a person:**
|
|
918
918
|
`+l.map(S=>`- \`${S.command}\`${S.why?` - ${S.why}`:""}`).join(`
|
|
919
919
|
`)+`
|
|
920
920
|
|
|
921
|
-
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),gt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${C+1} "${v.name}" exit ${O.code}`+(
|
|
922
|
-
${(
|
|
921
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),gt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${C+1} "${v.name}" exit ${O.code}`+(B||u?`
|
|
922
|
+
${(B||u).slice(0,500)}`:"")}),l.length&&Wf(e,l),n("failed",{error:g.slice(0,4e3),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${C+1}/${r.steps.length}: ${v.name}`)}}finally{hf(t.runId)}if(p=await tt(c).catch(()=>"")||p,r.servePath?.trim()){let C=r.servePath.trim(),v=r.branch.trim(),j=await tt(C).catch(()=>"");if(!j)e("warn",`serving check: cannot read a git HEAD at ${C} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{p=j;let O=v?await Ll(C,v):"";if(!O)e("warn",`serving check: ${C} is at ${j.slice(0,10)}, but `+(v?`origin/${v} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${v||"commit"} could not be verified`);else if(j!==O){let H=await Ul(C,j,O),B=`The steps all succeeded, but the live checkout at ${C} is at ${j.slice(0,10)} while origin/${v} is at ${O.slice(0,10)}`+(H?` - ${H} commit(s) behind`:"")+`. Users are NOT getting the latest ${v}. Usually one of: a step pulls a different directory than the one that serves, the pull failed quietly, or the serve path in this environment's settings points at the wrong checkout.`;e("error",`serving check: ${B}`),await wt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
|
|
923
923
|
|
|
924
|
-
${
|
|
924
|
+
${B}`),gt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${j.slice(0,10)}, origin/${v} at ${O.slice(0,10)} (${C})`}),n("failed",{error:B,deployedRef:p});return}else e("info",`serving check: ${C} is at ${j.slice(0,10)} = origin/${v} - users get this build`)}}n("posting");let A=Math.round((Date.now()-o)/1e3),J=null;r.publicUrl?.trim()&&(J=await ES(r.publicUrl.trim()),e(J?"warn":"info",J??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Gr.BRANCH_DEPLOY_ISSUE_KEY&&await wt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
|
|
925
925
|
|
|
926
926
|
`+(J?`> **Live where?** ${J}
|
|
927
927
|
|
|
@@ -968,7 +968,7 @@ THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
|
|
|
968
968
|
- ${f.note}
|
|
969
969
|
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:Ff(qf({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,Zc.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=nu(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=tm(r.resultText),d=l?Oi(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 p=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return p?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:p==="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."+(c?" A fix ticket is drafted below - creating it starts the ordinary implement flow.":""),...p==="CODE"&&c?{fixTicketSummary:c.summary,fixTicketDescription:c.description}:{}}:{ok:!0,...s,notes:i||s.notes,docPath:d?.path??(l?"DEPLOY.md":""),docContent:l}}async function tu(t){let e=Oi(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=em(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=hn(Gr.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,Zc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=nu(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
970
970
|
`+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 nu(t){for(let e of $S(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=IS.safeParse(PS(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function $S(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 PS(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:Jf(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,d=Gc(c.run,c.command,c.cmd,c.script,c.shell);return d?{name:(Gc(c.name,c.title,c.description)??Jf(d,l)).slice(0,120),run:d,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:Gc(e.notes,e.note,e.explanation)??""}}function Gc(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Jf(t,e){return(t.split(`
|
|
971
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}var zs,Kr,ua,Wc,Zc,Gr,Ds,Gf,wS,vS,IS,Zf,Vf,Ls=Q(()=>{"use strict";zs=E(require("node:fs"),1);Es();If();Kr=E(require("node:path"),1),ua=require("node:child_process"),Wc=E(require("node:readline"),1),Zc=require("node:crypto"),Gr=E(Ee(),1);In();Ae();yt();Ds=E(Ee(),1);vc();Ft();Ct();Or();Ko();Ti();la();Fc();Kc();Fr();At();Gf=4e3,wS=4e3;vS=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;IS=k.object({steps:k.array(Gr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),Zf=24e3;Vf=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"]});var um={};at(um,{MAX_CHAIN_DEPTH:()=>su,breakChain:()=>lu,breakSingleModeChain:()=>hu,chainOf:()=>ou,chainSessionFor:()=>ga,loadBatchPlan:()=>iu,nextMemberWillChain:()=>pu,parsePlanAnswer:()=>fu,recordChainSession:()=>au,recordSingleModeSession:()=>uu,saveBatchPlan:()=>jS,singleModeChainIntact:()=>du,singleModeSessionFor:()=>cu});function jS(t){Us.default.mkdirSync(ru(),{recursive:!0,mode:448}),Us.default.writeFileSync(ma.default.join(ru(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function iu(t){if(!t)return null;try{return JSON.parse(Us.default.readFileSync(ma.default.join(ru(),`${t}.json`),"utf8"))}catch{return null}}function ou(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function ga(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=mn.get(fa(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=su||!Us.default.existsSync(s.worktreePath)?null:s}function au(t,e,n,r){let s=mn.get(fa(t,e));mn.set(fa(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function lu(t,e){mn.delete(fa(t,e))}function cu(t){let e=mn.get(Mi(t));return!e||e.depth>=su||!Us.default.existsSync(e.worktreePath)?null:e}function uu(t,e,n,r){let s=mn.get(Mi(t));mn.set(Mi(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function du(t,e){return mn.get(Mi(t))?.lastIssue===e}function hu(t){mn.delete(Mi(t))}function pu(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function fu(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(o.length!==e.length||!o.every(p=>i.has(p))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(p=>Array.isArray(p)?p.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(p=>p.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),d=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:d}}var Us,ma,su,ru,mn,fa,Mi,ya=Q(()=>{"use strict";Us=E(require("node:fs"),1),ma=E(require("node:path"),1);Ae();su=3,ru=()=>ma.default.join(ne(),"autopilot-plans");mn=new Map,fa=(t,e)=>`${t}:${e[0]}`;Mi=t=>`${t}:__single__`});var gn=he((RA,Jm)=>{"use strict";var Zm=["nodebuffer","arraybuffer","fragments"],Vm=typeof Blob<"u";Vm&&Zm.push("blob");Jm.exports={BINARY_TYPES:Zm,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Vm,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Li=he((EA,Sa)=>{"use strict";var{EMPTY_BUFFER:l0}=gn(),Su=Buffer[Symbol.species];function c0(t,e){if(t.length===0)return l0;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 Su(n.buffer,n.byteOffset,r):n}function Ym(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Xm(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function u0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Tu(t){if(Tu.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Su(t):ArrayBuffer.isView(t)?e=new Su(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Tu.readOnly=!1),e}Sa.exports={concat:c0,mask:Ym,toArrayBuffer:u0,toBuffer:Tu,unmask:Xm};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Sa.exports.mask=function(e,n,r,s,i){i<48?Ym(e,n,r,s,i):t.mask(e,n,r,s,i)},Sa.exports.unmask=function(e,n){e.length<32?Xm(e,n):t.unmask(e,n)}}catch{}});var tg=he((AA,eg)=>{"use strict";var Qm=Symbol("kDone"),xu=Symbol("kRun"),Iu=class{constructor(e){this[Qm]=()=>{this.pending--,this[xu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xu]()}[xu](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Qm])}}};eg.exports=Iu});var Bs=he((CA,ig)=>{"use strict";var Ui=require("zlib"),ng=Li(),d0=tg(),{kStatusCode:rg}=gn(),h0=Buffer[Symbol.species],p0=Buffer.from([0,0,255,255]),xa=Symbol("permessage-deflate"),yn=Symbol("total-length"),qs=Symbol("callback"),Wn=Symbol("buffers"),Fs=Symbol("error"),Ta,Ru=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,!Ta){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ta=new d0(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[qs];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){Ta.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Ta.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"?Ui.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ui.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[xa]=this,this._inflate[yn]=0,this._inflate[Wn]=[],this._inflate.on("error",m0),this._inflate.on("data",sg)}this._inflate[qs]=r,this._inflate.write(e),n&&this._inflate.write(p0),this._inflate.flush(()=>{let i=this._inflate[Fs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=ng.concat(this._inflate[Wn],this._inflate[yn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[yn]=0,this._inflate[Wn]=[],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"?Ui.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ui.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[yn]=0,this._deflate[Wn]=[],this._deflate.on("data",f0)}this._deflate[qs]=r,this._deflate.write(e),this._deflate.flush(Ui.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ng.concat(this._deflate[Wn],this._deflate[yn]);n&&(i=new h0(i.buffer,i.byteOffset,i.length-4)),this._deflate[qs]=null,this._deflate[yn]=0,this._deflate[Wn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ig.exports=Ru;function f0(t){this[Wn].push(t),this[yn]+=t.length}function sg(t){if(this[yn]+=t.length,this[xa]._maxPayload<1||this[yn]<=this[xa]._maxPayload){this[Wn].push(t);return}this[Fs]=new RangeError("Max payload size exceeded"),this[Fs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fs][rg]=1009,this.removeListener("data",sg),this.reset()}function m0(t){if(this[xa]._inflate=null,this[Fs]){this[qs](this[Fs]);return}t[rg]=1007,this[qs](t)}});var Hs=he(($A,Ia)=>{"use strict";var{isUtf8:og}=require("buffer"),{hasBlob:g0}=gn(),y0=[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 b0(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Eu(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 w0(t){return g0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ia.exports={isBlob:w0,isValidStatusCode:b0,isValidUTF8:Eu,tokenChars:y0};if(og)Ia.exports.isValidUTF8=function(t){return t.length<24?Eu(t):og(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ia.exports.isValidUTF8=function(e){return e.length<32?Eu(e):t(e)}}catch{}});var Nu=he((PA,pg)=>{"use strict";var{Writable:v0}=require("stream"),ag=Bs(),{BINARY_TYPES:k0,EMPTY_BUFFER:lg,kStatusCode:_0,kWebSocket:S0}=gn(),{concat:Au,toArrayBuffer:T0,unmask:x0}=Li(),{isValidStatusCode:I0,isValidUTF8:cg}=Hs(),Ra=Buffer[Symbol.species],kt=0,ug=1,dg=2,hg=3,Cu=4,$u=5,Ea=6,Pu=class extends v0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||k0[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[S0]=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=kt}_write(e,n,r){if(this._opcode===8&&this._state==kt)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 Ra(r.buffer,r.byteOffset+e,r.length-e),new Ra(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 Ra(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 kt:this.getInfo(e);break;case ug:this.getPayloadLength16(e);break;case dg:this.getPayloadLength64(e);break;case hg:this.getMask();break;case Cu:this.getData(e);break;case $u:case Ea: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[ag.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=ug:this._payloadLength===127?this._state=dg: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=hg:this._state=Cu}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Cu}getData(e){let n=lg;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&&x0(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=$u,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[ag.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===kt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=kt;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=Au(r,n):this._binaryType==="arraybuffer"?s=T0(Au(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=kt):(this._state=Ea,setImmediate(()=>{this.emit("message",s,!0),this._state=kt,this.startLoop(e)}))}else{let s=Au(r,n);if(!this._skipUTF8Validation&&!cg(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===$u||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=kt):(this._state=Ea,setImmediate(()=>{this.emit("message",s,!1),this._state=kt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,lg),this.end();else{let r=e.readUInt16BE(0);if(!I0(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Ra(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!cg(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=kt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=kt):(this._state=Ea,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=kt,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[_0]=s,o}};pg.exports=Pu});var Mu=he((jA,gg)=>{"use strict";var{Duplex:NA}=require("stream"),{randomFillSync:R0}=require("crypto"),{types:{isUint8Array:E0}}=require("util"),fg=Bs(),{EMPTY_BUFFER:A0,kWebSocket:C0,NOOP:$0}=gn(),{isBlob:Ks,isValidStatusCode:P0}=Hs(),{mask:mg,toBuffer:Xr}=Li(),_t=Symbol("kByteLength"),N0=Buffer.alloc(4),Aa=8*1024,Qr,Gs=Aa,$t=0,j0=1,O0=2,ju=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=$t,this.onerror=$0,this[C0]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||N0,n.generateMask?n.generateMask(r):(Gs===Aa&&(Qr===void 0&&(Qr=Buffer.alloc(Aa)),R0(Qr,0,Aa),Gs=0),r[0]=Qr[Gs++],r[1]=Qr[Gs++],r[2]=Qr[Gs++],r[3]=Qr[Gs++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[_t]!==void 0?l=n[_t]:(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 d=Buffer.allocUnsafe(s?l+i:i);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(l,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(l,4,6)),n.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(mg(e,r,d,i,l),[d]):(mg(e,r,e,0,l),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=A0;else{if(typeof e!="number"||!P0(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(E0(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[_t]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==$t?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):Ks(e)?(s=e.size,i=!1):(e=Xr(e),s=e.length,i=Xr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[_t]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ks(e)?this._state!==$t?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==$t?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):Ks(e)?(s=e.size,i=!1):(e=Xr(e),s=e.length,i=Xr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[_t]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ks(e)?this._state!==$t?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==$t?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[fg.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Ks(e)?(l=e.size,c=!1):(e=Xr(e),l=e.length,c=Xr.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 d={[_t]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Ks(e)?this._state!==$t?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==$t?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[_t],this._state=O0,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Ou,this,l,s);return}this._bufferedBytes-=r[_t];let o=Xr(i);n?this.dispatch(o,n,r,s):(this._state=$t,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(M0,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[fg.extensionName];this._bufferedBytes+=r[_t],this._state=j0,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ou(this,c,s);return}this._bufferedBytes-=r[_t],this._state=$t,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===$t&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_t],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_t],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)}};gg.exports=ju;function Ou(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 M0(t,e,n){Ou(t,e,n),t.onerror(e)}});var xg=he((OA,Tg)=>{"use strict";var{kForOnEventAttribute:qi,kListener:zu}=gn(),yg=Symbol("kCode"),bg=Symbol("kData"),wg=Symbol("kError"),vg=Symbol("kMessage"),kg=Symbol("kReason"),Ws=Symbol("kTarget"),_g=Symbol("kType"),Sg=Symbol("kWasClean"),bn=class{constructor(e){this[Ws]=null,this[_g]=e}get target(){return this[Ws]}get type(){return this[_g]}};Object.defineProperty(bn.prototype,"target",{enumerable:!0});Object.defineProperty(bn.prototype,"type",{enumerable:!0});var es=class extends bn{constructor(e,n={}){super(e),this[yg]=n.code===void 0?0:n.code,this[kg]=n.reason===void 0?"":n.reason,this[Sg]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[yg]}get reason(){return this[kg]}get wasClean(){return this[Sg]}};Object.defineProperty(es.prototype,"code",{enumerable:!0});Object.defineProperty(es.prototype,"reason",{enumerable:!0});Object.defineProperty(es.prototype,"wasClean",{enumerable:!0});var Zs=class extends bn{constructor(e,n={}){super(e),this[wg]=n.error===void 0?null:n.error,this[vg]=n.message===void 0?"":n.message}get error(){return this[wg]}get message(){return this[vg]}};Object.defineProperty(Zs.prototype,"error",{enumerable:!0});Object.defineProperty(Zs.prototype,"message",{enumerable:!0});var Fi=class extends bn{constructor(e,n={}){super(e),this[bg]=n.data===void 0?null:n.data}get data(){return this[bg]}};Object.defineProperty(Fi.prototype,"data",{enumerable:!0});var z0={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[qi]&&s[zu]===e&&!s[qi])return;let r;if(t==="message")r=function(i,o){let l=new Fi("message",{data:o?i:i.toString()});l[Ws]=this,Ca(e,this,l)};else if(t==="close")r=function(i,o){let l=new es("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ws]=this,Ca(e,this,l)};else if(t==="error")r=function(i){let o=new Zs("error",{error:i,message:i.message});o[Ws]=this,Ca(e,this,o)};else if(t==="open")r=function(){let i=new bn("open");i[Ws]=this,Ca(e,this,i)};else return;r[qi]=!!n[qi],r[zu]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[zu]===e&&!n[qi]){this.removeListener(t,n);break}}};Tg.exports={CloseEvent:es,ErrorEvent:Zs,Event:bn,EventTarget:z0,MessageEvent:Fi};function Ca(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var $a=he((MA,Ig)=>{"use strict";var{tokenChars:Bi}=Hs();function Wt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function D0(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,d=-1,p=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),o===void 0)if(p===-1&&Bi[d]===1)c===-1&&(c=f);else if(f!==0&&(d===32||d===9))p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(c,p);d===44?(Wt(e,w,n),n=Object.create(null)):o=w,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&Bi[d]===1)c===-1&&(c=f);else if(d===32||d===9)p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),Wt(n,t.slice(c,p),!0),d===44&&(Wt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(d===61&&c!==-1&&p===-1)l=t.slice(c,f),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(Bi[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(Bi[d]===1)c===-1&&(c=f);else if(d===34&&c!==-1)i=!1,p=f;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Bi[d]===1)c===-1&&(c=f);else if(c!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(c,p);r&&(w=w.replace(/\\/g,""),r=!1),Wt(n,l,w),d===44&&(Wt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let b=t.slice(c,p);return o===void 0?Wt(e,b,n):(l===void 0?Wt(n,b,!0):r?Wt(n,l,b.replace(/\\/g,"")):Wt(n,l,b),Wt(e,o,n)),e}function L0(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(", ")}Ig.exports={format:L0,parse:D0}});var Oa=he((LA,Dg)=>{"use strict";var U0=require("events"),q0=require("https"),F0=require("http"),Ag=require("net"),B0=require("tls"),{randomBytes:H0,createHash:K0}=require("crypto"),{Duplex:zA,Readable:DA}=require("stream"),{URL:Du}=require("url"),Zn=Bs(),G0=Nu(),W0=Mu(),{isBlob:Z0}=Hs(),{BINARY_TYPES:Rg,CLOSE_TIMEOUT:V0,EMPTY_BUFFER:Pa,GUID:J0,kForOnEventAttribute:Lu,kListener:Y0,kStatusCode:X0,kWebSocket:Oe,NOOP:Cg}=gn(),{EventTarget:{addEventListener:Q0,removeEventListener:eT}}=xg(),{format:tT,parse:nT}=$a(),{toBuffer:rT}=Li(),$g=Symbol("kAborted"),Uu=[8,13],wn=["CONNECTING","OPEN","CLOSING","CLOSED"],sT=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends U0{constructor(e,n,r){super(),this._binaryType=Rg[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pa,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]),Pg(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Rg.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 G0({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 W0(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Oe]=this,i[Oe]=this,e[Oe]=this,s.on("conclude",aT),s.on("drain",lT),s.on("error",cT),s.on("message",uT),s.on("ping",dT),s.on("pong",hT),i.onerror=pT,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Og),e.on("data",ja),e.on("end",Mg),e.on("error",zg),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[Zn.extensionName]&&this._extensions[Zn.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){it(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())}),jg(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){qu(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Pa,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){qu(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Pa,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){qu(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Zn.extensionName]||(s.compress=!1),this._sender.send(e||Pa,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){it(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:wn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:wn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:wn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:wn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:wn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:wn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:wn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:wn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Lu])return e[Y0];return null},set(e){for(let n of this.listeners(t))if(n[Lu]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Lu]:!0})}})});we.prototype.addEventListener=Q0;we.prototype.removeEventListener=eT;Dg.exports=we;function Pg(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:V0,protocolVersion:Uu[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,!Uu.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Uu.join(", ")})`);let i;if(e instanceof Du)i=e;else try{i=new Du(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;Na(t,x);return}let d=o?443:80,p=H0(16).toString("base64"),f=o?q0.request:F0.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?oT:iT),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Zn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=tT({[Zn.extensionName]:w.offer()})),n.length){for(let x of n){if(typeof x!="string"||!sT.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.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 _;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[R,A]of Object.entries(x))r.headers[R.toLowerCase()]=A}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")),_=t._req=f(s),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(s);s.timeout&&_.on("timeout",()=>{it(t,_,"Opening handshake has timed out")}),_.on("error",x=>{_===null||_[$g]||(_=t._req=null,Na(t,x))}),_.on("response",x=>{let R=x.headers.location,A=x.statusCode;if(R&&s.followRedirects&&A>=300&&A<400){if(++t._redirects>s.maxRedirects){it(t,_,"Maximum redirects exceeded");return}_.abort();let J;try{J=new Du(R,e)}catch{let C=new SyntaxError(`Invalid URL: ${R}`);Na(t,C);return}Pg(t,J,n,r)}else t.emit("unexpected-response",_,x)||it(t,_,`Unexpected server response: ${x.statusCode}`)}),_.on("upgrade",(x,R,A)=>{if(t.emit("upgrade",x),t.readyState!==we.CONNECTING)return;_=t._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){it(t,R,"Invalid Upgrade header");return}let Y=K0("sha1").update(p+J0).digest("base64");if(x.headers["sec-websocket-accept"]!==Y){it(t,R,"Invalid Sec-WebSocket-Accept header");return}let C=x.headers["sec-websocket-protocol"],v;if(C!==void 0?b.size?b.has(C)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":b.size&&(v="Server sent no subprotocol"),v){it(t,R,v);return}C&&(t._protocol=C);let N=x.headers["sec-websocket-extensions"];if(N!==void 0){if(!w){it(t,R,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=nT(N)}catch{it(t,R,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(O);if(B.length!==1||B[0]!==Zn.extensionName){it(t,R,"Server indicated an extension that was not requested");return}try{w.accept(O[Zn.extensionName])}catch{it(t,R,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Zn.extensionName]=w}t.setSocket(R,A,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(_,t):_.end()}function Na(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function iT(t){return t.path=t.socketPath,Ag.connect(t)}function oT(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ag.isIP(t.host)?"":t.host),B0.connect(t)}function it(t,e,n){t._readyState=we.CLOSING;let r=new Error(n);Error.captureStackTrace(r,it),e.setHeader?(e[$g]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Na,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function qu(t,e,n){if(e){let r=Z0(e)?e.size:rT(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${wn[t.readyState]})`);process.nextTick(n,r)}}function aT(t,e){let n=this[Oe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Oe]!==void 0&&(n._socket.removeListener("data",ja),process.nextTick(Ng,n._socket),t===1005?n.close():n.close(t,e))}function lT(){let t=this[Oe];t.isPaused||t._socket.resume()}function cT(t){let e=this[Oe];e._socket[Oe]!==void 0&&(e._socket.removeListener("data",ja),process.nextTick(Ng,e._socket),e.close(t[X0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Eg(){this[Oe].emitClose()}function uT(t,e){this[Oe].emit("message",t,e)}function dT(t){let e=this[Oe];e._autoPong&&e.pong(t,!this._isServer,Cg),e.emit("ping",t)}function hT(t){this[Oe].emit("pong",t)}function Ng(t){t.resume()}function pT(t){let e=this[Oe];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,jg(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function jg(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Og(){let t=this[Oe];if(this.removeListener("close",Og),this.removeListener("data",ja),this.removeListener("end",Mg),t._readyState=we.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[Oe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Eg),t._receiver.on("finish",Eg))}function ja(t){this[Oe]._receiver.write(t)||this.pause()}function Mg(){let t=this[Oe];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function zg(){let t=this[Oe];this.removeListener("error",zg),this.on("error",Cg),t&&(t._readyState=we.CLOSING,this.destroy())}});var Fg=he((qA,qg)=>{"use strict";var UA=Oa(),{Duplex:fT}=require("stream");function Lg(t){t.emit("close")}function mT(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ug(t){this.removeListener("error",Ug),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gT(t,e){let n=!0,r=new fT({...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(Lg,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(Lg,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",mT),r.on("error",Ug),r}qg.exports=gT});var Fu=he((FA,Bg)=>{"use strict";var{tokenChars:yT}=Hs();function bT(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&&yT[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}Bg.exports={parse:bT}});var Jg=he((HA,Vg)=>{"use strict";var wT=require("events"),Ma=require("http"),{Duplex:BA}=require("stream"),{createHash:vT}=require("crypto"),Hg=$a(),ts=Bs(),kT=Fu(),_T=Oa(),{CLOSE_TIMEOUT:ST,GUID:TT,kWebSocket:xT}=gn(),IT=/^[+/0-9A-Za-z]{22}==$/,Kg=0,Gg=1,Zg=2,Bu=class extends wT{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:ST,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:_T,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ma.createServer((r,s)=>{let i=Ma.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=RT(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=Kg}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===Zg){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Hi,this);return}if(e&&this.once("close",e),this._state!==Gg)if(this._state=Gg,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(Hi,this):process.nextTick(Hi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Hi(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",Wg);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ns(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ns(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!IT.test(i)){ns(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){ns(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ki(n,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=kT.parse(c)}catch{ns(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let b=new ts({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Hg.parse(p);w[ts.extensionName]&&(b.accept(w[ts.extensionName]),f[ts.extensionName]=b)}catch{ns(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,_,x,R)=>{if(!w)return Ki(n,_||401,x,R);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(b))return Ki(n,401)}this.completeUpgrade(f,i,d,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[xT])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kg)return Ki(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${vT("sha1").update(n+TT).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[ts.extensionName]){let f=e[ts.extensionName].params,b=Hg.format({[ts.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
971
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}var zs,Kr,ua,Wc,Zc,Gr,Ds,Gf,wS,vS,IS,Zf,Vf,Ls=Q(()=>{"use strict";zs=E(require("node:fs"),1);Es();If();Kr=E(require("node:path"),1),ua=require("node:child_process"),Wc=E(require("node:readline"),1),Zc=require("node:crypto"),Gr=E(Ee(),1);In();Ae();yt();Ds=E(Ee(),1);vc();Ft();Ct();Or();Ko();Ti();la();Fc();Kc();Fr();At();Gf=4e3,wS=4e3;vS=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;IS=k.object({steps:k.array(Gr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),Zf=24e3;Vf=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"]});var um={};at(um,{MAX_CHAIN_DEPTH:()=>su,breakChain:()=>lu,breakSingleModeChain:()=>hu,chainOf:()=>ou,chainSessionFor:()=>ga,loadBatchPlan:()=>iu,nextMemberWillChain:()=>pu,parsePlanAnswer:()=>fu,recordChainSession:()=>au,recordSingleModeSession:()=>uu,saveBatchPlan:()=>jS,singleModeChainIntact:()=>du,singleModeSessionFor:()=>cu});function jS(t){Us.default.mkdirSync(ru(),{recursive:!0,mode:448}),Us.default.writeFileSync(ma.default.join(ru(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function iu(t){if(!t)return null;try{return JSON.parse(Us.default.readFileSync(ma.default.join(ru(),`${t}.json`),"utf8"))}catch{return null}}function ou(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function ga(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=mn.get(fa(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=su||!Us.default.existsSync(s.worktreePath)?null:s}function au(t,e,n,r){let s=mn.get(fa(t,e));mn.set(fa(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function lu(t,e){mn.delete(fa(t,e))}function cu(t){let e=mn.get(Mi(t));return!e||e.depth>=su||!Us.default.existsSync(e.worktreePath)?null:e}function uu(t,e,n,r){let s=mn.get(Mi(t));mn.set(Mi(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function du(t,e){return mn.get(Mi(t))?.lastIssue===e}function hu(t){mn.delete(Mi(t))}function pu(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function fu(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(o.length!==e.length||!o.every(p=>i.has(p))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(p=>Array.isArray(p)?p.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(p=>p.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),d=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:d}}var Us,ma,su,ru,mn,fa,Mi,ya=Q(()=>{"use strict";Us=E(require("node:fs"),1),ma=E(require("node:path"),1);Ae();su=3,ru=()=>ma.default.join(ne(),"autopilot-plans");mn=new Map,fa=(t,e)=>`${t}:${e[0]}`;Mi=t=>`${t}:__single__`});var gn=he((RA,Jm)=>{"use strict";var Zm=["nodebuffer","arraybuffer","fragments"],Vm=typeof Blob<"u";Vm&&Zm.push("blob");Jm.exports={BINARY_TYPES:Zm,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Vm,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Li=he((EA,Sa)=>{"use strict";var{EMPTY_BUFFER:l0}=gn(),Su=Buffer[Symbol.species];function c0(t,e){if(t.length===0)return l0;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 Su(n.buffer,n.byteOffset,r):n}function Ym(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Xm(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function u0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Tu(t){if(Tu.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Su(t):ArrayBuffer.isView(t)?e=new Su(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Tu.readOnly=!1),e}Sa.exports={concat:c0,mask:Ym,toArrayBuffer:u0,toBuffer:Tu,unmask:Xm};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Sa.exports.mask=function(e,n,r,s,i){i<48?Ym(e,n,r,s,i):t.mask(e,n,r,s,i)},Sa.exports.unmask=function(e,n){e.length<32?Xm(e,n):t.unmask(e,n)}}catch{}});var tg=he((AA,eg)=>{"use strict";var Qm=Symbol("kDone"),xu=Symbol("kRun"),Iu=class{constructor(e){this[Qm]=()=>{this.pending--,this[xu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xu]()}[xu](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Qm])}}};eg.exports=Iu});var Bs=he((CA,ig)=>{"use strict";var Ui=require("zlib"),ng=Li(),d0=tg(),{kStatusCode:rg}=gn(),h0=Buffer[Symbol.species],p0=Buffer.from([0,0,255,255]),xa=Symbol("permessage-deflate"),yn=Symbol("total-length"),qs=Symbol("callback"),Wn=Symbol("buffers"),Fs=Symbol("error"),Ta,Ru=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,!Ta){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ta=new d0(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[qs];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){Ta.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Ta.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"?Ui.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ui.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[xa]=this,this._inflate[yn]=0,this._inflate[Wn]=[],this._inflate.on("error",m0),this._inflate.on("data",sg)}this._inflate[qs]=r,this._inflate.write(e),n&&this._inflate.write(p0),this._inflate.flush(()=>{let i=this._inflate[Fs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=ng.concat(this._inflate[Wn],this._inflate[yn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[yn]=0,this._inflate[Wn]=[],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"?Ui.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ui.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[yn]=0,this._deflate[Wn]=[],this._deflate.on("data",f0)}this._deflate[qs]=r,this._deflate.write(e),this._deflate.flush(Ui.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ng.concat(this._deflate[Wn],this._deflate[yn]);n&&(i=new h0(i.buffer,i.byteOffset,i.length-4)),this._deflate[qs]=null,this._deflate[yn]=0,this._deflate[Wn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ig.exports=Ru;function f0(t){this[Wn].push(t),this[yn]+=t.length}function sg(t){if(this[yn]+=t.length,this[xa]._maxPayload<1||this[yn]<=this[xa]._maxPayload){this[Wn].push(t);return}this[Fs]=new RangeError("Max payload size exceeded"),this[Fs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fs][rg]=1009,this.removeListener("data",sg),this.reset()}function m0(t){if(this[xa]._inflate=null,this[Fs]){this[qs](this[Fs]);return}t[rg]=1007,this[qs](t)}});var Hs=he(($A,Ia)=>{"use strict";var{isUtf8:og}=require("buffer"),{hasBlob:g0}=gn(),y0=[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 b0(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Eu(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 w0(t){return g0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ia.exports={isBlob:w0,isValidStatusCode:b0,isValidUTF8:Eu,tokenChars:y0};if(og)Ia.exports.isValidUTF8=function(t){return t.length<24?Eu(t):og(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ia.exports.isValidUTF8=function(e){return e.length<32?Eu(e):t(e)}}catch{}});var Nu=he((PA,pg)=>{"use strict";var{Writable:v0}=require("stream"),ag=Bs(),{BINARY_TYPES:k0,EMPTY_BUFFER:lg,kStatusCode:_0,kWebSocket:S0}=gn(),{concat:Au,toArrayBuffer:T0,unmask:x0}=Li(),{isValidStatusCode:I0,isValidUTF8:cg}=Hs(),Ra=Buffer[Symbol.species],kt=0,ug=1,dg=2,hg=3,Cu=4,$u=5,Ea=6,Pu=class extends v0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||k0[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[S0]=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=kt}_write(e,n,r){if(this._opcode===8&&this._state==kt)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 Ra(r.buffer,r.byteOffset+e,r.length-e),new Ra(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 Ra(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 kt:this.getInfo(e);break;case ug:this.getPayloadLength16(e);break;case dg:this.getPayloadLength64(e);break;case hg:this.getMask();break;case Cu:this.getData(e);break;case $u:case Ea: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[ag.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=ug:this._payloadLength===127?this._state=dg: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=hg:this._state=Cu}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Cu}getData(e){let n=lg;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&&x0(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=$u,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[ag.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===kt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=kt;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=Au(r,n):this._binaryType==="arraybuffer"?s=T0(Au(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=kt):(this._state=Ea,setImmediate(()=>{this.emit("message",s,!0),this._state=kt,this.startLoop(e)}))}else{let s=Au(r,n);if(!this._skipUTF8Validation&&!cg(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===$u||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=kt):(this._state=Ea,setImmediate(()=>{this.emit("message",s,!1),this._state=kt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,lg),this.end();else{let r=e.readUInt16BE(0);if(!I0(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Ra(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!cg(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=kt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=kt):(this._state=Ea,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=kt,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[_0]=s,o}};pg.exports=Pu});var Mu=he((jA,gg)=>{"use strict";var{Duplex:NA}=require("stream"),{randomFillSync:R0}=require("crypto"),{types:{isUint8Array:E0}}=require("util"),fg=Bs(),{EMPTY_BUFFER:A0,kWebSocket:C0,NOOP:$0}=gn(),{isBlob:Ks,isValidStatusCode:P0}=Hs(),{mask:mg,toBuffer:Xr}=Li(),_t=Symbol("kByteLength"),N0=Buffer.alloc(4),Aa=8*1024,Qr,Gs=Aa,$t=0,j0=1,O0=2,ju=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=$t,this.onerror=$0,this[C0]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||N0,n.generateMask?n.generateMask(r):(Gs===Aa&&(Qr===void 0&&(Qr=Buffer.alloc(Aa)),R0(Qr,0,Aa),Gs=0),r[0]=Qr[Gs++],r[1]=Qr[Gs++],r[2]=Qr[Gs++],r[3]=Qr[Gs++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[_t]!==void 0?l=n[_t]:(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 d=Buffer.allocUnsafe(s?l+i:i);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(l,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(l,4,6)),n.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(mg(e,r,d,i,l),[d]):(mg(e,r,e,0,l),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=A0;else{if(typeof e!="number"||!P0(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(E0(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[_t]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==$t?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):Ks(e)?(s=e.size,i=!1):(e=Xr(e),s=e.length,i=Xr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[_t]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ks(e)?this._state!==$t?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==$t?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):Ks(e)?(s=e.size,i=!1):(e=Xr(e),s=e.length,i=Xr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[_t]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ks(e)?this._state!==$t?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==$t?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[fg.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Ks(e)?(l=e.size,c=!1):(e=Xr(e),l=e.length,c=Xr.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 d={[_t]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Ks(e)?this._state!==$t?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==$t?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[_t],this._state=O0,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Ou,this,l,s);return}this._bufferedBytes-=r[_t];let o=Xr(i);n?this.dispatch(o,n,r,s):(this._state=$t,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(M0,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[fg.extensionName];this._bufferedBytes+=r[_t],this._state=j0,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ou(this,c,s);return}this._bufferedBytes-=r[_t],this._state=$t,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===$t&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_t],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_t],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)}};gg.exports=ju;function Ou(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 M0(t,e,n){Ou(t,e,n),t.onerror(e)}});var xg=he((OA,Tg)=>{"use strict";var{kForOnEventAttribute:qi,kListener:zu}=gn(),yg=Symbol("kCode"),bg=Symbol("kData"),wg=Symbol("kError"),vg=Symbol("kMessage"),kg=Symbol("kReason"),Ws=Symbol("kTarget"),_g=Symbol("kType"),Sg=Symbol("kWasClean"),bn=class{constructor(e){this[Ws]=null,this[_g]=e}get target(){return this[Ws]}get type(){return this[_g]}};Object.defineProperty(bn.prototype,"target",{enumerable:!0});Object.defineProperty(bn.prototype,"type",{enumerable:!0});var es=class extends bn{constructor(e,n={}){super(e),this[yg]=n.code===void 0?0:n.code,this[kg]=n.reason===void 0?"":n.reason,this[Sg]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[yg]}get reason(){return this[kg]}get wasClean(){return this[Sg]}};Object.defineProperty(es.prototype,"code",{enumerable:!0});Object.defineProperty(es.prototype,"reason",{enumerable:!0});Object.defineProperty(es.prototype,"wasClean",{enumerable:!0});var Zs=class extends bn{constructor(e,n={}){super(e),this[wg]=n.error===void 0?null:n.error,this[vg]=n.message===void 0?"":n.message}get error(){return this[wg]}get message(){return this[vg]}};Object.defineProperty(Zs.prototype,"error",{enumerable:!0});Object.defineProperty(Zs.prototype,"message",{enumerable:!0});var Fi=class extends bn{constructor(e,n={}){super(e),this[bg]=n.data===void 0?null:n.data}get data(){return this[bg]}};Object.defineProperty(Fi.prototype,"data",{enumerable:!0});var z0={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[qi]&&s[zu]===e&&!s[qi])return;let r;if(t==="message")r=function(i,o){let l=new Fi("message",{data:o?i:i.toString()});l[Ws]=this,Ca(e,this,l)};else if(t==="close")r=function(i,o){let l=new es("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ws]=this,Ca(e,this,l)};else if(t==="error")r=function(i){let o=new Zs("error",{error:i,message:i.message});o[Ws]=this,Ca(e,this,o)};else if(t==="open")r=function(){let i=new bn("open");i[Ws]=this,Ca(e,this,i)};else return;r[qi]=!!n[qi],r[zu]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[zu]===e&&!n[qi]){this.removeListener(t,n);break}}};Tg.exports={CloseEvent:es,ErrorEvent:Zs,Event:bn,EventTarget:z0,MessageEvent:Fi};function Ca(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var $a=he((MA,Ig)=>{"use strict";var{tokenChars:Bi}=Hs();function Wt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function D0(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,d=-1,p=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),o===void 0)if(p===-1&&Bi[d]===1)c===-1&&(c=f);else if(f!==0&&(d===32||d===9))p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(c,p);d===44?(Wt(e,w,n),n=Object.create(null)):o=w,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&Bi[d]===1)c===-1&&(c=f);else if(d===32||d===9)p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),Wt(n,t.slice(c,p),!0),d===44&&(Wt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(d===61&&c!==-1&&p===-1)l=t.slice(c,f),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(Bi[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(Bi[d]===1)c===-1&&(c=f);else if(d===34&&c!==-1)i=!1,p=f;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Bi[d]===1)c===-1&&(c=f);else if(c!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(c,p);r&&(w=w.replace(/\\/g,""),r=!1),Wt(n,l,w),d===44&&(Wt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let b=t.slice(c,p);return o===void 0?Wt(e,b,n):(l===void 0?Wt(n,b,!0):r?Wt(n,l,b.replace(/\\/g,"")):Wt(n,l,b),Wt(e,o,n)),e}function L0(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(", ")}Ig.exports={format:L0,parse:D0}});var Oa=he((LA,Dg)=>{"use strict";var U0=require("events"),q0=require("https"),F0=require("http"),Ag=require("net"),B0=require("tls"),{randomBytes:H0,createHash:K0}=require("crypto"),{Duplex:zA,Readable:DA}=require("stream"),{URL:Du}=require("url"),Zn=Bs(),G0=Nu(),W0=Mu(),{isBlob:Z0}=Hs(),{BINARY_TYPES:Rg,CLOSE_TIMEOUT:V0,EMPTY_BUFFER:Pa,GUID:J0,kForOnEventAttribute:Lu,kListener:Y0,kStatusCode:X0,kWebSocket:Oe,NOOP:Cg}=gn(),{EventTarget:{addEventListener:Q0,removeEventListener:eT}}=xg(),{format:tT,parse:nT}=$a(),{toBuffer:rT}=Li(),$g=Symbol("kAborted"),Uu=[8,13],wn=["CONNECTING","OPEN","CLOSING","CLOSED"],sT=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends U0{constructor(e,n,r){super(),this._binaryType=Rg[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pa,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]),Pg(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Rg.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 G0({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 W0(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Oe]=this,i[Oe]=this,e[Oe]=this,s.on("conclude",aT),s.on("drain",lT),s.on("error",cT),s.on("message",uT),s.on("ping",dT),s.on("pong",hT),i.onerror=pT,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Og),e.on("data",ja),e.on("end",Mg),e.on("error",zg),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[Zn.extensionName]&&this._extensions[Zn.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){it(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())}),jg(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){qu(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Pa,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){qu(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Pa,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){qu(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Zn.extensionName]||(s.compress=!1),this._sender.send(e||Pa,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){it(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:wn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:wn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:wn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:wn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:wn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:wn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:wn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:wn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Lu])return e[Y0];return null},set(e){for(let n of this.listeners(t))if(n[Lu]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Lu]:!0})}})});we.prototype.addEventListener=Q0;we.prototype.removeEventListener=eT;Dg.exports=we;function Pg(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:V0,protocolVersion:Uu[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,!Uu.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Uu.join(", ")})`);let i;if(e instanceof Du)i=e;else try{i=new Du(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;Na(t,x);return}let d=o?443:80,p=H0(16).toString("base64"),f=o?q0.request:F0.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?oT:iT),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Zn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=tT({[Zn.extensionName]:w.offer()})),n.length){for(let x of n){if(typeof x!="string"||!sT.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.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 _;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[R,A]of Object.entries(x))r.headers[R.toLowerCase()]=A}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")),_=t._req=f(s),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(s);s.timeout&&_.on("timeout",()=>{it(t,_,"Opening handshake has timed out")}),_.on("error",x=>{_===null||_[$g]||(_=t._req=null,Na(t,x))}),_.on("response",x=>{let R=x.headers.location,A=x.statusCode;if(R&&s.followRedirects&&A>=300&&A<400){if(++t._redirects>s.maxRedirects){it(t,_,"Maximum redirects exceeded");return}_.abort();let J;try{J=new Du(R,e)}catch{let C=new SyntaxError(`Invalid URL: ${R}`);Na(t,C);return}Pg(t,J,n,r)}else t.emit("unexpected-response",_,x)||it(t,_,`Unexpected server response: ${x.statusCode}`)}),_.on("upgrade",(x,R,A)=>{if(t.emit("upgrade",x),t.readyState!==we.CONNECTING)return;_=t._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){it(t,R,"Invalid Upgrade header");return}let Y=K0("sha1").update(p+J0).digest("base64");if(x.headers["sec-websocket-accept"]!==Y){it(t,R,"Invalid Sec-WebSocket-Accept header");return}let C=x.headers["sec-websocket-protocol"],v;if(C!==void 0?b.size?b.has(C)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":b.size&&(v="Server sent no subprotocol"),v){it(t,R,v);return}C&&(t._protocol=C);let j=x.headers["sec-websocket-extensions"];if(j!==void 0){if(!w){it(t,R,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=nT(j)}catch{it(t,R,"Invalid Sec-WebSocket-Extensions header");return}let H=Object.keys(O);if(H.length!==1||H[0]!==Zn.extensionName){it(t,R,"Server indicated an extension that was not requested");return}try{w.accept(O[Zn.extensionName])}catch{it(t,R,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Zn.extensionName]=w}t.setSocket(R,A,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(_,t):_.end()}function Na(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function iT(t){return t.path=t.socketPath,Ag.connect(t)}function oT(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ag.isIP(t.host)?"":t.host),B0.connect(t)}function it(t,e,n){t._readyState=we.CLOSING;let r=new Error(n);Error.captureStackTrace(r,it),e.setHeader?(e[$g]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Na,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function qu(t,e,n){if(e){let r=Z0(e)?e.size:rT(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${wn[t.readyState]})`);process.nextTick(n,r)}}function aT(t,e){let n=this[Oe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Oe]!==void 0&&(n._socket.removeListener("data",ja),process.nextTick(Ng,n._socket),t===1005?n.close():n.close(t,e))}function lT(){let t=this[Oe];t.isPaused||t._socket.resume()}function cT(t){let e=this[Oe];e._socket[Oe]!==void 0&&(e._socket.removeListener("data",ja),process.nextTick(Ng,e._socket),e.close(t[X0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Eg(){this[Oe].emitClose()}function uT(t,e){this[Oe].emit("message",t,e)}function dT(t){let e=this[Oe];e._autoPong&&e.pong(t,!this._isServer,Cg),e.emit("ping",t)}function hT(t){this[Oe].emit("pong",t)}function Ng(t){t.resume()}function pT(t){let e=this[Oe];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,jg(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function jg(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Og(){let t=this[Oe];if(this.removeListener("close",Og),this.removeListener("data",ja),this.removeListener("end",Mg),t._readyState=we.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[Oe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Eg),t._receiver.on("finish",Eg))}function ja(t){this[Oe]._receiver.write(t)||this.pause()}function Mg(){let t=this[Oe];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function zg(){let t=this[Oe];this.removeListener("error",zg),this.on("error",Cg),t&&(t._readyState=we.CLOSING,this.destroy())}});var Fg=he((qA,qg)=>{"use strict";var UA=Oa(),{Duplex:fT}=require("stream");function Lg(t){t.emit("close")}function mT(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ug(t){this.removeListener("error",Ug),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gT(t,e){let n=!0,r=new fT({...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(Lg,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(Lg,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",mT),r.on("error",Ug),r}qg.exports=gT});var Fu=he((FA,Bg)=>{"use strict";var{tokenChars:yT}=Hs();function bT(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&&yT[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}Bg.exports={parse:bT}});var Jg=he((HA,Vg)=>{"use strict";var wT=require("events"),Ma=require("http"),{Duplex:BA}=require("stream"),{createHash:vT}=require("crypto"),Hg=$a(),ts=Bs(),kT=Fu(),_T=Oa(),{CLOSE_TIMEOUT:ST,GUID:TT,kWebSocket:xT}=gn(),IT=/^[+/0-9A-Za-z]{22}==$/,Kg=0,Gg=1,Zg=2,Bu=class extends wT{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:ST,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:_T,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ma.createServer((r,s)=>{let i=Ma.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=RT(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=Kg}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===Zg){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Hi,this);return}if(e&&this.once("close",e),this._state!==Gg)if(this._state=Gg,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(Hi,this):process.nextTick(Hi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Hi(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",Wg);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ns(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ns(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!IT.test(i)){ns(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){ns(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ki(n,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=kT.parse(c)}catch{ns(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let b=new ts({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Hg.parse(p);w[ts.extensionName]&&(b.accept(w[ts.extensionName]),f[ts.extensionName]=b)}catch{ns(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,_,x,R)=>{if(!w)return Ki(n,_||401,x,R);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(b))return Ki(n,401)}this.completeUpgrade(f,i,d,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[xT])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kg)return Ki(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${vT("sha1").update(n+TT).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[ts.extensionName]){let f=e[ts.extensionName].params,b=Hg.format({[ts.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
972
972
|
`).join(`\r
|
|
973
973
|
`)),i.removeListener("error",Wg),p.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(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Hi,this)})),l(p,s)}};Vg.exports=Bu;function RT(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 Hi(t){t._state=Zg,t.emit("close")}function Wg(){this.destroy()}function Ki(t,e,n,r){n=n||Ma.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} ${Ma.STATUS_CODES[e]}\r
|
|
974
974
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
@@ -1130,7 +1130,7 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
|
|
|
1130
1130
|
Answer with ONLY a fenced json block, nothing after it:
|
|
1131
1131
|
\`\`\`json
|
|
1132
1132
|
{"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
|
|
1133
|
-
\`\`\``}function Hh(t,e){let r=t.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??t.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!r)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(r),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}Ko();yi();qo();var Gn=E(Ee(),1);Ae();fi();Fr();Ls();Ft();Ti();Fr();Ct();Or();Ko();yt();var ha=E(require("node:fs"),1),rm=E(require("node:path"),1);Ae();var NS=1440*6e4,sm=()=>rm.default.join(ne(),"agent-overrides.json");function im(){try{return JSON.parse(ha.default.readFileSync(sm(),"utf8"))}catch{return{}}}function om(t){ha.default.mkdirSync(ne(),{recursive:!0,mode:448}),ha.default.writeFileSync(sm(),JSON.stringify(t,null,2),{mode:384})}var am=(t,e)=>`${t}:${e}`;function lm(t,e,n){let r=(n??"").trim();if(!r)return;let s=im();s[am(t,e)]={agentId:r,at:new Date().toISOString()},om(s)}function cm(t,e){let n=im(),r=am(t,e),s=n[r];return!s||(delete n[r],om(n),Date.now()-Date.parse(s.at)>NS)?"":s.agentId}function pa(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}}}qo();At();ya();var dm=24*3600*1e3,ba=14,OS=ba*24*3600*1e3,MS=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]);function hm(t,e){let n=(e??"").trim();if(!n||!("agent"in t.action))return{rule:t,agentId:""};if(t.action.agent===n)return{rule:t,agentId:""};let r={...t.action,agent:n};return{rule:{...t,action:r},agentId:n}}var wa=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!!fo(this.cfg,e)}get jiraless(){return ai(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,y.info("no Jira credentials on this runner - Jira polling is off. That is the deploy-only setup; add them with `allwright jira set-default` and polling starts without a restart."))}jiraWarned=new Set;warnNoJiraForRepo(e){this.jiraWarned.has(e)||(this.jiraWarned.add(e),y.warn(`no Jira credential for repo "${e}" - its rules are not being polled. Add a runner-wide one with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${e}"\`.`))}routingWarned=new Set;warnRoutingOnce(e,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),this.jiraless?this.noteJiraless():y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=np(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Se(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await $s({projectId:n.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){if(this.jiraless){this.noteJiraless();return}this.jiralessLogged=!1,this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}if(!this.hasJira(r.repoName)){this.warnNoJiraForRepo(r.repoName);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let N=Date.parse(e.pausedUntil);Number.isFinite(N)&&(this.autopilotPausedUntil=N);return}let n=e.item;if(!n)return;let r=this.rules.find(N=>N.id===n.ruleId&&N.enabled),s=this.projects.find(N=>N.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=pa(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,d=hm(c,n.agentId);y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:"")+(d.agentId?` -> agent ${d.agentId}`:""));let p=this.jiraOf(o),f="";try{f=(await p.getIssue(n.issueKey))?.summary??""}catch(N){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${N instanceof Error?N.message:String(N)}`});return}let b=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!b.accepted||!b.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:b.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:b.runId});let w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let _=this.resolveClaudeProfile(b.runId,b.claudeProfile),x=!!(n.batchId&&n.branchOverride),R=n.batchId?iu(n.batchId):null,A=!n.continueBranch&&!x?ou(R,n.issueKey):null,J=A?ga(n.batchId,A,n.issueKey):null,Y=x&&n.continueBranch?cu(n.batchId):null,C=J??Y,v=pu(A,n.issueKey)||x&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await Ei({runId:b.runId,rule:d.rule,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:p,transport:this.transport,claudeConfigDir:_,actorEmail:b.actorEmail,continueBranch:n.continueBranch,...C?{chain:{sessionId:C.sessionId,worktreePath:C.worktreePath}}:{},keepWorktree:v,onChainSession:A?N=>au(n.batchId,A,n.issueKey,N):x&&v?N=>uu(n.batchId,n.issueKey,N,!!Y):void 0}),A&&!ga(n.batchId,A,A[A.indexOf(n.issueKey)+1]??"")&&A.indexOf(n.issueKey)<A.length-1&&lu(n.batchId,A),x&&!du(n.batchId,n.issueKey)&&hu(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(Si());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let o=Fe(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new He(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,d;try{[c,d]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!d){let w=`PR #${i.prNumber} can no longer be read on GitHub (deleted, moved, or this runner's token lost access) - Allwright cannot tell whether it merged. Check ${i.prUrl} and finish the ticket by hand.`;y.warn(`PR #${i.prNumber} for ${i.issueKey} is unreadable - reporting, not guessing`),await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket can no longer be read.**
|
|
1133
|
+
\`\`\``}function Hh(t,e){let r=t.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??t.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!r)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(r),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}Ko();yi();qo();var Gn=E(Ee(),1);Ae();fi();Fr();Ls();Ft();Ti();Fr();Ct();Or();Ko();yt();var ha=E(require("node:fs"),1),rm=E(require("node:path"),1);Ae();var NS=1440*6e4,sm=()=>rm.default.join(ne(),"agent-overrides.json");function im(){try{return JSON.parse(ha.default.readFileSync(sm(),"utf8"))}catch{return{}}}function om(t){ha.default.mkdirSync(ne(),{recursive:!0,mode:448}),ha.default.writeFileSync(sm(),JSON.stringify(t,null,2),{mode:384})}var am=(t,e)=>`${t}:${e}`;function lm(t,e,n){let r=(n??"").trim();if(!r)return;let s=im();s[am(t,e)]={agentId:r,at:new Date().toISOString()},om(s)}function cm(t,e){let n=im(),r=am(t,e),s=n[r];return!s||(delete n[r],om(n),Date.now()-Date.parse(s.at)>NS)?"":s.agentId}function pa(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}}}qo();At();ya();var dm=24*3600*1e3,ba=14,OS=ba*24*3600*1e3,MS=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]);function hm(t,e){let n=(e??"").trim();if(!n||!("agent"in t.action))return{rule:t,agentId:""};if(t.action.agent===n)return{rule:t,agentId:""};let r={...t.action,agent:n};return{rule:{...t,action:r},agentId:n}}var wa=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!!fo(this.cfg,e)}get jiraless(){return ai(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,y.info("no Jira credentials on this runner - Jira polling is off. That is the deploy-only setup; add them with `allwright jira set-default` and polling starts without a restart."))}jiraWarned=new Set;warnNoJiraForRepo(e){this.jiraWarned.has(e)||(this.jiraWarned.add(e),y.warn(`no Jira credential for repo "${e}" - its rules are not being polled. Add a runner-wide one with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${e}"\`.`))}routingWarned=new Set;warnRoutingOnce(e,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),this.jiraless?this.noteJiraless():y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=np(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Se(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await $s({projectId:n.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){if(this.jiraless){this.noteJiraless();return}this.jiralessLogged=!1,this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}if(!this.hasJira(r.repoName)){this.warnNoJiraForRepo(r.repoName);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let j=Date.parse(e.pausedUntil);Number.isFinite(j)&&(this.autopilotPausedUntil=j);return}let n=e.item;if(!n)return;let r=this.rules.find(j=>j.id===n.ruleId&&j.enabled),s=this.projects.find(j=>j.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=pa(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,d=hm(c,n.agentId);y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:"")+(d.agentId?` -> agent ${d.agentId}`:""));let p=this.jiraOf(o),f="";try{f=(await p.getIssue(n.issueKey))?.summary??""}catch(j){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${j instanceof Error?j.message:String(j)}`});return}let b=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!b.accepted||!b.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:b.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:b.runId});let w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let _=this.resolveClaudeProfile(b.runId,b.claudeProfile),x=!!(n.batchId&&n.branchOverride),R=n.batchId?iu(n.batchId):null,A=!n.continueBranch&&!x?ou(R,n.issueKey):null,J=A?ga(n.batchId,A,n.issueKey):null,Y=x&&n.continueBranch?cu(n.batchId):null,C=J??Y,v=pu(A,n.issueKey)||x&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await Ei({runId:b.runId,rule:d.rule,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:p,transport:this.transport,claudeConfigDir:_,actorEmail:b.actorEmail,continueBranch:n.continueBranch,...C?{chain:{sessionId:C.sessionId,worktreePath:C.worktreePath}}:{},keepWorktree:v,onChainSession:A?j=>au(n.batchId,A,n.issueKey,j):x&&v?j=>uu(n.batchId,n.issueKey,j,!!Y):void 0}),A&&!ga(n.batchId,A,A[A.indexOf(n.issueKey)+1]??"")&&A.indexOf(n.issueKey)<A.length-1&&lu(n.batchId,A),x&&!du(n.batchId,n.issueKey)&&hu(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(Si());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let o=Fe(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new He(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,d;try{[c,d]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!d){let w=`PR #${i.prNumber} can no longer be read on GitHub (deleted, moved, or this runner's token lost access) - Allwright cannot tell whether it merged. Check ${i.prUrl} and finish the ticket by hand.`;y.warn(`PR #${i.prNumber} for ${i.issueKey} is unreadable - reporting, not guessing`),await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket can no longer be read.**
|
|
1134
1134
|
|
|
1135
1135
|
${w}
|
|
1136
1136
|
|
|
@@ -1181,8 +1181,8 @@ Rules:
|
|
|
1181
1181
|
- When you are done, every listed file must contain no conflict markers and must be syntactically valid.
|
|
1182
1182
|
|
|
1183
1183
|
Conflicted files:
|
|
1184
|
-
`;async function mm(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=fm.default.join(un(),`conflict-${(0,mu.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await pi(n,l,r),c=!0;let d=await Gl(l,s);if(d.ok&&d.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(!d.ok&&d.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${d.reason}`};let p={},f=!1;if(!d.ok){let _=d.conflicts;o("info",`git merged everything except ${_.length} file(s): ${_.slice(0,20).join(", ")}`+(_.length>20?", \u2026":""));let x=Ze(t.agentId);if(!x)return await Dn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let R=Bn(t.agentId,"edit_no_shell");if(R)return await Dn(l),{ok:!1,note:`${R} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let A=-1,J=setInterval(()=>{Zl(l,_).then(v=>{let
|
|
1185
|
-
`),timeoutSeconds:t.timeoutSeconds,bin:je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,mu.randomUUID)(),onLog:(v,
|
|
1184
|
+
`;async function mm(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=fm.default.join(un(),`conflict-${(0,mu.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await pi(n,l,r),c=!0;let d=await Gl(l,s);if(d.ok&&d.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(!d.ok&&d.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${d.reason}`};let p={},f=!1;if(!d.ok){let _=d.conflicts;o("info",`git merged everything except ${_.length} file(s): ${_.slice(0,20).join(", ")}`+(_.length>20?", \u2026":""));let x=Ze(t.agentId);if(!x)return await Dn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let R=Bn(t.agentId,"edit_no_shell");if(R)return await Dn(l),{ok:!1,note:`${R} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let A=-1,J=setInterval(()=>{Zl(l,_).then(v=>{let j=_.filter(O=>!v.includes(O));j.length!==A&&(A=j.length,o("info",`Conflict progress: ${j.length}/${_.length} resolved`+(j.length?` \xB7 clean: ${j.join(", ")}`:"")+(v.length?` \xB7 still conflicted: ${v.join(", ")}`:"")))}).catch(()=>{})},12e3),Y=await Ri(x,{repoPath:l,prompt:DS+_.map(v=>`- ${v}`).join(`
|
|
1185
|
+
`),timeoutSeconds:t.timeoutSeconds,bin:je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,mu.randomUUID)(),onLog:(v,j)=>o(v,j)},(v,j)=>o(v==="warn"?"warn":v,j));if(clearInterval(J),p={costUsd:Y.costUsd,inputTokens:Y.inputTokens,outputTokens:Y.outputTokens},!Y.ok)return await Dn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${Y.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let C=await jo(l);if(C.length)return await Dn(l),{ok:!1,...p,note:`The agent left conflict markers in ${C.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await Wl(l,`${i}: merge ${s}, conflicts resolved by the agent
|
|
1186
1186
|
|
|
1187
1187
|
Resolved via Allwright`)}let b=await zn(l,s);if(!b.ok){let _=b.forbidden.length?`the merged result touches protected paths (${b.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${b.files} files, ${b.insertions+b.deletions} lines; limits ${jn}/${On})`;return await Dn(l),{ok:!1,...p,note:`Nothing was pushed: ${_}. The merge was rolled back.`}}await Nr(l,r);let w=await tt(l);return o("info",`Pushed the merge to ${r} (${w.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:w,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(d){return await Dn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${d instanceof Error?d.message.slice(0,300):String(d)}`}}finally{c&&(await qt(n,l).catch(()=>{}),pm.default.rmSync(l,{recursive:!0,force:!0}))}}var gu=E(require("node:fs"),1),gm=E(require("node:path"),1),yu=require("node:crypto");Ft();yt();Fr();bi();function LS(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
|
|
1188
1188
|
${r.tail.slice(-2e3)}`).join(`
|
|
@@ -1209,12 +1209,12 @@ Your ONLY job is to address that finding, with the smallest change possible.
|
|
|
1209
1209
|
- If the finding is wrong, or is pre-existing on the base branch and not caused by this PR, change NOTHING and say so in one sentence - a disagreement recorded is worth more than a change made to look busy.
|
|
1210
1210
|
- Do not ask questions; if you cannot fix it safely, say what you found and stop.
|
|
1211
1211
|
- You have no shell; the runner re-runs the documented tests after you finish.
|
|
1212
|
-
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function ym(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=gm.default.join(un(),`testfix-${(0,yu.randomUUID)().slice(0,8)}`),d=!1;try{let p=Ze(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Bn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await Mn(n,r),await pi(n,c,r),d=!0,await Ts(c,`origin/${r}`);let b=await tt(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await Ri(p,{repoPath:c,prompt:t.finding?US(i,t.finding):LS(i,o),timeoutSeconds:t.timeoutSeconds,bin:je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,yu.randomUUID)(),onLog:(O,
|
|
1212
|
+
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function ym(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=gm.default.join(un(),`testfix-${(0,yu.randomUUID)().slice(0,8)}`),d=!1;try{let p=Ze(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Bn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await Mn(n,r),await pi(n,c,r),d=!0,await Ts(c,`origin/${r}`);let b=await tt(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await Ri(p,{repoPath:c,prompt:t.finding?US(i,t.finding):LS(i,o),timeoutSeconds:t.timeoutSeconds,bin:je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,yu.randomUUID)(),onLog:(O,H)=>l(O,H)},(O,H)=>l(O==="warn"?"warn":O,H)),_={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(!w.ok)return{ok:!1,..._,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await Ss(c);for(let O of x.refused)l("warn",`${cn} entry refused: ${O}`);let R=!0;try{await Pr(c,t.finding?`${i}: ${t.finding.title.slice(0,60)}
|
|
1213
1213
|
|
|
1214
1214
|
Allwright finding-fix run`:`${i}: fix failing TEST.md commands
|
|
1215
1215
|
|
|
1216
|
-
Allwright test-fix run`)}catch{R=!1}if(!R){let O=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",O),{ok:!0,..._,remaining:o,note:O}}let A=await zn(c,s);if(!A.ok){await Ts(c,b);let O=A.forbidden.length?`the fixed result touches protected paths (${A.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${A.files} files, ${A.insertions+A.deletions} lines; limits ${jn}/${On})`;return{ok:!1,..._,note:`Nothing was pushed: ${O}. The fix commit was discarded; the PR is unchanged.`}}let J=o,Y,C,v=Cs(c);if(v){let O=Fn(gu.default.readFileSync(v,"utf8"));if(O.length){l("info",`Re-running ${O.length} documented test command(s)`);let
|
|
1217
|
-
${
|
|
1216
|
+
Allwright test-fix run`)}catch{R=!1}if(!R){let O=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",O),{ok:!0,..._,remaining:o,note:O}}let A=await zn(c,s);if(!A.ok){await Ts(c,b);let O=A.forbidden.length?`the fixed result touches protected paths (${A.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${A.files} files, ${A.insertions+A.deletions} lines; limits ${jn}/${On})`;return{ok:!1,..._,note:`Nothing was pushed: ${O}. The fix commit was discarded; the PR is unchanged.`}}let J=o,Y,C,v=Cs(c);if(v){let O=Fn(gu.default.readFileSync(v,"utf8"));if(O.length){l("info",`Re-running ${O.length} documented test command(s)`);let H=await dn(c,O,{perCommandTimeoutMs:15*6e4});for(let B of H)l(B.exitCode===0?"info":"warn",`${B.exitCode===0?"PASS":"FAIL"} ${B.command} (exit ${B.exitCode})`+(B.exitCode===0?"":`
|
|
1217
|
+
${B.tail.slice(-1500)}`));J=H.filter(B=>B.exitCode!==0).slice(0,20).map(B=>({command:B.command.slice(0,500),exitCode:B.exitCode,tail:B.tail.slice(-4e3)})),C=H.length,Y=H.length-J.length}}await Nr(c,r);let j=await tt(c);return l("info",`Pushed the fix to ${r} (${j.slice(0,7)})`),{ok:!0,..._,headSha:j,remaining:J,testsPassed:Y,testsTotal:C,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(p){return{ok:!1,note:`Could not fix the tests: ${p instanceof Error?p.message.slice(0,300):String(p)}`}}finally{d&&(await qt(n,c).catch(()=>{}),gu.default.rmSync(c,{recursive:!0,force:!0}))}}Es();Ct();var Wr=E(require("node:fs"),1),bm=E(require("node:path"),1);In();Ae();var qS=k.object({role:k.enum(["user","agent"]),text:k.string(),steps:k.array(k.string()).default([]),files:k.array(k.string()).default([]),at:k.string().default(""),ms:k.number().int().nonnegative().default(0),tokens:k.number().int().nonnegative().default(0)}),FS=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),ownerUserId:k.string().default(""),agentId:k.string().default(""),messages:k.array(qS).default([])}),BS=k.record(FS),HS=10,KS=200,bu=2e4,GS=30,WS=2e3,wm=8,vm=255;function km(){return bm.default.join(ne(),"chat-sessions.json")}function zi(){let t=km();if(!Wr.default.existsSync(t))return{};try{return BS.parse(JSON.parse(Wr.default.readFileSync(t,"utf8")))}catch{return{}}}function _m(t){Wr.default.mkdirSync(ne(),{recursive:!0,mode:448});let e=km(),n=e+".tmp";Wr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
1218
1218
|
`,{mode:384}),Wr.default.renameSync(n,e),Wr.default.chmodSync(e,384)}function wu(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function Sm(t,e){e.messages=e.messages.slice(-KS),e.updatedAt=new Date().toISOString(),t[e.sessionId]=e;let n=Object.values(t).filter(r=>r.projectId===e.projectId).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt));for(let r of n.slice(HS))delete t[r.sessionId];_m(t)}function Tm(t,e,n,r=[],s=new Date().toISOString(),i="",o=""){let l=zi(),c=l[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:s,ownerUserId:i,agentId:o,messages:[]};!c.ownerUserId&&i&&(c.ownerUserId=i),!c.agentId&&o&&(c.agentId=o),wu(c),c.messages.push({role:"user",text:n.slice(0,bu),steps:[],files:r.slice(0,wm).map(d=>d.slice(0,vm)),at:s,ms:0,tokens:0}),Sm(l,c)}function va(t){let e=zi(),n=e[t];if(!n)return;let r=n.messages.length;wu(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,_m(e))}function xm(t,e,n,r,s=[],i=[],o={},l="",c=""){let d=zi(),f=d[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),ownerUserId:l,agentId:c,messages:[]};!f.ownerUserId&&l&&(f.ownerUserId=l),!f.agentId&&c&&(f.agentId=c),wu(f),f.messages.push({role:"user",text:n.slice(0,bu),steps:[],files:i.slice(0,wm).map(b=>b.slice(0,vm)),at:o.askedAt||new Date().toISOString(),ms:0,tokens:0},{role:"agent",text:r.slice(0,bu),steps:s.slice(0,GS).map(b=>b.slice(0,WS)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0)),tokens:Math.max(0,Math.round(o.tokens??0))}),Sm(d,f)}function Im(t){return Object.values(zi()).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,ownerUserId:e.ownerUserId??"",agentId:e.agentId??""}))}function Zr(t){return zi()[t]??null}yt();At();var Rm=36,Em=60;function Am(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 ZS=`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:
|
|
1219
1219
|
Goal: what the user is trying to achieve.
|
|
1220
1220
|
Decided: choices already made, including ones you talked them out of - each as one line.
|
|
@@ -1259,8 +1259,8 @@ ${r}
|
|
|
1259
1259
|
${e.length>8e3?`\u2026
|
|
1260
1260
|
|
|
1261
1261
|
${e.slice(-8e3)}`:e}`}var $e=new kd;$e.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(Eo);function Vy(t){y.info(`Create the token at ${be.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of be.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(be.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}$e.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",Xs.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=Vn.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=Nh(t),o=i==="skip";i==="offer-skip"&&(y.info("Jira: the credential below is what this machine polls your board with, and comments back under. A server that only DEPLOYS never reads a board and does not need one."),o=jh(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=vl.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let d=await new qe(c.jira).myself();y.info(`Jira credential OK - authenticated as ${d.displayName}`)}c=await kh(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${sn()} (mode 600, this machine only)`),c.jira||y.info("No Jira credentials stored - this machine polls no board. That is the deploy-only setup; add them whenever you need with `allwright jira set-default` (applies live, no reinstall)."),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var rd=$e.command("repo").description("Map control-plane repo names to local checkouts");rd.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=de(),s=Yt.default.resolve(e.replace(/^~(?=\/|$)/,Xs.default.homedir()));if(!n.force){if(!Ke.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(!Ke.default.existsSync(Yt.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},me(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Ft(),Ah));y.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}Tt()||y.warn(`"${t}" is saved but NOT live yet - the running runner still does not know about it, and runs will keep saying it is not mapped until it reloads.`)});rd.command("list").description("Show configured repo mappings").action(()=>{let t=de(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var Jy=$e.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Jy.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=de(),n=e.claudeProfiles[t]?.configDir??`${sn().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ke.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},me(e),y.info(`profile "${t}" -> ${n}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,jt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),Tt()});Jy.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=de(),e=Object.entries(t.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=Ke.default.existsSync(r.configDir)&&Ke.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});rd.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=de();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),me(e),y.info(`Removed "${t}" (was ${n})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var sd=$e.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");sd.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(t=>{if(t.print){y.info(`
|
|
1262
|
-
`+tc(ec()));return}Lh(y)});sd.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(()=>Uh(y));sd.command("status").description("systemctl status for the runner service").action(()=>{(0,jt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});$e.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let t=(0,jt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Qs=$e.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Qs.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=de();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=Km(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 qe(l).myself();if(e.repos[t].jira=l,me(e),y.info(`The token already on this server works on ${r} - authenticated as ${c.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new qe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}Tt();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Vn.default.createInterface({input:process.stdin,output:process.stdout});try{let c=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!c||!p||!f)throw new Error("all three values are required");let b={baseUrl:c,email:p,apiToken:f},w=await new qe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${c}`),e.repos[t].jira=b,me(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),Tt()}finally{o.close()}});Qs.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=de(),e=Vn.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 qe(l).myself();t.jira=l,me(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${sn()} (mode 600, this machine only). Repo overrides are untouched.`),Tt()}finally{e.close()}});Qs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=de();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Qs.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=de(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Vn.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(d=>d.jira)].filter(d=>!!d),l=new Set,c=!1;for(let d of o)if(!l.has(d.baseUrl)){l.add(d.baseUrl);try{let p=await new qe({baseUrl:d.baseUrl,email:s,apiToken:i}).myself();y.info(`${d.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{y.warn(`${d.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},me(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Qs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=de(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});Qs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=de(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],me(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var ei=$e.command("github").description("GitHub credential for implement-mode rules");ei.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=Vn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Vy("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(()=>(Ct(),zr)),s=await new r(n).whoami(),i=de();i.github={token:n,login:s},me(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${sn()} (mode 600, this machine only)`)}finally{e.close()}});ei.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=de();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&&Ke.default.existsSync(r))try{let i=(0,jt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=Rt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(Ct(),zr)),c=new l(n),d=await c.repoAccess(o.owner,o.repo);if(d.ok&&d.canPush){let p=await c.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${p} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Vn.default.createInterface({input:process.stdin,output:process.stdout});try{Vy(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(Ct(),zr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},me(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});ei.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=de(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Vn.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(()=>(Ct(),zr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},me(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});ei.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=de(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});ei.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=de(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],me(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});ei.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=de();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var id=$e.command("audit").description("Recurring specialist audits on this runner");id.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=de();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}],me(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});id.command("schedules").description("List scheduled audits").action(()=>{let t=de();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});id.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=de(),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");me(n),y.info("Removed. Restart the runner to apply.")});var od=$e.command("deploy").description("Deployment settings for this machine");od.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=de();t.deploy={enabled:!0},me(t),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),Tt()});od.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=de();t.deploy={enabled:!1},me(t),y.info("deployments DISABLED on this runner"),Tt()});od.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=de();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var Va=$e.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Va.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=de(),s=po(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 d=l.slice(0,c).trim();i.secrets[d]=l.slice(c+1),o.push(d)}r.environments[s]=i,me(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${sn()} (mode 600, this machine only)`),Tt()});Va.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=de().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(()=>(by(),yy));await o({repoName:t,envName:e,dir:Yt.default.resolve(i.replace(/^~(?=\/|$)/,Xs.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});Va.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=de(),s=po(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,me(r),y.info(`removed ${n.join(", ")} from ${s}`)});Va.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=de(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});$e.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=zd(t);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${Yt.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});$e.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=pr();if(e&&fr(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=Dd(t);y.info(`Restored ${n.restored.length} entries into ${ne()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});$e.command("agent <action> [agentId] [binPath]").description("Which BINARY each agent runs as on this machine: list | set-bin <agentId> <path> | clear-bin <agentId>. Only needed when an agent is installed under a different name or path than its id (claude-code is set with `allwright init` instead).").action(async(t,e,n)=>{let r=de(),s=be.REGISTERED_AGENTS.map(o=>o.id);if(t==="list"){for(let o of be.REGISTERED_AGENTS){let l=je(r,o.id),c=r.agents[o.id]?.bin?" (set here)":" (default: its own id)",d="";try{d=(0,jt.execFileSync)(l,["--version"],{timeout:1e4,encoding:"utf8"}).trim().slice(0,60)}catch{d="not runnable on this machine"}y.info(`${o.id}: ${l}${c} - ${d}`)}return}if(!e||!s.includes(e)){y.error(`unknown agent "${e??""}" - this runner knows: ${s.join(", ")}. Use \`allwright agent list\` to see which of them run here.`),process.exitCode=1;return}if(t==="clear-bin"){delete r.agents[e],me(r),y.info(`${e} is back to its default binary ("${e}" on PATH).`),Tt();return}if(t!=="set-bin"||!n){y.error("usage: allwright agent list | set-bin <agentId> <path> | clear-bin <agentId>"),process.exitCode=1;return}let i="";try{i=(0,jt.execFileSync)(n,["--version"],{timeout:15e3,encoding:"utf8"}).trim()}catch(o){y.error(`"${n}" did not answer \`--version\` (${o instanceof Error?o.message:o}) - nothing was saved. Check the path, or that the binary is executable by this user.`),process.exitCode=1;return}r.agents[e]={bin:n},me(r),y.info(`${e} now runs as "${n}" (${i.slice(0,60)}) on this machine.`),Tt()});$e.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=de();if(t==="on"||t==="off"){e.operatorEnabled=t==="on",me(e),t==="on"?y.info("operator mode ENABLED on this machine. Dashboard users who also hold the 'Operator mode' permission can now let the Compose agent run commands here as this runner's user, inside a consented, time-boxed session. Every tool call is recorded (`allwright operator log`). Turn it off any time: `allwright operator off`."):y.info("operator mode DISABLED on this machine - Compose is back to read-only here."),Tt();return}if(t==="status"){y.info(e.operatorEnabled?"operator mode is ENABLED on this machine (allwright operator off to disable).":"operator mode is DISABLED on this machine (allwright operator on to enable).");return}if(t==="log"){let n=zm();if(!n.length){y.info("no operator turns have run on this machine.");return}for(let r of n){y.info(`${r.at} ${r.userName||r.userId||"someone"} [${r.sessionId}] asked: ${r.ask}`);for(let s of r.commands)y.info(` - ${s}`)}return}y.error(`unknown action "${t}" - use on | off | status | log`),process.exitCode=1});$e.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=de(),e=Object.keys(t.repos),n=ai(t);n&&y.warn("no Jira credentials on this runner - it polls no board. Expected on a deploy-only server; add them any time with `allwright jira set-default`.");let r=e.length?e.map(i=>({jiraProjectKey:"*",repoName:i})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],s=!0;for(let i of r){let o=await Ua(t,i),l=!fo(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||y.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let d=c.ok?"PASS":"FAIL";(c.ok?y.info:y.error)(`[${d}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function Tt(){let t=pr()??ms();if(t&&fr(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?Zd(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"Could not signal the running runner - it may run as another user (the service usually runs as root, and `sudo` is what lets you signal it). Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function jx(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Wd();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Tl);let n=t.jira?new qe(t.jira):Xl(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let g=r.get(u);return g||(g=new qe(m),r.set(u,g)),g},i=new Map,o=(u,m)=>{let g=Ph(ke()??t,u,m);switch(g.kind){case"legacy":return{jira:s(u),authored:!1};case"self":return{jira:s(u),authored:!0};case"missing":return{error:g.error};case"user":{let S=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,$=i.get(S);return $||($=new qe(g.creds),i.set(S,$)),{jira:$,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],d=[],p=[],f,b=null,w={cfg:t,jiraFor:s,transport:null},_=new Set,x=async(u,m,g)=>{if(!(m.length<2))for(let S=0;S<m.length;S++){let{text:$,changed:j}=Mh(g[S]??"",m);j&&await u.updateDescription(m[S],$).then(()=>y.info(`Compose: rewrote sibling ticket refs in ${m[S]} to real keys`)).catch(G=>y.warn(`Compose: could not rewrite refs in ${m[S]}: ${G instanceof Error?G.message:G}`))}},R=u=>{let m=c.find(S=>S.id===u),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A=u=>{let m=c.find($=>$.id===u),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let S=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${S}. 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 w.transport},lookup:(u,m)=>{let g=R(u),S=p.find($=>$.projectId===u&&$.name===m);return g&&S?{...g,environment:S}:null}},Y=new Map,C=new Set,v=new za(l.toString(),t.runnerToken,{runnerVersion:Eo},{onConfig:u=>{c=u.projects,Hm(u.projects),d=u.rules,p=u.environments,Mf(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments)},onDeployFix:async u=>{let m=R(u.projectId);if(!m){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(u.projectId)});return}let g=Se(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${u.environmentName}" (step: ${u.failedStep||"?"})`);let S=await eu({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,failedStep:u.failedStep,errorText:u.errorText,cfg:t});v.sendDeploySuggestResult(u.requestId,S)},onProjectTest:async u=>{let m=c.find(S=>S.id===u.projectId);if(!m){v.sendProjectTestResult(u.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await Ua(ke()??t,m,p.filter(S=>S.projectId===m.id),d.filter(S=>S.projectId===m.id).map(S=>"agent"in S.action?S.action.agent:"").filter(Boolean));v.sendProjectTestResult(u.requestId,g.every(S=>S.ok),g)},onRuleDiagnose:async u=>{let m=d.find(U=>U.id===u.ruleId),g=m&&c.find(U=>U.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(u.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let S=await Ua(ke()??t,g,m.action.type==="deploy"?p.filter(U=>U.projectId===g.id):[]),$=m.action.type==="implement"?S:S.filter(U=>U.name!=="github-token"),{matchedCount:j,excludedCount:G,excludedSample:H}=await f.diagnoseRule(m,g);v.sendRuleDiagnoseResult(u.requestId,{checks:$,matchedCount:j,excludedCount:G,excludedSample:H})},onCancel:u=>{uf(u)?y.info(`run ${u} stopped from the dashboard`):y.warn(`cancel requested for run ${u}, but nothing is running under that id here - it likely finished already`)},onApproved:(u,m)=>{if(da(u)){Yc(J,u).catch(g=>y.error(`deploy approval crashed for ${u}: ${g instanceof Error?g.stack:g}`));return}Ai(w,u,m).catch(g=>y.error(`approval handling crashed for ${u}: ${g instanceof Error?g.stack:g}`))},onRetryPush:u=>{let m=Qo(u),g=()=>vf(w,u).catch(S=>y.error(`retry push crashed for ${u}: ${S instanceof Error?S.stack:S}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:u=>{if(da(u)){Xc(J,u).catch(m=>y.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}wf(w,u).catch(m=>y.error(`rejection handling crashed for ${u}: ${m instanceof Error?m.stack:m}`))},onDeployStart:u=>{let m=`${u.runId}#${u.attempt}`;if(_.has(m))return;_.add(m);let g=R(u.projectId);if(!g){let S=A(u.projectId);y.error(`deploy ${u.runId}: ${S}`),v.send({type:"run.status",runId:u.runId,status:"failed",error:S});return}y.info(`deploy ${u.runId} requested from the dashboard: ${u.issueKey} \u2192 ${u.environment.name}`),f.runOnEnvironmentQueue(u.environment.id,()=>Ni({runId:u.runId,project:g.project,environment:u.environment,issueKey:u.issueKey,issueSummary:u.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:v,requestedBy:u.requestedBy}).catch(S=>y.error(`deploy crashed for ${u.runId}: ${S instanceof Error?S.stack:S}`)))},onDeploySuggest:async u=>{let m=R(u.projectId);if(!m){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(u.projectId)});return}let g=Se(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${u.environmentName}" deploy steps in ${m.repoPath}`);let S=await tu({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,notes:u.notes,timeoutSeconds:u.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(u.requestId,S)},onEnvPreflight:async u=>{let m=R(u.projectId);if(!m){v.sendEnvPreflightResult(u.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Qc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,requiredSecrets:u.requiredSecrets,workdir:u.workdir,branch:u.branch,publicUrl:u.publicUrl,cfg:t});v.sendEnvPreflightResult(u.requestId,g)},onSelfMigrationApply:async u=>{let m=R(u.projectId);if(!m){v.sendSelfMigrationApplyResult(u.requestId,{ok:!1,file:u.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(u.projectId)});return}y.info(`applying migration ${u.file} for "${u.environmentName}"`);let g=await Wm({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,file:u.file,urlSecret:u.urlSecret,cfg:t});y.info(g.ok?`migration ${u.file} applied`:`migration ${u.file} failed: ${g.error}`),v.sendSelfMigrationApplyResult(u.requestId,g)},onAutopilotPlan:async u=>{try{let m=R(u.projectId);if(!m){v.sendAutopilotPlanResult(u.requestId,{ok:!1,error:A(u.projectId)});return}let g=s(m.project.repoName),S=[];for(let L of u.issueKeys)try{let ce=await g.getIssue(L);S.push(`${L}: ${ce.summary}
|
|
1263
|
-
${(ce.description||"").slice(0,500)}`)}catch{S.push(`${L}: (could not read from Jira)`)}let $=Se(t,m.project,"assist");if("error"in $){v.sendAutopilotPlanResult(u.requestId,{ok:!1,error:$.error});return}let
|
|
1262
|
+
`+tc(ec()));return}Lh(y)});sd.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(()=>Uh(y));sd.command("status").description("systemctl status for the runner service").action(()=>{(0,jt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});$e.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let t=(0,jt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Qs=$e.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Qs.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=de();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=Km(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 qe(l).myself();if(e.repos[t].jira=l,me(e),y.info(`The token already on this server works on ${r} - authenticated as ${c.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new qe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}Tt();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Vn.default.createInterface({input:process.stdin,output:process.stdout});try{let c=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!c||!p||!f)throw new Error("all three values are required");let b={baseUrl:c,email:p,apiToken:f},w=await new qe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${c}`),e.repos[t].jira=b,me(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),Tt()}finally{o.close()}});Qs.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=de(),e=Vn.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 qe(l).myself();t.jira=l,me(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${sn()} (mode 600, this machine only). Repo overrides are untouched.`),Tt()}finally{e.close()}});Qs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=de();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Qs.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=de(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Vn.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(d=>d.jira)].filter(d=>!!d),l=new Set,c=!1;for(let d of o)if(!l.has(d.baseUrl)){l.add(d.baseUrl);try{let p=await new qe({baseUrl:d.baseUrl,email:s,apiToken:i}).myself();y.info(`${d.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{y.warn(`${d.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},me(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Qs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=de(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});Qs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=de(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],me(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var ei=$e.command("github").description("GitHub credential for implement-mode rules");ei.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=Vn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Vy("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(()=>(Ct(),zr)),s=await new r(n).whoami(),i=de();i.github={token:n,login:s},me(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${sn()} (mode 600, this machine only)`)}finally{e.close()}});ei.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=de();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&&Ke.default.existsSync(r))try{let i=(0,jt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=Rt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(Ct(),zr)),c=new l(n),d=await c.repoAccess(o.owner,o.repo);if(d.ok&&d.canPush){let p=await c.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${p} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Vn.default.createInterface({input:process.stdin,output:process.stdout});try{Vy(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(Ct(),zr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},me(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});ei.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=de(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Vn.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(()=>(Ct(),zr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},me(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});ei.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=de(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});ei.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=de(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],me(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});ei.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=de();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var id=$e.command("audit").description("Recurring specialist audits on this runner");id.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=de();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}],me(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});id.command("schedules").description("List scheduled audits").action(()=>{let t=de();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});id.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=de(),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");me(n),y.info("Removed. Restart the runner to apply.")});var od=$e.command("deploy").description("Deployment settings for this machine");od.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=de();t.deploy={enabled:!0},me(t),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),Tt()});od.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=de();t.deploy={enabled:!1},me(t),y.info("deployments DISABLED on this runner"),Tt()});od.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=de();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var Va=$e.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Va.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=de(),s=po(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 d=l.slice(0,c).trim();i.secrets[d]=l.slice(c+1),o.push(d)}r.environments[s]=i,me(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${sn()} (mode 600, this machine only)`),Tt()});Va.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=de().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(()=>(by(),yy));await o({repoName:t,envName:e,dir:Yt.default.resolve(i.replace(/^~(?=\/|$)/,Xs.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});Va.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=de(),s=po(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,me(r),y.info(`removed ${n.join(", ")} from ${s}`)});Va.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=de(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});$e.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=zd(t);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${Yt.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});$e.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=pr();if(e&&fr(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=Dd(t);y.info(`Restored ${n.restored.length} entries into ${ne()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});$e.command("agent <action> [agentId] [binPath]").description("Which BINARY each agent runs as on this machine: list | set-bin <agentId> <path> | clear-bin <agentId>. Only needed when an agent is installed under a different name or path than its id (claude-code is set with `allwright init` instead).").action(async(t,e,n)=>{let r=de(),s=be.REGISTERED_AGENTS.map(o=>o.id);if(t==="list"){for(let o of be.REGISTERED_AGENTS){let l=je(r,o.id),c=r.agents[o.id]?.bin?" (set here)":" (default: its own id)",d="";try{d=(0,jt.execFileSync)(l,["--version"],{timeout:1e4,encoding:"utf8"}).trim().slice(0,60)}catch{d="not runnable on this machine"}y.info(`${o.id}: ${l}${c} - ${d}`)}return}if(!e||!s.includes(e)){y.error(`unknown agent "${e??""}" - this runner knows: ${s.join(", ")}. Use \`allwright agent list\` to see which of them run here.`),process.exitCode=1;return}if(t==="clear-bin"){delete r.agents[e],me(r),y.info(`${e} is back to its default binary ("${e}" on PATH).`),Tt();return}if(t!=="set-bin"||!n){y.error("usage: allwright agent list | set-bin <agentId> <path> | clear-bin <agentId>"),process.exitCode=1;return}let i="";try{i=(0,jt.execFileSync)(n,["--version"],{timeout:15e3,encoding:"utf8"}).trim()}catch(o){y.error(`"${n}" did not answer \`--version\` (${o instanceof Error?o.message:o}) - nothing was saved. Check the path, or that the binary is executable by this user.`),process.exitCode=1;return}r.agents[e]={bin:n},me(r),y.info(`${e} now runs as "${n}" (${i.slice(0,60)}) on this machine.`),Tt()});$e.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=de();if(t==="on"||t==="off"){e.operatorEnabled=t==="on",me(e),t==="on"?y.info("operator mode ENABLED on this machine. Dashboard users who also hold the 'Operator mode' permission can now let the Compose agent run commands here as this runner's user, inside a consented, time-boxed session. Every tool call is recorded (`allwright operator log`). Turn it off any time: `allwright operator off`."):y.info("operator mode DISABLED on this machine - Compose is back to read-only here."),Tt();return}if(t==="status"){y.info(e.operatorEnabled?"operator mode is ENABLED on this machine (allwright operator off to disable).":"operator mode is DISABLED on this machine (allwright operator on to enable).");return}if(t==="log"){let n=zm();if(!n.length){y.info("no operator turns have run on this machine.");return}for(let r of n){y.info(`${r.at} ${r.userName||r.userId||"someone"} [${r.sessionId}] asked: ${r.ask}`);for(let s of r.commands)y.info(` - ${s}`)}return}y.error(`unknown action "${t}" - use on | off | status | log`),process.exitCode=1});$e.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=de(),e=Object.keys(t.repos),n=ai(t);n&&y.warn("no Jira credentials on this runner - it polls no board. Expected on a deploy-only server; add them any time with `allwright jira set-default`.");let r=e.length?e.map(i=>({jiraProjectKey:"*",repoName:i})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],s=!0;for(let i of r){let o=await Ua(t,i),l=!fo(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||y.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let d=c.ok?"PASS":"FAIL";(c.ok?y.info:y.error)(`[${d}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function Tt(){let t=pr()??ms();if(t&&fr(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?Zd(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"Could not signal the running runner - it may run as another user (the service usually runs as root, and `sudo` is what lets you signal it). Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function jx(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Wd();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Tl);let n=t.jira?new qe(t.jira):Xl(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let g=r.get(u);return g||(g=new qe(m),r.set(u,g)),g},i=new Map,o=(u,m)=>{let g=Ph(ke()??t,u,m);switch(g.kind){case"legacy":return{jira:s(u),authored:!1};case"self":return{jira:s(u),authored:!0};case"missing":return{error:g.error};case"user":{let S=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,$=i.get(S);return $||($=new qe(g.creds),i.set(S,$)),{jira:$,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],d=[],p=[],f,b=null,w={cfg:t,jiraFor:s,transport:null},_=new Set,x=async(u,m,g)=>{if(!(m.length<2))for(let S=0;S<m.length;S++){let{text:$,changed:N}=Mh(g[S]??"",m);N&&await u.updateDescription(m[S],$).then(()=>y.info(`Compose: rewrote sibling ticket refs in ${m[S]} to real keys`)).catch(G=>y.warn(`Compose: could not rewrite refs in ${m[S]}: ${G instanceof Error?G.message:G}`))}},R=u=>{let m=c.find(S=>S.id===u),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A=u=>{let m=c.find($=>$.id===u),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let S=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${S}. 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 w.transport},lookup:(u,m)=>{let g=R(u),S=p.find($=>$.projectId===u&&$.name===m);return g&&S?{...g,environment:S}:null}},Y=new Map,C=new Set,v=new za(l.toString(),t.runnerToken,{runnerVersion:Eo},{onConfig:u=>{c=u.projects,Hm(u.projects),d=u.rules,p=u.environments,Mf(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments)},onDeployFix:async u=>{let m=R(u.projectId);if(!m){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(u.projectId)});return}let g=Se(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${u.environmentName}" (step: ${u.failedStep||"?"})`);let S=await eu({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,failedStep:u.failedStep,errorText:u.errorText,cfg:t});v.sendDeploySuggestResult(u.requestId,S)},onProjectTest:async u=>{let m=c.find(S=>S.id===u.projectId);if(!m){v.sendProjectTestResult(u.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await Ua(ke()??t,m,p.filter(S=>S.projectId===m.id),d.filter(S=>S.projectId===m.id).map(S=>"agent"in S.action?S.action.agent:"").filter(Boolean));v.sendProjectTestResult(u.requestId,g.every(S=>S.ok),g)},onRuleDiagnose:async u=>{let m=d.find(q=>q.id===u.ruleId),g=m&&c.find(q=>q.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(u.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let S=await Ua(ke()??t,g,m.action.type==="deploy"?p.filter(q=>q.projectId===g.id):[]),$=m.action.type==="implement"?S:S.filter(q=>q.name!=="github-token"),{matchedCount:N,excludedCount:G,excludedSample:U}=await f.diagnoseRule(m,g);v.sendRuleDiagnoseResult(u.requestId,{checks:$,matchedCount:N,excludedCount:G,excludedSample:U})},onCancel:u=>{uf(u)?y.info(`run ${u} stopped from the dashboard`):y.warn(`cancel requested for run ${u}, but nothing is running under that id here - it likely finished already`)},onApproved:(u,m)=>{if(da(u)){Yc(J,u).catch(g=>y.error(`deploy approval crashed for ${u}: ${g instanceof Error?g.stack:g}`));return}Ai(w,u,m).catch(g=>y.error(`approval handling crashed for ${u}: ${g instanceof Error?g.stack:g}`))},onRetryPush:u=>{let m=Qo(u),g=()=>vf(w,u).catch(S=>y.error(`retry push crashed for ${u}: ${S instanceof Error?S.stack:S}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:u=>{if(da(u)){Xc(J,u).catch(m=>y.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}wf(w,u).catch(m=>y.error(`rejection handling crashed for ${u}: ${m instanceof Error?m.stack:m}`))},onDeployStart:u=>{let m=`${u.runId}#${u.attempt}`;if(_.has(m))return;_.add(m);let g=R(u.projectId);if(!g){let S=A(u.projectId);y.error(`deploy ${u.runId}: ${S}`),v.send({type:"run.status",runId:u.runId,status:"failed",error:S});return}y.info(`deploy ${u.runId} requested from the dashboard: ${u.issueKey} \u2192 ${u.environment.name}`),f.runOnEnvironmentQueue(u.environment.id,()=>Ni({runId:u.runId,project:g.project,environment:u.environment,issueKey:u.issueKey,issueSummary:u.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:v,requestedBy:u.requestedBy}).catch(S=>y.error(`deploy crashed for ${u.runId}: ${S instanceof Error?S.stack:S}`)))},onDeploySuggest:async u=>{let m=R(u.projectId);if(!m){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(u.projectId)});return}let g=Se(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${u.environmentName}" deploy steps in ${m.repoPath}`);let S=await tu({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,notes:u.notes,timeoutSeconds:u.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(u.requestId,S)},onEnvPreflight:async u=>{let m=R(u.projectId);if(!m){v.sendEnvPreflightResult(u.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Qc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,requiredSecrets:u.requiredSecrets,workdir:u.workdir,branch:u.branch,publicUrl:u.publicUrl,cfg:t});v.sendEnvPreflightResult(u.requestId,g)},onSelfMigrationApply:async u=>{let m=R(u.projectId);if(!m){v.sendSelfMigrationApplyResult(u.requestId,{ok:!1,file:u.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(u.projectId)});return}y.info(`applying migration ${u.file} for "${u.environmentName}"`);let g=await Wm({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,file:u.file,urlSecret:u.urlSecret,cfg:t});y.info(g.ok?`migration ${u.file} applied`:`migration ${u.file} failed: ${g.error}`),v.sendSelfMigrationApplyResult(u.requestId,g)},onAutopilotPlan:async u=>{try{let m=R(u.projectId);if(!m){v.sendAutopilotPlanResult(u.requestId,{ok:!1,error:A(u.projectId)});return}let g=s(m.project.repoName),S=[];for(let L of u.issueKeys)try{let ce=await g.getIssue(L);S.push(`${L}: ${ce.summary}
|
|
1263
|
+
${(ce.description||"").slice(0,500)}`)}catch{S.push(`${L}: (could not read from Jira)`)}let $=Se(t,m.project,"assist");if("error"in $){v.sendAutopilotPlanResult(u.requestId,{ok:!1,error:$.error});return}let N=`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.
|
|
1264
1264
|
|
|
1265
1265
|
`+S.join(`
|
|
1266
1266
|
|
|
@@ -1273,7 +1273,7 @@ Rules:
|
|
|
1273
1273
|
- "order": every key exactly once. Prerequisites before the work that needs them.
|
|
1274
1274
|
- "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.
|
|
1275
1275
|
- "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
|
|
1276
|
-
- "reasoning": 2-3 short lines a person can check your plan against.`,G=await $.adapter.run({repoPath:m.repoPath,prompt:
|
|
1276
|
+
- "reasoning": 2-3 short lines a person can check your plan against.`,G=await $.adapter.run({repoPath:m.repoPath,prompt:N,timeoutSeconds:90,bin:$.bin,mode:"read_only",maxTurns:3,model:$.adapter.fastModel,sessionId:(0,vn.randomUUID)(),onLog:()=>{}}),U=fu(G.resultText,u.issueKeys);if(!U){v.sendAutopilotPlanResult(u.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:q}=await Promise.resolve().then(()=>(ya(),um));q({batchId:u.batchId,projectId:u.projectId,order:U.order,chains:U.chains,dependencies:U.dependencies,reasoning:U.reasoning}),v.sendAutopilotPlanResult(u.requestId,{ok:!0,...U})}catch(m){v.sendAutopilotPlanResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async u=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(Qu(),iy)),g=await m({command:u.command,args:u.args});y.info(`chat diagnostic (user-approved): ${g.commandLine}`),v.sendChatDiagnosticResult(u.requestId,g)}catch(m){v.sendChatDiagnosticResult(u.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatStepRun:async u=>{let m=J.lookup(u.projectId,u.environmentName);if(!m){v.sendChatStepRunResult(u.requestId,{ok:!1,error:`this runner has no environment "${u.environmentName}" for that project`});return}let{environment:g}=m,S=g.steps[u.stepIndex];if(!S||S.name!==u.stepName){v.sendChatStepRunResult(u.requestId,{ok:!1,error:`step ${u.stepIndex+1} of "${g.name}" is ${S?`"${S.name}"`:"not there"} on this machine, not "${u.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let $=`${u.projectId}:${g.name}:${u.stepIndex}`;if(C.has($)){v.sendChatStepRunResult(u.requestId,{ok:!1,stepName:S.name,error:"that step is already running here - wait for it to finish"});return}C.add($),y.info(`chat step re-run (user-approved): [${g.name}] ${S.name}`);try{let{runSavedStep:N}=await Promise.resolve().then(()=>(Ls(),nm)),G=await N({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:g.name,workdir:g.workdir,branch:g.branch,step:S,cfg:t,timeoutMs:Math.min(g.timeoutSeconds*1e3,$x)});v.sendChatStepRunResult(u.requestId,{ok:!0,stepName:S.name,...G})}catch(N){v.sendChatStepRunResult(u.requestId,{ok:!1,stepName:S.name,error:N instanceof Error?N.message:String(N)})}finally{C.delete($)}},onChatCancel:u=>{let m=Y.get(u.turnId);m&&(m.abort(),y.info(`chat turn ${u.turnId} stopped from the dashboard`))},onChatTurn:async u=>{let m=R(u.projectId);if(!m){v.sendChatTurnResult(u.requestId,{ok:!1,sessionId:u.sessionId??"",reply:"",error:A(u.projectId)});return}let g=u.sessionId||(0,vn.randomUUID)(),S=!u.sessionId,$=u.sessionId?Zr(u.sessionId):null,N=$?.agentId||u.agentId||m.project.defaultAgent||be.DEFAULT_AGENT_ID;if(!S&&u.userId){let Re=$?.ownerUserId??"";if(Re&&Re!==u.userId){v.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat belongs to someone else - you can read it, but only its owner can continue it. Start your own chat for this."});return}}let G=u.operator===!0;if(G&&!t.operatorEnabled){v.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"operator mode is not enabled on this machine. Whoever administers the server must run `allwright operator on` there once (and `allwright operator off` turns it back off) - a dashboard permission alone is deliberately not enough."});return}let U=S?0:$?.messages.length??0,q=!1,L=0,ce="";if(!S&&U>=Rm){let Re=await Cm(m,g,t);if(Re)q=!0,L=U,ce=Re,g=(0,vn.randomUUID)(),S=!0,y.info(`chat compacted: ${U} message(s) summarized into a fresh session`);else if(U>=Em){v.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let V=u.files.length?qd(m.repoPath,u.requestId,u.files):null,re=(0,be.replyPreferenceAppendix)({language:u.replyLanguage,languageInstruction:u.replyLanguageInstruction,style:u.replyStyle})+(0,be.pendingMigrationsAppendix)(u.pendingMigrations)+(0,be.deployTargetsAppendix)(u.environments)+(0,be.savedStepChecksAppendix)(u.environmentSteps)+(0,be.composeCommandAppendix)(u.command),Ie=Px(m.repoPath)+qn("compose",m.repoPath,{summary:u.message,ruleName:""});Yo(m,t);let Pe="```",Ge=S?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
1277
1277
|
|
|
1278
1278
|
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.
|
|
1279
1279
|
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.
|
|
@@ -1294,26 +1294,26 @@ ${ce}
|
|
|
1294
1294
|
${u.userName||"The user"} says: ${u.message}`+(V?.section??""):re+be.TICKET_RULES_APPENDIX+`
|
|
1295
1295
|
|
|
1296
1296
|
`+Ie+`
|
|
1297
|
-
${u.userName||"The user"} says: ${u.message}`+(V?.section??""),ti=0,kn=0,fe=new Date;Tm(u.projectId,g,u.message,u.files.map(Re=>Re.name),fe.toISOString(),u.userId,
|
|
1297
|
+
${u.userName||"The user"} says: ${u.message}`+(V?.section??""),ti=0,kn=0,fe=new Date;Tm(u.projectId,g,u.message,u.files.map(Re=>Re.name),fe.toISOString(),u.userId,N),v.send({type:"chat.session",requestId:u.requestId,sessionId:g});let Je=[],Ja=[],se;try{let Re=Se(t,m.project,G?"operator":"chat",N);if("error"in Re){va(g),v.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:Re.error});return}let Jn=new AbortController;Y.set(u.requestId,Jn);let Xy=Date.now(),ad={repoPath:m.repoPath,prompt:Ge,signal:Jn.signal,timeoutSeconds:Ix,bin:Re.bin,mode:G?"operator":"read_only_web",maxTurns:25,model:u.model||Re.adapter.fastModel,sessionId:g,resume:!S,onLog:(ze,ot)=>{ze==="agent"&&(Je.push(ot.slice(0,4e3)),v.send({type:"chat.stream",requestId:u.requestId,seq:ti++,text:ot.slice(0,8e3)}))},onTool:(ze,ot)=>{G&&(Ja.push(`${ze}: ${ot}`),Je.push(`${ze}: ${ot}`.slice(0,4e3))),v.send({type:"chat.activity",requestId:u.requestId,seq:kn++,verb:ze,target:ot})},onUsage:ze=>{v.send({type:"chat.usage",requestId:u.requestId,inputTokens:Math.round(ze.inputTokens),outputTokens:Math.round(ze.outputTokens),cacheReadTokens:ze.cacheReadTokens===void 0?void 0:Math.round(ze.cacheReadTokens),turns:ze.turns})}};se=await Re.adapter.run(ad);let Ya=0;for(;!se.ok&&se.turnLimitHit&&!se.cancelled&&Re.adapter.capabilities.sessionResume&&Ya<Zy;){let ze=Wy-(Date.now()-Xy);if(ze<Rx)break;Ya++,y.info(`chat turn ${u.requestId}: turn limit hit - resuming the same session (resume ${Ya}/${Zy}, ${Math.round(ze/1e3)}s left)`);let ot=await Re.adapter.run({...ad,prompt:ze<=Cx?Ex:Ax,resume:!0,timeoutSeconds:Math.floor(ze/1e3)});ot.costUsd+=se.costUsd,ot.inputTokens+=se.inputTokens,ot.outputTokens+=se.outputTokens,ot.cacheReadTokens+=se.cacheReadTokens,se=ot}!se.ok&&(se.turnLimitHit||se.timedOut)&&!se.resultText.trim()&&Je.length&&(se.resultText=Nx(Je))}finally{if(Y.delete(u.requestId),V&&Ke.default.rmSync(V.dir,{recursive:!0,force:!0}),G&&Ja.length)try{Mm({projectId:u.projectId,sessionId:g,userId:u.userId,userName:u.userName,ask:u.message,commands:Ja})}catch(Re){y.warn(`operator ledger write failed: ${Re instanceof Error?Re.message:Re}`)}}if(se.cancelled){va(g),v.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:se.inputTokens,outputTokens:se.outputTokens,cacheReadTokens:se.cacheReadTokens});return}if(!se.ok&&se.timedOut&&(se.error=`this has been running for ${Math.round(Wy/6e4)} minutes, so I stopped to check in - nothing is lost. What it had worked out is below; say "continue" and it picks up in the same session, exactly where it left off. If it is really a job rather than a question, make it a ticket instead: a full run has hours, and can change code and open a PR.`),se.ok||se.resultText.trim()){let Re=Je.filter(Jn=>Jn.trim()&&!se.resultText.trim().startsWith(Jn.trim()));se.ok||(se.resultText=`${se.resultText.trim()}
|
|
1298
1298
|
|
|
1299
1299
|
---
|
|
1300
|
-
_Unfinished: ${se.error||"the turn ended early"}._`),xm(u.projectId,g,u.message,se.resultText,Re,u.files.map(Jn=>Jn.name),{askedAt:fe.toISOString(),ms:Date.now()-fe.getTime(),tokens:(se.inputTokens??0)+(se.outputTokens??0)},u.userId,
|
|
1300
|
+
_Unfinished: ${se.error||"the turn ended early"}._`),xm(u.projectId,g,u.message,se.resultText,Re,u.files.map(Jn=>Jn.name),{askedAt:fe.toISOString(),ms:Date.now()-fe.getTime(),tokens:(se.inputTokens??0)+(se.outputTokens??0)},u.userId,N)}else va(g);let Yy=(se.inputTokens??0)+(se.cacheReadTokens??0);v.sendChatTurnResult(u.requestId,{contextTokens:Yy,contextLimit:Am(se.model||u.model||""),compacted:q,compactedMessages:L,ok:se.ok,sessionId:g,reply:se.resultText,outputTruncated:!!se.outputTruncated,error:se.ok?void 0:se.error??"the agent produced no reply",inputTokens:se.inputTokens,outputTokens:se.outputTokens,cacheReadTokens:se.cacheReadTokens,costUsd:se.costUsd,model:se.model??""})},onChatList:u=>{v.sendChatListResult(u.requestId,Im(u.projectId))},onRepoDocs:u=>{let m=R(u.projectId);if(!m){v.sendRepoDocsResult(u.requestId,{ok:!1,docs:[],error:A(u.projectId)});return}v.sendRepoDocsResult(u.requestId,{ok:!0,docs:Um(m.repoPath)})},onRepoDocRead:u=>{let m=R(u.projectId);if(!m){v.sendRepoDocReadResult(u.requestId,{ok:!1,path:u.path,content:"",truncated:!1,error:A(u.projectId)});return}let g=qm(m.repoPath,u.path);v.sendRepoDocReadResult(u.requestId,{ok:g.ok,path:g.ok?g.path:u.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:u=>{let m=Zr(u.sessionId);v.sendChatLoadResult(u.requestId,{ok:m!==null,projectId:m?.projectId??"",ownerUserId:m?.ownerUserId??"",agentId:m?.agentId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async u=>{let m=R(u.projectId);if(!m){v.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:A(u.projectId)});return}try{let g=s(m.project.repoName),S;try{S=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{S=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let $=await g.boardColumns(m.project.jiraProjectKey),N;if($){N=$.map(q=>({name:q.name,issues:[]}));let U=new Map;for(let q of S){let L=$.findIndex(V=>V.statusIds.includes(q.statusId)),ce={key:q.key,summary:q.summary,labels:q.labels,components:q.components};if(L>=0)N[L].issues.push(ce);else{let V=U.get(q.status)??[];V.push(ce),U.set(q.status,V)}}for(let[q,L]of U)N.push({name:q,issues:L})}else{let U=re=>re.trim().toLowerCase(),q=new Map,L=new Map;for(let re of S){let Ie=U(re.status);q.has(Ie)||q.set(Ie,re.status.trim());let Pe=L.get(Ie)??[];Pe.push({key:re.key,summary:re.summary,labels:re.labels,components:re.components}),L.set(Ie,Pe)}let ce=[];try{ce=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let V=[];for(let re of ce){let Ie=U(re);!V.includes(Ie)&&L.has(Ie)&&V.push(Ie)}for(let re of L.keys())V.includes(re)||V.push(re);N=V.map(re=>({name:q.get(re)??re,issues:L.get(re)??[]}))}let G=t.repos[m.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(u.requestId,{ok:!0,browseBaseUrl:(G?.baseUrl??"").replace(/\/+$/,""),columns:N})}catch(g){v.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async u=>{let m=R(u.projectId);if(!m){v.sendBoardTriggerResult(u.requestId,{ok:!1,error:A(u.projectId)});return}try{let g=s(m.project.repoName);u.agentId&&lm(u.projectId,u.issueKey,u.agentId);let S=u.comment.trim()?o(m.project.repoName,u.requestedByEmail):{jira:g,authored:!1};if(S.error!==void 0){v.sendBoardTriggerResult(u.requestId,{ok:!1,error:S.error});return}if(u.reimplement){let $=await g.getIssue(u.issueKey),N=$.comments.filter(q=>mt(q.body)),G=N.length?Math.max(...N.map(q=>new Date(q.created).getTime())):0;if(!$.comments.some(q=>!mt(q.body)&&new Date(q.created).getTime()>G)){v.sendBoardTriggerResult(u.requestId,{ok:!1,error:`${u.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await g.editLabels(u.issueKey,{remove:["agent-implemented"]})}u.removeLabel.trim()&&await g.editLabels(u.issueKey,{remove:[u.removeLabel.trim()]}),u.comment.trim()&&await S.jira.addTriggerComment(u.issueKey,`${u.comment.trim()}`+(!S.authored&&u.requestedBy?`
|
|
1301
1301
|
|
|
1302
1302
|
_(requested by ${u.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${u.issueKey}`+(u.comment?` comment "${u.comment.trim()}"`:"")+(u.removeLabel?` -label ${u.removeLabel}`:"")+(u.agentId?` agent ${u.agentId}`:"")+(u.requestedBy?` by ${u.requestedBy}`:"")),v.sendBoardTriggerResult(u.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async u=>{let m=R(u.projectId);if(!m){v.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:A(u.projectId)});return}try{let g=o(m.project.repoName,u.requestedByEmail);if(g.error!==void 0){v.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:g.error});return}let S=`
|
|
1303
1303
|
|
|
1304
1304
|
---
|
|
1305
|
-
_Created via Allwright Compose`+(!g.authored&&u.requestedBy?` by ${u.requestedBy}`:"")+", drafted with the project agent._",$="";if(u.chatSessionId&&(!u.asEpic||u.createAs==="epic_with_children")){let
|
|
1305
|
+
_Created via Allwright Compose`+(!g.authored&&u.requestedBy?` by ${u.requestedBy}`:"")+", drafted with the project agent._",$="";if(u.chatSessionId&&(!u.asEpic||u.createAs==="epic_with_children")){let U=Zr(u.chatSessionId)?.ownerUserId??"";if(!U||!u.userId||U===u.userId){let q=await $m(m,u.chatSessionId,t);q&&($=`
|
|
1306
1306
|
|
|
1307
1307
|
----
|
|
1308
1308
|
*Context from the Compose chat this ticket came from (machine-summarized ${new Date().toISOString().slice(0,10)} - the code may have moved since; verify against the repo):*
|
|
1309
1309
|
|
|
1310
|
-
${
|
|
1310
|
+
${q}`)}}if(u.asEpic&&u.createAs!=="epic_with_children"&&u.children.length){let U=u.createAs==="separate_epics"?"Epic":"Task",q=[],L=[];for(let ce of u.children){let V=(ce.description||"(no description)")+S,re=await g.jira.createIssue(m.project.jiraProjectKey,ce.summary,V,U,void 0,u.component?[u.component]:[]);q.push(re.key),L.push(V)}await x(g.jira,q,L),y.info(`Compose created ${q.length} standalone ${U.toLowerCase()}(s)`),v.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:q[0]??"",childKeys:q});return}let{key:N}=await g.jira.createIssue(m.project.jiraProjectKey,u.summary,(u.description||"(no description)")+$+S,u.asEpic?"Epic":"Task",void 0,u.component?[u.component]:[]);u.files.length&&await g.jira.addAttachments(N,u.files.map(U=>({name:U.name,content:Buffer.from(U.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${u.files.length} file(s) to ${N}`)).catch(U=>y.warn(`Compose could not attach files to ${N}: ${U instanceof Error?U.message:U}`));let G=[];if(u.asEpic){let U=[];for(let q of u.children){let L=(q.description||"(no description)")+S,ce=await g.jira.createIssue(m.project.jiraProjectKey,q.summary,L,"Task",N,u.component?[u.component]:[]);G.push(ce.key),U.push(L)}await x(g.jira,G,U),y.info(`Compose created epic ${N} with ${G.length} child ticket(s)`),v.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:N,childKeys:G});return}u.triggerComment.trim()&&await g.jira.addTriggerComment(N,`${u.triggerComment.trim()}`+(!g.authored&&u.requestedBy?`
|
|
1311
1311
|
|
|
1312
|
-
_(requested by ${u.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${
|
|
1312
|
+
_(requested by ${u.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${N}`+(u.requestedBy?` for ${u.requestedBy}`:"")+(u.triggerComment?` with trigger "${u.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:N})}catch(g){v.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async u=>{let m=R(u.projectId);if(!m){v.sendAuditStartResult(u.requestId,{ok:!1,error:A(u.projectId)});return}try{y.info(`Audit (${u.role}) starting on ${m.project.repoName}`+(u.scope.kind!=="repo"?` scoped to ${u.scope.kind}:${u.scope.ref}`:""));let g=Se(t,m.project,"assist");if("error"in g){v.sendAuditStartResult(u.requestId,{ok:!1,error:g.error});return}let S=await $s({projectId:u.projectId,repoPath:m.repoPath,role:u.role,scope:u.scope,detailLevel:u.detailLevel,model:u.model,agent:g,jira:s(m.project.repoName),baseUrl:u.baseUrl});if(!S.ok){v.sendAuditStartResult(u.requestId,{ok:!1,error:S.error});return}v.sendAuditStartResult(u.requestId,{ok:!0,audit:S.audit})}catch(g){v.sendAuditStartResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async u=>{try{v.sendAuditListResult(u.requestId,{ok:!0,audits:ep(u.projectId)})}catch(m){v.sendAuditListResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async u=>{try{let m=cc(u.projectId,u.auditId),g=m?.findings.find(q=>q.id===u.findingId);if(!m||!g){v.sendAuditExplainResult(u.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let S=R(u.projectId);if(!S){v.sendAuditExplainResult(u.requestId,{ok:!1,error:A(u.projectId)});return}let $=Se(t,S.project,"assist");if("error"in $){v.sendAuditExplainResult(u.requestId,{ok:!1,error:$.error});return}let N=`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.
|
|
1313
1313
|
|
|
1314
1314
|
FINDING (${g.severity}${g.ruleId?`, rule ${g.ruleId}`:""}):
|
|
1315
1315
|
${g.title}
|
|
1316
|
-
`+g.evidence.map(
|
|
1316
|
+
`+g.evidence.map(q=>`- ${q.file}${q.line?`:${q.line}`:""} ${q.note}`.trim()).join(`
|
|
1317
1317
|
`)+(g.fix?`
|
|
1318
1318
|
Proposed fix: ${g.fix}`:"")+`
|
|
1319
1319
|
|
|
@@ -1324,7 +1324,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
|
|
|
1324
1324
|
**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.
|
|
1325
1325
|
**How urgent:** now / before the next release / when convenient - and why.
|
|
1326
1326
|
**What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
|
|
1327
|
-
Nothing else - no preamble, no code.`,G=await $.adapter.run({repoPath:S.repoPath,prompt:
|
|
1327
|
+
Nothing else - no preamble, no code.`,G=await $.adapter.run({repoPath:S.repoPath,prompt:N,timeoutSeconds:120,bin:$.bin,mode:"read_only",maxTurns:8,sessionId:(0,vn.randomUUID)(),onLog:()=>{}}),U=G.resultText.trim();if(!G.ok||!U){v.sendAuditExplainResult(u.requestId,{ok:!1,error:G.error??"the agent returned nothing - try again"});return}v.sendAuditExplainResult(u.requestId,{ok:!0,explanation:U})}catch(m){v.sendAuditExplainResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async u=>{try{let m=cc(u.projectId,u.auditId);if(!m){v.sendAuditGetResult(u.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(u.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async u=>{try{let m=lc(u.projectId,u.auditId,{selected:u.selected,ticketed:u.ticketed,verdicts:u.verdicts,verdictBy:u.verdictBy});if(!m){v.sendAuditReviewResult(u.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=R(u.projectId);if(g&&u.verdicts.length){let S=[];for(let $ of u.verdicts){if($.verdict==="valid"||m.lessonsWritten.includes($.findingId))continue;let N=m.findings.find(G=>G.id===$.findingId);N&&(pc(g.repoPath,m.role,lp(N,$.verdict,$.note,u.verdictBy)),S.push($.findingId),y.info(`Lesson written (${m.role}): ${$.verdict} - ${N.title.slice(0,60)}`))}S.length&&(m=lc(u.projectId,u.auditId,{markLessonsWritten:S})??m)}v.sendAuditReviewResult(u.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async u=>{let m=R(u.projectId);if(!m){v.sendKnowledgeListResult(u.requestId,{ok:!1,error:A(u.projectId)});return}try{v.sendKnowledgeListResult(u.requestId,{ok:!0,files:up(m.repoPath)})}catch(g){v.sendKnowledgeListResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async u=>{let m=R(u.projectId);if(!m){v.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:A(u.projectId)});return}try{u.append?pc(m.repoPath,u.role,cp(u.content,u.by),u.level):dp(m.repoPath,u.role,u.level,u.source,u.name,u.content),y.info(`Knowledge ${u.append?"taught":"saved"}: ${u.role}/${u.level}/${u.name}`),v.sendKnowledgeSaveResult(u.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async u=>{let m=R(u.projectId);if(!m){v.sendEpicListResult(u.requestId,{ok:!1,error:A(u.projectId)});return}try{let g=s(m.project.repoName);if(u.epicKey){let S=await g.epicChildren(u.epicKey);v.sendEpicListResult(u.requestId,{ok:!0,children:S})}else{let S=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(u.requestId,{ok:!0,epics:S})}}catch(g){v.sendEpicListResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async u=>{let m=R(u.projectId);if(!m){v.sendEpicSuggestResult(u.requestId,{ok:!1,error:A(u.projectId)});return}try{let g=s(m.project.repoName),S=await g.epicChildren(u.epicKey),$=Fh(S);if(!$.length){v.sendEpicSuggestResult(u.requestId,{ok:!1,error:`every child of ${u.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if($.length===1){v.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:$[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let N=await Promise.all($.slice(0,12).map(async ce=>{try{let V=await g.getIssue(ce.key);return{...ce,description:V.description}}catch{return{...ce,description:""}}})),G=(await g.getIssue(u.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${N.length} pending children of ${u.epicKey}`);let U=Se(t,m.project,"assist");if("error"in U){v.sendEpicSuggestResult(u.requestId,{ok:!1,error:U.error});return}let q=await U.adapter.run({repoPath:m.repoPath,prompt:Bh(u.epicKey,G,N),timeoutSeconds:150,bin:U.bin,mode:"read_only",maxTurns:20,sessionId:(0,vn.randomUUID)(),model:u.model||"claude-sonnet-5",onLog:()=>{}}),L=Hh(q.resultText,N.map(ce=>ce.key));if("error"in L){v.sendEpicSuggestResult(u.requestId,{ok:!1,error:L.error});return}y.info(`Epic suggest: ${u.epicKey} -> do ${L.issueKey} first`),v.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:L.issueKey,reason:L.reason,considered:N.length})}catch(g){v.sendEpicSuggestResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async u=>{try{let m=ke()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:S}=await Promise.resolve().then(()=>(Ct(),zr));m.github.login=await new S(m.github.token).whoami(),me(m)}catch{}let g=Oh(m,u.emails);v.sendTeamCredsResult(u.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:u=>{try{let m=ke();if(!m){v.sendRepoUnmapResult(u.requestId,{ok:!1,error:"this runner has no config file"});return}let g=m.repos[u.repoName];if(!g){v.sendRepoUnmapResult(u.requestId,{ok:!0,removedPath:""});return}let S=g.path;delete m.repos[u.repoName];for(let $ of Object.keys(m.environments).filter(N=>N.startsWith(`${u.repoName}:`)))delete m.environments[$];m.auditSchedules=m.auditSchedules.filter($=>$.repoName!==u.repoName),me(m),Tt(),y.info(`Unmapped "${u.repoName}" (was ${S}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),v.sendRepoUnmapResult(u.requestId,{ok:!0,removedPath:S})}catch(m){v.sendRepoUnmapResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:u=>{try{let m=R(u.projectId);if(!m){v.sendSetupRecheckResult(u.requestId,{ok:!1,error:A(u.projectId)});return}v.sendSetupRecheckResult(u.requestId,{ok:!0,checks:jf({repoPath:m.repoPath,environments:u.environments})})}catch(m){v.sendSetupRecheckResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRebirthStudy:async u=>{let m=c.find(U=>U.id===u.projectId&&!U.repoName),g=m?{project:m,repoPath:""}:R(u.projectId);if(!g){v.sendRebirthStudyResult(u.requestId,{ok:!1,error:A(u.projectId)});return}let{runRebirthStudy:S,rebirthStudyInFlight:$}=await Promise.resolve().then(()=>(_y(),ky));if($(u.rebirthId)){v.sendRebirthStudyResult(u.requestId,{ok:!1,error:"a study is already running for this rebirth - it reports progress as it goes"});return}let N=Ke.default.existsSync(g.repoPath),G=N?g.repoPath:Ke.default.mkdtempSync(Yt.default.join(Xs.default.tmpdir(),"rebirth-"));v.sendRebirthStudyResult(u.requestId,{ok:!0}),S({msg:u,cfg:t,project:g.project,repoPath:G,repoAvailable:N,jira:ai(t)&&!t.repos[g.project.repoName]?.jira?null:s(g.project.repoName),transport:v}).then(U=>{U.ok||y.warn(`rebirth study ${u.rebirthId} failed: ${U.error}`)}).finally(()=>{N||Ke.default.rmSync(G,{recursive:!0,force:!0})})},onTimelineDigest:async u=>{let m=R(u.projectId);if(!m){v.sendTimelineDigestResult(u.requestId,{ok:!1,text:"",error:A(u.projectId)});return}let g=Se(t,m.project,"assist");if("error"in g){v.sendTimelineDigestResult(u.requestId,{ok:!1,text:"",error:g.error});return}try{let S=await g.adapter.run({repoPath:m.repoPath,prompt:u.prompt,timeoutSeconds:90,bin:g.bin,mode:"read_only",maxTurns:2,model:g.adapter.fastModel,sessionId:(0,vn.randomUUID)(),onLog:()=>{}});v.sendTimelineDigestResult(u.requestId,{ok:S.ok&&!!S.resultText.trim(),text:S.resultText.trim().slice(0,8e3),error:S.ok?void 0:S.error||"the agent did not answer"})}catch(S){v.sendTimelineDigestResult(u.requestId,{ok:!1,text:"",error:S instanceof Error?S.message:String(S)})}},onServerInventory:async u=>{try{let{collectServerInventory:m}=await Promise.resolve().then(()=>(Py(),$y)),g=await m(ke()??t);v.sendServerInventoryResult(u.requestId,{ok:!0,...g})}catch(m){v.sendServerInventoryResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m),checkouts:[],services:[],containers:[],ports:[],processes:[]})}},onSetupStatus:async u=>{try{let m=ke()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(Gy(),Ky)),S=await g(m,u.repoNames,t);v.sendSetupStatusResult(u.requestId,{ok:!0,...S})}catch(m){v.sendSetupStatusResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async u=>{try{let m=R(u.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let S="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.",$=`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.
|
|
1328
1328
|
|
|
1329
1329
|
Ten things decide whether this document can actually be run:
|
|
1330
1330
|
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.
|
|
@@ -1343,7 +1343,7 @@ Reply with ONLY the file content - no preamble, no fences around the whole thing
|
|
|
1343
1343
|
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:
|
|
1344
1344
|
`+u.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(`
|
|
1345
1345
|
`)+`
|
|
1346
|
-
If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(u.kind==="deploy"?qc({repoPath:m.repoPath,urls:u.environments.map(V=>V.publicUrl).filter(Boolean)})+Pi(m.repoPath):""),
|
|
1346
|
+
If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(u.kind==="deploy"?qc({repoPath:m.repoPath,urls:u.environments.map(V=>V.publicUrl).filter(Boolean)})+Pi(m.repoPath):""),N=`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.`,G=qn("implement",m.repoPath,{summary:u.blockers.join(" "),description:u.machineState.join(" ")})+`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.
|
|
1347
1347
|
|
|
1348
1348
|
BLOCKERS AS REPORTED:
|
|
1349
1349
|
`+u.blockers.map((V,re)=>`${re+1}. ${V}`).join(`
|
|
@@ -1383,7 +1383,7 @@ Reply with ONLY the guide - no preamble.`+(u.environments.length?`
|
|
|
1383
1383
|
|
|
1384
1384
|
THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
|
|
1385
1385
|
`+u.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(`
|
|
1386
|
-
`):"")+qc({repoPath:m.repoPath,urls:u.environments.map(V=>V.publicUrl).filter(Boolean)})+Pi(m.repoPath),
|
|
1386
|
+
`):"")+qc({repoPath:m.repoPath,urls:u.environments.map(V=>V.publicUrl).filter(Boolean)})+Pi(m.repoPath),U=Se(t,m.project,"assist");if("error"in U){v.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,content:"",error:U.error});return}let q=0,L=await U.adapter.run({repoPath:m.repoPath,prompt:u.kind==="deploy"?$:u.kind==="design"?N:u.kind==="unblock"?G:S,timeoutSeconds:600,bin:U.bin,mode:"read_only",maxTurns:40,sessionId:(0,vn.randomUUID)(),onLog:(V,re)=>{V==="agent"&&u.streamId&&v.send({type:"chat.stream",requestId:u.streamId,seq:q++,text:re.slice(0,8e3)})}}),ce=L.resultText.trim();if(!ce){v.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"the agent returned no content - try again"});return}L.outputTruncated&&y.warn(`Setup: the ${g} draft was cut off at the agent's output limit - ${ce.length} chars, incomplete`),v.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!0,content:ce,truncated:!!L.outputTruncated})}catch(m){v.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async u=>{try{let m=R(u.projectId);if(!m){v.sendSetupAskResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=Se(t,m.project,"assist");if("error"in g){v.sendSetupAskResult(u.requestId,{ok:!1,error:g.error});return}y.info(`Setup: question about "${u.subject.slice(0,60)}" (${m.project.repoName})`);let S="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."+(u.subject?`
|
|
1387
1387
|
|
|
1388
1388
|
WHAT THEY ARE WORKING ON:
|
|
1389
1389
|
${u.subject}`:"")+(u.command?`
|
|
@@ -1405,4 +1405,4 @@ ${u.question}
|
|
|
1405
1405
|
|
|
1406
1406
|
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.
|
|
1407
1407
|
|
|
1408
|
-
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.`,j=(await g.adapter.run({repoPath:m.repoPath,prompt:S,timeoutSeconds:120,bin:g.bin,mode:"read_only",maxTurns:6,sessionId:(0,vn.randomUUID)(),onLog:()=>{}})).resultText.trim();v.sendSetupAskResult(u.requestId,j?{ok:!0,answer:j}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){v.sendSetupAskResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async u=>{try{let m=R(u.projectId);if(!m){v.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md",S=await Wu({repoPath:m.repoPath,relPath:g,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});S.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${S.note}`),v.sendSetupClaudeMdSaveResult(u.requestId,S)}catch(m){v.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async u=>{try{let m=R(u.projectId);if(!m){v.sendRepoDocSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await Wu({repoPath:m.repoPath,relPath:u.relPath,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${u.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${u.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(u.requestId,g)}catch(m){v.sendRepoDocSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:u=>{try{v.sendAuditStatsResult(u.requestId,{ok:!0,byProject:tp(u.projectIds,u.since)})}catch(m){v.sendAuditStatsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async u=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(u.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let S=Yt.default.dirname(process.execPath),$=Ke.default.existsSync(Yt.default.join(S,"npm"))?Yt.default.join(S,"npm"):"npm";(0,jt.execFile)($,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${S}:${process.env.PATH??""}`}},(j,G,H)=>{if(j){v.sendRunnerUpdateResult(u.requestId,{ok:!1,error:`npm install failed: ${(H||j.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(u.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(b){v.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;v.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s)/chat turn(s) to finish`),b=setInterval(()=>{f.idle&&(clearInterval(b),b=null,m())},5e3)},onRunnerUninstall:u=>{if(!f.idle){v.sendRunnerUninstallResult(u.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=ic()}catch(S){v.sendRunnerUninstallResult(u.requestId,{ok:!1,error:S instanceof Error?S.message:String(S)});return}let g=m.problems.length===0;if(v.sendRunnerUninstallResult(u.requestId,{ok:g,error:g?void 0:m.problems.join("; "),note:g?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!g){y.info("Uninstall requested from the dashboard, but it could not complete here");return}y.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{sc(),process.exit(0)},1500)},onTestFix:async u=>{let m=g=>v.sendTestFixResult(u.requestId,{ok:!1,note:g});try{let g=js(u.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let S=t.repos[g.repoName];if(!S){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let $=Fe(t,g.repoName);if(!$){m("no GitHub token on this runner for that repo");return}let j=await new He($).getPullRequest(g.owner,g.repo,g.prNumber);if(!j){m("that pull request no longer exists on GitHub");return}if(j.merged||j.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let G=c.find(ce=>ce.repoName===g.repoName),H=g.nextDecisionSeq??1e5,U=(ce,V)=>{v.send({type:"run.log",runId:u.runId,seq:H++,ts:new Date().toISOString(),level:ce,message:V}),g.nextDecisionSeq=H,bt(g)},L=await ym({cfg:t,repoPath:S.path,branch:g.branch,baseBranch:j.baseRef||"main",issueKey:g.issueKey,agentId:G?.defaultAgent||be.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:u.failedTests,...u.finding?{finding:{title:u.finding.title,detail:u.finding.detail}}:{},timeoutSeconds:900,onLog:U});L.ok&&L.headSha&&(g.headSha=L.headSha,bt(g),v.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),gt(S.path,{issueKey:g.issueKey,runId:u.runId,title:u.finding?L.ok?L.headSha?`finding fixed on the PR: ${u.finding.title.slice(0,80)}`:`finding declined by the agent: ${u.finding.title.slice(0,80)}`:"dashboard finding fix failed":L.ok?L.headSha?(L.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:L.note.slice(0,500)}),v.sendTestFixResult(u.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async u=>{try{let m=await f.answerPendingInput(u.runId,u.text,u.answeredBy);v.sendRunAnswerResult(u.requestId,m)}catch(m){v.sendRunAnswerResult(u.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async u=>{let m=g=>v.sendResolveConflictResult(u.requestId,{ok:!1,note:g});try{let g=js(u.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let S=t.repos[g.repoName];if(!S){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let $=Fe(t,g.repoName);if(!$){m("no GitHub token on this runner for that repo");return}let j=await new He($).getPullRequest(g.owner,g.repo,g.prNumber);if(!j){m("that pull request no longer exists on GitHub");return}if(!j.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let G=c.find(ce=>ce.repoName===g.repoName),H=g.nextDecisionSeq??1e5,U=(ce,V)=>{v.send({type:"run.log",runId:u.runId,seq:H++,ts:new Date().toISOString(),level:ce,message:V}),g.nextDecisionSeq=H,bt(g)},L=await mm({cfg:t,repoPath:S.path,branch:g.branch,baseBranch:j.baseRef,issueKey:g.issueKey,agentId:G?.defaultAgent||be.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:U});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,bt(g),v.send({type:"run.pr.conflict",runId:u.runId,conflicted:!1}),v.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),v.sendResolveConflictResult(u.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:u=>{try{let m=S=>{try{return Ke.default.existsSync(S)&&Ke.default.readdirSync(S).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([S,$])=>({agent:"claude-code",name:S,loggedIn:m($.configDir)}));v.sendAgentProfilesResult(u.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(Yt.default.join(Xs.default.homedir(),".claude")),agentsWithoutProfiles:be.REGISTERED_AGENTS.filter(S=>!S.capabilities.loginProfiles).map(S=>S.id)})}catch(m){v.sendAgentProfilesResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async u=>{try{let m=await n.searchUsers(u.query);v.sendJiraUsersResult(u.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(u.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,f=new wa(t,s,v),f.setExternalBusy(()=>Y.size);let N=Object.values(Dr()).filter(u=>u.kind==="implement").map(u=>u.repoPath);ql(Object.values(t.repos).map(u=>u.path),N).catch(()=>{}),v.start(),f.start();let O=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),Kd(process.pid),Tl(),process.exit(0)},B=!1,F=()=>{if(B){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(B=!0,f.stop(),f.idle){O();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let u=setInterval(()=>{f.idle&&(clearInterval(u),O())},3e3)};process.on("SIGINT",F),process.on("SIGTERM",F),process.on("SIGHUP",()=>{try{let u=de();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new qe(u.jira):Xl(),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(u){y.error(`config reload failed - keeping the running config: ${u instanceof Error?u.message:String(u)}`)}})}$e.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async t=>{let e=de();if(t.foreground){jx(e);return}let n=pr();if(n&&fr(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ms();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Fd(),i=(0,jt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Hd(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${bo()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});$e.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(t=>{let e=pr();if(!e||!fr(e)){y.info("no background runner is running"),e&&Ke.default.rmSync(fs(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ke.default.rmSync(fs(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});$e.command("status").description("Check whether the background runner is running").action(()=>{let t=pr();t&&fr(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});$e.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|
|
1408
|
+
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.`,N=(await g.adapter.run({repoPath:m.repoPath,prompt:S,timeoutSeconds:120,bin:g.bin,mode:"read_only",maxTurns:6,sessionId:(0,vn.randomUUID)(),onLog:()=>{}})).resultText.trim();v.sendSetupAskResult(u.requestId,N?{ok:!0,answer:N}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){v.sendSetupAskResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async u=>{try{let m=R(u.projectId);if(!m){v.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md",S=await Wu({repoPath:m.repoPath,relPath:g,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});S.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${S.note}`),v.sendSetupClaudeMdSaveResult(u.requestId,S)}catch(m){v.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async u=>{try{let m=R(u.projectId);if(!m){v.sendRepoDocSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await Wu({repoPath:m.repoPath,relPath:u.relPath,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${u.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${u.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(u.requestId,g)}catch(m){v.sendRepoDocSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:u=>{try{v.sendAuditStatsResult(u.requestId,{ok:!0,byProject:tp(u.projectIds,u.since)})}catch(m){v.sendAuditStatsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async u=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(u.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let S=Yt.default.dirname(process.execPath),$=Ke.default.existsSync(Yt.default.join(S,"npm"))?Yt.default.join(S,"npm"):"npm";(0,jt.execFile)($,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${S}:${process.env.PATH??""}`}},(N,G,U)=>{if(N){v.sendRunnerUpdateResult(u.requestId,{ok:!1,error:`npm install failed: ${(U||N.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(u.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(b){v.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;v.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s)/chat turn(s) to finish`),b=setInterval(()=>{f.idle&&(clearInterval(b),b=null,m())},5e3)},onRunnerUninstall:u=>{if(!f.idle){v.sendRunnerUninstallResult(u.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=ic()}catch(S){v.sendRunnerUninstallResult(u.requestId,{ok:!1,error:S instanceof Error?S.message:String(S)});return}let g=m.problems.length===0;if(v.sendRunnerUninstallResult(u.requestId,{ok:g,error:g?void 0:m.problems.join("; "),note:g?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!g){y.info("Uninstall requested from the dashboard, but it could not complete here");return}y.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{sc(),process.exit(0)},1500)},onTestFix:async u=>{let m=g=>v.sendTestFixResult(u.requestId,{ok:!1,note:g});try{let g=js(u.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let S=t.repos[g.repoName];if(!S){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let $=Fe(t,g.repoName);if(!$){m("no GitHub token on this runner for that repo");return}let N=await new He($).getPullRequest(g.owner,g.repo,g.prNumber);if(!N){m("that pull request no longer exists on GitHub");return}if(N.merged||N.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let G=c.find(ce=>ce.repoName===g.repoName),U=g.nextDecisionSeq??1e5,q=(ce,V)=>{v.send({type:"run.log",runId:u.runId,seq:U++,ts:new Date().toISOString(),level:ce,message:V}),g.nextDecisionSeq=U,bt(g)},L=await ym({cfg:t,repoPath:S.path,branch:g.branch,baseBranch:N.baseRef||"main",issueKey:g.issueKey,agentId:G?.defaultAgent||be.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:u.failedTests,...u.finding?{finding:{title:u.finding.title,detail:u.finding.detail}}:{},timeoutSeconds:900,onLog:q});L.ok&&L.headSha&&(g.headSha=L.headSha,bt(g),v.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),gt(S.path,{issueKey:g.issueKey,runId:u.runId,title:u.finding?L.ok?L.headSha?`finding fixed on the PR: ${u.finding.title.slice(0,80)}`:`finding declined by the agent: ${u.finding.title.slice(0,80)}`:"dashboard finding fix failed":L.ok?L.headSha?(L.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:L.note.slice(0,500)}),v.sendTestFixResult(u.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async u=>{try{let m=await f.answerPendingInput(u.runId,u.text,u.answeredBy);v.sendRunAnswerResult(u.requestId,m)}catch(m){v.sendRunAnswerResult(u.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async u=>{let m=g=>v.sendResolveConflictResult(u.requestId,{ok:!1,note:g});try{let g=js(u.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let S=t.repos[g.repoName];if(!S){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let $=Fe(t,g.repoName);if(!$){m("no GitHub token on this runner for that repo");return}let N=await new He($).getPullRequest(g.owner,g.repo,g.prNumber);if(!N){m("that pull request no longer exists on GitHub");return}if(!N.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let G=c.find(ce=>ce.repoName===g.repoName),U=g.nextDecisionSeq??1e5,q=(ce,V)=>{v.send({type:"run.log",runId:u.runId,seq:U++,ts:new Date().toISOString(),level:ce,message:V}),g.nextDecisionSeq=U,bt(g)},L=await mm({cfg:t,repoPath:S.path,branch:g.branch,baseBranch:N.baseRef,issueKey:g.issueKey,agentId:G?.defaultAgent||be.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:q});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,bt(g),v.send({type:"run.pr.conflict",runId:u.runId,conflicted:!1}),v.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),v.sendResolveConflictResult(u.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:u=>{try{let m=S=>{try{return Ke.default.existsSync(S)&&Ke.default.readdirSync(S).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([S,$])=>({agent:"claude-code",name:S,loggedIn:m($.configDir)}));v.sendAgentProfilesResult(u.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(Yt.default.join(Xs.default.homedir(),".claude")),agentsWithoutProfiles:be.REGISTERED_AGENTS.filter(S=>!S.capabilities.loginProfiles).map(S=>S.id)})}catch(m){v.sendAgentProfilesResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async u=>{try{let m=await n.searchUsers(u.query);v.sendJiraUsersResult(u.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(u.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,f=new wa(t,s,v),f.setExternalBusy(()=>Y.size);let j=Object.values(Dr()).filter(u=>u.kind==="implement").map(u=>u.repoPath);ql(Object.values(t.repos).map(u=>u.path),j).catch(()=>{}),v.start(),f.start();let O=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),Kd(process.pid),Tl(),process.exit(0)},H=!1,B=()=>{if(H){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(H=!0,f.stop(),f.idle){O();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let u=setInterval(()=>{f.idle&&(clearInterval(u),O())},3e3)};process.on("SIGINT",B),process.on("SIGTERM",B),process.on("SIGHUP",()=>{try{let u=de();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new qe(u.jira):Xl(),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(u){y.error(`config reload failed - keeping the running config: ${u instanceof Error?u.message:String(u)}`)}})}$e.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async t=>{let e=de();if(t.foreground){jx(e);return}let n=pr();if(n&&fr(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ms();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Fd(),i=(0,jt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Hd(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${bo()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});$e.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(t=>{let e=pr();if(!e||!fr(e)){y.info("no background runner is running"),e&&Ke.default.rmSync(fs(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ke.default.rmSync(fs(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});$e.command("status").description("Check whether the background runner is running").action(()=>{let t=pr();t&&fr(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});$e.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|