allwright 1.124.0 → 1.125.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.
Files changed (2) hide show
  1. package/bin/allwright.js +71 -71
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -20,8 +20,8 @@ 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 ze.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()}`,ze.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new g0(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=a=>{let c=a.attributeName(),l=this.getOptionValue(c),u=this.options.find(f=>f.negate&&c===f.attributeName()),p=this.options.find(f=>!f.negate&&c===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:p||a},s=a=>{let c=r(a),l=c.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${c.envVar}'`:`option '${c.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 a=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);s=s.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);n=gp(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=gp(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=>f0(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=Sn.basename(e,Sn.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=ze.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 a;typeof n=="function"?a=n({error:i.error,command:i.command}):a=n,a&&i.write(`${a}
23
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function yp(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})}bp.Command=jl});var _p=be(xt=>{var{Argument:vp}=ca(),{Command:Ml}=wp(),{CommanderError:y0,InvalidArgumentError:kp}=Vi(),{Help:b0}=Rl(),{Option:Sp}=$l();xt.program=new Ml;xt.createCommand=t=>new Ml(t);xt.createOption=(t,e)=>new Sp(t,e);xt.createArgument=(t,e)=>new vp(t,e);xt.Command=Ml;xt.Option=Sp;xt.Argument=vp;xt.Help=b0;xt.CommanderError=y0;xt.InvalidArgumentError=kp;xt.InvalidOptionArgumentError=kp});var fe,Ol,G,sn,Zi=J(()=>{(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 a of s)i[a]=a;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(let c of i)a[c]=s[c];return t.objectValues(a)},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 a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(let a of s)if(i(a))return a},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(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(fe||(fe={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ol||(Ol={}));G=fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sn=t=>{switch(typeof t){case"undefined":return G.undefined;case"string":return G.string;case"number":return Number.isNaN(t)?G.nan:G.number;case"boolean":return G.boolean;case"function":return G.function;case"bigint":return G.bigint;case"symbol":return G.symbol;case"object":return Array.isArray(t)?G.array:t===null?G.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?G.promise:typeof Map<"u"&&t instanceof Map?G.map:typeof Set<"u"&&t instanceof Set?G.set:typeof Date<"u"&&t instanceof Date?G.date:G.object;default:return G.unknown}}});var z,w0,ut,la=J(()=>{Zi();z=fe.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"]),w0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ut=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 a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};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,fe.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()}};ut.create=t=>new ut(t)});var v0,_n,zl=J(()=>{la();Zi();v0=(t,e)=>{let n;switch(t.code){case z.invalid_type:t.received===G.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,fe.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:n=`Unrecognized key(s) in object: ${fe.joinValues(t.keys,", ")}`;break;case z.invalid_union:n="Invalid input";break;case z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${fe.joinValues(t.options)}`;break;case z.invalid_enum_value:n=`Invalid enum value. Expected ${fe.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:n="Invalid function arguments";break;case z.invalid_return_type:n="Invalid function return type";break;case z.invalid_date:n="Invalid date";break;case z.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}"`:fe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case z.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 z.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 z.custom:n="Invalid input";break;case z.invalid_intersection_types:n="Intersection results could not be merged";break;case z.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:n="Number must be finite";break;default:n=e.defaultError,fe.assertNever(t)}return{message:n}},_n=v0});function k0(t){Rp=t}function Zs(){return Rp}var Rp,ua=J(()=>{zl();Rp=_n});function W(t,e){let n=Zs(),r=Ji({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===_n?void 0:_n].filter(s=>!!s)});t.common.issues.push(r)}var Ji,S0,Je,ie,Cr,et,da,ha,Jn,Js,Dl=J(()=>{ua();zl();Ji=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}},S0=[];Je=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 ie;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,a=await s.value;r.push({key:i,value:a})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return ie;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},ie=Object.freeze({status:"aborted"}),Cr=t=>({status:"dirty",value:t}),et=t=>({status:"valid",value:t}),da=t=>t.status==="aborted",ha=t=>t.status==="dirty",Jn=t=>t.status==="valid",Js=t=>typeof Promise<"u"&&t instanceof Promise});var Ip=J(()=>{});var Q,Ep=J(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Q||(Q={}))});function le(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:(a,c)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},description:s}}function Pp(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 L0(t){return new RegExp(`^${Pp(t)}$`)}function Np(t){let e=`${Cp}T${Pp(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 U0(t,e){return!!((e==="v4"||!e)&&P0.test(t)||(e==="v6"||!e)&&j0.test(t))}function q0(t,e){if(!E0.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 F0(t,e){return!!((e==="v4"||!e)&&N0.test(t)||(e==="v6"||!e)&&M0.test(t))}function B0(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(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}function Ys(t){if(t instanceof dt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Tt.create(Ys(r))}return new dt({...t._def,shape:()=>e})}else return t instanceof Rn?new Rn({...t._def,type:Ys(t.element)}):t instanceof Tt?Tt.create(Ys(t.unwrap())):t instanceof an?an.create(Ys(t.unwrap())):t instanceof on?on.create(t.items.map(e=>Ys(e))):t}function Ul(t,e){let n=sn(t),r=sn(e);if(t===e)return{valid:!0,data:t};if(n===G.object&&r===G.object){let s=fe.objectKeys(e),i=fe.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=Ul(t[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===G.array&&r===G.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=e[i],l=Ul(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===G.date&&r===G.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function jp(t,e){return new Fr({values:t,typeName:oe.ZodEnum,...le(e)})}function $p(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Mp(t,e={},n){return t?Xn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=$p(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=$p(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Xn.create()}var Rt,Ap,he,_0,x0,T0,R0,I0,E0,A0,$0,C0,Ll,P0,N0,j0,M0,O0,z0,Cp,D0,Yn,Pr,Nr,jr,Mr,Xs,Or,zr,Xn,Tn,Kt,Qs,Rn,dt,Dr,xn,pa,Lr,on,fa,ei,ti,ma,Ur,qr,Fr,Br,Qn,It,Tt,an,Hr,Kr,ni,H0,Yi,Xi,Wr,K0,oe,W0,Op,zp,G0,V0,Dp,Z0,J0,Y0,X0,Q0,eS,tS,nS,rS,sS,iS,oS,aS,cS,lS,uS,dS,hS,pS,fS,mS,gS,yS,bS,wS,vS,kS,SS,_S,xS,TS,RS,IS,ES,Lp=J(()=>{la();ua();Ep();Dl();Zi();Rt=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}},Ap=(t,e)=>{if(Jn(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 ut(t.common.issues);return this._error=n,this._error}}};he=class{get description(){return this._def.description}_getType(e){return sn(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:sn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Je,ctx:{common:e.parent.common,data:e.data,parsedType:sn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Js(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:sn(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ap(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Jn(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=>Jn(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:sn(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Js(s)?s:Promise.resolve(s));return Ap(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 a=e(s),c=()=>i.addIssue({code:z.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!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 It({schema:this,typeName:oe.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 Tt.create(this,this._def)}nullable(){return an.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rn.create(this)}promise(){return Qn.create(this,this._def)}or(e){return Dr.create([this,e],this._def)}and(e){return Lr.create(this,e,this._def)}transform(e){return new It({...le(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Hr({...le(this._def),innerType:this,defaultValue:n,typeName:oe.ZodDefault})}brand(){return new Yi({typeName:oe.ZodBranded,type:this,...le(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Kr({...le(this._def),innerType:this,catchValue:n,typeName:oe.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Xi.create(this,e)}readonly(){return Wr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},_0=/^c[^\s-]{8,}$/i,x0=/^[0-9a-z]+$/,T0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,R0=/^[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,I0=/^[a-z0-9_-]{21}$/i,E0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A0=/^[-+]?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)?)??$/,$0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,C0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",P0=/^(?:(?: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])$/,N0=/^(?:(?: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])$/,j0=/^(([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]))$/,M0=/^(([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])$/,O0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cp="((\\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])))",D0=new RegExp(`^${Cp}$`);Yn=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==G.string){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_type,expected:G.string,received:i.parsedType}),ie}let r=new Je,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),W(s,{code:z.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),W(s,{code:z.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?W(s,{code:z.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&W(s,{code:z.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"email",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ll||(Ll=new RegExp(C0,"u")),Ll.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"emoji",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")R0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"uuid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")I0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"nanoid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")_0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"cuid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")x0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"cuid2",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")T0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"ulid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),W(s,{validation:"url",code:z.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),W(s,{validation:"regex",code:z.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),W(s,{code:z.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),W(s,{code:z.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Np(i).test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?D0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?L0(i).test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?A0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"duration",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?U0(e.data,i.version)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"ip",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?q0(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"jwt",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?F0(e.data,i.version)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"cidr",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?O0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"base64",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?z0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"base64url",code:z.invalid_string,message:i.message}),r.dirty()):fe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:z.invalid_string,...Q.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Q.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Q.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Q.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Q.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Q.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Q.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Q.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Q.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Q.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Q.errToObj(n)})}nonempty(e){return this.min(1,Q.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}};Yn.create=t=>new Yn({checks:[],typeName:oe.ZodString,coerce:t?.coerce??!1,...le(t)});Pr=class t extends he{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)!==G.number){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_type,expected:G.number,received:i.parsedType}),ie}let r,s=new Je;for(let i of this._def.checks)i.kind==="int"?fe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),W(r,{code:z.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),W(r,{code:z.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),W(r,{code:z.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?B0(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),W(r,{code:z.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),W(r,{code:z.not_finite,message:i.message}),s.dirty()):fe.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Q.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Q.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Q.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Q.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"&&fe.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)}};Pr.create=t=>new Pr({checks:[],typeName:oe.ZodNumber,coerce:t?.coerce||!1,...le(t)});Nr=class t extends he{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)!==G.bigint)return this._getInvalidInput(e);let r,s=new Je;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),W(r,{code:z.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),W(r,{code:z.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),W(r,{code:z.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):fe.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return W(n,{code:z.invalid_type,expected:G.bigint,received:n.parsedType}),ie}gte(e,n){return this.setLimit("min",e,!0,Q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Q.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Q.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:Q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Q.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}};Nr.create=t=>new Nr({checks:[],typeName:oe.ZodBigInt,coerce:t?.coerce??!1,...le(t)});jr=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==G.boolean){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.boolean,received:r.parsedType}),ie}return et(e.data)}};jr.create=t=>new jr({typeName:oe.ZodBoolean,coerce:t?.coerce||!1,...le(t)});Mr=class t extends he{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==G.date){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_type,expected:G.date,received:i.parsedType}),ie}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_date}),ie}let r=new Je,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),W(s,{code:z.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),W(s,{code:z.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):fe.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:Q.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Q.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}};Mr.create=t=>new Mr({checks:[],coerce:t?.coerce||!1,typeName:oe.ZodDate,...le(t)});Xs=class extends he{_parse(e){if(this._getType(e)!==G.symbol){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.symbol,received:r.parsedType}),ie}return et(e.data)}};Xs.create=t=>new Xs({typeName:oe.ZodSymbol,...le(t)});Or=class extends he{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.undefined,received:r.parsedType}),ie}return et(e.data)}};Or.create=t=>new Or({typeName:oe.ZodUndefined,...le(t)});zr=class extends he{_parse(e){if(this._getType(e)!==G.null){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.null,received:r.parsedType}),ie}return et(e.data)}};zr.create=t=>new zr({typeName:oe.ZodNull,...le(t)});Xn=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return et(e.data)}};Xn.create=t=>new Xn({typeName:oe.ZodAny,...le(t)});Tn=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return et(e.data)}};Tn.create=t=>new Tn({typeName:oe.ZodUnknown,...le(t)});Kt=class extends he{_parse(e){let n=this._getOrReturnCtx(e);return W(n,{code:z.invalid_type,expected:G.never,received:n.parsedType}),ie}};Kt.create=t=>new Kt({typeName:oe.ZodNever,...le(t)});Qs=class extends he{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.void,received:r.parsedType}),ie}return et(e.data)}};Qs.create=t=>new Qs({typeName:oe.ZodVoid,...le(t)});Rn=class t extends he{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==G.array)return W(n,{code:z.invalid_type,expected:G.array,received:n.parsedType}),ie;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(W(n,{code:a?z.too_big:z.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?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&&(W(n,{code:z.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&&(W(n,{code:z.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((a,c)=>s.type._parseAsync(new Rt(n,a,n.path,c)))).then(a=>Je.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new Rt(n,a,n.path,c)));return Je.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Q.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Q.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Q.toString(n)}})}nonempty(e){return this.min(1,e)}};Rn.create=(t,e)=>new Rn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...le(e)});dt=class t extends he{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=fe.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==G.object){let u=this._getOrReturnCtx(e);return W(u,{code:z.invalid_type,expected:G.object,received:u.parsedType}),ie}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Kt&&this._def.unknownKeys==="strip"))for(let u in s.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let p=i[u],f=s.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new Rt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Kt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")c.length>0&&(W(s,{code:z.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new Rt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let f=await p.key,m=await p.value;u.push({key:f,value:m,alwaysSet:p.alwaysSet})}return u}).then(u=>Je.mergeObjectSync(r,u)):Je.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return Q.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:Q.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:oe.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 fe.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 fe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Ys(this)}partial(e){let n={};for(let r of fe.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 fe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Tt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return jp(fe.objectKeys(this.shape))}};dt.create=(t,e)=>new dt({shape:()=>t,unknownKeys:"strip",catchall:Kt.create(),typeName:oe.ZodObject,...le(e)});dt.strictCreate=(t,e)=>new dt({shape:()=>t,unknownKeys:"strict",catchall:Kt.create(),typeName:oe.ZodObject,...le(e)});dt.lazycreate=(t,e)=>new dt({shape:t,unknownKeys:"strip",catchall:Kt.create(),typeName:oe.ZodObject,...le(e)});Dr=class extends he{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new ut(c.ctx.common.issues));return W(n,{code:z.invalid_union,unionErrors:a}),ie}if(n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new ut(l));return W(n,{code:z.invalid_union,unionErrors:c}),ie}}get options(){return this._def.options}};Dr.create=(t,e)=>new Dr({options:t,typeName:oe.ZodUnion,...le(e)});xn=t=>t instanceof Ur?xn(t.schema):t instanceof It?xn(t.innerType()):t instanceof qr?[t.value]:t instanceof Fr?t.options:t instanceof Br?fe.objectValues(t.enum):t instanceof Hr?xn(t._def.innerType):t instanceof Or?[void 0]:t instanceof zr?[null]:t instanceof Tt?[void 0,...xn(t.unwrap())]:t instanceof an?[null,...xn(t.unwrap())]:t instanceof Yi||t instanceof Wr?xn(t.unwrap()):t instanceof Kr?xn(t._def.innerType):[],pa=class t extends he{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.object)return W(n,{code:z.invalid_type,expected:G.object,received:n.parsedType}),ie;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}):(W(n,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ie)}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 a=xn(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new t({typeName:oe.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...le(r)})}};Lr=class extends he{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(da(i)||da(a))return ie;let c=Ul(i.value,a.value);return c.valid?((ha(i)||ha(a))&&n.dirty(),{status:n.value,value:c.data}):(W(r,{code:z.invalid_intersection_types}),ie)};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,a])=>s(i,a)):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}))}};Lr.create=(t,e,n)=>new Lr({left:t,right:e,typeName:oe.ZodIntersection,...le(n)});on=class t extends he{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.array)return W(r,{code:z.invalid_type,expected:G.array,received:r.parsedType}),ie;if(r.data.length<this._def.items.length)return W(r,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ie;!this._def.rest&&r.data.length>this._def.items.length&&(W(r,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Rt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Je.mergeArray(n,a)):Je.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};on.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new on({items:t,typeName:oe.ZodTuple,rest:null,...le(e)})};fa=class t extends he{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!==G.object)return W(r,{code:z.invalid_type,expected:G.object,received:r.parsedType}),ie;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new Rt(r,c,r.path,c)),value:a._parse(new Rt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Je.mergeObjectAsync(n,s):Je.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof he?new t({keyType:e,valueType:n,typeName:oe.ZodRecord,...le(r)}):new t({keyType:Yn.create(),valueType:e,typeName:oe.ZodRecord,...le(n)})}},ei=class extends he{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!==G.map)return W(r,{code:z.invalid_type,expected:G.map,received:r.parsedType}),ie;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:s._parse(new Rt(r,c,r.path,[u,"key"])),value:i._parse(new Rt(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return ie;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return ie;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}}}};ei.create=(t,e,n)=>new ei({valueType:e,keyType:t,typeName:oe.ZodMap,...le(n)});ti=class t extends he{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.set)return W(r,{code:z.invalid_type,expected:G.set,received:r.parsedType}),ie;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(W(r,{code:z.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&&(W(r,{code:z.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let u=new Set;for(let p of l){if(p.status==="aborted")return ie;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let c=[...r.data.values()].map((l,u)=>i._parse(new Rt(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(e,n){return new t({...this._def,minSize:{value:e,message:Q.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Q.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};ti.create=(t,e)=>new ti({valueType:t,minSize:null,maxSize:null,typeName:oe.ZodSet,...le(e)});ma=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.function)return W(n,{code:z.invalid_type,expected:G.function,received:n.parsedType}),ie;function r(c,l){return Ji({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zs(),_n].filter(u=>!!u),issueData:{code:z.invalid_arguments,argumentsError:l}})}function s(c,l){return Ji({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zs(),_n].filter(u=>!!u),issueData:{code:z.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Qn){let c=this;return et(async function(...l){let u=new ut([]),p=await c._def.args.parseAsync(l,i).catch(w=>{throw u.addIssue(r(l,w)),u}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let c=this;return et(function(...l){let u=c._def.args.safeParse(l,i);if(!u.success)throw new ut([r(l,u.error)]);let p=Reflect.apply(a,this,u.data),f=c._def.returns.safeParse(p,i);if(!f.success)throw new ut([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:on.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||on.create([]).rest(Tn.create()),returns:n||Tn.create(),typeName:oe.ZodFunction,...le(r)})}},Ur=class extends he{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})}};Ur.create=(t,e)=>new Ur({getter:t,typeName:oe.ZodLazy,...le(e)});qr=class extends he{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return W(n,{received:n.data,code:z.invalid_literal,expected:this._def.value}),ie}return{status:"valid",value:e.data}}get value(){return this._def.value}};qr.create=(t,e)=>new qr({value:t,typeName:oe.ZodLiteral,...le(e)});Fr=class t extends he{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return W(n,{expected:fe.joinValues(r),received:n.parsedType,code:z.invalid_type}),ie}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 W(n,{received:n.data,code:z.invalid_enum_value,options:r}),ie}return et(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})}};Fr.create=jp;Br=class extends he{_parse(e){let n=fe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==G.string&&r.parsedType!==G.number){let s=fe.objectValues(n);return W(r,{expected:fe.joinValues(s),received:r.parsedType,code:z.invalid_type}),ie}if(this._cache||(this._cache=new Set(fe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=fe.objectValues(n);return W(r,{received:r.data,code:z.invalid_enum_value,options:s}),ie}return et(e.data)}get enum(){return this._def.values}};Br.create=(t,e)=>new Br({values:t,typeName:oe.ZodNativeEnum,...le(e)});Qn=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.promise&&n.common.async===!1)return W(n,{code:z.invalid_type,expected:G.promise,received:n.parsedType}),ie;let r=n.parsedType===G.promise?n.data:Promise.resolve(n.data);return et(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Qn.create=(t,e)=>new Qn({type:t,typeName:oe.ZodPromise,...le(e)});It=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.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:a=>{W(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return ie;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?ie:l.status==="dirty"?Cr(l.value):n.value==="dirty"?Cr(l.value):l});{if(n.value==="aborted")return ie;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ie:c.status==="dirty"?Cr(c.value):n.value==="dirty"?Cr(c.value):c}}if(s.type==="refinement"){let a=c=>{let l=s.refinement(c,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?ie:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?ie:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Jn(a))return ie;let c=s.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Jn(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):ie);fe.assertNever(s)}};It.create=(t,e,n)=>new It({schema:t,typeName:oe.ZodEffects,effect:e,...le(n)});It.createWithPreprocess=(t,e,n)=>new It({schema:e,effect:{type:"preprocess",transform:t},typeName:oe.ZodEffects,...le(n)});Tt=class extends he{_parse(e){return this._getType(e)===G.undefined?et(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Tt.create=(t,e)=>new Tt({innerType:t,typeName:oe.ZodOptional,...le(e)});an=class extends he{_parse(e){return this._getType(e)===G.null?et(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};an.create=(t,e)=>new an({innerType:t,typeName:oe.ZodNullable,...le(e)});Hr=class extends he{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===G.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Hr.create=(t,e)=>new Hr({innerType:t,typeName:oe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...le(e)});Kr=class extends he{_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 Js(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ut(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ut(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Kr.create=(t,e)=>new Kr({innerType:t,typeName:oe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...le(e)});ni=class extends he{_parse(e){if(this._getType(e)!==G.nan){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.nan,received:r.parsedType}),ie}return{status:"valid",value:e.data}}};ni.create=t=>new ni({typeName:oe.ZodNaN,...le(t)});H0=Symbol("zod_brand"),Yi=class extends he{_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}},Xi=class t extends he{_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"?ie:i.status==="dirty"?(n.dirty(),Cr(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"?ie: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:oe.ZodPipeline})}},Wr=class extends he{_parse(e){let n=this._def.innerType._parse(e),r=s=>(Jn(s)&&(s.value=Object.freeze(s.value)),s);return Js(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Wr.create=(t,e)=>new Wr({innerType:t,typeName:oe.ZodReadonly,...le(e)});K0={object:dt.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"})(oe||(oe={}));W0=(t,e={message:`Input not instance of ${t.name}`})=>Mp(n=>n instanceof t,e),Op=Yn.create,zp=Pr.create,G0=ni.create,V0=Nr.create,Dp=jr.create,Z0=Mr.create,J0=Xs.create,Y0=Or.create,X0=zr.create,Q0=Xn.create,eS=Tn.create,tS=Kt.create,nS=Qs.create,rS=Rn.create,sS=dt.create,iS=dt.strictCreate,oS=Dr.create,aS=pa.create,cS=Lr.create,lS=on.create,uS=fa.create,dS=ei.create,hS=ti.create,pS=ma.create,fS=Ur.create,mS=qr.create,gS=Fr.create,yS=Br.create,bS=Qn.create,wS=It.create,vS=Tt.create,kS=an.create,SS=It.createWithPreprocess,_S=Xi.create,xS=()=>Op().optional(),TS=()=>zp().optional(),RS=()=>Dp().optional(),IS={string:(t=>Yn.create({...t,coerce:!0})),number:(t=>Pr.create({...t,coerce:!0})),boolean:(t=>jr.create({...t,coerce:!0})),bigint:(t=>Nr.create({...t,coerce:!0})),date:(t=>Mr.create({...t,coerce:!0}))},ES=ie});var k={};Fe(k,{BRAND:()=>H0,DIRTY:()=>Cr,EMPTY_PATH:()=>S0,INVALID:()=>ie,NEVER:()=>ES,OK:()=>et,ParseStatus:()=>Je,Schema:()=>he,ZodAny:()=>Xn,ZodArray:()=>Rn,ZodBigInt:()=>Nr,ZodBoolean:()=>jr,ZodBranded:()=>Yi,ZodCatch:()=>Kr,ZodDate:()=>Mr,ZodDefault:()=>Hr,ZodDiscriminatedUnion:()=>pa,ZodEffects:()=>It,ZodEnum:()=>Fr,ZodError:()=>ut,ZodFirstPartyTypeKind:()=>oe,ZodFunction:()=>ma,ZodIntersection:()=>Lr,ZodIssueCode:()=>z,ZodLazy:()=>Ur,ZodLiteral:()=>qr,ZodMap:()=>ei,ZodNaN:()=>ni,ZodNativeEnum:()=>Br,ZodNever:()=>Kt,ZodNull:()=>zr,ZodNullable:()=>an,ZodNumber:()=>Pr,ZodObject:()=>dt,ZodOptional:()=>Tt,ZodParsedType:()=>G,ZodPipeline:()=>Xi,ZodPromise:()=>Qn,ZodReadonly:()=>Wr,ZodRecord:()=>fa,ZodSchema:()=>he,ZodSet:()=>ti,ZodString:()=>Yn,ZodSymbol:()=>Xs,ZodTransformer:()=>It,ZodTuple:()=>on,ZodType:()=>he,ZodUndefined:()=>Or,ZodUnion:()=>Dr,ZodUnknown:()=>Tn,ZodVoid:()=>Qs,addIssueToContext:()=>W,any:()=>Q0,array:()=>rS,bigint:()=>V0,boolean:()=>Dp,coerce:()=>IS,custom:()=>Mp,date:()=>Z0,datetimeRegex:()=>Np,defaultErrorMap:()=>_n,discriminatedUnion:()=>aS,effect:()=>wS,enum:()=>gS,function:()=>pS,getErrorMap:()=>Zs,getParsedType:()=>sn,instanceof:()=>W0,intersection:()=>cS,isAborted:()=>da,isAsync:()=>Js,isDirty:()=>ha,isValid:()=>Jn,late:()=>K0,lazy:()=>fS,literal:()=>mS,makeIssue:()=>Ji,map:()=>dS,nan:()=>G0,nativeEnum:()=>yS,never:()=>tS,null:()=>X0,nullable:()=>kS,number:()=>zp,object:()=>sS,objectUtil:()=>Ol,oboolean:()=>RS,onumber:()=>TS,optional:()=>vS,ostring:()=>xS,pipeline:()=>_S,preprocess:()=>SS,promise:()=>bS,quotelessJson:()=>w0,record:()=>uS,set:()=>hS,setErrorMap:()=>k0,strictObject:()=>iS,string:()=>Op,symbol:()=>J0,transformer:()=>wS,tuple:()=>lS,undefined:()=>Y0,union:()=>oS,unknown:()=>eS,util:()=>fe,void:()=>nS});var ql=J(()=>{ua();Dl();Ip();Zi();Lp();la()});var ht=J(()=>{ql();ql()});function X(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ya.default.join(ga.default.homedir(),".config","allwright"),n=ya.default.join(ga.default.homedir(),".config","ticketpilot");return!In.default.existsSync(e)&&In.default.existsSync(n)?n:e}function En(){return ya.default.join(X(),"runner.json")}function ke(){let t=En();if(!In.default.existsSync(t))return null;let e=JSON.parse(In.default.readFileSync(t,"utf8"));return Fl.parse(e)}function xe(t){let e=X();In.default.mkdirSync(e,{recursive:!0,mode:448});let n=En(),r=n+".tmp";In.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384}),In.default.renameSync(r,n),In.default.chmodSync(n,384)}function ba(t,e){return`${t}:${e}`}function cn(t,e,n){return t.environments[ba(e,n)]?.secrets??{}}function Qi(t,e){return t.repos[e]?.jira??t.jira}function eo(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ge(){let t=ke();if(!t)throw new Error(`No runner config found at ${En()}. Run \`allwright init\` first.`);return t}var In,ga,ya,Up,Fl,Te=J(()=>{"use strict";In=E(require("node:fs"),1),ga=E(require("node:os"),1),ya=E(require("node:path"),1);ht();Up=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Fl=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(ga.default.hostname()),jira:Up.optional(),repos:k.record(k.object({path:k.string(),jira:Up.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)})});var to=be(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.getParsedType=Re.ZodParsedType=Re.objectUtil=Re.util=void 0;var Bl;(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 a of s)i[a]=a;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(let c of i)a[c]=s[c];return t.objectValues(a)},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 a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(let a of s)if(i(a))return a},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(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Bl||(Re.util=Bl={}));var Bp;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Bp||(Re.objectUtil=Bp={}));Re.ZodParsedType=Bl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var CS=t=>{switch(typeof t){case"undefined":return Re.ZodParsedType.undefined;case"string":return Re.ZodParsedType.string;case"number":return Number.isNaN(t)?Re.ZodParsedType.nan:Re.ZodParsedType.number;case"boolean":return Re.ZodParsedType.boolean;case"function":return Re.ZodParsedType.function;case"bigint":return Re.ZodParsedType.bigint;case"symbol":return Re.ZodParsedType.symbol;case"object":return Array.isArray(t)?Re.ZodParsedType.array:t===null?Re.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Re.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?Re.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?Re.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?Re.ZodParsedType.date:Re.ZodParsedType.object;default:return Re.ZodParsedType.unknown}};Re.getParsedType=CS});var ka=be(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.ZodError=er.quotelessJson=er.ZodIssueCode=void 0;var Hp=to();er.ZodIssueCode=Hp.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var PS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");er.quotelessJson=PS;var no=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 a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};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,Hp.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};er.ZodError=no;no.create=t=>new no(t)});var Kl=be(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var tt=ka(),Gr=to(),NS=(t,e)=>{let n;switch(t.code){case tt.ZodIssueCode.invalid_type:t.received===Gr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case tt.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Gr.util.jsonStringifyReplacer)}`;break;case tt.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Gr.util.joinValues(t.keys,", ")}`;break;case tt.ZodIssueCode.invalid_union:n="Invalid input";break;case tt.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Gr.util.joinValues(t.options)}`;break;case tt.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Gr.util.joinValues(t.options)}, received '${t.received}'`;break;case tt.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case tt.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case tt.ZodIssueCode.invalid_date:n="Invalid date";break;case tt.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Gr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case tt.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case tt.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case tt.ZodIssueCode.custom:n="Invalid input";break;case tt.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case tt.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case tt.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Gr.util.assertNever(t)}return{message:n}};Hl.default=NS});var Sa=be(tr=>{"use strict";var jS=tr&&tr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tr,"__esModule",{value:!0});tr.defaultErrorMap=void 0;tr.setErrorMap=MS;tr.getErrorMap=OS;var Kp=jS(Kl());tr.defaultErrorMap=Kp.default;var Wp=Kp.default;function MS(t){Wp=t}function OS(){return Wp}});var Gl=be(we=>{"use strict";var zS=we&&we.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(we,"__esModule",{value:!0});we.isAsync=we.isValid=we.isDirty=we.isAborted=we.OK=we.DIRTY=we.INVALID=we.ParseStatus=we.EMPTY_PATH=we.makeIssue=void 0;we.addIssueToContext=US;var DS=Sa(),Gp=zS(Kl()),LS=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}};we.makeIssue=LS;we.EMPTY_PATH=[];function US(t,e){let n=(0,DS.getErrorMap)(),r=(0,we.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Gp.default?void 0:Gp.default].filter(s=>!!s)});t.common.issues.push(r)}var Wl=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 we.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,a=await s.value;r.push({key:i,value:a})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return we.INVALID;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}};we.ParseStatus=Wl;we.INVALID=Object.freeze({status:"aborted"});var qS=t=>({status:"dirty",value:t});we.DIRTY=qS;var FS=t=>({status:"valid",value:t});we.OK=FS;var BS=t=>t.status==="aborted";we.isAborted=BS;var HS=t=>t.status==="dirty";we.isDirty=HS;var KS=t=>t.status==="valid";we.isValid=KS;var WS=t=>typeof Promise<"u"&&t instanceof Promise;we.isAsync=WS});var Zp=be(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0})});var Yp=be(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.errorUtil=void 0;var Jp;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Jp||(_a.errorUtil=Jp={}))});var uf=be(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.discriminatedUnion=R.date=R.boolean=R.bigint=R.array=R.any=R.coerce=R.ZodFirstPartyTypeKind=R.late=R.ZodSchema=R.Schema=R.ZodReadonly=R.ZodPipeline=R.ZodBranded=R.BRAND=R.ZodNaN=R.ZodCatch=R.ZodDefault=R.ZodNullable=R.ZodOptional=R.ZodTransformer=R.ZodEffects=R.ZodPromise=R.ZodNativeEnum=R.ZodEnum=R.ZodLiteral=R.ZodLazy=R.ZodFunction=R.ZodSet=R.ZodMap=R.ZodRecord=R.ZodTuple=R.ZodIntersection=R.ZodDiscriminatedUnion=R.ZodUnion=R.ZodObject=R.ZodArray=R.ZodVoid=R.ZodNever=R.ZodUnknown=R.ZodAny=R.ZodNull=R.ZodUndefined=R.ZodSymbol=R.ZodDate=R.ZodBoolean=R.ZodBigInt=R.ZodNumber=R.ZodString=R.ZodType=void 0;R.NEVER=R.void=R.unknown=R.union=R.undefined=R.tuple=R.transformer=R.symbol=R.string=R.strictObject=R.set=R.record=R.promise=R.preprocess=R.pipeline=R.ostring=R.optional=R.onumber=R.oboolean=R.object=R.number=R.nullable=R.null=R.never=R.nativeEnum=R.nan=R.map=R.literal=R.lazy=R.intersection=R.instanceof=R.function=R.enum=R.effect=void 0;R.datetimeRegex=nf;R.custom=sf;var q=ka(),xa=Sa(),ne=Yp(),I=Gl(),H=to(),At=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}},Xp=(t,e)=>{if((0,I.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new q.ZodError(t.common.issues);return this._error=n,this._error}}};function ue(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:(a,c)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},description:s}}var de=class{get description(){return this._def.description}_getType(e){return(0,H.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,H.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,H.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,I.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,H.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Xp(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,H.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,I.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,I.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,H.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,I.isAsync)(s)?s:Promise.resolve(s));return Xp(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 a=e(s),c=()=>i.addIssue({code:q.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!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 yt({schema:this,typeName:ce.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 Et.create(this,this._def)}nullable(){return un.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cn.create(this)}promise(){return sr.create(this,this._def)}or(e){return es.create([this,e],this._def)}and(e){return ts.create(this,e,this._def)}transform(e){return new yt({...ue(this._def),schema:this,typeName:ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new os({...ue(this._def),innerType:this,defaultValue:n,typeName:ce.ZodDefault})}brand(){return new ro({typeName:ce.ZodBranded,type:this,...ue(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new as({...ue(this._def),innerType:this,catchValue:n,typeName:ce.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return so.create(this,e)}readonly(){return cs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};R.ZodType=de;R.Schema=de;R.ZodSchema=de;var GS=/^c[^\s-]{8,}$/i,VS=/^[0-9a-z]+$/,ZS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,JS=/^[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,YS=/^[a-z0-9_-]{21}$/i,XS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QS=/^[-+]?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)?)??$/,e_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,t_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Vl,n_=/^(?:(?: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])$/,r_=/^(?:(?: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])$/,s_=/^(([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]))$/,i_=/^(([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])$/,o_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,a_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ef="((\\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])))",c_=new RegExp(`^${ef}$`);function tf(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 l_(t){return new RegExp(`^${tf(t)}$`)}function nf(t){let e=`${ef}T${tf(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 u_(t,e){return!!((e==="v4"||!e)&&n_.test(t)||(e==="v6"||!e)&&s_.test(t))}function d_(t,e){if(!XS.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 h_(t,e){return!!((e==="v4"||!e)&&r_.test(t)||(e==="v6"||!e)&&i_.test(t))}var nr=class t extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.string,received:i.parsedType}),I.INVALID}let r=new I.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")e_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"email",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Vl||(Vl=new RegExp(t_,"u")),Vl.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"emoji",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")JS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"uuid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")YS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"nanoid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")GS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"cuid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")VS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"cuid2",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ZS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"ulid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"url",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"regex",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?nf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?c_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?l_(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?QS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"duration",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?u_(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"ip",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?d_(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"jwt",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?h_(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"cidr",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?o_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"base64",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?a_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"base64url",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):H.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:q.ZodIssueCode.invalid_string,...ne.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ne.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ne.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ne.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ne.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ne.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ne.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ne.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ne.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ne.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ne.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ne.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ne.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ne.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ne.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ne.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ne.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...ne.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...ne.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...ne.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...ne.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...ne.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...ne.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...ne.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,ne.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};R.ZodString=nr;nr.create=t=>new nr({checks:[],typeName:ce.ZodString,coerce:t?.coerce??!1,...ue(t)});function p_(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(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}var Vr=class t extends de{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)!==H.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.number,received:i.parsedType}),I.INVALID}let r,s=new I.ParseStatus;for(let i of this._def.checks)i.kind==="int"?H.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?p_(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.not_finite,message:i.message}),s.dirty()):H.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,ne.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ne.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ne.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ne.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ne.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ne.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ne.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ne.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ne.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ne.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ne.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:ne.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ne.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ne.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};R.ZodNumber=Vr;Vr.create=t=>new Vr({checks:[],typeName:ce.ZodNumber,coerce:t?.coerce||!1,...ue(t)});var Zr=class t extends de{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)!==H.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new I.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):H.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.bigint,received:n.parsedType}),I.INVALID}gte(e,n){return this.setLimit("min",e,!0,ne.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ne.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ne.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ne.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ne.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ne.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ne.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ne.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ne.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ne.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};R.ZodBigInt=Zr;Zr.create=t=>new Zr({checks:[],typeName:ce.ZodBigInt,coerce:t?.coerce??!1,...ue(t)});var Jr=class extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.boolean,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodBoolean=Jr;Jr.create=t=>new Jr({typeName:ce.ZodBoolean,coerce:t?.coerce||!1,...ue(t)});var Yr=class t extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.date,received:i.parsedType}),I.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_date}),I.INVALID}let r=new I.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):H.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:ne.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:ne.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};R.ZodDate=Yr;Yr.create=t=>new Yr({checks:[],coerce:t?.coerce||!1,typeName:ce.ZodDate,...ue(t)});var si=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.symbol,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodSymbol=si;si.create=t=>new si({typeName:ce.ZodSymbol,...ue(t)});var Xr=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.undefined,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodUndefined=Xr;Xr.create=t=>new Xr({typeName:ce.ZodUndefined,...ue(t)});var Qr=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.null,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodNull=Qr;Qr.create=t=>new Qr({typeName:ce.ZodNull,...ue(t)});var rr=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodAny=rr;rr.create=t=>new rr({typeName:ce.ZodAny,...ue(t)});var $n=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodUnknown=$n;$n.create=t=>new $n({typeName:ce.ZodUnknown,...ue(t)});var Wt=class extends de{_parse(e){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.never,received:n.parsedType}),I.INVALID}};R.ZodNever=Wt;Wt.create=t=>new Wt({typeName:ce.ZodNever,...ue(t)});var ii=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.void,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodVoid=ii;ii.create=t=>new ii({typeName:ce.ZodVoid,...ue(t)});var Cn=class t extends de{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==H.ZodParsedType.array)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.array,received:n.parsedType}),I.INVALID;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&((0,I.addIssueToContext)(n,{code:a?q.ZodIssueCode.too_big:q.ZodIssueCode.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,I.addIssueToContext)(n,{code:q.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,I.addIssueToContext)(n,{code:q.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new At(n,a,n.path,c)))).then(a=>I.ParseStatus.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new At(n,a,n.path,c)));return I.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:ne.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:ne.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:ne.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};R.ZodArray=Cn;Cn.create=(t,e)=>new Cn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ce.ZodArray,...ue(e)});function ri(t){if(t instanceof pt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Et.create(ri(r))}return new pt({...t._def,shape:()=>e})}else return t instanceof Cn?new Cn({...t._def,type:ri(t.element)}):t instanceof Et?Et.create(ri(t.unwrap())):t instanceof un?un.create(ri(t.unwrap())):t instanceof ln?ln.create(t.items.map(e=>ri(e))):t}var pt=class t extends de{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=H.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==H.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(u,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.object,received:u.parsedType}),I.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Wt&&this._def.unknownKeys==="strip"))for(let u in s.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let p=i[u],f=s.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new At(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Wt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")c.length>0&&((0,I.addIssueToContext)(s,{code:q.ZodIssueCode.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new At(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let f=await p.key,m=await p.value;u.push({key:f,value:m,alwaysSet:p.alwaysSet})}return u}).then(u=>I.ParseStatus.mergeObjectSync(r,u)):I.ParseStatus.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return ne.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:ne.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ce.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 H.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of H.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ri(this)}partial(e){let n={};for(let r of H.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of H.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Et;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return rf(H.util.objectKeys(this.shape))}};R.ZodObject=pt;pt.create=(t,e)=>new pt({shape:()=>t,unknownKeys:"strip",catchall:Wt.create(),typeName:ce.ZodObject,...ue(e)});pt.strictCreate=(t,e)=>new pt({shape:()=>t,unknownKeys:"strict",catchall:Wt.create(),typeName:ce.ZodObject,...ue(e)});pt.lazycreate=(t,e)=>new pt({shape:t,unknownKeys:"strip",catchall:Wt.create(),typeName:ce.ZodObject,...ue(e)});var es=class extends de{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new q.ZodError(c.ctx.common.issues));return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_union,unionErrors:a}),I.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new q.ZodError(l));return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_union,unionErrors:c}),I.INVALID}}get options(){return this._def.options}};R.ZodUnion=es;es.create=(t,e)=>new es({options:t,typeName:ce.ZodUnion,...ue(e)});var An=t=>t instanceof ns?An(t.schema):t instanceof yt?An(t.innerType()):t instanceof rs?[t.value]:t instanceof ss?t.options:t instanceof is?H.util.objectValues(t.enum):t instanceof os?An(t._def.innerType):t instanceof Xr?[void 0]:t instanceof Qr?[null]:t instanceof Et?[void 0,...An(t.unwrap())]:t instanceof un?[null,...An(t.unwrap())]:t instanceof ro||t instanceof cs?An(t.unwrap()):t instanceof as?An(t._def.innerType):[],Ta=class t extends de{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.ZodParsedType.object)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.object,received:n.parsedType}),I.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),I.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let a=An(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new t({typeName:ce.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ue(r)})}};R.ZodDiscriminatedUnion=Ta;function Zl(t,e){let n=(0,H.getParsedType)(t),r=(0,H.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===H.ZodParsedType.object&&r===H.ZodParsedType.object){let s=H.util.objectKeys(e),i=H.util.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=Zl(t[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===H.ZodParsedType.array&&r===H.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=e[i],l=Zl(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===H.ZodParsedType.date&&r===H.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ts=class extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if((0,I.isAborted)(i)||(0,I.isAborted)(a))return I.INVALID;let c=Zl(i.value,a.value);return c.valid?(((0,I.isDirty)(i)||(0,I.isDirty)(a))&&n.dirty(),{status:n.value,value:c.data}):((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_intersection_types}),I.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):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}))}};R.ZodIntersection=ts;ts.create=(t,e,n)=>new ts({left:t,right:e,typeName:ce.ZodIntersection,...ue(n)});var ln=class t extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.ZodParsedType.array)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.array,received:r.parsedType}),I.INVALID;if(r.data.length<this._def.items.length)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new At(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>I.ParseStatus.mergeArray(n,a)):I.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};R.ZodTuple=ln;ln.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ln({items:t,typeName:ce.ZodTuple,rest:null,...ue(e)})};var Ra=class t extends de{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!==H.ZodParsedType.object)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.object,received:r.parsedType}),I.INVALID;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new At(r,c,r.path,c)),value:a._parse(new At(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?I.ParseStatus.mergeObjectAsync(n,s):I.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof de?new t({keyType:e,valueType:n,typeName:ce.ZodRecord,...ue(r)}):new t({keyType:nr.create(),valueType:e,typeName:ce.ZodRecord,...ue(n)})}};R.ZodRecord=Ra;var oi=class extends de{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!==H.ZodParsedType.map)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.map,received:r.parsedType}),I.INVALID;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:s._parse(new At(r,c,r.path,[u,"key"])),value:i._parse(new At(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return I.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return I.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}}}};R.ZodMap=oi;oi.create=(t,e,n)=>new oi({valueType:e,keyType:t,typeName:ce.ZodMap,...ue(n)});var ai=class t extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.ZodParsedType.set)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.set,received:r.parsedType}),I.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let u=new Set;for(let p of l){if(p.status==="aborted")return I.INVALID;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let c=[...r.data.values()].map((l,u)=>i._parse(new At(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(e,n){return new t({...this._def,minSize:{value:e,message:ne.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:ne.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};R.ZodSet=ai;ai.create=(t,e)=>new ai({valueType:t,minSize:null,maxSize:null,typeName:ce.ZodSet,...ue(e)});var Ia=class t extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.ZodParsedType.function)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.function,received:n.parsedType}),I.INVALID;function r(c,l){return(0,I.makeIssue)({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,xa.getErrorMap)(),xa.defaultErrorMap].filter(u=>!!u),issueData:{code:q.ZodIssueCode.invalid_arguments,argumentsError:l}})}function s(c,l){return(0,I.makeIssue)({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,xa.getErrorMap)(),xa.defaultErrorMap].filter(u=>!!u),issueData:{code:q.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof sr){let c=this;return(0,I.OK)(async function(...l){let u=new q.ZodError([]),p=await c._def.args.parseAsync(l,i).catch(w=>{throw u.addIssue(r(l,w)),u}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let c=this;return(0,I.OK)(function(...l){let u=c._def.args.safeParse(l,i);if(!u.success)throw new q.ZodError([r(l,u.error)]);let p=Reflect.apply(a,this,u.data),f=c._def.returns.safeParse(p,i);if(!f.success)throw new q.ZodError([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ln.create(e).rest($n.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||ln.create([]).rest($n.create()),returns:n||$n.create(),typeName:ce.ZodFunction,...ue(r)})}};R.ZodFunction=Ia;var ns=class extends de{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})}};R.ZodLazy=ns;ns.create=(t,e)=>new ns({getter:t,typeName:ce.ZodLazy,...ue(e)});var rs=class extends de{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{received:n.data,code:q.ZodIssueCode.invalid_literal,expected:this._def.value}),I.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};R.ZodLiteral=rs;rs.create=(t,e)=>new rs({value:t,typeName:ce.ZodLiteral,...ue(e)});function rf(t,e){return new ss({values:t,typeName:ce.ZodEnum,...ue(e)})}var ss=class t extends de{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,I.addIssueToContext)(n,{expected:H.util.joinValues(r),received:n.parsedType,code:q.ZodIssueCode.invalid_type}),I.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,I.addIssueToContext)(n,{received:n.data,code:q.ZodIssueCode.invalid_enum_value,options:r}),I.INVALID}return(0,I.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};R.ZodEnum=ss;ss.create=rf;var is=class extends de{_parse(e){let n=H.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==H.ZodParsedType.string&&r.parsedType!==H.ZodParsedType.number){let s=H.util.objectValues(n);return(0,I.addIssueToContext)(r,{expected:H.util.joinValues(s),received:r.parsedType,code:q.ZodIssueCode.invalid_type}),I.INVALID}if(this._cache||(this._cache=new Set(H.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=H.util.objectValues(n);return(0,I.addIssueToContext)(r,{received:r.data,code:q.ZodIssueCode.invalid_enum_value,options:s}),I.INVALID}return(0,I.OK)(e.data)}get enum(){return this._def.values}};R.ZodNativeEnum=is;is.create=(t,e)=>new is({values:t,typeName:ce.ZodNativeEnum,...ue(e)});var sr=class extends de{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.ZodParsedType.promise&&n.common.async===!1)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.promise,received:n.parsedType}),I.INVALID;let r=n.parsedType===H.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,I.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};R.ZodPromise=sr;sr.create=(t,e)=>new sr({type:t,typeName:ce.ZodPromise,...ue(e)});var yt=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ce.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:a=>{(0,I.addIssueToContext)(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return I.INVALID;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?I.INVALID:l.status==="dirty"||n.value==="dirty"?(0,I.DIRTY)(l.value):l});{if(n.value==="aborted")return I.INVALID;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?I.INVALID:c.status==="dirty"||n.value==="dirty"?(0,I.DIRTY)(c.value):c}}if(s.type==="refinement"){let a=c=>{let l=s.refinement(c,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?I.INVALID:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?I.INVALID:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,I.isValid)(a))return I.INVALID;let c=s.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>(0,I.isValid)(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):I.INVALID);H.util.assertNever(s)}};R.ZodEffects=yt;R.ZodTransformer=yt;yt.create=(t,e,n)=>new yt({schema:t,typeName:ce.ZodEffects,effect:e,...ue(n)});yt.createWithPreprocess=(t,e,n)=>new yt({schema:e,effect:{type:"preprocess",transform:t},typeName:ce.ZodEffects,...ue(n)});var Et=class extends de{_parse(e){return this._getType(e)===H.ZodParsedType.undefined?(0,I.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodOptional=Et;Et.create=(t,e)=>new Et({innerType:t,typeName:ce.ZodOptional,...ue(e)});var un=class extends de{_parse(e){return this._getType(e)===H.ZodParsedType.null?(0,I.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodNullable=un;un.create=(t,e)=>new un({innerType:t,typeName:ce.ZodNullable,...ue(e)});var os=class extends de{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===H.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};R.ZodDefault=os;os.create=(t,e)=>new os({innerType:t,typeName:ce.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ue(e)});var as=class extends de{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,I.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new q.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new q.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};R.ZodCatch=as;as.create=(t,e)=>new as({innerType:t,typeName:ce.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ue(e)});var ci=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.nan,received:r.parsedType}),I.INVALID}return{status:"valid",value:e.data}}};R.ZodNaN=ci;ci.create=t=>new ci({typeName:ce.ZodNaN,...ue(t)});R.BRAND=Symbol("zod_brand");var ro=class extends de{_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}};R.ZodBranded=ro;var so=class t extends de{_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"?I.INVALID:i.status==="dirty"?(n.dirty(),(0,I.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?I.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:ce.ZodPipeline})}};R.ZodPipeline=so;var cs=class extends de{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,I.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,I.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};R.ZodReadonly=cs;cs.create=(t,e)=>new cs({innerType:t,typeName:ce.ZodReadonly,...ue(e)});function Qp(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function sf(t,e={},n){return t?rr.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=Qp(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=Qp(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):rr.create()}R.late={object:pt.lazycreate};var ce;(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"})(ce||(R.ZodFirstPartyTypeKind=ce={}));var f_=(t,e={message:`Input not instance of ${t.name}`})=>sf(n=>n instanceof t,e);R.instanceof=f_;var of=nr.create;R.string=of;var af=Vr.create;R.number=af;var m_=ci.create;R.nan=m_;var g_=Zr.create;R.bigint=g_;var cf=Jr.create;R.boolean=cf;var y_=Yr.create;R.date=y_;var b_=si.create;R.symbol=b_;var w_=Xr.create;R.undefined=w_;var v_=Qr.create;R.null=v_;var k_=rr.create;R.any=k_;var S_=$n.create;R.unknown=S_;var __=Wt.create;R.never=__;var x_=ii.create;R.void=x_;var T_=Cn.create;R.array=T_;var R_=pt.create;R.object=R_;var I_=pt.strictCreate;R.strictObject=I_;var E_=es.create;R.union=E_;var A_=Ta.create;R.discriminatedUnion=A_;var $_=ts.create;R.intersection=$_;var C_=ln.create;R.tuple=C_;var P_=Ra.create;R.record=P_;var N_=oi.create;R.map=N_;var j_=ai.create;R.set=j_;var M_=Ia.create;R.function=M_;var O_=ns.create;R.lazy=O_;var z_=rs.create;R.literal=z_;var D_=ss.create;R.enum=D_;var L_=is.create;R.nativeEnum=L_;var U_=sr.create;R.promise=U_;var lf=yt.create;R.effect=lf;R.transformer=lf;var q_=Et.create;R.optional=q_;var F_=un.create;R.nullable=F_;var B_=yt.createWithPreprocess;R.preprocess=B_;var H_=so.create;R.pipeline=H_;var K_=()=>of().optional();R.ostring=K_;var W_=()=>af().optional();R.onumber=W_;var G_=()=>cf().optional();R.oboolean=G_;R.coerce={string:(t=>nr.create({...t,coerce:!0})),number:(t=>Vr.create({...t,coerce:!0})),boolean:(t=>Jr.create({...t,coerce:!0})),bigint:(t=>Zr.create({...t,coerce:!0})),date:(t=>Yr.create({...t,coerce:!0}))};R.NEVER=I.INVALID});var Jl=be($t=>{"use strict";var V_=$t&&$t.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),li=$t&&$t.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&V_(e,t,n)};Object.defineProperty($t,"__esModule",{value:!0});li(Sa(),$t);li(Gl(),$t);li(Zp(),$t);li(to(),$t);li(uf(),$t);li(ka(),$t)});var pf=be(ft=>{"use strict";var df=ft&&ft.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Z_=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),J_=ft&&ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&df(e,t,n);return Z_(e,t),e},Y_=ft&&ft.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&df(e,t,n)};Object.defineProperty(ft,"__esModule",{value:!0});ft.z=void 0;var hf=J_(Jl());ft.z=hf;Y_(Jl(),ft);ft.default=hf});var Me=be(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.RunContextMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.AiSpendMsg=h.AI_SPEND_SURFACES=h.MONITOR_CATALOG=h.MONITOR_BASELINE_TYPES=h.MONITOR_PARAM_SCHEMAS=h.MonitorCheckConfig=h.MonitorParseRules=h.MonitorCommand=h.MonitorSchedule=h.MonitorStatus=h.RuleConfig=h.PACK_CATALOG=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.DEPLOY_DOC_CANDIDATES=h.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.TICKET_RULES_APPENDIX=h.COMPOSE_COMMANDS=h.MAX_FAILURE_CHARS=h.MAX_FAILURE_LINES=h.FAILURE_BLOCK_LINES=h.FAILURE_CONTEXT_LINES=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatSessionMsg=h.ChatActivityMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.JiraVersionsResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=void 0;h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupAskResultMsg=h.SetupAskMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatStepRunResultMsg=h.ChatStepRunMsg=h.ChatDiagnosticResultMsg=void 0;h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.RebirthStudyResultMsg=h.RebirthStudyUpdateMsg=h.RebirthStudyMsg=h.TimelineDigestResultMsg=h.TimelineDigestMsg=h.RebirthDesignResultMsg=h.RebirthDesignMsg=h.RebirthUploadChunkResultMsg=h.RebirthUploadChunkMsg=h.RebirthUploadBeginResultMsg=h.RebirthUploadBeginMsg=h.SiteAuditResultMsg=h.SiteAuditMsg=h.ServerDecommissionProgressMsg=h.ServerDecommissionResultMsg=h.ServerDecommissionExecuteMsg=h.ServerDecommissionPlanResultMsg=h.ServerDecommissionPlanMsg=h.MonitorDiscoverResultMsg=h.MonitorDiscoverMsg=h.MonitorRebaselineResultMsg=h.MonitorRebaselineMsg=h.MonitorSuggestResultMsg=h.MonitorSuggestMsg=h.MonitorRunResultMsg=h.MonitorRunMsg=h.MonitorResultMsg=h.ServerInventoryResultMsg=h.ServerInventoryMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.REVISION_PROMPT=h.FOCUSED_READING_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraVersionsMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=void 0;h.missingAgentCapabilities=X_;h.replyPreferenceAppendix=ex;h.monitorChecksAppendix=tx;h.pendingMigrationsAppendix=nx;h.deployTargetsAppendix=rx;h.savedStepChecksAppendix=sx;h.failureCollector=ff;h.failureLines=cx;h.composeCommandAppendix=lx;h.isSelfMigrationFilename=ux;h.parseRunnerMsg=dx;h.parseServerMsg=hx;var o=pf();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.124";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";h.DEPLOY_DOC_CANDIDATES=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"];h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0,fullAccess:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1,fullAccess:!1},suggestedModels:[],experimental:!0},{id:"kimi",displayName:"Moonshot Kimi Code CLI",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!0,costReporting:!1,modelSelection:!0,loginProfiles:!1,fullAccess:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"],operator:["fullAccess","sessionResume"]};function X_(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Q_=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=Q_;h.RunStatus=o.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=o.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=o.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=o.z.object({type:o.z.literal("label_added"),label:o.z.string().min(1),doneLabel:o.z.string().min(1).default("agent-planned"),failedLabel:o.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=o.z.object({type:o.z.literal("comment_keyword"),keyword:o.z.string().min(1),doneLabel:o.z.string().min(1).default("agent-implemented"),failedLabel:o.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=o.z.object({type:o.z.literal("status_changed"),status:o.z.string().min(1),doneLabel:o.z.string().min(1).default("agent-deployed"),failedLabel:o.z.string().min(1).default("agent-failed")});h.TriggerConfig=o.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=o.z.object({type:o.z.literal("plan_only"),promptTemplate:o.z.string().min(1),allowWeb:o.z.boolean().default(!1),timeoutSeconds:o.z.number().int().positive().max(3600).default(900),agent:o.z.string().default(h.DEFAULT_AGENT_ID),model:o.z.string().default("")});h.ImplementAction=o.z.object({type:o.z.literal("implement"),promptTemplate:o.z.string().min(1),timeoutSeconds:o.z.number().int().positive().max(7200).default(1800),maxTurns:o.z.number().int().positive().max(500).default(120),maxCostUsd:o.z.number().positive().optional(),requireApproval:o.z.boolean().default(!0),branchTemplate:o.z.string().min(1).default("agent/{{issueKey}}").refine(t=>t.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:o.z.string().min(1).default("main"),jiraTransition:o.z.string().optional(),jiraTransitionOnStart:o.z.string().optional(),jiraTransitionOnMerge:o.z.string().optional(),agent:o.z.string().default(h.DEFAULT_AGENT_ID),model:o.z.string().default(""),updateMemory:o.z.boolean().default(!1),allowWeb:o.z.boolean().default(!1),writeTests:o.z.boolean().default(!0),runTests:o.z.boolean().default(!0),mergeOnApprove:o.z.boolean().default(!0),mergeMethod:o.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:o.z.boolean().default(!0)});h.RespondAction=o.z.object({type:o.z.literal("respond"),promptTemplate:o.z.string().min(1),timeoutSeconds:o.z.number().int().positive().max(3600).default(600),agent:o.z.string().default(h.DEFAULT_AGENT_ID),model:o.z.string().default("")});h.DeployStep=o.z.object({name:o.z.string().min(1).max(120),run:o.z.string().min(1).max(4e3),continueOnError:o.z.boolean().default(!1)});h.PromotionMode=o.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=o.z.object({id:o.z.string(),projectId:o.z.string(),name:o.z.string(),rank:o.z.number().int().nonnegative(),auditBeforeDeploy:o.z.enum(["","security","testing"]).default(""),branch:o.z.string().default(""),publicUrl:o.z.string().default(""),servePath:o.z.string().default(""),useDedicatedCheckout:o.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:o.z.string().default("agent/{{issueKey}}"),steps:o.z.array(h.DeployStep).default([]),workdir:o.z.string().default(""),timeoutSeconds:o.z.number().int().positive().max(21600).default(1800),requiredSecrets:o.z.array(o.z.string()).default([]),requireApproval:o.z.boolean().default(!1),requireSyncCheck:o.z.boolean().default(!1),previousEnvBranch:o.z.string().optional(),deployFromColumn:o.z.string().default(""),deployToColumn:o.z.string().default("")});h.DeployAction=o.z.object({type:o.z.literal("deploy"),envSelection:o.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:o.z.string().optional(),requireStatus:o.z.string().optional()});h.ActionConfig=o.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=o.z.object({id:o.z.string(),name:o.z.string(),jiraProjectKey:o.z.string(),goLiveIssueKey:o.z.string().default(""),repoName:o.z.string(),jiraSiteUrl:o.z.string().default(""),defaultAgent:o.z.string().default("claude-code"),componentRoutes:o.z.array(o.z.object({component:o.z.string().min(1),repoName:o.z.string().min(1)})).default([]),packs:o.z.array(o.z.string().max(60)).max(40).default([])});h.PACK_CATALOG=[{id:"owasp",title:"OWASP Top 10",kind:"compliance",description:"Security audits cite OWASP Top 10 (2021) categories - findings carry OWASP-A01\u2026A10 ids.",roles:["security"]},{id:"pci-dss",title:"PCI DSS",kind:"compliance",description:"Payment-card compliance: findings cite PCI DSS requirement numbers (PCI-3.x, PCI-6.x\u2026).",roles:["security"]},{id:"gdpr",title:"GDPR build rules",kind:"compliance",description:"Implement runs follow GDPR build rules while WRITING code (GDPR-B01\u2026B09 - no PII in logs, retention ships with every new store, third-party sends are processor decisions). Security audits already check GDPR readiness globally; this adds the build-time half.",roles:["implement"]},{id:"laravel",title:"Laravel conventions",kind:"stack",description:"Laravel-specific rules for implement runs and architecture audits.",roles:["implement","architecture"]},{id:"react",title:"React conventions",kind:"stack",description:"React/Next-specific rules for implement runs and architecture audits.",roles:["implement","architecture"]},{id:"node",title:"Node.js backend conventions",kind:"stack",description:"Node/Express/Nest backend rules for implement runs and architecture audits.",roles:["implement","architecture"]}];h.RuleConfig=o.z.object({id:o.z.string(),projectId:o.z.string(),name:o.z.string(),enabled:o.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.MonitorStatus=o.z.enum(["green","amber","red","error","skipped"]);h.MonitorSchedule=o.z.discriminatedUnion("kind",[o.z.object({kind:o.z.literal("every"),minutes:o.z.number().int().min(1).max(1440)}),o.z.object({kind:o.z.literal("daily"),at:o.z.string().regex(/^\d{2}:\d{2}$/)}),o.z.object({kind:o.z.literal("weekly"),day:o.z.number().int().min(0).max(6),at:o.z.string().regex(/^\d{2}:\d{2}$/)})]);h.MonitorCommand=o.z.object({name:o.z.string().min(1).max(120),run:o.z.string().min(1).max(4e3)});h.MonitorParseRules=o.z.object({amberPattern:o.z.string().max(400).default(""),redPattern:o.z.string().max(400).default(""),greenRequires:o.z.string().max(400).default("")});h.MonitorCheckConfig=o.z.object({id:o.z.string(),type:o.z.string().max(60),name:o.z.string().min(1).max(120),projectId:o.z.string().default(""),params:o.z.record(o.z.unknown()).default({}),schedule:h.MonitorSchedule,shell:o.z.enum(["bash","powershell"]).default("bash"),commands:o.z.array(h.MonitorCommand).max(20).default([]),parseRules:h.MonitorParseRules.default({}),enabled:o.z.boolean().default(!0),jiraNotify:o.z.boolean().default(!1)});h.MONITOR_PARAM_SCHEMAS={disk_space:o.z.object({warnPct:o.z.number().int().min(1).max(99).default(80),critPct:o.z.number().int().min(1).max(99).default(90),mounts:o.z.array(o.z.string().max(300)).max(20).default([])}),memory:o.z.object({warnPct:o.z.number().int().min(1).max(99).default(85),critPct:o.z.number().int().min(1).max(99).default(95)}),cpu_load:o.z.object({warnPerCore:o.z.number().positive().max(64).default(2),critPerCore:o.z.number().positive().max(64).default(4)}),uptime_reboot:o.z.object({maxUptimeDays:o.z.number().int().positive().max(3650).default(180)}),services:o.z.object({names:o.z.array(o.z.string().min(1).max(120)).min(1).max(40)}),http_check:o.z.object({url:o.z.string().min(1).max(500),expectStatus:o.z.number().int().min(100).max(599).default(200),expectString:o.z.string().max(200).default(""),warnMs:o.z.number().int().positive().max(6e4).default(2e3),timeoutMs:o.z.number().int().positive().max(6e4).default(1e4)}),tls_cert:o.z.object({domains:o.z.array(o.z.string().min(1).max(253)).min(1).max(40),warnDays:o.z.number().int().min(1).max(365).default(21),critDays:o.z.number().int().min(0).max(364).default(7)}),sites:o.z.object({extraHosts:o.z.array(o.z.string().min(1).max(253)).max(30).default([]),excludeHosts:o.z.array(o.z.string().min(1).max(253)).max(30).default([]),warnMs:o.z.number().int().positive().max(6e4).default(3e3),certWarnDays:o.z.number().int().min(1).max(365).default(21),certCritDays:o.z.number().int().min(0).max(364).default(7)}),db_health:o.z.object({repoName:o.z.string().min(1).max(200),envName:o.z.string().min(1).max(100),secretName:o.z.string().min(1).max(100).default("DATABASE_URL"),warnConnections:o.z.number().int().positive().max(1e4).default(50),longQuerySeconds:o.z.number().int().positive().max(3600).default(60)}),docker_containers:o.z.object({expected:o.z.array(o.z.string().min(1).max(120)).max(40).default([])}),log_scan:o.z.object({files:o.z.array(o.z.string().min(1).max(400)).min(1).max(10),hardPatterns:o.z.array(o.z.string().max(200)).max(10).default(["oom-killer","kernel panic","segfault"]),errorPattern:o.z.string().max(200).default("\\b(error|fatal)\\b"),warnCount:o.z.number().int().positive().max(1e5).default(50),tailKB:o.z.number().int().min(16).max(1024).default(256)}),backup_freshness:o.z.object({noBackups:o.z.boolean().default(!1),targets:o.z.array(o.z.object({pathGlob:o.z.string().min(1).max(500),maxAgeHours:o.z.number().positive().max(2160).default(26),minSizeMB:o.z.number().nonnegative().max(1e6).default(1)})).max(20).default([])}),ports_baseline:o.z.object({}),users_baseline:o.z.object({}),cron_baseline:o.z.object({}),auth_activity:o.z.object({failedWarnCount:o.z.number().int().positive().max(1e5).default(100)}),webroot_integrity:o.z.object({roots:o.z.array(o.z.string().min(1).max(400)).min(1).max(10),excludes:o.z.array(o.z.string().min(1).max(200)).max(20).default(["node_modules",".git","cache","wp-content/uploads",".next","vendor"])}),wordpress:o.z.object({wpPaths:o.z.array(o.z.string().min(1).max(400)).min(1).max(10)}),process_hog:o.z.object({cpuPct:o.z.number().min(1).max(100).default(80)}),windows_update:o.z.object({maxHotfixAgeDays:o.z.number().int().positive().max(3650).default(60)}),custom:o.z.object({})};h.MONITOR_BASELINE_TYPES=["ports_baseline","users_baseline","cron_baseline","auth_activity","webroot_integrity","wordpress"];h.MONITOR_CATALOG=[{id:"disk_space",title:"Disk space",group:"health",question:"Is any filesystem filling up?",os:"both",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"memory",title:"Memory & swap",group:"health",question:"Is the machine under memory pressure?",os:"both",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"cpu_load",title:"CPU load",group:"health",question:"Is the load average sustainably high?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"uptime_reboot",title:"Uptime & pending restart",group:"health",question:"When did this box last boot, and does the OS want a reboot?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"06:00"}},{id:"services",title:"Services running",group:"health",question:"Are these named services active?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:5}},{id:"http_check",title:"HTTP check",group:"web",question:"Does this URL answer correctly, and fast enough?",os:"both",minMinutes:1,defaultSchedule:{kind:"every",minutes:5}},{id:"tls_cert",title:"TLS certificate expiry",group:"web",question:"How many days are left on these certificates?",os:"both",minMinutes:60,defaultSchedule:{kind:"daily",at:"07:00"}},{id:"backup_freshness",title:"Backup freshness",group:"backups",question:"Did a fresh, healthy-sized backup actually appear?",os:"both",minMinutes:60,defaultSchedule:{kind:"daily",at:"08:00"}},{id:"sites",title:"Sites this box serves",group:"web",question:"Every nginx/caddy/IIS vhost, live-probed: up, fast, certified?",os:"both",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"db_health",title:"Database health",group:"db",question:"Reachable, size, connections, long-running queries?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:30}},{id:"docker_containers",title:"Docker containers",group:"health",question:"Are the containers running - and staying up?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:5}},{id:"log_scan",title:"Log scan",group:"health",question:"Are named logs quiet - no OOM kills, no error spikes?",os:"linux",minMinutes:15,defaultSchedule:{kind:"every",minutes:60}},{id:"ports_baseline",title:"Listening ports vs baseline",group:"security",question:"Did a new port start listening that no one vouched for?",os:"both",minMinutes:30,defaultSchedule:{kind:"every",minutes:60}},{id:"users_baseline",title:"System users vs baseline",group:"security",question:"Did a new account appear - especially a root-level one?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:00"}},{id:"cron_baseline",title:"Cron vs baseline",group:"security",question:"Did any crontab change since a human last accepted it?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:10"}},{id:"auth_activity",title:"SSH & access grants",group:"security",question:"Brute-force spikes; new authorized_keys or sudoers grants?",os:"linux",minMinutes:30,defaultSchedule:{kind:"every",minutes:60}},{id:"webroot_integrity",title:"Webroot integrity",group:"security",question:"Did site files change outside a deploy?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:20"}},{id:"wordpress",title:"WordPress compromise signals",group:"security",question:"Core checksums, PHP in uploads, new admin users?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:30"}},{id:"process_hog",title:"Runaway process",group:"security",question:"Is something eating the CPU - from a location it shouldn't?",os:"linux",minMinutes:15,defaultSchedule:{kind:"every",minutes:30}},{id:"windows_update",title:"Windows updates",group:"health",question:"Pending reboot; how stale is the newest hotfix?",os:"windows",minMinutes:60,defaultSchedule:{kind:"daily",at:"06:30"}},{id:"custom",title:"Custom check",group:"custom",question:"Your own saved commands - exit code decides, patterns refine.",os:"both",minMinutes:5,defaultSchedule:{kind:"daily",at:"06:00"}}];h.AI_SPEND_SURFACES=[{id:"run_plan",label:"Plan runs",group:"people"},{id:"run_implement",label:"Implement runs",group:"people"},{id:"run_respond",label:"Ticket answers",group:"people"},{id:"run_testfix",label:"Test fixes",group:"people"},{id:"run_conflict_resolve",label:"Conflict resolves",group:"people"},{id:"chat_turn",label:"Compose chat",group:"people"},{id:"audit",label:"Audits",group:"people"},{id:"audit_explain",label:"Audit explanations",group:"people"},{id:"rebirth_study",label:"Rebirth studies",group:"people"},{id:"rebirth_refold",label:"Rebirth refolds",group:"people"},{id:"rebirth_design",label:"Rebirth design passes",group:"people"},{id:"rebirth_techstack",label:"Rebirth tech-stack passes",group:"people"},{id:"deploy_fix",label:"Deploy-failure diagnoses",group:"people"},{id:"deploy_suggest",label:"Deploy step proposals",group:"people"},{id:"setup_docs",label:"Setup doc drafting",group:"people"},{id:"setup_ask",label:"Setup questions",group:"people"},{id:"incident_diagnosis",label:"Incident diagnoses",group:"people"},{id:"monitor_suggest",label:"Check proposals",group:"people"},{id:"chat_compact",label:"Chat compaction",group:"platform"},{id:"chat_capsule",label:"Ticket context capsules",group:"platform"},{id:"repo_brief",label:"Repo briefs",group:"platform"},{id:"timeline_digest",label:"Timeline digests",group:"platform"},{id:"autopilot_plan",label:"Autopilot planning",group:"platform"},{id:"epic_suggest",label:"Epic suggestions",group:"platform"}];h.AiSpendMsg=o.z.object({type:o.z.literal("ai.spend"),eventKey:o.z.string().min(1).max(200),surface:o.z.string().max(60),projectId:o.z.string().default(""),userId:o.z.string().default(""),agentId:o.z.string().default(""),model:o.z.string().max(200).default(""),billingMode:o.z.string().max(20).default(""),claudeProfile:o.z.string().max(200).default(""),inputTokens:o.z.number().int().nonnegative().default(0),outputTokens:o.z.number().int().nonnegative().default(0),cacheReadTokens:o.z.number().int().nonnegative().default(0),costUsd:o.z.number().nonnegative().default(0),turns:o.z.number().int().nonnegative().default(0),refKind:o.z.string().max(20).default(""),refId:o.z.string().max(200).default(""),refLabel:o.z.string().max(200).default(""),at:o.z.string().default("")});h.HelloMsg=o.z.object({type:o.z.literal("hello"),protocolVersion:o.z.string(),runnerVersion:o.z.string(),platform:o.z.string(),justBooted:o.z.boolean().optional()});h.HeartbeatMsg=o.z.object({type:o.z.literal("heartbeat"),ts:o.z.string()});h.RunClaimMsg=o.z.object({type:o.z.literal("run.claim"),requestId:o.z.string(),ruleId:o.z.string(),issueKey:o.z.string(),issueSummary:o.z.string().default(""),triggerFingerprint:o.z.string(),dedupKey:o.z.string().optional(),triggeredByAccountId:o.z.string().optional()});h.RunLogMsg=o.z.object({type:o.z.literal("run.log"),runId:o.z.string(),seq:o.z.number().int().nonnegative(),ts:o.z.string(),level:o.z.enum(["info","warn","error","agent"]),message:o.z.string().max(16384)});h.RunUsageMsg=o.z.object({type:o.z.literal("run.usage"),runId:o.z.string(),inputTokens:o.z.number().int().nonnegative(),outputTokens:o.z.number().int().nonnegative(),cacheReadTokens:o.z.number().int().nonnegative().optional(),costUsd:o.z.number().nonnegative().optional(),turns:o.z.number().int().nonnegative().optional()});h.FailedTest=o.z.object({command:o.z.string().max(500),exitCode:o.z.number().int(),tail:o.z.string().max(4e3)});h.RunContextMsg=o.z.object({type:o.z.literal("run.context"),runId:o.z.string(),pieces:o.z.array(o.z.object({part:o.z.string().max(80),chars:o.z.number().int().nonnegative()})).max(30),totalChars:o.z.number().int().nonnegative(),sessionMode:o.z.enum(["fresh","chained","timeout-resume","preflight-resume"])});h.RunStatusMsg=o.z.object({type:o.z.literal("run.status"),runId:o.z.string(),status:h.RunStatus,error:o.z.string().optional(),note:o.z.string().max(300).optional(),errorKind:o.z.enum(["guard"]).optional(),costUsd:o.z.number().nonnegative().optional(),inputTokens:o.z.number().int().nonnegative().optional(),outputTokens:o.z.number().int().nonnegative().optional(),cacheReadTokens:o.z.number().int().nonnegative().optional(),resultSummary:o.z.string().max(2e3).optional(),billingMode:o.z.enum(["subscription","api","unknown"]).optional(),model:o.z.string().max(200).optional(),prUrl:o.z.string().optional(),headSha:o.z.string().optional(),deployedRef:o.z.string().optional(),retryAvailable:o.z.boolean().optional(),failedTests:o.z.array(h.FailedTest).max(20).optional(),testsPassed:o.z.number().int().nonnegative().optional(),testsTotal:o.z.number().int().nonnegative().optional(),manualSteps:o.z.array(o.z.object({command:o.z.string().max(500),why:o.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:o.z.string().max(4e3).optional(),inputQuestions:o.z.string().max(4e3).optional(),inputOptions:o.z.array(o.z.string().max(200)).max(5).optional()});h.ProjectTestResultMsg=o.z.object({type:o.z.literal("project.test.result"),requestId:o.z.string(),ok:o.z.boolean(),checks:o.z.array(o.z.object({name:o.z.string(),ok:o.z.boolean(),detail:o.z.string(),kind:o.z.enum(["connection","content"]).default("connection"),fix:o.z.array(o.z.string()).default([]),fixNote:o.z.string().default("")}))});h.RuleDiagnoseResultMsg=o.z.object({type:o.z.literal("rule.diagnose.result"),requestId:o.z.string(),checks:o.z.array(o.z.object({name:o.z.string(),ok:o.z.boolean(),detail:o.z.string(),kind:o.z.enum(["connection","content"]).default("connection"),fix:o.z.array(o.z.string()).default([]),fixNote:o.z.string().default("")})),matchedCount:o.z.number().int().nonnegative(),excludedCount:o.z.number().int().nonnegative(),excludedSample:o.z.array(o.z.string()).max(5)});h.DeployClaimMsg=o.z.object({type:o.z.literal("deploy.claim"),requestId:o.z.string(),projectId:o.z.string(),ruleId:o.z.string(),issueKey:o.z.string(),issueSummary:o.z.string().default(""),environmentName:o.z.string(),requestedByAccountId:o.z.string().optional(),requestedByDisplayName:o.z.string().default(""),dedupKey:o.z.string(),triggerFingerprint:o.z.string()});h.DeployClaimResultMsg=o.z.object({type:o.z.literal("deploy.claim.result"),requestId:o.z.string(),accepted:o.z.boolean(),runId:o.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:o.z.string().optional(),code:o.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraVersionsResultMsg=o.z.object({type:o.z.literal("jira.versions.result"),requestId:o.z.string(),ok:o.z.boolean(),error:o.z.string().default(""),versions:o.z.array(o.z.object({id:o.z.string(),name:o.z.string(),released:o.z.boolean().default(!1)})).max(100).default([])});h.JiraUsersResultMsg=o.z.object({type:o.z.literal("jira.users.result"),requestId:o.z.string(),ok:o.z.boolean(),users:o.z.array(o.z.object({accountId:o.z.string(),displayName:o.z.string(),email:o.z.string().default(""),active:o.z.boolean().default(!0)})).default([]),error:o.z.string().optional()});h.ChatStreamMsg=o.z.object({type:o.z.literal("chat.stream"),requestId:o.z.string(),seq:o.z.number().int().nonnegative(),text:o.z.string().max(8e3)});h.ChatUsageMsg=o.z.object({type:o.z.literal("chat.usage"),requestId:o.z.string(),inputTokens:o.z.number().int().nonnegative(),outputTokens:o.z.number().int().nonnegative(),cacheReadTokens:o.z.number().int().nonnegative().optional(),turns:o.z.number().int().nonnegative().optional()});h.ChatActivityMsg=o.z.object({type:o.z.literal("chat.activity"),requestId:o.z.string(),seq:o.z.number().int().nonnegative(),verb:o.z.string().max(40),target:o.z.string().max(200).default("")});h.ChatSessionMsg=o.z.object({type:o.z.literal("chat.session"),requestId:o.z.string(),sessionId:o.z.string()});h.ChatListMsg=o.z.object({type:o.z.literal("chat.list"),requestId:o.z.string(),projectId:o.z.string()});h.ChatListResultMsg=o.z.object({type:o.z.literal("chat.list.result"),requestId:o.z.string(),sessions:o.z.array(o.z.object({sessionId:o.z.string(),title:o.z.string().default(""),updatedAt:o.z.string().default(""),messageCount:o.z.number().int().nonnegative().default(0),ownerUserId:o.z.string().default(""),agentId:o.z.string().default("")})).default([])});h.ChatLoadMsg=o.z.object({type:o.z.literal("chat.load"),requestId:o.z.string(),sessionId:o.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function ex(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
23
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function yp(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})}bp.Command=jl});var _p=be(xt=>{var{Argument:vp}=ca(),{Command:Ml}=wp(),{CommanderError:y0,InvalidArgumentError:kp}=Vi(),{Help:b0}=Rl(),{Option:Sp}=$l();xt.program=new Ml;xt.createCommand=t=>new Ml(t);xt.createOption=(t,e)=>new Sp(t,e);xt.createArgument=(t,e)=>new vp(t,e);xt.Command=Ml;xt.Option=Sp;xt.Argument=vp;xt.Help=b0;xt.CommanderError=y0;xt.InvalidArgumentError=kp;xt.InvalidOptionArgumentError=kp});var fe,Ol,G,sn,Zi=J(()=>{(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 a of s)i[a]=a;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(let c of i)a[c]=s[c];return t.objectValues(a)},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 a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(let a of s)if(i(a))return a},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(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(fe||(fe={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ol||(Ol={}));G=fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sn=t=>{switch(typeof t){case"undefined":return G.undefined;case"string":return G.string;case"number":return Number.isNaN(t)?G.nan:G.number;case"boolean":return G.boolean;case"function":return G.function;case"bigint":return G.bigint;case"symbol":return G.symbol;case"object":return Array.isArray(t)?G.array:t===null?G.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?G.promise:typeof Map<"u"&&t instanceof Map?G.map:typeof Set<"u"&&t instanceof Set?G.set:typeof Date<"u"&&t instanceof Date?G.date:G.object;default:return G.unknown}}});var z,w0,ut,la=J(()=>{Zi();z=fe.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"]),w0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ut=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 a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};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,fe.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()}};ut.create=t=>new ut(t)});var v0,_n,zl=J(()=>{la();Zi();v0=(t,e)=>{let n;switch(t.code){case z.invalid_type:t.received===G.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,fe.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:n=`Unrecognized key(s) in object: ${fe.joinValues(t.keys,", ")}`;break;case z.invalid_union:n="Invalid input";break;case z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${fe.joinValues(t.options)}`;break;case z.invalid_enum_value:n=`Invalid enum value. Expected ${fe.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:n="Invalid function arguments";break;case z.invalid_return_type:n="Invalid function return type";break;case z.invalid_date:n="Invalid date";break;case z.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}"`:fe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case z.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 z.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 z.custom:n="Invalid input";break;case z.invalid_intersection_types:n="Intersection results could not be merged";break;case z.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:n="Number must be finite";break;default:n=e.defaultError,fe.assertNever(t)}return{message:n}},_n=v0});function k0(t){Rp=t}function Zs(){return Rp}var Rp,ua=J(()=>{zl();Rp=_n});function W(t,e){let n=Zs(),r=Ji({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===_n?void 0:_n].filter(s=>!!s)});t.common.issues.push(r)}var Ji,S0,Je,ie,Cr,tt,da,ha,Jn,Js,Dl=J(()=>{ua();zl();Ji=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}},S0=[];Je=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 ie;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,a=await s.value;r.push({key:i,value:a})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return ie;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},ie=Object.freeze({status:"aborted"}),Cr=t=>({status:"dirty",value:t}),tt=t=>({status:"valid",value:t}),da=t=>t.status==="aborted",ha=t=>t.status==="dirty",Jn=t=>t.status==="valid",Js=t=>typeof Promise<"u"&&t instanceof Promise});var Ip=J(()=>{});var Q,Ep=J(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Q||(Q={}))});function le(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:(a,c)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},description:s}}function Pp(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 L0(t){return new RegExp(`^${Pp(t)}$`)}function Np(t){let e=`${Cp}T${Pp(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 U0(t,e){return!!((e==="v4"||!e)&&P0.test(t)||(e==="v6"||!e)&&j0.test(t))}function q0(t,e){if(!E0.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 F0(t,e){return!!((e==="v4"||!e)&&N0.test(t)||(e==="v6"||!e)&&M0.test(t))}function B0(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(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}function Ys(t){if(t instanceof dt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Tt.create(Ys(r))}return new dt({...t._def,shape:()=>e})}else return t instanceof Rn?new Rn({...t._def,type:Ys(t.element)}):t instanceof Tt?Tt.create(Ys(t.unwrap())):t instanceof an?an.create(Ys(t.unwrap())):t instanceof on?on.create(t.items.map(e=>Ys(e))):t}function Ul(t,e){let n=sn(t),r=sn(e);if(t===e)return{valid:!0,data:t};if(n===G.object&&r===G.object){let s=fe.objectKeys(e),i=fe.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=Ul(t[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===G.array&&r===G.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=e[i],l=Ul(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===G.date&&r===G.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function jp(t,e){return new Fr({values:t,typeName:oe.ZodEnum,...le(e)})}function $p(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Mp(t,e={},n){return t?Xn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=$p(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=$p(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Xn.create()}var Rt,Ap,he,_0,x0,T0,R0,I0,E0,A0,$0,C0,Ll,P0,N0,j0,M0,O0,z0,Cp,D0,Yn,Pr,Nr,jr,Mr,Xs,Or,zr,Xn,Tn,Kt,Qs,Rn,dt,Dr,xn,pa,Lr,on,fa,ei,ti,ma,Ur,qr,Fr,Br,Qn,It,Tt,an,Hr,Kr,ni,H0,Yi,Xi,Wr,K0,oe,W0,Op,zp,G0,V0,Dp,Z0,J0,Y0,X0,Q0,eS,tS,nS,rS,sS,iS,oS,aS,cS,lS,uS,dS,hS,pS,fS,mS,gS,yS,bS,wS,vS,kS,SS,_S,xS,TS,RS,IS,ES,Lp=J(()=>{la();ua();Ep();Dl();Zi();Rt=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}},Ap=(t,e)=>{if(Jn(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 ut(t.common.issues);return this._error=n,this._error}}};he=class{get description(){return this._def.description}_getType(e){return sn(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:sn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Je,ctx:{common:e.parent.common,data:e.data,parsedType:sn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Js(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:sn(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ap(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Jn(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=>Jn(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:sn(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Js(s)?s:Promise.resolve(s));return Ap(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 a=e(s),c=()=>i.addIssue({code:z.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!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 It({schema:this,typeName:oe.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 Tt.create(this,this._def)}nullable(){return an.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rn.create(this)}promise(){return Qn.create(this,this._def)}or(e){return Dr.create([this,e],this._def)}and(e){return Lr.create(this,e,this._def)}transform(e){return new It({...le(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Hr({...le(this._def),innerType:this,defaultValue:n,typeName:oe.ZodDefault})}brand(){return new Yi({typeName:oe.ZodBranded,type:this,...le(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Kr({...le(this._def),innerType:this,catchValue:n,typeName:oe.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Xi.create(this,e)}readonly(){return Wr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},_0=/^c[^\s-]{8,}$/i,x0=/^[0-9a-z]+$/,T0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,R0=/^[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,I0=/^[a-z0-9_-]{21}$/i,E0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A0=/^[-+]?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)?)??$/,$0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,C0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",P0=/^(?:(?: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])$/,N0=/^(?:(?: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])$/,j0=/^(([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]))$/,M0=/^(([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])$/,O0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cp="((\\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])))",D0=new RegExp(`^${Cp}$`);Yn=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==G.string){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_type,expected:G.string,received:i.parsedType}),ie}let r=new Je,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),W(s,{code:z.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),W(s,{code:z.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?W(s,{code:z.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&W(s,{code:z.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"email",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ll||(Ll=new RegExp(C0,"u")),Ll.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"emoji",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")R0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"uuid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")I0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"nanoid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")_0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"cuid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")x0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"cuid2",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")T0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"ulid",code:z.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),W(s,{validation:"url",code:z.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),W(s,{validation:"regex",code:z.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),W(s,{code:z.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),W(s,{code:z.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Np(i).test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?D0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?L0(i).test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:z.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?A0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"duration",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?U0(e.data,i.version)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"ip",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?q0(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"jwt",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?F0(e.data,i.version)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"cidr",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?O0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"base64",code:z.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?z0.test(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{validation:"base64url",code:z.invalid_string,message:i.message}),r.dirty()):fe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:z.invalid_string,...Q.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Q.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Q.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Q.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Q.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Q.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Q.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Q.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Q.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Q.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Q.errToObj(n)})}nonempty(e){return this.min(1,Q.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}};Yn.create=t=>new Yn({checks:[],typeName:oe.ZodString,coerce:t?.coerce??!1,...le(t)});Pr=class t extends he{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)!==G.number){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_type,expected:G.number,received:i.parsedType}),ie}let r,s=new Je;for(let i of this._def.checks)i.kind==="int"?fe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),W(r,{code:z.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),W(r,{code:z.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),W(r,{code:z.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?B0(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),W(r,{code:z.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),W(r,{code:z.not_finite,message:i.message}),s.dirty()):fe.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Q.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Q.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Q.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Q.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"&&fe.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)}};Pr.create=t=>new Pr({checks:[],typeName:oe.ZodNumber,coerce:t?.coerce||!1,...le(t)});Nr=class t extends he{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)!==G.bigint)return this._getInvalidInput(e);let r,s=new Je;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),W(r,{code:z.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),W(r,{code:z.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),W(r,{code:z.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):fe.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return W(n,{code:z.invalid_type,expected:G.bigint,received:n.parsedType}),ie}gte(e,n){return this.setLimit("min",e,!0,Q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Q.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Q.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:Q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Q.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}};Nr.create=t=>new Nr({checks:[],typeName:oe.ZodBigInt,coerce:t?.coerce??!1,...le(t)});jr=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==G.boolean){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.boolean,received:r.parsedType}),ie}return tt(e.data)}};jr.create=t=>new jr({typeName:oe.ZodBoolean,coerce:t?.coerce||!1,...le(t)});Mr=class t extends he{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==G.date){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_type,expected:G.date,received:i.parsedType}),ie}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return W(i,{code:z.invalid_date}),ie}let r=new Je,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),W(s,{code:z.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),W(s,{code:z.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):fe.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:Q.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Q.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}};Mr.create=t=>new Mr({checks:[],coerce:t?.coerce||!1,typeName:oe.ZodDate,...le(t)});Xs=class extends he{_parse(e){if(this._getType(e)!==G.symbol){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.symbol,received:r.parsedType}),ie}return tt(e.data)}};Xs.create=t=>new Xs({typeName:oe.ZodSymbol,...le(t)});Or=class extends he{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.undefined,received:r.parsedType}),ie}return tt(e.data)}};Or.create=t=>new Or({typeName:oe.ZodUndefined,...le(t)});zr=class extends he{_parse(e){if(this._getType(e)!==G.null){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.null,received:r.parsedType}),ie}return tt(e.data)}};zr.create=t=>new zr({typeName:oe.ZodNull,...le(t)});Xn=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return tt(e.data)}};Xn.create=t=>new Xn({typeName:oe.ZodAny,...le(t)});Tn=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return tt(e.data)}};Tn.create=t=>new Tn({typeName:oe.ZodUnknown,...le(t)});Kt=class extends he{_parse(e){let n=this._getOrReturnCtx(e);return W(n,{code:z.invalid_type,expected:G.never,received:n.parsedType}),ie}};Kt.create=t=>new Kt({typeName:oe.ZodNever,...le(t)});Qs=class extends he{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.void,received:r.parsedType}),ie}return tt(e.data)}};Qs.create=t=>new Qs({typeName:oe.ZodVoid,...le(t)});Rn=class t extends he{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==G.array)return W(n,{code:z.invalid_type,expected:G.array,received:n.parsedType}),ie;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(W(n,{code:a?z.too_big:z.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?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&&(W(n,{code:z.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&&(W(n,{code:z.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((a,c)=>s.type._parseAsync(new Rt(n,a,n.path,c)))).then(a=>Je.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new Rt(n,a,n.path,c)));return Je.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Q.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Q.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Q.toString(n)}})}nonempty(e){return this.min(1,e)}};Rn.create=(t,e)=>new Rn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...le(e)});dt=class t extends he{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=fe.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==G.object){let u=this._getOrReturnCtx(e);return W(u,{code:z.invalid_type,expected:G.object,received:u.parsedType}),ie}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Kt&&this._def.unknownKeys==="strip"))for(let u in s.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let p=i[u],f=s.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new Rt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Kt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")c.length>0&&(W(s,{code:z.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new Rt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let f=await p.key,m=await p.value;u.push({key:f,value:m,alwaysSet:p.alwaysSet})}return u}).then(u=>Je.mergeObjectSync(r,u)):Je.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return Q.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:Q.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:oe.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 fe.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 fe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Ys(this)}partial(e){let n={};for(let r of fe.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 fe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Tt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return jp(fe.objectKeys(this.shape))}};dt.create=(t,e)=>new dt({shape:()=>t,unknownKeys:"strip",catchall:Kt.create(),typeName:oe.ZodObject,...le(e)});dt.strictCreate=(t,e)=>new dt({shape:()=>t,unknownKeys:"strict",catchall:Kt.create(),typeName:oe.ZodObject,...le(e)});dt.lazycreate=(t,e)=>new dt({shape:t,unknownKeys:"strip",catchall:Kt.create(),typeName:oe.ZodObject,...le(e)});Dr=class extends he{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new ut(c.ctx.common.issues));return W(n,{code:z.invalid_union,unionErrors:a}),ie}if(n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new ut(l));return W(n,{code:z.invalid_union,unionErrors:c}),ie}}get options(){return this._def.options}};Dr.create=(t,e)=>new Dr({options:t,typeName:oe.ZodUnion,...le(e)});xn=t=>t instanceof Ur?xn(t.schema):t instanceof It?xn(t.innerType()):t instanceof qr?[t.value]:t instanceof Fr?t.options:t instanceof Br?fe.objectValues(t.enum):t instanceof Hr?xn(t._def.innerType):t instanceof Or?[void 0]:t instanceof zr?[null]:t instanceof Tt?[void 0,...xn(t.unwrap())]:t instanceof an?[null,...xn(t.unwrap())]:t instanceof Yi||t instanceof Wr?xn(t.unwrap()):t instanceof Kr?xn(t._def.innerType):[],pa=class t extends he{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.object)return W(n,{code:z.invalid_type,expected:G.object,received:n.parsedType}),ie;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}):(W(n,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ie)}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 a=xn(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new t({typeName:oe.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...le(r)})}};Lr=class extends he{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(da(i)||da(a))return ie;let c=Ul(i.value,a.value);return c.valid?((ha(i)||ha(a))&&n.dirty(),{status:n.value,value:c.data}):(W(r,{code:z.invalid_intersection_types}),ie)};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,a])=>s(i,a)):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}))}};Lr.create=(t,e,n)=>new Lr({left:t,right:e,typeName:oe.ZodIntersection,...le(n)});on=class t extends he{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.array)return W(r,{code:z.invalid_type,expected:G.array,received:r.parsedType}),ie;if(r.data.length<this._def.items.length)return W(r,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ie;!this._def.rest&&r.data.length>this._def.items.length&&(W(r,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Rt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Je.mergeArray(n,a)):Je.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};on.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new on({items:t,typeName:oe.ZodTuple,rest:null,...le(e)})};fa=class t extends he{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!==G.object)return W(r,{code:z.invalid_type,expected:G.object,received:r.parsedType}),ie;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new Rt(r,c,r.path,c)),value:a._parse(new Rt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Je.mergeObjectAsync(n,s):Je.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof he?new t({keyType:e,valueType:n,typeName:oe.ZodRecord,...le(r)}):new t({keyType:Yn.create(),valueType:e,typeName:oe.ZodRecord,...le(n)})}},ei=class extends he{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!==G.map)return W(r,{code:z.invalid_type,expected:G.map,received:r.parsedType}),ie;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:s._parse(new Rt(r,c,r.path,[u,"key"])),value:i._parse(new Rt(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return ie;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return ie;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}}}};ei.create=(t,e,n)=>new ei({valueType:e,keyType:t,typeName:oe.ZodMap,...le(n)});ti=class t extends he{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.set)return W(r,{code:z.invalid_type,expected:G.set,received:r.parsedType}),ie;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(W(r,{code:z.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&&(W(r,{code:z.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let u=new Set;for(let p of l){if(p.status==="aborted")return ie;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let c=[...r.data.values()].map((l,u)=>i._parse(new Rt(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(e,n){return new t({...this._def,minSize:{value:e,message:Q.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Q.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};ti.create=(t,e)=>new ti({valueType:t,minSize:null,maxSize:null,typeName:oe.ZodSet,...le(e)});ma=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.function)return W(n,{code:z.invalid_type,expected:G.function,received:n.parsedType}),ie;function r(c,l){return Ji({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zs(),_n].filter(u=>!!u),issueData:{code:z.invalid_arguments,argumentsError:l}})}function s(c,l){return Ji({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zs(),_n].filter(u=>!!u),issueData:{code:z.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Qn){let c=this;return tt(async function(...l){let u=new ut([]),p=await c._def.args.parseAsync(l,i).catch(w=>{throw u.addIssue(r(l,w)),u}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let c=this;return tt(function(...l){let u=c._def.args.safeParse(l,i);if(!u.success)throw new ut([r(l,u.error)]);let p=Reflect.apply(a,this,u.data),f=c._def.returns.safeParse(p,i);if(!f.success)throw new ut([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:on.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||on.create([]).rest(Tn.create()),returns:n||Tn.create(),typeName:oe.ZodFunction,...le(r)})}},Ur=class extends he{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})}};Ur.create=(t,e)=>new Ur({getter:t,typeName:oe.ZodLazy,...le(e)});qr=class extends he{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return W(n,{received:n.data,code:z.invalid_literal,expected:this._def.value}),ie}return{status:"valid",value:e.data}}get value(){return this._def.value}};qr.create=(t,e)=>new qr({value:t,typeName:oe.ZodLiteral,...le(e)});Fr=class t extends he{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return W(n,{expected:fe.joinValues(r),received:n.parsedType,code:z.invalid_type}),ie}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 W(n,{received:n.data,code:z.invalid_enum_value,options:r}),ie}return tt(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})}};Fr.create=jp;Br=class extends he{_parse(e){let n=fe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==G.string&&r.parsedType!==G.number){let s=fe.objectValues(n);return W(r,{expected:fe.joinValues(s),received:r.parsedType,code:z.invalid_type}),ie}if(this._cache||(this._cache=new Set(fe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=fe.objectValues(n);return W(r,{received:r.data,code:z.invalid_enum_value,options:s}),ie}return tt(e.data)}get enum(){return this._def.values}};Br.create=(t,e)=>new Br({values:t,typeName:oe.ZodNativeEnum,...le(e)});Qn=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.promise&&n.common.async===!1)return W(n,{code:z.invalid_type,expected:G.promise,received:n.parsedType}),ie;let r=n.parsedType===G.promise?n.data:Promise.resolve(n.data);return tt(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Qn.create=(t,e)=>new Qn({type:t,typeName:oe.ZodPromise,...le(e)});It=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.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:a=>{W(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return ie;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?ie:l.status==="dirty"?Cr(l.value):n.value==="dirty"?Cr(l.value):l});{if(n.value==="aborted")return ie;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ie:c.status==="dirty"?Cr(c.value):n.value==="dirty"?Cr(c.value):c}}if(s.type==="refinement"){let a=c=>{let l=s.refinement(c,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?ie:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?ie:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Jn(a))return ie;let c=s.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Jn(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):ie);fe.assertNever(s)}};It.create=(t,e,n)=>new It({schema:t,typeName:oe.ZodEffects,effect:e,...le(n)});It.createWithPreprocess=(t,e,n)=>new It({schema:e,effect:{type:"preprocess",transform:t},typeName:oe.ZodEffects,...le(n)});Tt=class extends he{_parse(e){return this._getType(e)===G.undefined?tt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Tt.create=(t,e)=>new Tt({innerType:t,typeName:oe.ZodOptional,...le(e)});an=class extends he{_parse(e){return this._getType(e)===G.null?tt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};an.create=(t,e)=>new an({innerType:t,typeName:oe.ZodNullable,...le(e)});Hr=class extends he{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===G.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Hr.create=(t,e)=>new Hr({innerType:t,typeName:oe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...le(e)});Kr=class extends he{_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 Js(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ut(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ut(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Kr.create=(t,e)=>new Kr({innerType:t,typeName:oe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...le(e)});ni=class extends he{_parse(e){if(this._getType(e)!==G.nan){let r=this._getOrReturnCtx(e);return W(r,{code:z.invalid_type,expected:G.nan,received:r.parsedType}),ie}return{status:"valid",value:e.data}}};ni.create=t=>new ni({typeName:oe.ZodNaN,...le(t)});H0=Symbol("zod_brand"),Yi=class extends he{_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}},Xi=class t extends he{_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"?ie:i.status==="dirty"?(n.dirty(),Cr(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"?ie: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:oe.ZodPipeline})}},Wr=class extends he{_parse(e){let n=this._def.innerType._parse(e),r=s=>(Jn(s)&&(s.value=Object.freeze(s.value)),s);return Js(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Wr.create=(t,e)=>new Wr({innerType:t,typeName:oe.ZodReadonly,...le(e)});K0={object:dt.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"})(oe||(oe={}));W0=(t,e={message:`Input not instance of ${t.name}`})=>Mp(n=>n instanceof t,e),Op=Yn.create,zp=Pr.create,G0=ni.create,V0=Nr.create,Dp=jr.create,Z0=Mr.create,J0=Xs.create,Y0=Or.create,X0=zr.create,Q0=Xn.create,eS=Tn.create,tS=Kt.create,nS=Qs.create,rS=Rn.create,sS=dt.create,iS=dt.strictCreate,oS=Dr.create,aS=pa.create,cS=Lr.create,lS=on.create,uS=fa.create,dS=ei.create,hS=ti.create,pS=ma.create,fS=Ur.create,mS=qr.create,gS=Fr.create,yS=Br.create,bS=Qn.create,wS=It.create,vS=Tt.create,kS=an.create,SS=It.createWithPreprocess,_S=Xi.create,xS=()=>Op().optional(),TS=()=>zp().optional(),RS=()=>Dp().optional(),IS={string:(t=>Yn.create({...t,coerce:!0})),number:(t=>Pr.create({...t,coerce:!0})),boolean:(t=>jr.create({...t,coerce:!0})),bigint:(t=>Nr.create({...t,coerce:!0})),date:(t=>Mr.create({...t,coerce:!0}))},ES=ie});var k={};Fe(k,{BRAND:()=>H0,DIRTY:()=>Cr,EMPTY_PATH:()=>S0,INVALID:()=>ie,NEVER:()=>ES,OK:()=>tt,ParseStatus:()=>Je,Schema:()=>he,ZodAny:()=>Xn,ZodArray:()=>Rn,ZodBigInt:()=>Nr,ZodBoolean:()=>jr,ZodBranded:()=>Yi,ZodCatch:()=>Kr,ZodDate:()=>Mr,ZodDefault:()=>Hr,ZodDiscriminatedUnion:()=>pa,ZodEffects:()=>It,ZodEnum:()=>Fr,ZodError:()=>ut,ZodFirstPartyTypeKind:()=>oe,ZodFunction:()=>ma,ZodIntersection:()=>Lr,ZodIssueCode:()=>z,ZodLazy:()=>Ur,ZodLiteral:()=>qr,ZodMap:()=>ei,ZodNaN:()=>ni,ZodNativeEnum:()=>Br,ZodNever:()=>Kt,ZodNull:()=>zr,ZodNullable:()=>an,ZodNumber:()=>Pr,ZodObject:()=>dt,ZodOptional:()=>Tt,ZodParsedType:()=>G,ZodPipeline:()=>Xi,ZodPromise:()=>Qn,ZodReadonly:()=>Wr,ZodRecord:()=>fa,ZodSchema:()=>he,ZodSet:()=>ti,ZodString:()=>Yn,ZodSymbol:()=>Xs,ZodTransformer:()=>It,ZodTuple:()=>on,ZodType:()=>he,ZodUndefined:()=>Or,ZodUnion:()=>Dr,ZodUnknown:()=>Tn,ZodVoid:()=>Qs,addIssueToContext:()=>W,any:()=>Q0,array:()=>rS,bigint:()=>V0,boolean:()=>Dp,coerce:()=>IS,custom:()=>Mp,date:()=>Z0,datetimeRegex:()=>Np,defaultErrorMap:()=>_n,discriminatedUnion:()=>aS,effect:()=>wS,enum:()=>gS,function:()=>pS,getErrorMap:()=>Zs,getParsedType:()=>sn,instanceof:()=>W0,intersection:()=>cS,isAborted:()=>da,isAsync:()=>Js,isDirty:()=>ha,isValid:()=>Jn,late:()=>K0,lazy:()=>fS,literal:()=>mS,makeIssue:()=>Ji,map:()=>dS,nan:()=>G0,nativeEnum:()=>yS,never:()=>tS,null:()=>X0,nullable:()=>kS,number:()=>zp,object:()=>sS,objectUtil:()=>Ol,oboolean:()=>RS,onumber:()=>TS,optional:()=>vS,ostring:()=>xS,pipeline:()=>_S,preprocess:()=>SS,promise:()=>bS,quotelessJson:()=>w0,record:()=>uS,set:()=>hS,setErrorMap:()=>k0,strictObject:()=>iS,string:()=>Op,symbol:()=>J0,transformer:()=>wS,tuple:()=>lS,undefined:()=>Y0,union:()=>oS,unknown:()=>eS,util:()=>fe,void:()=>nS});var ql=J(()=>{ua();Dl();Ip();Zi();Lp();la()});var ht=J(()=>{ql();ql()});function X(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ya.default.join(ga.default.homedir(),".config","allwright"),n=ya.default.join(ga.default.homedir(),".config","ticketpilot");return!In.default.existsSync(e)&&In.default.existsSync(n)?n:e}function En(){return ya.default.join(X(),"runner.json")}function ke(){let t=En();if(!In.default.existsSync(t))return null;let e=JSON.parse(In.default.readFileSync(t,"utf8"));return Fl.parse(e)}function xe(t){let e=X();In.default.mkdirSync(e,{recursive:!0,mode:448});let n=En(),r=n+".tmp";In.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384}),In.default.renameSync(r,n),In.default.chmodSync(n,384)}function ba(t,e){return`${t}:${e}`}function cn(t,e,n){return t.environments[ba(e,n)]?.secrets??{}}function Qi(t,e){return t.repos[e]?.jira??t.jira}function eo(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ge(){let t=ke();if(!t)throw new Error(`No runner config found at ${En()}. Run \`allwright init\` first.`);return t}var In,ga,ya,Up,Fl,Te=J(()=>{"use strict";In=E(require("node:fs"),1),ga=E(require("node:os"),1),ya=E(require("node:path"),1);ht();Up=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Fl=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(ga.default.hostname()),jira:Up.optional(),repos:k.record(k.object({path:k.string(),jira:Up.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)})});var to=be(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.getParsedType=Re.ZodParsedType=Re.objectUtil=Re.util=void 0;var Bl;(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 a of s)i[a]=a;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(let c of i)a[c]=s[c];return t.objectValues(a)},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 a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(let a of s)if(i(a))return a},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(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Bl||(Re.util=Bl={}));var Bp;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Bp||(Re.objectUtil=Bp={}));Re.ZodParsedType=Bl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var CS=t=>{switch(typeof t){case"undefined":return Re.ZodParsedType.undefined;case"string":return Re.ZodParsedType.string;case"number":return Number.isNaN(t)?Re.ZodParsedType.nan:Re.ZodParsedType.number;case"boolean":return Re.ZodParsedType.boolean;case"function":return Re.ZodParsedType.function;case"bigint":return Re.ZodParsedType.bigint;case"symbol":return Re.ZodParsedType.symbol;case"object":return Array.isArray(t)?Re.ZodParsedType.array:t===null?Re.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Re.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?Re.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?Re.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?Re.ZodParsedType.date:Re.ZodParsedType.object;default:return Re.ZodParsedType.unknown}};Re.getParsedType=CS});var ka=be(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.ZodError=er.quotelessJson=er.ZodIssueCode=void 0;var Hp=to();er.ZodIssueCode=Hp.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var PS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");er.quotelessJson=PS;var no=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 a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};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,Hp.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};er.ZodError=no;no.create=t=>new no(t)});var Kl=be(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var nt=ka(),Gr=to(),NS=(t,e)=>{let n;switch(t.code){case nt.ZodIssueCode.invalid_type:t.received===Gr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case nt.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Gr.util.jsonStringifyReplacer)}`;break;case nt.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Gr.util.joinValues(t.keys,", ")}`;break;case nt.ZodIssueCode.invalid_union:n="Invalid input";break;case nt.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Gr.util.joinValues(t.options)}`;break;case nt.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Gr.util.joinValues(t.options)}, received '${t.received}'`;break;case nt.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case nt.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case nt.ZodIssueCode.invalid_date:n="Invalid date";break;case nt.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Gr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case nt.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case nt.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case nt.ZodIssueCode.custom:n="Invalid input";break;case nt.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case nt.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case nt.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Gr.util.assertNever(t)}return{message:n}};Hl.default=NS});var Sa=be(tr=>{"use strict";var jS=tr&&tr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tr,"__esModule",{value:!0});tr.defaultErrorMap=void 0;tr.setErrorMap=MS;tr.getErrorMap=OS;var Kp=jS(Kl());tr.defaultErrorMap=Kp.default;var Wp=Kp.default;function MS(t){Wp=t}function OS(){return Wp}});var Gl=be(we=>{"use strict";var zS=we&&we.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(we,"__esModule",{value:!0});we.isAsync=we.isValid=we.isDirty=we.isAborted=we.OK=we.DIRTY=we.INVALID=we.ParseStatus=we.EMPTY_PATH=we.makeIssue=void 0;we.addIssueToContext=US;var DS=Sa(),Gp=zS(Kl()),LS=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}};we.makeIssue=LS;we.EMPTY_PATH=[];function US(t,e){let n=(0,DS.getErrorMap)(),r=(0,we.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Gp.default?void 0:Gp.default].filter(s=>!!s)});t.common.issues.push(r)}var Wl=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 we.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,a=await s.value;r.push({key:i,value:a})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return we.INVALID;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}};we.ParseStatus=Wl;we.INVALID=Object.freeze({status:"aborted"});var qS=t=>({status:"dirty",value:t});we.DIRTY=qS;var FS=t=>({status:"valid",value:t});we.OK=FS;var BS=t=>t.status==="aborted";we.isAborted=BS;var HS=t=>t.status==="dirty";we.isDirty=HS;var KS=t=>t.status==="valid";we.isValid=KS;var WS=t=>typeof Promise<"u"&&t instanceof Promise;we.isAsync=WS});var Zp=be(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0})});var Yp=be(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.errorUtil=void 0;var Jp;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Jp||(_a.errorUtil=Jp={}))});var uf=be(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.discriminatedUnion=R.date=R.boolean=R.bigint=R.array=R.any=R.coerce=R.ZodFirstPartyTypeKind=R.late=R.ZodSchema=R.Schema=R.ZodReadonly=R.ZodPipeline=R.ZodBranded=R.BRAND=R.ZodNaN=R.ZodCatch=R.ZodDefault=R.ZodNullable=R.ZodOptional=R.ZodTransformer=R.ZodEffects=R.ZodPromise=R.ZodNativeEnum=R.ZodEnum=R.ZodLiteral=R.ZodLazy=R.ZodFunction=R.ZodSet=R.ZodMap=R.ZodRecord=R.ZodTuple=R.ZodIntersection=R.ZodDiscriminatedUnion=R.ZodUnion=R.ZodObject=R.ZodArray=R.ZodVoid=R.ZodNever=R.ZodUnknown=R.ZodAny=R.ZodNull=R.ZodUndefined=R.ZodSymbol=R.ZodDate=R.ZodBoolean=R.ZodBigInt=R.ZodNumber=R.ZodString=R.ZodType=void 0;R.NEVER=R.void=R.unknown=R.union=R.undefined=R.tuple=R.transformer=R.symbol=R.string=R.strictObject=R.set=R.record=R.promise=R.preprocess=R.pipeline=R.ostring=R.optional=R.onumber=R.oboolean=R.object=R.number=R.nullable=R.null=R.never=R.nativeEnum=R.nan=R.map=R.literal=R.lazy=R.intersection=R.instanceof=R.function=R.enum=R.effect=void 0;R.datetimeRegex=nf;R.custom=sf;var q=ka(),xa=Sa(),ne=Yp(),I=Gl(),H=to(),At=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}},Xp=(t,e)=>{if((0,I.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new q.ZodError(t.common.issues);return this._error=n,this._error}}};function ue(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:(a,c)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},description:s}}var de=class{get description(){return this._def.description}_getType(e){return(0,H.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,H.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,H.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,I.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,H.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Xp(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,H.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,I.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,I.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,H.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,I.isAsync)(s)?s:Promise.resolve(s));return Xp(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 a=e(s),c=()=>i.addIssue({code:q.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!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 yt({schema:this,typeName:ce.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 Et.create(this,this._def)}nullable(){return un.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cn.create(this)}promise(){return sr.create(this,this._def)}or(e){return es.create([this,e],this._def)}and(e){return ts.create(this,e,this._def)}transform(e){return new yt({...ue(this._def),schema:this,typeName:ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new os({...ue(this._def),innerType:this,defaultValue:n,typeName:ce.ZodDefault})}brand(){return new ro({typeName:ce.ZodBranded,type:this,...ue(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new as({...ue(this._def),innerType:this,catchValue:n,typeName:ce.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return so.create(this,e)}readonly(){return cs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};R.ZodType=de;R.Schema=de;R.ZodSchema=de;var GS=/^c[^\s-]{8,}$/i,VS=/^[0-9a-z]+$/,ZS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,JS=/^[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,YS=/^[a-z0-9_-]{21}$/i,XS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QS=/^[-+]?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)?)??$/,e_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,t_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Vl,n_=/^(?:(?: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])$/,r_=/^(?:(?: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])$/,s_=/^(([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]))$/,i_=/^(([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])$/,o_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,a_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ef="((\\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])))",c_=new RegExp(`^${ef}$`);function tf(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 l_(t){return new RegExp(`^${tf(t)}$`)}function nf(t){let e=`${ef}T${tf(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 u_(t,e){return!!((e==="v4"||!e)&&n_.test(t)||(e==="v6"||!e)&&s_.test(t))}function d_(t,e){if(!XS.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 h_(t,e){return!!((e==="v4"||!e)&&r_.test(t)||(e==="v6"||!e)&&i_.test(t))}var nr=class t extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.string,received:i.parsedType}),I.INVALID}let r=new I.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")e_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"email",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Vl||(Vl=new RegExp(t_,"u")),Vl.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"emoji",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")JS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"uuid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")YS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"nanoid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")GS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"cuid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")VS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"cuid2",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ZS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"ulid",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"url",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"regex",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?nf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?c_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?l_(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?QS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"duration",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?u_(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"ip",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?d_(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"jwt",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?h_(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"cidr",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?o_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"base64",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?a_.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"base64url",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):H.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:q.ZodIssueCode.invalid_string,...ne.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ne.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ne.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ne.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ne.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ne.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ne.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ne.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ne.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ne.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ne.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ne.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ne.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ne.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ne.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ne.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ne.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...ne.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...ne.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...ne.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...ne.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...ne.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...ne.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...ne.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,ne.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};R.ZodString=nr;nr.create=t=>new nr({checks:[],typeName:ce.ZodString,coerce:t?.coerce??!1,...ue(t)});function p_(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(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}var Vr=class t extends de{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)!==H.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.number,received:i.parsedType}),I.INVALID}let r,s=new I.ParseStatus;for(let i of this._def.checks)i.kind==="int"?H.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?p_(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.not_finite,message:i.message}),s.dirty()):H.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,ne.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ne.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ne.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ne.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ne.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ne.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ne.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ne.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ne.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ne.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ne.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:ne.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ne.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ne.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};R.ZodNumber=Vr;Vr.create=t=>new Vr({checks:[],typeName:ce.ZodNumber,coerce:t?.coerce||!1,...ue(t)});var Zr=class t extends de{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)!==H.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new I.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):H.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.bigint,received:n.parsedType}),I.INVALID}gte(e,n){return this.setLimit("min",e,!0,ne.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ne.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ne.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ne.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ne.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ne.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ne.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ne.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ne.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ne.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};R.ZodBigInt=Zr;Zr.create=t=>new Zr({checks:[],typeName:ce.ZodBigInt,coerce:t?.coerce??!1,...ue(t)});var Jr=class extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.boolean,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodBoolean=Jr;Jr.create=t=>new Jr({typeName:ce.ZodBoolean,coerce:t?.coerce||!1,...ue(t)});var Yr=class t extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.date,received:i.parsedType}),I.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_date}),I.INVALID}let r=new I.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{code:q.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):H.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:ne.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:ne.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};R.ZodDate=Yr;Yr.create=t=>new Yr({checks:[],coerce:t?.coerce||!1,typeName:ce.ZodDate,...ue(t)});var si=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.symbol,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodSymbol=si;si.create=t=>new si({typeName:ce.ZodSymbol,...ue(t)});var Xr=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.undefined,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodUndefined=Xr;Xr.create=t=>new Xr({typeName:ce.ZodUndefined,...ue(t)});var Qr=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.null,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodNull=Qr;Qr.create=t=>new Qr({typeName:ce.ZodNull,...ue(t)});var rr=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodAny=rr;rr.create=t=>new rr({typeName:ce.ZodAny,...ue(t)});var $n=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodUnknown=$n;$n.create=t=>new $n({typeName:ce.ZodUnknown,...ue(t)});var Wt=class extends de{_parse(e){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.never,received:n.parsedType}),I.INVALID}};R.ZodNever=Wt;Wt.create=t=>new Wt({typeName:ce.ZodNever,...ue(t)});var ii=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.void,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodVoid=ii;ii.create=t=>new ii({typeName:ce.ZodVoid,...ue(t)});var Cn=class t extends de{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==H.ZodParsedType.array)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.array,received:n.parsedType}),I.INVALID;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&((0,I.addIssueToContext)(n,{code:a?q.ZodIssueCode.too_big:q.ZodIssueCode.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,I.addIssueToContext)(n,{code:q.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,I.addIssueToContext)(n,{code:q.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new At(n,a,n.path,c)))).then(a=>I.ParseStatus.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new At(n,a,n.path,c)));return I.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:ne.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:ne.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:ne.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};R.ZodArray=Cn;Cn.create=(t,e)=>new Cn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ce.ZodArray,...ue(e)});function ri(t){if(t instanceof pt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Et.create(ri(r))}return new pt({...t._def,shape:()=>e})}else return t instanceof Cn?new Cn({...t._def,type:ri(t.element)}):t instanceof Et?Et.create(ri(t.unwrap())):t instanceof un?un.create(ri(t.unwrap())):t instanceof ln?ln.create(t.items.map(e=>ri(e))):t}var pt=class t extends de{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=H.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==H.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(u,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.object,received:u.parsedType}),I.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Wt&&this._def.unknownKeys==="strip"))for(let u in s.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let p=i[u],f=s.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new At(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Wt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")c.length>0&&((0,I.addIssueToContext)(s,{code:q.ZodIssueCode.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new At(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let f=await p.key,m=await p.value;u.push({key:f,value:m,alwaysSet:p.alwaysSet})}return u}).then(u=>I.ParseStatus.mergeObjectSync(r,u)):I.ParseStatus.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return ne.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:ne.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ce.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 H.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of H.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ri(this)}partial(e){let n={};for(let r of H.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of H.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Et;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return rf(H.util.objectKeys(this.shape))}};R.ZodObject=pt;pt.create=(t,e)=>new pt({shape:()=>t,unknownKeys:"strip",catchall:Wt.create(),typeName:ce.ZodObject,...ue(e)});pt.strictCreate=(t,e)=>new pt({shape:()=>t,unknownKeys:"strict",catchall:Wt.create(),typeName:ce.ZodObject,...ue(e)});pt.lazycreate=(t,e)=>new pt({shape:t,unknownKeys:"strip",catchall:Wt.create(),typeName:ce.ZodObject,...ue(e)});var es=class extends de{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new q.ZodError(c.ctx.common.issues));return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_union,unionErrors:a}),I.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new q.ZodError(l));return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_union,unionErrors:c}),I.INVALID}}get options(){return this._def.options}};R.ZodUnion=es;es.create=(t,e)=>new es({options:t,typeName:ce.ZodUnion,...ue(e)});var An=t=>t instanceof ns?An(t.schema):t instanceof yt?An(t.innerType()):t instanceof rs?[t.value]:t instanceof ss?t.options:t instanceof is?H.util.objectValues(t.enum):t instanceof os?An(t._def.innerType):t instanceof Xr?[void 0]:t instanceof Qr?[null]:t instanceof Et?[void 0,...An(t.unwrap())]:t instanceof un?[null,...An(t.unwrap())]:t instanceof ro||t instanceof cs?An(t.unwrap()):t instanceof as?An(t._def.innerType):[],Ta=class t extends de{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.ZodParsedType.object)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.object,received:n.parsedType}),I.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),I.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let a=An(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new t({typeName:ce.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ue(r)})}};R.ZodDiscriminatedUnion=Ta;function Zl(t,e){let n=(0,H.getParsedType)(t),r=(0,H.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===H.ZodParsedType.object&&r===H.ZodParsedType.object){let s=H.util.objectKeys(e),i=H.util.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=Zl(t[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===H.ZodParsedType.array&&r===H.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=e[i],l=Zl(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===H.ZodParsedType.date&&r===H.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ts=class extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if((0,I.isAborted)(i)||(0,I.isAborted)(a))return I.INVALID;let c=Zl(i.value,a.value);return c.valid?(((0,I.isDirty)(i)||(0,I.isDirty)(a))&&n.dirty(),{status:n.value,value:c.data}):((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_intersection_types}),I.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):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}))}};R.ZodIntersection=ts;ts.create=(t,e,n)=>new ts({left:t,right:e,typeName:ce.ZodIntersection,...ue(n)});var ln=class t extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.ZodParsedType.array)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.array,received:r.parsedType}),I.INVALID;if(r.data.length<this._def.items.length)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new At(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>I.ParseStatus.mergeArray(n,a)):I.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};R.ZodTuple=ln;ln.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ln({items:t,typeName:ce.ZodTuple,rest:null,...ue(e)})};var Ra=class t extends de{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!==H.ZodParsedType.object)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.object,received:r.parsedType}),I.INVALID;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new At(r,c,r.path,c)),value:a._parse(new At(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?I.ParseStatus.mergeObjectAsync(n,s):I.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof de?new t({keyType:e,valueType:n,typeName:ce.ZodRecord,...ue(r)}):new t({keyType:nr.create(),valueType:e,typeName:ce.ZodRecord,...ue(n)})}};R.ZodRecord=Ra;var oi=class extends de{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!==H.ZodParsedType.map)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.map,received:r.parsedType}),I.INVALID;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:s._parse(new At(r,c,r.path,[u,"key"])),value:i._parse(new At(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return I.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return I.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(u.value,p.value)}return{status:n.value,value:c}}}};R.ZodMap=oi;oi.create=(t,e,n)=>new oi({valueType:e,keyType:t,typeName:ce.ZodMap,...ue(n)});var ai=class t extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.ZodParsedType.set)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.set,received:r.parsedType}),I.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,I.addIssueToContext)(r,{code:q.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(l){let u=new Set;for(let p of l){if(p.status==="aborted")return I.INVALID;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let c=[...r.data.values()].map((l,u)=>i._parse(new At(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(e,n){return new t({...this._def,minSize:{value:e,message:ne.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:ne.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};R.ZodSet=ai;ai.create=(t,e)=>new ai({valueType:t,minSize:null,maxSize:null,typeName:ce.ZodSet,...ue(e)});var Ia=class t extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.ZodParsedType.function)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.function,received:n.parsedType}),I.INVALID;function r(c,l){return(0,I.makeIssue)({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,xa.getErrorMap)(),xa.defaultErrorMap].filter(u=>!!u),issueData:{code:q.ZodIssueCode.invalid_arguments,argumentsError:l}})}function s(c,l){return(0,I.makeIssue)({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,xa.getErrorMap)(),xa.defaultErrorMap].filter(u=>!!u),issueData:{code:q.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof sr){let c=this;return(0,I.OK)(async function(...l){let u=new q.ZodError([]),p=await c._def.args.parseAsync(l,i).catch(w=>{throw u.addIssue(r(l,w)),u}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let c=this;return(0,I.OK)(function(...l){let u=c._def.args.safeParse(l,i);if(!u.success)throw new q.ZodError([r(l,u.error)]);let p=Reflect.apply(a,this,u.data),f=c._def.returns.safeParse(p,i);if(!f.success)throw new q.ZodError([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ln.create(e).rest($n.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||ln.create([]).rest($n.create()),returns:n||$n.create(),typeName:ce.ZodFunction,...ue(r)})}};R.ZodFunction=Ia;var ns=class extends de{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})}};R.ZodLazy=ns;ns.create=(t,e)=>new ns({getter:t,typeName:ce.ZodLazy,...ue(e)});var rs=class extends de{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{received:n.data,code:q.ZodIssueCode.invalid_literal,expected:this._def.value}),I.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};R.ZodLiteral=rs;rs.create=(t,e)=>new rs({value:t,typeName:ce.ZodLiteral,...ue(e)});function rf(t,e){return new ss({values:t,typeName:ce.ZodEnum,...ue(e)})}var ss=class t extends de{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,I.addIssueToContext)(n,{expected:H.util.joinValues(r),received:n.parsedType,code:q.ZodIssueCode.invalid_type}),I.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,I.addIssueToContext)(n,{received:n.data,code:q.ZodIssueCode.invalid_enum_value,options:r}),I.INVALID}return(0,I.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};R.ZodEnum=ss;ss.create=rf;var is=class extends de{_parse(e){let n=H.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==H.ZodParsedType.string&&r.parsedType!==H.ZodParsedType.number){let s=H.util.objectValues(n);return(0,I.addIssueToContext)(r,{expected:H.util.joinValues(s),received:r.parsedType,code:q.ZodIssueCode.invalid_type}),I.INVALID}if(this._cache||(this._cache=new Set(H.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=H.util.objectValues(n);return(0,I.addIssueToContext)(r,{received:r.data,code:q.ZodIssueCode.invalid_enum_value,options:s}),I.INVALID}return(0,I.OK)(e.data)}get enum(){return this._def.values}};R.ZodNativeEnum=is;is.create=(t,e)=>new is({values:t,typeName:ce.ZodNativeEnum,...ue(e)});var sr=class extends de{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.ZodParsedType.promise&&n.common.async===!1)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.promise,received:n.parsedType}),I.INVALID;let r=n.parsedType===H.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,I.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};R.ZodPromise=sr;sr.create=(t,e)=>new sr({type:t,typeName:ce.ZodPromise,...ue(e)});var yt=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ce.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:a=>{(0,I.addIssueToContext)(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return I.INVALID;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?I.INVALID:l.status==="dirty"||n.value==="dirty"?(0,I.DIRTY)(l.value):l});{if(n.value==="aborted")return I.INVALID;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?I.INVALID:c.status==="dirty"||n.value==="dirty"?(0,I.DIRTY)(c.value):c}}if(s.type==="refinement"){let a=c=>{let l=s.refinement(c,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?I.INVALID:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?I.INVALID:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,I.isValid)(a))return I.INVALID;let c=s.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>(0,I.isValid)(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):I.INVALID);H.util.assertNever(s)}};R.ZodEffects=yt;R.ZodTransformer=yt;yt.create=(t,e,n)=>new yt({schema:t,typeName:ce.ZodEffects,effect:e,...ue(n)});yt.createWithPreprocess=(t,e,n)=>new yt({schema:e,effect:{type:"preprocess",transform:t},typeName:ce.ZodEffects,...ue(n)});var Et=class extends de{_parse(e){return this._getType(e)===H.ZodParsedType.undefined?(0,I.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodOptional=Et;Et.create=(t,e)=>new Et({innerType:t,typeName:ce.ZodOptional,...ue(e)});var un=class extends de{_parse(e){return this._getType(e)===H.ZodParsedType.null?(0,I.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodNullable=un;un.create=(t,e)=>new un({innerType:t,typeName:ce.ZodNullable,...ue(e)});var os=class extends de{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===H.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};R.ZodDefault=os;os.create=(t,e)=>new os({innerType:t,typeName:ce.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ue(e)});var as=class extends de{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,I.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new q.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new q.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};R.ZodCatch=as;as.create=(t,e)=>new as({innerType:t,typeName:ce.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ue(e)});var ci=class extends de{_parse(e){if(this._getType(e)!==H.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:H.ZodParsedType.nan,received:r.parsedType}),I.INVALID}return{status:"valid",value:e.data}}};R.ZodNaN=ci;ci.create=t=>new ci({typeName:ce.ZodNaN,...ue(t)});R.BRAND=Symbol("zod_brand");var ro=class extends de{_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}};R.ZodBranded=ro;var so=class t extends de{_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"?I.INVALID:i.status==="dirty"?(n.dirty(),(0,I.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?I.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:ce.ZodPipeline})}};R.ZodPipeline=so;var cs=class extends de{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,I.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,I.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};R.ZodReadonly=cs;cs.create=(t,e)=>new cs({innerType:t,typeName:ce.ZodReadonly,...ue(e)});function Qp(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function sf(t,e={},n){return t?rr.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=Qp(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=Qp(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):rr.create()}R.late={object:pt.lazycreate};var ce;(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"})(ce||(R.ZodFirstPartyTypeKind=ce={}));var f_=(t,e={message:`Input not instance of ${t.name}`})=>sf(n=>n instanceof t,e);R.instanceof=f_;var of=nr.create;R.string=of;var af=Vr.create;R.number=af;var m_=ci.create;R.nan=m_;var g_=Zr.create;R.bigint=g_;var cf=Jr.create;R.boolean=cf;var y_=Yr.create;R.date=y_;var b_=si.create;R.symbol=b_;var w_=Xr.create;R.undefined=w_;var v_=Qr.create;R.null=v_;var k_=rr.create;R.any=k_;var S_=$n.create;R.unknown=S_;var __=Wt.create;R.never=__;var x_=ii.create;R.void=x_;var T_=Cn.create;R.array=T_;var R_=pt.create;R.object=R_;var I_=pt.strictCreate;R.strictObject=I_;var E_=es.create;R.union=E_;var A_=Ta.create;R.discriminatedUnion=A_;var $_=ts.create;R.intersection=$_;var C_=ln.create;R.tuple=C_;var P_=Ra.create;R.record=P_;var N_=oi.create;R.map=N_;var j_=ai.create;R.set=j_;var M_=Ia.create;R.function=M_;var O_=ns.create;R.lazy=O_;var z_=rs.create;R.literal=z_;var D_=ss.create;R.enum=D_;var L_=is.create;R.nativeEnum=L_;var U_=sr.create;R.promise=U_;var lf=yt.create;R.effect=lf;R.transformer=lf;var q_=Et.create;R.optional=q_;var F_=un.create;R.nullable=F_;var B_=yt.createWithPreprocess;R.preprocess=B_;var H_=so.create;R.pipeline=H_;var K_=()=>of().optional();R.ostring=K_;var W_=()=>af().optional();R.onumber=W_;var G_=()=>cf().optional();R.oboolean=G_;R.coerce={string:(t=>nr.create({...t,coerce:!0})),number:(t=>Vr.create({...t,coerce:!0})),boolean:(t=>Jr.create({...t,coerce:!0})),bigint:(t=>Zr.create({...t,coerce:!0})),date:(t=>Yr.create({...t,coerce:!0}))};R.NEVER=I.INVALID});var Jl=be($t=>{"use strict";var V_=$t&&$t.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),li=$t&&$t.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&V_(e,t,n)};Object.defineProperty($t,"__esModule",{value:!0});li(Sa(),$t);li(Gl(),$t);li(Zp(),$t);li(to(),$t);li(uf(),$t);li(ka(),$t)});var pf=be(ft=>{"use strict";var df=ft&&ft.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Z_=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),J_=ft&&ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&df(e,t,n);return Z_(e,t),e},Y_=ft&&ft.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&df(e,t,n)};Object.defineProperty(ft,"__esModule",{value:!0});ft.z=void 0;var hf=J_(Jl());ft.z=hf;Y_(Jl(),ft);ft.default=hf});var Me=be(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.RunContextMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.AiSpendMsg=h.AI_SPEND_SURFACES=h.MONITOR_CATALOG=h.MONITOR_BASELINE_TYPES=h.MONITOR_PARAM_SCHEMAS=h.MonitorCheckConfig=h.MonitorParseRules=h.MonitorCommand=h.MonitorSchedule=h.MonitorStatus=h.RuleConfig=h.PACK_CATALOG=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.DEPLOY_DOC_CANDIDATES=h.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.TICKET_RULES_APPENDIX=h.COMPOSE_COMMANDS=h.MAX_FAILURE_CHARS=h.MAX_FAILURE_LINES=h.FAILURE_BLOCK_LINES=h.FAILURE_CONTEXT_LINES=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatSessionMsg=h.ChatActivityMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.JiraVersionsResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=void 0;h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupAskResultMsg=h.SetupAskMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatStepRunResultMsg=h.ChatStepRunMsg=h.ChatDiagnosticResultMsg=void 0;h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.RebirthStudyResultMsg=h.RebirthStudyUpdateMsg=h.RebirthStudyMsg=h.TimelineDigestResultMsg=h.TimelineDigestMsg=h.RebirthDesignResultMsg=h.RebirthDesignMsg=h.RebirthUploadChunkResultMsg=h.RebirthUploadChunkMsg=h.RebirthUploadBeginResultMsg=h.RebirthUploadBeginMsg=h.SiteAuditResultMsg=h.SiteAuditMsg=h.ServerDecommissionProgressMsg=h.ServerDecommissionResultMsg=h.ServerDecommissionExecuteMsg=h.ServerDecommissionPlanResultMsg=h.ServerDecommissionPlanMsg=h.MonitorDiscoverResultMsg=h.MonitorDiscoverMsg=h.MonitorRebaselineResultMsg=h.MonitorRebaselineMsg=h.MonitorSuggestResultMsg=h.MonitorSuggestMsg=h.MonitorRunResultMsg=h.MonitorRunMsg=h.MonitorResultMsg=h.ServerInventoryResultMsg=h.ServerInventoryMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.REVISION_PROMPT=h.FOCUSED_READING_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraVersionsMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=void 0;h.missingAgentCapabilities=X_;h.replyPreferenceAppendix=ex;h.monitorChecksAppendix=tx;h.pendingMigrationsAppendix=nx;h.deployTargetsAppendix=rx;h.savedStepChecksAppendix=sx;h.failureCollector=ff;h.failureLines=cx;h.composeCommandAppendix=lx;h.isSelfMigrationFilename=ux;h.parseRunnerMsg=dx;h.parseServerMsg=hx;var o=pf();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.124";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";h.DEPLOY_DOC_CANDIDATES=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"];h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0,fullAccess:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1,fullAccess:!1},suggestedModels:[],experimental:!0},{id:"kimi",displayName:"Moonshot Kimi Code CLI",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!0,costReporting:!1,modelSelection:!0,loginProfiles:!1,fullAccess:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"],operator:["fullAccess","sessionResume"]};function X_(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Q_=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=Q_;h.RunStatus=o.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=o.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=o.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=o.z.object({type:o.z.literal("label_added"),label:o.z.string().min(1),doneLabel:o.z.string().min(1).default("agent-planned"),failedLabel:o.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=o.z.object({type:o.z.literal("comment_keyword"),keyword:o.z.string().min(1),doneLabel:o.z.string().min(1).default("agent-implemented"),failedLabel:o.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=o.z.object({type:o.z.literal("status_changed"),status:o.z.string().min(1),doneLabel:o.z.string().min(1).default("agent-deployed"),failedLabel:o.z.string().min(1).default("agent-failed")});h.TriggerConfig=o.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=o.z.object({type:o.z.literal("plan_only"),promptTemplate:o.z.string().min(1),allowWeb:o.z.boolean().default(!1),timeoutSeconds:o.z.number().int().positive().max(3600).default(900),agent:o.z.string().default(h.DEFAULT_AGENT_ID),model:o.z.string().default("")});h.ImplementAction=o.z.object({type:o.z.literal("implement"),promptTemplate:o.z.string().min(1),timeoutSeconds:o.z.number().int().positive().max(7200).default(1800),maxTurns:o.z.number().int().positive().max(500).default(120),maxCostUsd:o.z.number().positive().optional(),requireApproval:o.z.boolean().default(!0),branchTemplate:o.z.string().min(1).default("agent/{{issueKey}}").refine(t=>t.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:o.z.string().min(1).default("main"),jiraTransition:o.z.string().optional(),jiraTransitionOnStart:o.z.string().optional(),jiraTransitionOnMerge:o.z.string().optional(),agent:o.z.string().default(h.DEFAULT_AGENT_ID),model:o.z.string().default(""),updateMemory:o.z.boolean().default(!1),allowWeb:o.z.boolean().default(!1),writeTests:o.z.boolean().default(!0),runTests:o.z.boolean().default(!0),mergeOnApprove:o.z.boolean().default(!0),mergeMethod:o.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:o.z.boolean().default(!0)});h.RespondAction=o.z.object({type:o.z.literal("respond"),promptTemplate:o.z.string().min(1),timeoutSeconds:o.z.number().int().positive().max(3600).default(600),agent:o.z.string().default(h.DEFAULT_AGENT_ID),model:o.z.string().default("")});h.DeployStep=o.z.object({name:o.z.string().min(1).max(120),run:o.z.string().min(1).max(4e3),continueOnError:o.z.boolean().default(!1)});h.PromotionMode=o.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=o.z.object({id:o.z.string(),projectId:o.z.string(),name:o.z.string(),rank:o.z.number().int().nonnegative(),auditBeforeDeploy:o.z.enum(["","security","testing"]).default(""),branch:o.z.string().default(""),publicUrl:o.z.string().default(""),servePath:o.z.string().default(""),useDedicatedCheckout:o.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:o.z.string().default("agent/{{issueKey}}"),steps:o.z.array(h.DeployStep).default([]),workdir:o.z.string().default(""),timeoutSeconds:o.z.number().int().positive().max(21600).default(1800),requiredSecrets:o.z.array(o.z.string()).default([]),requireApproval:o.z.boolean().default(!1),requireSyncCheck:o.z.boolean().default(!1),previousEnvBranch:o.z.string().optional(),deployFromColumn:o.z.string().default(""),deployToColumn:o.z.string().default("")});h.DeployAction=o.z.object({type:o.z.literal("deploy"),envSelection:o.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:o.z.string().optional(),requireStatus:o.z.string().optional()});h.ActionConfig=o.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=o.z.object({id:o.z.string(),name:o.z.string(),jiraProjectKey:o.z.string(),goLiveIssueKey:o.z.string().default(""),repoName:o.z.string(),jiraSiteUrl:o.z.string().default(""),defaultAgent:o.z.string().default("claude-code"),componentRoutes:o.z.array(o.z.object({component:o.z.string().min(1),repoName:o.z.string().min(1)})).default([]),packs:o.z.array(o.z.string().max(60)).max(40).default([])});h.PACK_CATALOG=[{id:"owasp",title:"OWASP Top 10",kind:"compliance",description:"Security audits cite OWASP Top 10 (2021) categories - findings carry OWASP-A01\u2026A10 ids.",roles:["security"]},{id:"pci-dss",title:"PCI DSS",kind:"compliance",description:"Payment-card compliance: findings cite PCI DSS requirement numbers (PCI-3.x, PCI-6.x\u2026).",roles:["security"]},{id:"gdpr",title:"GDPR build rules",kind:"compliance",description:"Implement runs follow GDPR build rules while WRITING code (GDPR-B01\u2026B09 - no PII in logs, retention ships with every new store, third-party sends are processor decisions). Security audits already check GDPR readiness globally; this adds the build-time half.",roles:["implement"]},{id:"laravel",title:"Laravel conventions",kind:"stack",description:"Laravel-specific rules for implement runs and architecture audits.",roles:["implement","architecture"]},{id:"react",title:"React conventions",kind:"stack",description:"React/Next-specific rules for implement runs and architecture audits.",roles:["implement","architecture"]},{id:"node",title:"Node.js backend conventions",kind:"stack",description:"Node/Express/Nest backend rules for implement runs and architecture audits.",roles:["implement","architecture"]}];h.RuleConfig=o.z.object({id:o.z.string(),projectId:o.z.string(),name:o.z.string(),enabled:o.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.MonitorStatus=o.z.enum(["green","amber","red","error","skipped"]);h.MonitorSchedule=o.z.discriminatedUnion("kind",[o.z.object({kind:o.z.literal("every"),minutes:o.z.number().int().min(1).max(1440)}),o.z.object({kind:o.z.literal("daily"),at:o.z.string().regex(/^\d{2}:\d{2}$/)}),o.z.object({kind:o.z.literal("weekly"),day:o.z.number().int().min(0).max(6),at:o.z.string().regex(/^\d{2}:\d{2}$/)})]);h.MonitorCommand=o.z.object({name:o.z.string().min(1).max(120),run:o.z.string().min(1).max(4e3)});h.MonitorParseRules=o.z.object({amberPattern:o.z.string().max(400).default(""),redPattern:o.z.string().max(400).default(""),greenRequires:o.z.string().max(400).default("")});h.MonitorCheckConfig=o.z.object({id:o.z.string(),type:o.z.string().max(60),name:o.z.string().min(1).max(120),projectId:o.z.string().default(""),params:o.z.record(o.z.unknown()).default({}),schedule:h.MonitorSchedule,shell:o.z.enum(["bash","powershell"]).default("bash"),commands:o.z.array(h.MonitorCommand).max(20).default([]),parseRules:h.MonitorParseRules.default({}),enabled:o.z.boolean().default(!0),jiraNotify:o.z.boolean().default(!1)});h.MONITOR_PARAM_SCHEMAS={disk_space:o.z.object({warnPct:o.z.number().int().min(1).max(99).default(80),critPct:o.z.number().int().min(1).max(99).default(90),mounts:o.z.array(o.z.string().max(300)).max(20).default([])}),memory:o.z.object({warnPct:o.z.number().int().min(1).max(99).default(85),critPct:o.z.number().int().min(1).max(99).default(95)}),cpu_load:o.z.object({warnPerCore:o.z.number().positive().max(64).default(2),critPerCore:o.z.number().positive().max(64).default(4)}),uptime_reboot:o.z.object({maxUptimeDays:o.z.number().int().positive().max(3650).default(180)}),services:o.z.object({names:o.z.array(o.z.string().min(1).max(120)).min(1).max(40)}),http_check:o.z.object({url:o.z.string().min(1).max(500),expectStatus:o.z.number().int().min(100).max(599).default(200),expectString:o.z.string().max(200).default(""),warnMs:o.z.number().int().positive().max(6e4).default(2e3),timeoutMs:o.z.number().int().positive().max(6e4).default(1e4)}),tls_cert:o.z.object({domains:o.z.array(o.z.string().min(1).max(253)).min(1).max(40),warnDays:o.z.number().int().min(1).max(365).default(21),critDays:o.z.number().int().min(0).max(364).default(7)}),sites:o.z.object({extraHosts:o.z.array(o.z.string().min(1).max(253)).max(30).default([]),excludeHosts:o.z.array(o.z.string().min(1).max(253)).max(30).default([]),warnMs:o.z.number().int().positive().max(6e4).default(3e3),certWarnDays:o.z.number().int().min(1).max(365).default(21),certCritDays:o.z.number().int().min(0).max(364).default(7)}),db_health:o.z.object({repoName:o.z.string().min(1).max(200),envName:o.z.string().min(1).max(100),secretName:o.z.string().min(1).max(100).default("DATABASE_URL"),warnConnections:o.z.number().int().positive().max(1e4).default(50),longQuerySeconds:o.z.number().int().positive().max(3600).default(60)}),docker_containers:o.z.object({expected:o.z.array(o.z.string().min(1).max(120)).max(40).default([])}),log_scan:o.z.object({files:o.z.array(o.z.string().min(1).max(400)).min(1).max(10),hardPatterns:o.z.array(o.z.string().max(200)).max(10).default(["oom-killer","kernel panic","segfault"]),errorPattern:o.z.string().max(200).default("\\b(error|fatal)\\b"),warnCount:o.z.number().int().positive().max(1e5).default(50),tailKB:o.z.number().int().min(16).max(1024).default(256)}),backup_freshness:o.z.object({noBackups:o.z.boolean().default(!1),targets:o.z.array(o.z.object({pathGlob:o.z.string().min(1).max(500),maxAgeHours:o.z.number().positive().max(2160).default(26),minSizeMB:o.z.number().nonnegative().max(1e6).default(1)})).max(20).default([])}),ports_baseline:o.z.object({}),users_baseline:o.z.object({}),cron_baseline:o.z.object({}),auth_activity:o.z.object({failedWarnCount:o.z.number().int().positive().max(1e5).default(100)}),webroot_integrity:o.z.object({roots:o.z.array(o.z.string().min(1).max(400)).min(1).max(10),excludes:o.z.array(o.z.string().min(1).max(200)).max(20).default(["node_modules",".git","cache","wp-content/uploads",".next","vendor"])}),wordpress:o.z.object({wpPaths:o.z.array(o.z.string().min(1).max(400)).min(1).max(10)}),process_hog:o.z.object({cpuPct:o.z.number().min(1).max(100).default(80)}),windows_update:o.z.object({maxHotfixAgeDays:o.z.number().int().positive().max(3650).default(60)}),custom:o.z.object({})};h.MONITOR_BASELINE_TYPES=["ports_baseline","users_baseline","cron_baseline","auth_activity","webroot_integrity","wordpress"];h.MONITOR_CATALOG=[{id:"disk_space",title:"Disk space",group:"health",question:"Is any filesystem filling up?",os:"both",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"memory",title:"Memory & swap",group:"health",question:"Is the machine under memory pressure?",os:"both",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"cpu_load",title:"CPU load",group:"health",question:"Is the load average sustainably high?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"uptime_reboot",title:"Uptime & pending restart",group:"health",question:"When did this box last boot, and does the OS want a reboot?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"06:00"}},{id:"services",title:"Services running",group:"health",question:"Are these named services active?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:5}},{id:"http_check",title:"HTTP check",group:"web",question:"Does this URL answer correctly, and fast enough?",os:"both",minMinutes:1,defaultSchedule:{kind:"every",minutes:5}},{id:"tls_cert",title:"TLS certificate expiry",group:"web",question:"How many days are left on these certificates?",os:"both",minMinutes:60,defaultSchedule:{kind:"daily",at:"07:00"}},{id:"backup_freshness",title:"Backup freshness",group:"backups",question:"Did a fresh, healthy-sized backup actually appear?",os:"both",minMinutes:60,defaultSchedule:{kind:"daily",at:"08:00"}},{id:"sites",title:"Sites this box serves",group:"web",question:"Every nginx/caddy/IIS vhost, live-probed: up, fast, certified?",os:"both",minMinutes:5,defaultSchedule:{kind:"every",minutes:15}},{id:"db_health",title:"Database health",group:"db",question:"Reachable, size, connections, long-running queries?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:30}},{id:"docker_containers",title:"Docker containers",group:"health",question:"Are the containers running - and staying up?",os:"linux",minMinutes:5,defaultSchedule:{kind:"every",minutes:5}},{id:"log_scan",title:"Log scan",group:"health",question:"Are named logs quiet - no OOM kills, no error spikes?",os:"linux",minMinutes:15,defaultSchedule:{kind:"every",minutes:60}},{id:"ports_baseline",title:"Listening ports vs baseline",group:"security",question:"Did a new port start listening that no one vouched for?",os:"both",minMinutes:30,defaultSchedule:{kind:"every",minutes:60}},{id:"users_baseline",title:"System users vs baseline",group:"security",question:"Did a new account appear - especially a root-level one?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:00"}},{id:"cron_baseline",title:"Cron vs baseline",group:"security",question:"Did any crontab change since a human last accepted it?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:10"}},{id:"auth_activity",title:"SSH & access grants",group:"security",question:"Brute-force spikes; new authorized_keys or sudoers grants?",os:"linux",minMinutes:30,defaultSchedule:{kind:"every",minutes:60}},{id:"webroot_integrity",title:"Webroot integrity",group:"security",question:"Did site files change outside a deploy?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:20"}},{id:"wordpress",title:"WordPress compromise signals",group:"security",question:"Core checksums, PHP in uploads, new admin users?",os:"linux",minMinutes:60,defaultSchedule:{kind:"daily",at:"05:30"}},{id:"process_hog",title:"Runaway process",group:"security",question:"Is something eating the CPU - from a location it shouldn't?",os:"linux",minMinutes:15,defaultSchedule:{kind:"every",minutes:30}},{id:"windows_update",title:"Windows updates",group:"health",question:"Pending reboot; how stale is the newest hotfix?",os:"windows",minMinutes:60,defaultSchedule:{kind:"daily",at:"06:30"}},{id:"custom",title:"Custom check",group:"custom",question:"Your own saved commands - exit code decides, patterns refine.",os:"both",minMinutes:5,defaultSchedule:{kind:"daily",at:"06:00"}}];h.AI_SPEND_SURFACES=[{id:"run_plan",label:"Plan runs",group:"people"},{id:"run_implement",label:"Implement runs",group:"people"},{id:"run_respond",label:"Ticket answers",group:"people"},{id:"run_testfix",label:"Test fixes",group:"people"},{id:"run_conflict_resolve",label:"Conflict resolves",group:"people"},{id:"chat_turn",label:"Compose chat",group:"people"},{id:"audit",label:"Audits",group:"people"},{id:"audit_explain",label:"Audit explanations",group:"people"},{id:"rebirth_study",label:"Rebirth studies",group:"people"},{id:"rebirth_refold",label:"Rebirth refolds",group:"people"},{id:"rebirth_design",label:"Rebirth design passes",group:"people"},{id:"rebirth_techstack",label:"Rebirth tech-stack passes",group:"people"},{id:"deploy_fix",label:"Deploy-failure diagnoses",group:"people"},{id:"deploy_suggest",label:"Deploy step proposals",group:"people"},{id:"setup_docs",label:"Setup doc drafting",group:"people"},{id:"setup_ask",label:"Setup questions",group:"people"},{id:"incident_diagnosis",label:"Incident diagnoses",group:"people"},{id:"monitor_suggest",label:"Check proposals",group:"people"},{id:"chat_compact",label:"Chat compaction",group:"platform"},{id:"chat_capsule",label:"Ticket context capsules",group:"platform"},{id:"repo_brief",label:"Repo briefs",group:"platform"},{id:"timeline_digest",label:"Timeline digests",group:"platform"},{id:"autopilot_plan",label:"Autopilot planning",group:"platform"},{id:"epic_suggest",label:"Epic suggestions",group:"platform"}];h.AiSpendMsg=o.z.object({type:o.z.literal("ai.spend"),eventKey:o.z.string().min(1).max(200),surface:o.z.string().max(60),projectId:o.z.string().default(""),userId:o.z.string().default(""),agentId:o.z.string().default(""),model:o.z.string().max(200).default(""),billingMode:o.z.string().max(20).default(""),claudeProfile:o.z.string().max(200).default(""),inputTokens:o.z.number().int().nonnegative().default(0),outputTokens:o.z.number().int().nonnegative().default(0),cacheReadTokens:o.z.number().int().nonnegative().default(0),costUsd:o.z.number().nonnegative().default(0),turns:o.z.number().int().nonnegative().default(0),refKind:o.z.string().max(20).default(""),refId:o.z.string().max(200).default(""),refLabel:o.z.string().max(200).default(""),at:o.z.string().default("")});h.HelloMsg=o.z.object({type:o.z.literal("hello"),protocolVersion:o.z.string(),runnerVersion:o.z.string(),platform:o.z.string(),justBooted:o.z.boolean().optional()});h.HeartbeatMsg=o.z.object({type:o.z.literal("heartbeat"),ts:o.z.string()});h.RunClaimMsg=o.z.object({type:o.z.literal("run.claim"),requestId:o.z.string(),ruleId:o.z.string(),issueKey:o.z.string(),issueSummary:o.z.string().default(""),triggerFingerprint:o.z.string(),dedupKey:o.z.string().optional(),triggeredByAccountId:o.z.string().optional()});h.RunLogMsg=o.z.object({type:o.z.literal("run.log"),runId:o.z.string(),seq:o.z.number().int().nonnegative(),ts:o.z.string(),level:o.z.enum(["info","warn","error","agent"]),message:o.z.string().max(16384)});h.RunUsageMsg=o.z.object({type:o.z.literal("run.usage"),runId:o.z.string(),inputTokens:o.z.number().int().nonnegative(),outputTokens:o.z.number().int().nonnegative(),cacheReadTokens:o.z.number().int().nonnegative().optional(),costUsd:o.z.number().nonnegative().optional(),turns:o.z.number().int().nonnegative().optional()});h.FailedTest=o.z.object({command:o.z.string().max(500),exitCode:o.z.number().int(),tail:o.z.string().max(4e3)});h.RunContextMsg=o.z.object({type:o.z.literal("run.context"),runId:o.z.string(),pieces:o.z.array(o.z.object({part:o.z.string().max(80),chars:o.z.number().int().nonnegative()})).max(30),totalChars:o.z.number().int().nonnegative(),sessionMode:o.z.enum(["fresh","chained","timeout-resume","preflight-resume"])});h.RunStatusMsg=o.z.object({type:o.z.literal("run.status"),runId:o.z.string(),status:h.RunStatus,error:o.z.string().optional(),note:o.z.string().max(300).optional(),errorKind:o.z.enum(["guard"]).optional(),costUsd:o.z.number().nonnegative().optional(),inputTokens:o.z.number().int().nonnegative().optional(),outputTokens:o.z.number().int().nonnegative().optional(),cacheReadTokens:o.z.number().int().nonnegative().optional(),resultSummary:o.z.string().max(2e3).optional(),billingMode:o.z.enum(["subscription","api","unknown"]).optional(),model:o.z.string().max(200).optional(),prUrl:o.z.string().optional(),headSha:o.z.string().optional(),deployedRef:o.z.string().optional(),retryAvailable:o.z.boolean().optional(),failedTests:o.z.array(h.FailedTest).max(20).optional(),testsPassed:o.z.number().int().nonnegative().optional(),testsTotal:o.z.number().int().nonnegative().optional(),manualSteps:o.z.array(o.z.object({command:o.z.string().max(500),why:o.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:o.z.string().max(4e3).optional(),inputQuestions:o.z.string().max(4e3).optional(),inputOptions:o.z.array(o.z.string().max(200)).max(5).optional()});h.ProjectTestResultMsg=o.z.object({type:o.z.literal("project.test.result"),requestId:o.z.string(),ok:o.z.boolean(),checks:o.z.array(o.z.object({name:o.z.string(),ok:o.z.boolean(),detail:o.z.string(),kind:o.z.enum(["connection","content"]).default("connection"),fix:o.z.array(o.z.string()).default([]),fixNote:o.z.string().default("")}))});h.RuleDiagnoseResultMsg=o.z.object({type:o.z.literal("rule.diagnose.result"),requestId:o.z.string(),checks:o.z.array(o.z.object({name:o.z.string(),ok:o.z.boolean(),detail:o.z.string(),kind:o.z.enum(["connection","content"]).default("connection"),fix:o.z.array(o.z.string()).default([]),fixNote:o.z.string().default("")})),matchedCount:o.z.number().int().nonnegative(),excludedCount:o.z.number().int().nonnegative(),excludedSample:o.z.array(o.z.string()).max(5)});h.DeployClaimMsg=o.z.object({type:o.z.literal("deploy.claim"),requestId:o.z.string(),projectId:o.z.string(),ruleId:o.z.string(),issueKey:o.z.string(),issueSummary:o.z.string().default(""),environmentName:o.z.string(),requestedByAccountId:o.z.string().optional(),requestedByDisplayName:o.z.string().default(""),dedupKey:o.z.string(),triggerFingerprint:o.z.string()});h.DeployClaimResultMsg=o.z.object({type:o.z.literal("deploy.claim.result"),requestId:o.z.string(),accepted:o.z.boolean(),runId:o.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:o.z.string().optional(),code:o.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraVersionsResultMsg=o.z.object({type:o.z.literal("jira.versions.result"),requestId:o.z.string(),ok:o.z.boolean(),error:o.z.string().default(""),versions:o.z.array(o.z.object({id:o.z.string(),name:o.z.string(),released:o.z.boolean().default(!1)})).max(100).default([])});h.JiraUsersResultMsg=o.z.object({type:o.z.literal("jira.users.result"),requestId:o.z.string(),ok:o.z.boolean(),users:o.z.array(o.z.object({accountId:o.z.string(),displayName:o.z.string(),email:o.z.string().default(""),active:o.z.boolean().default(!0)})).default([]),error:o.z.string().optional()});h.ChatStreamMsg=o.z.object({type:o.z.literal("chat.stream"),requestId:o.z.string(),seq:o.z.number().int().nonnegative(),text:o.z.string().max(8e3)});h.ChatUsageMsg=o.z.object({type:o.z.literal("chat.usage"),requestId:o.z.string(),inputTokens:o.z.number().int().nonnegative(),outputTokens:o.z.number().int().nonnegative(),cacheReadTokens:o.z.number().int().nonnegative().optional(),turns:o.z.number().int().nonnegative().optional()});h.ChatActivityMsg=o.z.object({type:o.z.literal("chat.activity"),requestId:o.z.string(),seq:o.z.number().int().nonnegative(),verb:o.z.string().max(40),target:o.z.string().max(200).default("")});h.ChatSessionMsg=o.z.object({type:o.z.literal("chat.session"),requestId:o.z.string(),sessionId:o.z.string()});h.ChatListMsg=o.z.object({type:o.z.literal("chat.list"),requestId:o.z.string(),projectId:o.z.string()});h.ChatListResultMsg=o.z.object({type:o.z.literal("chat.list.result"),requestId:o.z.string(),sessions:o.z.array(o.z.object({sessionId:o.z.string(),title:o.z.string().default(""),updatedAt:o.z.string().default(""),messageCount:o.z.number().int().nonnegative().default(0),ownerUserId:o.z.string().default(""),agentId:o.z.string().default("")})).default([])});h.ChatLoadMsg=o.z.object({type:o.z.literal("chat.load"),requestId:o.z.string(),sessionId:o.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function ex(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
25
25
 
26
26
  HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
27
27
  - ${e.join(`
@@ -344,18 +344,18 @@ Rules for the steps:
344
344
  - Prefer commands that are safe to re-run; a deploy may be retried.
345
345
  - A check that fails SILENTLY is only half a check. A pre-check chaining five bare \`test\`/\`grep -q\` guards with && dies as an uninvestigable "exit code 1" - the operator retries blind, twice, and then stops trusting the deploy (this happened; the culprit was a \`test -f\` with no message four conditions deep). Every guard that can fail must SAY what it found: \`test -f apps/api/.env || { echo "apps/api/.env is missing"; exit 1; }\` - the echo is not decoration, it is the entire difference between a five-second fix and a lost evening.
346
346
  - Order matters: install, build, test (if cheap), then release.
347
- - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});function mx(t){let e=Gt.default.join(t,".git"),n;try{n=nt.default.statSync(e)}catch{return null}if(n.isDirectory())return Gt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(nt.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=Gt.default.resolve(t,r[1].trim());try{let i=nt.default.readFileSync(Gt.default.join(s,"commondir"),"utf8").trim();return Gt.default.join(Gt.default.resolve(s,i),"info")}catch{return Gt.default.join(s,"info")}}function gx(t){try{let e=mx(t);if(!e)return;let n=Gt.default.join(e,"exclude"),r="";try{r=nt.default.readFileSync(n,"utf8")}catch{}if(r.split(`
348
- `).some(i=>i.trim()===mf))return;nt.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
347
+ - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});function mx(t){let e=Gt.default.join(t,".git"),n;try{n=rt.default.statSync(e)}catch{return null}if(n.isDirectory())return Gt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(rt.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=Gt.default.resolve(t,r[1].trim());try{let i=rt.default.readFileSync(Gt.default.join(s,"commondir"),"utf8").trim();return Gt.default.join(Gt.default.resolve(s,i),"info")}catch{return Gt.default.join(s,"info")}}function gx(t){try{let e=mx(t);if(!e)return;let n=Gt.default.join(e,"exclude"),r="";try{r=rt.default.readFileSync(n,"utf8")}catch{}if(r.split(`
348
+ `).some(i=>i.trim()===mf))return;rt.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
349
349
  `)?`
350
- `:"";nt.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
350
+ `:"";rt.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
351
351
  ${mf}
352
- `)}catch{}}function Yl(t){return Gt.default.join(t,".ticketpilot","memory","incidents.md")}function Ct(t,e){try{let n=Yl(t),r=Gt.default.dirname(n);nt.default.existsSync(r)||(nt.default.mkdirSync(r,{recursive:!0}),gx(t));let s=nt.default.existsSync(n)?"":gf,i=new Date().toISOString().slice(0,10),a=e.detail?.trim();nt.default.appendFileSync(n,s+`## ${i} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
352
+ `)}catch{}}function Yl(t){return Gt.default.join(t,".ticketpilot","memory","incidents.md")}function Ct(t,e){try{let n=Yl(t),r=Gt.default.dirname(n);rt.default.existsSync(r)||(rt.default.mkdirSync(r,{recursive:!0}),gx(t));let s=rt.default.existsSync(n)?"":gf,i=new Date().toISOString().slice(0,10),a=e.detail?.trim();rt.default.appendFileSync(n,s+`## ${i} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
353
353
  `+(a?`${a.slice(0,1500)}
354
354
  `:"")+`
355
- `),yx(n)}catch{}}function io(t,e){try{return nt.default.readFileSync(Yl(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function yx(t){if(nt.default.statSync(t).size<=px)return;let r=nt.default.readFileSync(t,"utf8").slice(-fx),s=r.indexOf(`
356
- ## `),i=s===-1?r:r.slice(s+1);nt.default.writeFileSync(t,gf+`*(older entries were rotated out)*
355
+ `),yx(n)}catch{}}function io(t,e){try{return rt.default.readFileSync(Yl(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function yx(t){if(rt.default.statSync(t).size<=px)return;let r=rt.default.readFileSync(t,"utf8").slice(-fx),s=r.indexOf(`
356
+ ## `),i=s===-1?r:r.slice(s+1);rt.default.writeFileSync(t,gf+`*(older entries were rotated out)*
357
357
 
358
- `+i)}function oo(t){try{return nt.default.readFileSync(Yl(t),"utf8")}catch{return null}}var nt,Gt,px,fx,mf,gf,ui=J(()=>{"use strict";nt=E(require("node:fs"),1),Gt=E(require("node:path"),1),px=25e4,fx=2e5,mf="/.ticketpilot/memory/";gf=`# Incident ledger
358
+ `+i)}function oo(t){try{return rt.default.readFileSync(Yl(t),"utf8")}catch{return null}}var rt,Gt,px,fx,mf,gf,ui=J(()=>{"use strict";rt=E(require("node:fs"),1),Gt=E(require("node:path"),1),px=25e4,fx=2e5,mf="/.ticketpilot/memory/";gf=`# Incident ledger
359
359
 
360
360
  Machine-written facts about this repository's runs: what failed, what
361
361
  resolved it. Appended by the Allwright runner; humans may edit freely.
@@ -385,8 +385,8 @@ YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
385
385
  `,n=t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
386
386
  `:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
387
387
  `,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.
388
- `:"";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 Ea=J(()=>{"use strict"});function _x(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Aa.default.join(Rf.default.homedir(),".claude");try{if(ru.default.existsSync(Aa.default.join(e,".credentials.json"))||ru.default.existsSync(Aa.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function xx(t,e,n){let r=a=>typeof e[a]=="string"?e[a]:"",i=(a=>a.startsWith(n+"/")?a.slice(n.length+1):a)(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 Tx(t){let e=Sx[t.mode].flatMap(s=>s.includes("(./**)")?[s,s.replace("(./**)",`(/${t.repoPath}/**)`)]:[s]),n=["-p","--output-format","stream-json","--verbose","--add-dir",t.repoPath,"--allowedTools",e.join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],r=_x(t.configDir);return r!=="unknown"&&t.onLog("info",r==="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(s=>{let i=(0,If.spawn)(t.bin,n,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),a={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:r==="subscription"?"subscription":r==="API key"?"api":"unknown"},c=0,l=!1,u=0,p=0,f=0,m=0,w=()=>{if(!t.onUsage)return;let C=Date.now();C-m<kx||(m=C,t.onUsage({inputTokens:u,outputTokens:p,cacheReadTokens:f,turns:c}))},S=!1,T=()=>{S||(S=!0,clearTimeout(A),t.signal?.removeEventListener("abort",x),s(a))},x=()=>{a.cancelled=!0,a.error="stopped from the dashboard",t.onLog("error",a.error),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",x,{once:!0});let A=setTimeout(()=>{a.timedOut=!0,a.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",a.error),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);i.stdin.write(t.prompt+di(t.mode)),i.stdin.end(),Ef.default.createInterface({input:i.stdout}).on("line",C=>{if(!C.trim())return;let $;try{$=JSON.parse(C)}catch{t.onLog("agent",C.slice(0,1e3));return}if($.type==="system"&&$.subtype==="init")a.model=typeof $.model=="string"?$.model:void 0,t.onLog("info",`Claude Code session started (model: ${$.model??"default"})`);else if($.type==="assistant"){c+=1,l=$.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=$.message?.usage;if(v){u+=Number(v.input_tokens??0)+Number(v.cache_creation_input_tokens??0);let P=JSON.stringify($.message?.content??[]).length;p+=Math.max(Number(v.output_tokens??0),Math.round(P/4)),f+=Number(v.cache_read_input_tokens??0),w()}for(let P of $.message?.content??[])if(P.type==="text"&&P.text?.trim())t.onLog("agent",P.text.trim().slice(0,4e3));else if(P.type==="tool_use"){let F=P.input??{},V=["file_path","path","pattern","command","description","url"].map(L=>typeof F[L]=="string"?`${L}=${F[L]}`:null).filter(Boolean).join(" "),te=JSON.stringify(F).slice(0,400);if(t.onLog("info",`tool ${P.name} ${V?`${V} `:""}${te}`),t.onTool){let L=xx(String(P.name??""),F,t.repoPath);t.onTool(L.verb,L.target.slice(0,200))}}}else $.type==="result"&&(a.costUsd=Number($.total_cost_usd??0),a.inputTokens=Number($.usage?.input_tokens??0)+Number($.usage?.cache_creation_input_tokens??0),a.outputTokens=Number($.usage?.output_tokens??0),u=Math.max(a.inputTokens,u),p=Math.max(a.outputTokens,p),a.inputTokens=u,a.outputTokens=p,f=Number($.usage?.cache_read_input_tokens??f),a.cacheReadTokens=f,t.onUsage&&(t.onUsage({inputTokens:u,outputTokens:p,cacheReadTokens:f,costUsd:a.costUsd,turns:c}),m=Date.now()),$.subtype==="success"&&!$.is_error?(a.ok=!0,a.resultText=String($.result??""),a.outputTruncated=l):$.subtype==="error_max_turns"?(a.turnLimitHit=!0,a.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):a.error||(a.error=$.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String($.result??$.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(a.error)&&(a.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${a.error.slice(0,400)}`)))});let K="";i.stderr.on("data",C=>{K=(K+C.toString()).slice(-2e3)}),i.on("error",C=>{a.error=`failed to start ${t.bin}: ${C.message}`,t.onLog("error",a.error),T()}),i.on("close",C=>{!a.ok&&!a.error&&(a.error=a.timedOut?a.error:`claude exited with code ${C}${K?`: ${K.slice(-500)}`:""}`),T()})})}var ru,Rf,Aa,If,Ef,Af,kx,Sx,$a,$f=J(()=>{"use strict";ru=E(require("node:fs"),1),Rf=E(require("node:os"),1),Aa=E(require("node:path"),1),If=require("node:child_process"),Ef=E(require("node:readline"),1),Af=E(Me(),1);Ea();kx=4e3,Sx={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"]};$a={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Af.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Tx}});async function Rx(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,Cf.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="",a=!1,c=()=>{a||(a=!0,clearTimeout(l),n(s))},l=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+di(t.mode)),r.stdin.end(),Pf.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let m;try{m=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let w=m.item??m.msg??m,S=w?.type??m.type,T=w?.text??w?.message??"";S==="agent_message"&&typeof T=="string"&&T.trim()?(i=T,t.onLog("agent",T.trim().slice(0,4e3))):S==="command_execution"||S==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):S==="error"&&typeof T=="string"&&T&&t.onLog("error",T.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),c()}),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)}`:"")),c()})})}var Cf,Pf,Nf,su,jf=J(()=>{"use strict";Cf=require("node:child_process"),Pf=E(require("node:readline"),1),Nf=E(Me(),1);Ea();su={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Nf.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Rx}});function Cx(t){return t.resume?t.sessionId?["--session",t.sessionId]:["--continue"]:t.sessionId?["--session",t.sessionId]:[]}function Nx(t,e,n){let r=l=>typeof e[l]=="string"?e[l]:"",s=(...l)=>l.map(r).find(u=>u)??"",a=(l=>l.startsWith(n+"/")?l.slice(n.length+1):l)(s("file_path","path","file","filename","dir","directory")),c=t.toLowerCase();if(c.includes("web")||c.includes("fetch")||c.includes("url")){let l=r("url");return l?{verb:"Fetched",target:l}:{verb:"Searched the web for",target:s("query","q")}}return c.includes("read")||c.includes("view")||c.includes("open")?{verb:"Read",target:a}:c.includes("glob")||c.includes("list")||c==="ls"?{verb:"Looked for files",target:s("pattern","glob")||a}:c.includes("grep")||c.includes("search")||c.includes("find")?{verb:"Searched for",target:s("pattern","query","regex")||a}:c.includes("write")||c.includes("create")?{verb:"Wrote",target:a}:c.includes("edit")||c.includes("replace")||c.includes("patch")?{verb:"Edited",target:a}:c.includes("shell")||c.includes("bash")||c.includes("exec")||c.includes("command")?{verb:"Ran",target:s("command","cmd","script")}:{verb:`Used ${t||"a tool"}`,target:s("description","command","query","pattern")||a}}function iu(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(`
389
- `):""}function jx(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 a=JSON.parse(i);a&&typeof a=="object"?s=a: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 Mx(t){let e=r=>({ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:r});if(!Ex.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+di(t.mode)+$x,"--output-format","stream-json",...t.model?["--model",t.model]:[],...Cx(t)];return t.onLog("info",Ax),new Promise(r=>{let s=(0,Mf.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},a="",c="",l=0,u=0,p=0,f=0,m=0,w=!1,S=new Set,T=(te=!1)=>{if(!t.onUsage||!w)return;let L=Date.now();if(!te&&L-m<Ix)return;m=L;let d={inputTokens:u,outputTokens:p,cacheReadTokens:f,turns:l};t.onUsage(d)},x=!1,A=()=>{x||(x=!0,clearTimeout(K),t.signal?.removeEventListener("abort",D),r(i))},D=()=>{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",D,{once:!0});let K=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=Of.default.createInterface({input:s.stdout});C.on("line",te=>{if(!te.trim())return;let L;try{L=JSON.parse(te)}catch{t.onLog("agent",te.slice(0,1e3));return}let d=L.message??L,g=String(d?.role??L.type??"");if(L.type==="system"&&L.subtype==="init"){typeof L.model=="string"&&(i.model=L.model),t.onLog("info",`Kimi session started (model: ${L.model??"default"})`);return}if(g==="assistant"){l+=1;let y=d?.usage??L.usage;y&&(w=!0,u+=Number(y.input_tokens??y.prompt_tokens??0),p+=Number(y.output_tokens??y.completion_tokens??0),f+=Number(y.cache_read_input_tokens??y.cached_tokens??0),T());let _=iu(d?.content).trim();_&&(a=_,t.onLog("agent",_.slice(0,4e3)));for(let M of jx(d)){let O=JSON.stringify(M.input).slice(0,400);if(t.onLog("info",`tool ${M.name} ${O}`),Px.test(M.name)&&!S.has(M.name)&&(S.add(M.name),t.onLog("error",`Kimi used "${M.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 B=Nx(M.name,M.input,t.repoPath);t.onTool(B.verb,B.target.slice(0,200))}}return}if(g==="tool"){let y=iu(d?.content).trim();y&&t.onLog("info",`tool result ${y.slice(0,300)}`);return}if(L.type==="result"){let y=L.usage;y&&(w=!0,u=Math.max(u,Number(y.input_tokens??y.prompt_tokens??0)),p=Math.max(p,Number(y.output_tokens??y.completion_tokens??0)),f=Math.max(f,Number(y.cache_read_input_tokens??0))),L.is_error||L.subtype&&L.subtype!=="success"?i.error||(i.error=String(L.result??L.error??L.subtype??"unknown Kimi error")):c=String(L.result??"");return}if(g==="error"||L.type==="error"){let y=iu(d?.content)||String(L.error??L.message??"");y&&t.onLog("error",y.slice(0,1e3))}});let $="";s.stderr.on("data",te=>{$=($+te.toString()).slice(-2e3)}),s.on("error",te=>{i.error=`failed to start ${t.bin}: ${te.message} - is the Kimi CLI installed and logged in?`,t.onLog("error",i.error),A()});let v=!1,P=!1,F=null,V=()=>{if(!v||!P||x)return;let te=(c||a).trim();F===0&&te&&!i.error?(i.ok=!0,i.resultText=te):i.error||(i.error=`kimi exited with code ${F}`+(te?"":" and produced no answer")+($?`: ${$.slice(-500)}`:"")),i.inputTokens=u,i.outputTokens=p,i.cacheReadTokens=f,T(!0),A()};C.on("close",()=>{v=!0,V()}),s.on("close",te=>{P=!0,F=te,V()})})}var Mf,Of,zf,Ix,Ex,Ax,$x,Px,ou,Df=J(()=>{"use strict";Mf=require("node:child_process"),Of=E(require("node:readline"),1),zf=E(Me(),1);Ea();Ix=4e3,Ex=["read_only","read_only_web"],Ax="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.",$x=`
388
+ `:"";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 Ea=J(()=>{"use strict"});function _x(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Aa.default.join(Rf.default.homedir(),".claude");try{if(ru.default.existsSync(Aa.default.join(e,".credentials.json"))||ru.default.existsSync(Aa.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function xx(t,e,n){let r=a=>typeof e[a]=="string"?e[a]:"",i=(a=>a.startsWith(n+"/")?a.slice(n.length+1):a)(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 Tx(t){let e=Sx[t.mode].flatMap(s=>s.includes("(./**)")?[s,s.replace("(./**)",`(/${t.repoPath}/**)`)]:[s]),n=["-p","--output-format","stream-json","--verbose","--add-dir",t.repoPath,"--allowedTools",e.join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],r=_x(t.configDir);return r!=="unknown"&&t.onLog("info",r==="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(s=>{let i=(0,If.spawn)(t.bin,n,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),a={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:r==="subscription"?"subscription":r==="API key"?"api":"unknown"},c=0,l=!1,u=0,p=0,f=0,m=0,w=()=>{if(!t.onUsage)return;let C=Date.now();C-m<kx||(m=C,t.onUsage({inputTokens:u,outputTokens:p,cacheReadTokens:f,turns:c}))},S=!1,T=()=>{S||(S=!0,clearTimeout(A),t.signal?.removeEventListener("abort",x),s(a))},x=()=>{a.cancelled=!0,a.error="stopped from the dashboard",t.onLog("error",a.error),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",x,{once:!0});let A=setTimeout(()=>{a.timedOut=!0,a.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",a.error),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);i.stdin.write(t.prompt+di(t.mode)),i.stdin.end(),Ef.default.createInterface({input:i.stdout}).on("line",C=>{if(!C.trim())return;let $;try{$=JSON.parse(C)}catch{t.onLog("agent",C.slice(0,1e3));return}if($.type==="system"&&$.subtype==="init")a.model=typeof $.model=="string"?$.model:void 0,t.onLog("info",`Claude Code session started (model: ${$.model??"default"})`);else if($.type==="assistant"){c+=1,l=$.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=$.message?.usage;if(v){u+=Number(v.input_tokens??0)+Number(v.cache_creation_input_tokens??0);let N=JSON.stringify($.message?.content??[]).length;p+=Math.max(Number(v.output_tokens??0),Math.round(N/4)),f+=Number(v.cache_read_input_tokens??0),w()}for(let N of $.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 B=N.input??{},V=["file_path","path","pattern","command","description","url"].map(L=>typeof B[L]=="string"?`${L}=${B[L]}`:null).filter(Boolean).join(" "),te=JSON.stringify(B).slice(0,400);if(t.onLog("info",`tool ${N.name} ${V?`${V} `:""}${te}`),t.onTool){let L=xx(String(N.name??""),B,t.repoPath);t.onTool(L.verb,L.target.slice(0,200))}}}else $.type==="result"&&(a.costUsd=Number($.total_cost_usd??0),a.inputTokens=Number($.usage?.input_tokens??0)+Number($.usage?.cache_creation_input_tokens??0),a.outputTokens=Number($.usage?.output_tokens??0),u=Math.max(a.inputTokens,u),p=Math.max(a.outputTokens,p),a.inputTokens=u,a.outputTokens=p,f=Number($.usage?.cache_read_input_tokens??f),a.cacheReadTokens=f,t.onUsage&&(t.onUsage({inputTokens:u,outputTokens:p,cacheReadTokens:f,costUsd:a.costUsd,turns:c}),m=Date.now()),$.subtype==="success"&&!$.is_error?(a.ok=!0,a.resultText=String($.result??""),a.outputTruncated=l):$.subtype==="error_max_turns"?(a.turnLimitHit=!0,a.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):a.error||(a.error=$.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String($.result??$.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(a.error)&&(a.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${a.error.slice(0,400)}`)))});let K="";i.stderr.on("data",C=>{K=(K+C.toString()).slice(-2e3)}),i.on("error",C=>{a.error=`failed to start ${t.bin}: ${C.message}`,t.onLog("error",a.error),T()}),i.on("close",C=>{!a.ok&&!a.error&&(a.error=a.timedOut?a.error:`claude exited with code ${C}${K?`: ${K.slice(-500)}`:""}`),T()})})}var ru,Rf,Aa,If,Ef,Af,kx,Sx,$a,$f=J(()=>{"use strict";ru=E(require("node:fs"),1),Rf=E(require("node:os"),1),Aa=E(require("node:path"),1),If=require("node:child_process"),Ef=E(require("node:readline"),1),Af=E(Me(),1);Ea();kx=4e3,Sx={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"]};$a={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Af.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Tx}});async function Rx(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,Cf.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="",a=!1,c=()=>{a||(a=!0,clearTimeout(l),n(s))},l=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+di(t.mode)),r.stdin.end(),Pf.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let m;try{m=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let w=m.item??m.msg??m,S=w?.type??m.type,T=w?.text??w?.message??"";S==="agent_message"&&typeof T=="string"&&T.trim()?(i=T,t.onLog("agent",T.trim().slice(0,4e3))):S==="command_execution"||S==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):S==="error"&&typeof T=="string"&&T&&t.onLog("error",T.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),c()}),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)}`:"")),c()})})}var Cf,Pf,Nf,su,jf=J(()=>{"use strict";Cf=require("node:child_process"),Pf=E(require("node:readline"),1),Nf=E(Me(),1);Ea();su={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Nf.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Rx}});function Cx(t){return t.resume?t.sessionId?["--session",t.sessionId]:["--continue"]:t.sessionId?["--session",t.sessionId]:[]}function Nx(t,e,n){let r=l=>typeof e[l]=="string"?e[l]:"",s=(...l)=>l.map(r).find(u=>u)??"",a=(l=>l.startsWith(n+"/")?l.slice(n.length+1):l)(s("file_path","path","file","filename","dir","directory")),c=t.toLowerCase();if(c.includes("web")||c.includes("fetch")||c.includes("url")){let l=r("url");return l?{verb:"Fetched",target:l}:{verb:"Searched the web for",target:s("query","q")}}return c.includes("read")||c.includes("view")||c.includes("open")?{verb:"Read",target:a}:c.includes("glob")||c.includes("list")||c==="ls"?{verb:"Looked for files",target:s("pattern","glob")||a}:c.includes("grep")||c.includes("search")||c.includes("find")?{verb:"Searched for",target:s("pattern","query","regex")||a}:c.includes("write")||c.includes("create")?{verb:"Wrote",target:a}:c.includes("edit")||c.includes("replace")||c.includes("patch")?{verb:"Edited",target:a}:c.includes("shell")||c.includes("bash")||c.includes("exec")||c.includes("command")?{verb:"Ran",target:s("command","cmd","script")}:{verb:`Used ${t||"a tool"}`,target:s("description","command","query","pattern")||a}}function iu(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(`
389
+ `):""}function jx(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 a=JSON.parse(i);a&&typeof a=="object"?s=a: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 Mx(t){let e=r=>({ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:r});if(!Ex.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+di(t.mode)+$x,"--output-format","stream-json",...t.model?["--model",t.model]:[],...Cx(t)];return t.onLog("info",Ax),new Promise(r=>{let s=(0,Mf.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},a="",c="",l=0,u=0,p=0,f=0,m=0,w=!1,S=new Set,T=(te=!1)=>{if(!t.onUsage||!w)return;let L=Date.now();if(!te&&L-m<Ix)return;m=L;let d={inputTokens:u,outputTokens:p,cacheReadTokens:f,turns:l};t.onUsage(d)},x=!1,A=()=>{x||(x=!0,clearTimeout(K),t.signal?.removeEventListener("abort",D),r(i))},D=()=>{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",D,{once:!0});let K=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=Of.default.createInterface({input:s.stdout});C.on("line",te=>{if(!te.trim())return;let L;try{L=JSON.parse(te)}catch{t.onLog("agent",te.slice(0,1e3));return}let d=L.message??L,g=String(d?.role??L.type??"");if(L.type==="system"&&L.subtype==="init"){typeof L.model=="string"&&(i.model=L.model),t.onLog("info",`Kimi session started (model: ${L.model??"default"})`);return}if(g==="assistant"){l+=1;let y=d?.usage??L.usage;y&&(w=!0,u+=Number(y.input_tokens??y.prompt_tokens??0),p+=Number(y.output_tokens??y.completion_tokens??0),f+=Number(y.cache_read_input_tokens??y.cached_tokens??0),T());let _=iu(d?.content).trim();_&&(a=_,t.onLog("agent",_.slice(0,4e3)));for(let M of jx(d)){let O=JSON.stringify(M.input).slice(0,400);if(t.onLog("info",`tool ${M.name} ${O}`),Px.test(M.name)&&!S.has(M.name)&&(S.add(M.name),t.onLog("error",`Kimi used "${M.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 F=Nx(M.name,M.input,t.repoPath);t.onTool(F.verb,F.target.slice(0,200))}}return}if(g==="tool"){let y=iu(d?.content).trim();y&&t.onLog("info",`tool result ${y.slice(0,300)}`);return}if(L.type==="result"){let y=L.usage;y&&(w=!0,u=Math.max(u,Number(y.input_tokens??y.prompt_tokens??0)),p=Math.max(p,Number(y.output_tokens??y.completion_tokens??0)),f=Math.max(f,Number(y.cache_read_input_tokens??0))),L.is_error||L.subtype&&L.subtype!=="success"?i.error||(i.error=String(L.result??L.error??L.subtype??"unknown Kimi error")):c=String(L.result??"");return}if(g==="error"||L.type==="error"){let y=iu(d?.content)||String(L.error??L.message??"");y&&t.onLog("error",y.slice(0,1e3))}});let $="";s.stderr.on("data",te=>{$=($+te.toString()).slice(-2e3)}),s.on("error",te=>{i.error=`failed to start ${t.bin}: ${te.message} - is the Kimi CLI installed and logged in?`,t.onLog("error",i.error),A()});let v=!1,N=!1,B=null,V=()=>{if(!v||!N||x)return;let te=(c||a).trim();B===0&&te&&!i.error?(i.ok=!0,i.resultText=te):i.error||(i.error=`kimi exited with code ${B}`+(te?"":" and produced no answer")+($?`: ${$.slice(-500)}`:"")),i.inputTokens=u,i.outputTokens=p,i.cacheReadTokens=f,T(!0),A()};C.on("close",()=>{v=!0,V()}),s.on("close",te=>{N=!0,B=te,V()})})}var Mf,Of,zf,Ix,Ex,Ax,$x,Px,ou,Df=J(()=>{"use strict";Mf=require("node:child_process"),Of=E(require("node:readline"),1),zf=E(Me(),1);Ea();Ix=4e3,Ex=["read_only","read_only_web"],Ax="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.",$x=`
390
390
 
391
391
  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:
392
392
  - Do NOT create, edit, move or delete any file, and do NOT run any shell command.
@@ -415,7 +415,7 @@ ${i}${a}`:"clean"}`}function jn(){let t=process.env.ALLWRIGHT_CACHE_DIR??process
415
415
  `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Na(t,e,n=6e4){let s=(await Z(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await Z(t,["diff","--stat",`${s}...${e}`]),a=await Z(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:a.slice(0,n)}}function Kf(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ie.default.existsSync(ye.default.join(hs.default.homedir(),".cache","ticketpilot"))?ye.default.join(hs.default.homedir(),".cache","ticketpilot"):ye.default.join(hs.default.homedir(),".cache","allwright"));return ye.default.join(t,"env-checkouts")}function Lf(t){return t.replace(/[^\w.-]+/g,"_")}async function wu(t,e,n){await Z(t,["fetch","origin"],{timeoutMs:3e5}),await Z(t,["reset","--hard"]),await Z(t,["checkout","-B",e,n])}function Wf(t,e){return ye.default.join(Kf(),Lf(t),Lf(e))}async function vu(t){let e=Wf(t.repoName,t.envName);return await Z(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Ie.default.existsSync(ye.default.join(e,".git"))?await Z(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Ie.default.rmSync(e,{recursive:!0,force:!0}),Ie.default.mkdirSync(ye.default.dirname(e),{recursive:!0,mode:448}),await Z(t.repoPath,["worktree","prune"]).catch(()=>{}),await Z(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await Z(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await Z(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function ku(t,e,n){try{await Z(t,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await Z(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await Z(t,["-c",`user.name=${co}`,"-c",`user.email=${lo}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await Z(t,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function Su(t,e){await Z(t,["fetch","origin",e],{timeoutMs:3e5});try{return await Z(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await Z(t,["-c",`user.name=${co}`,"-c",`user.email=${lo}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await Z(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
416
416
  `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await Z(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function dr(t){await Z(t,["merge","--abort"]).catch(()=>{})}async function _u(t,e){await Z(t,["add","-A"]),await Z(t,["-c",`user.name=${co}`,"-c",`user.email=${lo}`,"commit","--no-edit","-m",e])}async function xu(t){await Z(t,["add","-A"]),await Z(t,["-c",`user.name=${co}`,"-c",`user.email=${lo}`,"commit","--amend","--no-edit"])}async function Tu(t,e){let n=new Set(await ja(t));return e.filter(r=>n.has(r))}async function ja(t){let e=new Set;try{let r=await Z(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
417
417
  `).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await Z(t,["grep","-l","-I","-E","^={7}$"])).split(`
418
- `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await Z(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function ho(t,e,n){Ie.default.mkdirSync(ye.default.dirname(e),{recursive:!0,mode:448}),await Z(t,["fetch","origin",n],{timeoutMs:3e5}),await Z(t,["worktree","add","--detach",e,`origin/${n}`]),await Z(e,["checkout","-B",n,`origin/${n}`])}async function Ru(t,e){try{await Z(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function Iu(t,e,n){try{return await Ff("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function ms(t){return(await Z(t,["config","--get","remote.origin.url"])).trim()}function Jt(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var cu,Ie,hs,ye,Uf,qf,Ff,co,lo,or,ar,Bf,Nn,zx,dn=J(()=>{"use strict";cu=require("node:child_process"),Ie=E(require("node:fs"),1),hs=E(require("node:os"),1),ye=E(require("node:path"),1),Uf=require("node:child_process"),qf=require("node:util"),Ff=(0,qf.promisify)(Uf.execFile),co="Allwright Agent",lo="agent@ticketpilot.local",or=200,ar=2e4,Bf=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Nn=".ticketpilot-delete";zx=/(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|composer\.lock|Gemfile\.lock|poetry\.lock|go\.sum)$/});var gs={};Fe(gs,{GitHubClient:()=>rt});var Dx,rt,Yt=J(()=>{"use strict";Dx=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",rt=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${Dx}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let c=a?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${n} -> ${s.status}: ${c}`)}return{status:s.status,data:a}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:a}=await this.request("GET",`/repos/${e}/${n}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(a?.length){let c=a[0];return{number:c.number,url:c.html_url,state:c.state,merged:c.merged??!1,mergedBy:"",headSha:c.head.sha,mergeableState:null,baseRef:c.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,mergedBy:"",headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,mergedBy:s.merged_by?.login??"",headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(a){let c=a instanceof Error?a.message:String(a);return c.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:c.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:c.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:c}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});function po(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function st(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Vf(t,e){let n=[t.jira,...Object.values(t.repos).map(c=>c.jira)].filter(c=>!!c),r=new Set(n.map(c=>c.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(c=>c.github?.token),i=t.github?.login??Object.values(t.repos).find(c=>c.github?.login)?.github?.login??"",a=e.map(c=>{let l=c.trim().toLowerCase(),u=t.jiraUsers[l]?"own":r.has(l)?"runner-account":"missing",p=u==="own"?t.jiraUsers[l].email:u==="runner-account"?l:"",f=t.githubUsers[l]?"own":s?"shared":"missing",m=f==="own"?t.githubUsers[l].login??"":f==="shared"?i:"";return{email:l,jira:u,jiraAs:p,github:f,githubAs:m}});return{githubShared:s,sharedGithubLogin:i,entries:a}}var ys=J(()=>{"use strict"});function Jf(t,e,n,r={}){let s=e.map(m=>`### Pack: ${m.name}
418
+ `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await Z(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function ho(t,e,n){Ie.default.mkdirSync(ye.default.dirname(e),{recursive:!0,mode:448}),await Z(t,["fetch","origin",n],{timeoutMs:3e5}),await Z(t,["worktree","add","--detach",e,`origin/${n}`]),await Z(e,["checkout","-B",n,`origin/${n}`])}async function Ru(t,e){try{await Z(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function Iu(t,e,n){try{return await Ff("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function ms(t){return(await Z(t,["config","--get","remote.origin.url"])).trim()}function Jt(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var cu,Ie,hs,ye,Uf,qf,Ff,co,lo,or,ar,Bf,Nn,zx,dn=J(()=>{"use strict";cu=require("node:child_process"),Ie=E(require("node:fs"),1),hs=E(require("node:os"),1),ye=E(require("node:path"),1),Uf=require("node:child_process"),qf=require("node:util"),Ff=(0,qf.promisify)(Uf.execFile),co="Allwright Agent",lo="agent@ticketpilot.local",or=200,ar=2e4,Bf=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Nn=".ticketpilot-delete";zx=/(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|composer\.lock|Gemfile\.lock|poetry\.lock|go\.sum)$/});var gs={};Fe(gs,{GitHubClient:()=>Ye});var Dx,Ye,Yt=J(()=>{"use strict";Dx=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Ye=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${Dx}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let c=a?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${n} -> ${s.status}: ${c}`)}return{status:s.status,data:a}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:a}=await this.request("GET",`/repos/${e}/${n}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(a?.length){let c=a[0];return{number:c.number,url:c.html_url,state:c.state,merged:c.merged??!1,mergedBy:"",headSha:c.head.sha,mergeableState:null,baseRef:c.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,mergedBy:"",headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,mergedBy:s.merged_by?.login??"",headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(a){let c=a instanceof Error?a.message:String(a);return c.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:c.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:c.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:c}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});function po(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function st(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Vf(t,e){let n=[t.jira,...Object.values(t.repos).map(c=>c.jira)].filter(c=>!!c),r=new Set(n.map(c=>c.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(c=>c.github?.token),i=t.github?.login??Object.values(t.repos).find(c=>c.github?.login)?.github?.login??"",a=e.map(c=>{let l=c.trim().toLowerCase(),u=t.jiraUsers[l]?"own":r.has(l)?"runner-account":"missing",p=u==="own"?t.jiraUsers[l].email:u==="runner-account"?l:"",f=t.githubUsers[l]?"own":s?"shared":"missing",m=f==="own"?t.githubUsers[l].login??"":f==="shared"?i:"";return{email:l,jira:u,jiraAs:p,github:f,githubAs:m}});return{githubShared:s,sharedGithubLogin:i,entries:a}}var ys=J(()=>{"use strict"});function Jf(t,e,n,r={}){let s=e.map(m=>`### Pack: ${m.name}
419
419
 
420
420
  ${m.content}`).join(`
421
421
 
@@ -820,7 +820,7 @@ ${e}
820
820
  SITE-WIDE:
821
821
  ${t.notes.map(n=>`- ${n}`).join(`
822
822
  `)}`}var Ym=J(()=>{"use strict"});var Uu={};Fe(Uu,{AI_CRAWLERS:()=>rg,CATEGORIES:()=>tg,assertPublicHttpUrl:()=>ng,blockedAgents:()=>Lu,formatSiteAuditReport:()=>RT,probeSite:()=>TT});async function ng(t,e={}){let n=e.resolveDns??!0,r=new URL(t.includes("://")?t:`https://${t}`);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) can be audited, not ${r.protocol}`);let s=r.hostname.toLowerCase();if(s==="localhost"||s.endsWith(".local")||s.endsWith(".internal"))throw new Error(`${s} is not a public site`);let i=a=>/^(127\.|10\.|192\.168\.|169\.254\.|0\.)/.test(a)||/^172\.(1[6-9]|2\d|3[01])\./.test(a)||a==="::1"||a.toLowerCase().startsWith("fe80:")||a.toLowerCase().startsWith("fc")||a.toLowerCase().startsWith("fd");if(Qm.default.isIP(s)){if(i(s))throw new Error(`${s} is a private address - not a public site`);return r}if(!n)return r;try{if((await eg.default.lookup(s,{all:!0})).some(c=>i(c.address)))throw new Error(`${s} resolves to a private address - not a public site`)}catch(a){throw a instanceof Error&&a.message.includes("private")?a:new Error(`${s} does not resolve - is the URL right?`)}return r}function Lu(t,e){let n=[],r=null,s=!1;for(let a of t.split(`
823
- `)){let c=a.split("#")[0].trim();if(!c)continue;let l=/^user-agent:\s*(.+)$/i.exec(c);if(l){(!r||s)&&(r={agents:[],disallowAll:!1},n.push(r),s=!1),r.agents.push(l[1].trim());continue}r&&(s=!0,/^disallow:\s*\/\s*$/i.test(c)&&(r.disallowAll=!0))}let i=a=>{let c=n.filter(u=>u.agents.some(p=>p.toLowerCase()===a.toLowerCase()));return(c.length?c:n.filter(u=>u.agents.includes("*"))).some(u=>u.disallowAll)};return e.filter(i)}async function TT(t,e=Xm){let n=[],r=(N,U,re,j,ee,ae=2)=>n.push({id:N,category:U,label:re,status:j,detail:ee,weight:j==="info"?0:ae}),s;try{s=await ng(t,{resolveDns:e===Xm})}catch(N){return{ok:!1,error:N instanceof Error?N.message:String(N),url:t,overall:0,categories:[],checks:[]}}let i;try{i=await e(s.toString())}catch(N){return{ok:!1,error:`could not fetch ${s.hostname}: ${N instanceof Error?N.message:"unreachable"}`,url:s.toString(),overall:0,categories:[],checks:[]}}let a=i.body,c=new URL(i.finalUrl),l=c.origin;r("status","seo","Page responds successfully",i.status===200?"pass":"fail",`HTTP ${i.status}`,3),r("https","seo","Served over HTTPS",c.protocol==="https:"?"pass":"fail",c.origin,3);let u=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(a)?.[1]?.trim()??"";r("title","seo","Title tag present and sized for results (10-60 chars)",u?u.length>=10&&u.length<=60?"pass":"warn":"fail",u?`"${u.slice(0,80)}" (${u.length} chars)`:"no <title>",3);let p=On(a,"description");r("meta-description","seo","Meta description present and sized (50-160 chars)",p?p.length>=50&&p.length<=160?"pass":"warn":"fail",p?`${p.length} chars`:"missing",3);let f=a.match(/<h1[\s>]/gi)?.length??0;r("h1","seo","Exactly one H1",f===1?"pass":f===0?"fail":"warn",`${f} found`,2);let m=/<link[^>]+rel\s*=\s*["']canonical["'][^>]*>/i.exec(a)?.[0]??"";r("canonical","seo","Canonical URL declared",m?"pass":"warn",m?Du(m,"href"):"none",2),r("viewport","seo","Mobile viewport meta",On(a,"viewport")?"pass":"fail",On(a,"viewport"),2),r("lang","seo","Language declared on <html>",/<html[^>]+lang\s*=/i.test(a)?"pass":"warn",/<html[^>]+lang\s*=\s*["']([^"']+)/i.exec(a)?.[1]??"none",1);let w=On(a,"robots").toLowerCase();r("noindex","seo","Page is indexable (no noindex)",w.includes("noindex")?"fail":"pass",w||"no robots meta (indexable)",3);let S=a.match(/<img[^>]*>/gi)??[],T=S.filter(N=>Du(N,"alt")!=="").length;r("img-alt","seo","Images carry alt text",S.length===0?"info":T/S.length>=.8?"pass":"warn",S.length?`${T}/${S.length} images`:"no images on this page",1);let x="";try{let N=await e(`${l}/robots.txt`);x=N.status===200?N.body.slice(0,1e5):""}catch{x=""}r("robots","seo","robots.txt present",x?"pass":"warn",x?`${l}/robots.txt`:"missing",1),x&&Lu(x,["*"]).length&&r("robots-all","seo","robots.txt does not block the whole site","fail","Disallow: / for all agents",3);let A=/sitemap:\s*(\S+)/i.exec(x)?.[1]??"",D=!1;try{let N=await e(A||`${l}/sitemap.xml`);D=N.status===200&&N.body.includes("<")}catch{D=!1}r("sitemap","seo","XML sitemap reachable",D?"pass":"warn",A||`${l}/sitemap.xml`,2);let K=a.match(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)??[],C=new Set;for(let N of K)for(let U of N.matchAll(/"@type"\s*:\s*"([^"]+)"/g))C.add(U[1]);r("json-ld","aeo","Structured data (JSON-LD) present",K.length?"pass":"warn",K.length?[...C].slice(0,8).join(", "):"none found",3),r("faq-schema","aeo","Q&A-shaped schema (FAQPage/HowTo) - answer engines lift these",C.has("FAQPage")||C.has("HowTo")?"pass":"info",C.has("FAQPage")?"FAQPage found":C.has("HowTo")?"HowTo found":"none - worth adding where it fits the content",1);let $=xT(a);r("ssr-content","aeo","Content present in the initial HTML (answer engines read this, not the hydrated app)",$.length>400?"pass":$.length>100?"warn":"fail",`${$.length} chars of visible text before JavaScript`,3);let v=x?Lu(x,rg):[];r("ai-crawlers","aeo","AI crawlers allowed (GPTBot, ClaudeBot, PerplexityBot\u2026)",v.length===0?"pass":"warn",v.length?`blocked: ${v.join(", ")}`:"none blocked in robots.txt",2);let P=!1;try{let N=await e(`${l}/llms.txt`);P=N.status===200&&N.body.trim().length>0&&!N.body.trim().startsWith("<")}catch{P=!1}r("llms-txt","aeo","llms.txt (optional AI index - Google says unnecessary, early adopters ship it anyway)",P?"pass":"info",P?`${l}/llms.txt`:"not present - a bonus, not a defect",1);let F=[...a.matchAll(/<h([1-3])[\s>]/gi)].map(N=>Number(N[1]));r("headings","aeo","Heading structure starts at H1",F.length===0?"warn":F[0]===1?"pass":"warn",F.slice(0,10).map(N=>`h${N}`).join(" \u2192 ")||"no h1-h3 at all",1);let V={title:On(a,"og:title"),description:On(a,"og:description"),image:On(a,"og:image")};r("og","social","Open Graph card (og:title / og:description / og:image)",V.title&&V.image?"pass":V.title||V.description?"warn":"fail",Object.entries(V).map(([N,U])=>`${N}: ${U?"\u2713":"\u2717"}`).join(" \xB7 "),2),r("twitter","social","Twitter/X card",On(a,"twitter:card")?"pass":"warn",On(a,"twitter:card")||"no twitter:card meta",1);let te=N=>N.test(a),L=/G-[A-Z0-9]{6,}/.exec(a)?.[0]??"",d=/GTM-[A-Z0-9]{4,}/.exec(a)?.[0]??"",g=/AW-\d{6,}/.exec(a)?.[0]??"",y=te(/googletagmanager\.com|gtag\(/);r("google-tag","ads","Google tag installed (GA4 / Tag Manager)",y?"pass":"warn",[L&&`GA4 ${L}`,d&&`GTM ${d}`].filter(Boolean).join(" \xB7 ")||(y?"gtag present":"not found"),2),r("google-ads","ads","Google Ads conversion tag (AW-\u2026)",g?"pass":"info",g||"none - only needed when running Google Ads",1);let _=te(/connect\.facebook\.net|fbq\s*\(/);r("meta-pixel","ads","Meta (Facebook) pixel",_?"pass":"info",_?/fbq\s*\(\s*['"]init['"]\s*,\s*['"](\d+)/.exec(a)?.[1]??"pixel present":"none - only needed when running Meta ads",1);let M=[te(/snap\.licdn\.com|_linkedin_partner_id/)&&"LinkedIn",te(/analytics\.tiktok\.com/)&&"TikTok",te(/static\.hotjar\.com|clarity\.ms/)&&"Heatmaps",te(/plausible\.io|umami|posthog/)&&"Privacy analytics"].filter(Boolean);M.length&&r("other-tags","ads","Other marketing tags detected","info",M.join(", "),0);let O=tg.map(({key:N,label:U})=>{let re=n.filter(ae=>ae.category===N&&ae.weight>0),j=re.reduce((ae,pe)=>ae+pe.weight,0),ee=re.reduce((ae,pe)=>ae+(pe.status==="pass"?pe.weight:pe.status==="warn"?pe.weight/2:0),0);return{key:N,label:U,score:j?Math.round(100*ee/j):null}}),B=n.filter(N=>N.weight>0),Y=B.length?Math.round(100*B.reduce((N,U)=>N+(U.status==="pass"?U.weight:U.status==="warn"?U.weight/2:0),0)/B.reduce((N,U)=>N+U.weight,0)):0;return{ok:!0,url:i.finalUrl,overall:Y,categories:O,checks:n}}function RT(t){return t.ok?[`Site probe of ${t.url} (checks run by code, no model): overall ${t.overall}/100`,...t.categories.map(n=>`- ${n.label}: ${n.score===null?"n/a":`${n.score}/100`}`),"",...t.checks.map(n=>`[${n.status.toUpperCase()}] (${n.category}) ${n.label} - ${n.detail}`)].join(`
823
+ `)){let c=a.split("#")[0].trim();if(!c)continue;let l=/^user-agent:\s*(.+)$/i.exec(c);if(l){(!r||s)&&(r={agents:[],disallowAll:!1},n.push(r),s=!1),r.agents.push(l[1].trim());continue}r&&(s=!0,/^disallow:\s*\/\s*$/i.test(c)&&(r.disallowAll=!0))}let i=a=>{let c=n.filter(u=>u.agents.some(p=>p.toLowerCase()===a.toLowerCase()));return(c.length?c:n.filter(u=>u.agents.includes("*"))).some(u=>u.disallowAll)};return e.filter(i)}async function TT(t,e=Xm){let n=[],r=(P,U,re,j,ee,ae=2)=>n.push({id:P,category:U,label:re,status:j,detail:ee,weight:j==="info"?0:ae}),s;try{s=await ng(t,{resolveDns:e===Xm})}catch(P){return{ok:!1,error:P instanceof Error?P.message:String(P),url:t,overall:0,categories:[],checks:[]}}let i;try{i=await e(s.toString())}catch(P){return{ok:!1,error:`could not fetch ${s.hostname}: ${P instanceof Error?P.message:"unreachable"}`,url:s.toString(),overall:0,categories:[],checks:[]}}let a=i.body,c=new URL(i.finalUrl),l=c.origin;r("status","seo","Page responds successfully",i.status===200?"pass":"fail",`HTTP ${i.status}`,3),r("https","seo","Served over HTTPS",c.protocol==="https:"?"pass":"fail",c.origin,3);let u=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(a)?.[1]?.trim()??"";r("title","seo","Title tag present and sized for results (10-60 chars)",u?u.length>=10&&u.length<=60?"pass":"warn":"fail",u?`"${u.slice(0,80)}" (${u.length} chars)`:"no <title>",3);let p=On(a,"description");r("meta-description","seo","Meta description present and sized (50-160 chars)",p?p.length>=50&&p.length<=160?"pass":"warn":"fail",p?`${p.length} chars`:"missing",3);let f=a.match(/<h1[\s>]/gi)?.length??0;r("h1","seo","Exactly one H1",f===1?"pass":f===0?"fail":"warn",`${f} found`,2);let m=/<link[^>]+rel\s*=\s*["']canonical["'][^>]*>/i.exec(a)?.[0]??"";r("canonical","seo","Canonical URL declared",m?"pass":"warn",m?Du(m,"href"):"none",2),r("viewport","seo","Mobile viewport meta",On(a,"viewport")?"pass":"fail",On(a,"viewport"),2),r("lang","seo","Language declared on <html>",/<html[^>]+lang\s*=/i.test(a)?"pass":"warn",/<html[^>]+lang\s*=\s*["']([^"']+)/i.exec(a)?.[1]??"none",1);let w=On(a,"robots").toLowerCase();r("noindex","seo","Page is indexable (no noindex)",w.includes("noindex")?"fail":"pass",w||"no robots meta (indexable)",3);let S=a.match(/<img[^>]*>/gi)??[],T=S.filter(P=>Du(P,"alt")!=="").length;r("img-alt","seo","Images carry alt text",S.length===0?"info":T/S.length>=.8?"pass":"warn",S.length?`${T}/${S.length} images`:"no images on this page",1);let x="";try{let P=await e(`${l}/robots.txt`);x=P.status===200?P.body.slice(0,1e5):""}catch{x=""}r("robots","seo","robots.txt present",x?"pass":"warn",x?`${l}/robots.txt`:"missing",1),x&&Lu(x,["*"]).length&&r("robots-all","seo","robots.txt does not block the whole site","fail","Disallow: / for all agents",3);let A=/sitemap:\s*(\S+)/i.exec(x)?.[1]??"",D=!1;try{let P=await e(A||`${l}/sitemap.xml`);D=P.status===200&&P.body.includes("<")}catch{D=!1}r("sitemap","seo","XML sitemap reachable",D?"pass":"warn",A||`${l}/sitemap.xml`,2);let K=a.match(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)??[],C=new Set;for(let P of K)for(let U of P.matchAll(/"@type"\s*:\s*"([^"]+)"/g))C.add(U[1]);r("json-ld","aeo","Structured data (JSON-LD) present",K.length?"pass":"warn",K.length?[...C].slice(0,8).join(", "):"none found",3),r("faq-schema","aeo","Q&A-shaped schema (FAQPage/HowTo) - answer engines lift these",C.has("FAQPage")||C.has("HowTo")?"pass":"info",C.has("FAQPage")?"FAQPage found":C.has("HowTo")?"HowTo found":"none - worth adding where it fits the content",1);let $=xT(a);r("ssr-content","aeo","Content present in the initial HTML (answer engines read this, not the hydrated app)",$.length>400?"pass":$.length>100?"warn":"fail",`${$.length} chars of visible text before JavaScript`,3);let v=x?Lu(x,rg):[];r("ai-crawlers","aeo","AI crawlers allowed (GPTBot, ClaudeBot, PerplexityBot\u2026)",v.length===0?"pass":"warn",v.length?`blocked: ${v.join(", ")}`:"none blocked in robots.txt",2);let N=!1;try{let P=await e(`${l}/llms.txt`);N=P.status===200&&P.body.trim().length>0&&!P.body.trim().startsWith("<")}catch{N=!1}r("llms-txt","aeo","llms.txt (optional AI index - Google says unnecessary, early adopters ship it anyway)",N?"pass":"info",N?`${l}/llms.txt`:"not present - a bonus, not a defect",1);let B=[...a.matchAll(/<h([1-3])[\s>]/gi)].map(P=>Number(P[1]));r("headings","aeo","Heading structure starts at H1",B.length===0?"warn":B[0]===1?"pass":"warn",B.slice(0,10).map(P=>`h${P}`).join(" \u2192 ")||"no h1-h3 at all",1);let V={title:On(a,"og:title"),description:On(a,"og:description"),image:On(a,"og:image")};r("og","social","Open Graph card (og:title / og:description / og:image)",V.title&&V.image?"pass":V.title||V.description?"warn":"fail",Object.entries(V).map(([P,U])=>`${P}: ${U?"\u2713":"\u2717"}`).join(" \xB7 "),2),r("twitter","social","Twitter/X card",On(a,"twitter:card")?"pass":"warn",On(a,"twitter:card")||"no twitter:card meta",1);let te=P=>P.test(a),L=/G-[A-Z0-9]{6,}/.exec(a)?.[0]??"",d=/GTM-[A-Z0-9]{4,}/.exec(a)?.[0]??"",g=/AW-\d{6,}/.exec(a)?.[0]??"",y=te(/googletagmanager\.com|gtag\(/);r("google-tag","ads","Google tag installed (GA4 / Tag Manager)",y?"pass":"warn",[L&&`GA4 ${L}`,d&&`GTM ${d}`].filter(Boolean).join(" \xB7 ")||(y?"gtag present":"not found"),2),r("google-ads","ads","Google Ads conversion tag (AW-\u2026)",g?"pass":"info",g||"none - only needed when running Google Ads",1);let _=te(/connect\.facebook\.net|fbq\s*\(/);r("meta-pixel","ads","Meta (Facebook) pixel",_?"pass":"info",_?/fbq\s*\(\s*['"]init['"]\s*,\s*['"](\d+)/.exec(a)?.[1]??"pixel present":"none - only needed when running Meta ads",1);let M=[te(/snap\.licdn\.com|_linkedin_partner_id/)&&"LinkedIn",te(/analytics\.tiktok\.com/)&&"TikTok",te(/static\.hotjar\.com|clarity\.ms/)&&"Heatmaps",te(/plausible\.io|umami|posthog/)&&"Privacy analytics"].filter(Boolean);M.length&&r("other-tags","ads","Other marketing tags detected","info",M.join(", "),0);let O=tg.map(({key:P,label:U})=>{let re=n.filter(ae=>ae.category===P&&ae.weight>0),j=re.reduce((ae,pe)=>ae+pe.weight,0),ee=re.reduce((ae,pe)=>ae+(pe.status==="pass"?pe.weight:pe.status==="warn"?pe.weight/2:0),0);return{key:P,label:U,score:j?Math.round(100*ee/j):null}}),F=n.filter(P=>P.weight>0),Y=F.length?Math.round(100*F.reduce((P,U)=>P+(U.status==="pass"?U.weight:U.status==="warn"?U.weight/2:0),0)/F.reduce((P,U)=>P+U.weight,0)):0;return{ok:!0,url:i.finalUrl,overall:Y,categories:O,checks:n}}function RT(t){return t.ok?[`Site probe of ${t.url} (checks run by code, no model): overall ${t.overall}/100`,...t.categories.map(n=>`- ${n.label}: ${n.score===null?"n/a":`${n.score}/100`}`),"",...t.checks.map(n=>`[${n.status.toUpperCase()}] (${n.category}) ${n.label} - ${n.detail}`)].join(`
824
824
  `):`Site probe of ${t.url} FAILED: ${t.error}`}var Qm,eg,kT,ST,_T,tg,Xm,xT,Du,On,rg,qu=J(()=>{"use strict";Qm=E(require("node:net"),1),eg=E(require("node:dns/promises"),1),kT=2e4,ST=2e6,_T="AllwrightSiteAuditor/1.0 (+https://getallwright.com)",tg=[{key:"seo",label:"Technical SEO"},{key:"aeo",label:"AI visibility (AEO/GEO)"},{key:"social",label:"Social sharing"},{key:"ads",label:"Analytics & ads tags"}];Xm=async t=>{let e=await fetch(t,{headers:{"user-agent":_T,accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow",signal:AbortSignal.timeout(kT)}),n=Buffer.from(await e.arrayBuffer());return{status:e.status,finalUrl:e.url||t,body:n.subarray(0,ST).toString("utf8"),contentType:e.headers.get("content-type")??""}},xT=t=>t.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),Du=(t,e)=>{let n=new RegExp(`${e}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i").exec(t);return(n?.[2]??n?.[3]??"").trim()},On=(t,e)=>{let r=new RegExp(`<meta[^>]+(?:name|property)\\s*=\\s*["']${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["'][^>]*>`,"i").exec(t)?.[0];return r?Du(r,"content"):""},rg=["GPTBot","ClaudeBot","Claude-Web","PerplexityBot","Google-Extended","Bingbot"]});async function gi(t){let{packs:e,lessons:n}=fi(t.role,t.repoPath,t.packs??[]);if(!e.length&&t.role!=="functional"&&t.role!=="engineering"&&t.role!=="seo"&&t.role!=="incident")return{ok:!1,error:`no knowledge packs found for the ${t.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${t.role}/ on the runner`};let r;if(t.role==="functional"){if(!t.baseUrl?.trim())return{ok:!1,error:"a functional audit needs a URL to visit - pick the environment (or type the URL) when starting it"};let{crawlSite:S,formatCrawlReport:T}=await Promise.resolve().then(()=>(Ym(),Jm));try{r=T(await S(t.baseUrl.trim()))}catch(x){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${x instanceof Error?x.message:"unreachable"}`}}}let s;if(t.role==="seo"&&t.baseUrl?.trim()){let{probeSite:S,formatSiteAuditReport:T}=await Promise.resolve().then(()=>(qu(),Uu));try{s=T(await S(t.baseUrl.trim()))}catch(x){s=`Site probe of ${t.baseUrl} failed: ${x instanceof Error?x.message:"unreachable"}`}}let i="";if(t.brief?.trim()&&(i=t.brief.trim().slice(0,16e3)),t.scope.kind==="ticket"&&t.scope.ref){let S=t.scope.ref,T="";try{let A=await t.jira.getIssue(S);T=`Ticket ${S}: ${A.summary}
825
825
 
826
826
  ${A.description}`.slice(0,4e3)}catch{T=`Ticket ${S} (could not fetch its text from Jira).`}let x=await bu(t.repoPath,S).catch(()=>null);if(x){let{base:A,stat:D,diff:K}=await Na(t.repoPath,x).catch(()=>({base:"",stat:"",diff:""}));i=`${T}
@@ -893,14 +893,14 @@ ${i.join(`
893
893
  `)}
894
894
  Read them with the Read tool; images can be viewed directly.`,dir:r}}var wi,yr,Ya,ZT,JT,Rg,YT,XT,rd,QT,sd=J(()=>{"use strict";wi=E(require("node:fs"),1),yr=E(require("node:path"),1),Ya=".ticketpilot-attachments",ZT=15*1024*1024,JT=50*1024*1024,Rg=20;YT=16*1024*1024,XT=32*1024*1024;rd=t=>Math.max(1,Math.round(t/1024)),QT=t=>Math.round(t/(1024*1024)*10)/10});function tR(t){return t.length<=3e4?t:`${t.slice(0,3e4)}
895
895
 
896
- [description truncated by Allwright at 30,000 characters - read the rest on the ticket]`}function od(){return new Ye({baseUrl:"",email:"",apiToken:""},!1)}function Ag(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
896
+ [description truncated by Allwright at 30,000 characters - read the rest on the ticket]`}function od(){return new Xe({baseUrl:"",email:"",apiToken:""},!1)}function Ag(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
897
897
  `);for(let s of r.content??[])n(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
898
898
  `)};return n(t),e.join("").replace(/\n{3,}/g,`
899
899
 
900
900
  `).trim()}function Xa(t){let e=t.replace(/\r\n/g,`
901
901
  `).split(`
902
902
  `),n=[],r=0,s=i=>{let a=[],c=/(\*\*[^*]+\*\*|`[^`]+`)/g,l=0,u;for(;(u=c.exec(i))!==null;){u.index>l&&a.push({type:"text",text:i.slice(l,u.index)});let p=u[0];p.startsWith("**")?a.push({type:"text",text:p.slice(2,-2),marks:[{type:"strong"}]}):a.push({type:"text",text:p.slice(1,-1),marks:[{type:"code"}]}),l=u.index+p.length}return l<i.length&&a.push({type:"text",text:i.slice(l)}),a.length?a:[{type:"text",text:" "}]};for(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let a=i.match(/^```(\w*)\s*$/);if(a){let f=[];for(r++;r<e.length&&!/^```\s*$/.test(e[r]);)f.push(e[r]),r++;r++,n.push({type:"codeBlock",attrs:a[1]?{language:a[1]}:{},content:[{type:"text",text:f.join(`
903
- `)||" "}]});continue}let c=i.match(/^(#{1,6})\s+(.*)$/);if(c){n.push({type:"heading",attrs:{level:c[1].length},content:s(c[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let m=e[r].match(/^\s*[-*]\s+(.*)$/);if(!m)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(m[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let m=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!m)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(m[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let p=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)p.push(e[r]),r++;n.push({type:"paragraph",content:s(p.join(" "))})}return{type:"doc",version:1,content:n}}var $g,eR,jt,id,nR,Ye,To=J(()=>{"use strict";$g="Posted automatically by Allwright",eR=["Posted automatically by TicketPilot"],jt=t=>t.includes($g)||eR.some(e=>t.includes(e));id=200,nR="no Jira credentials on this runner - add them with `allwright jira set-default`";Ye=class{constructor(e,n=!0){this.auth=e;this.configured=n}auth;configured;get isConfigured(){return this.configured}assertConfigured(){if(!this.configured)throw new Error(nR)}headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,n,r){this.assertConfigured();let s=new URL(n,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:r===void 0?void 0:JSON.stringify(r)});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${n} -> ${i.status}: ${a.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,n=20){let r=await this.userSearch(e,n);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),n)}async userSearch(e,n){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${n}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let n=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of n??[])for(let a of i.statuses??[])a.name&&!r.has(a.name)&&r.set(a.name,a.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...r.entries()].sort((i,a)=>s(i[1])-s(a[1])).map(([i])=>i)}async searchEpics(e,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:n,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,n=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:n,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchHistory(e,n){let r=[],s,i=Math.min(n.pageSize??50,100);for(;;){let a=await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:i,fields:["summary","status"],...s?{nextPageToken:s}:{}});for(let c of a.issues??[])r.push({key:c.key,summary:c.fields?.summary??"",status:c.fields?.status?.name??""});if(n.onPage?.(r.length),!a.issues?.length||r.length>=n.max||a.isLast||!a.nextPageToken)break;s=a.nextPageToken}return r.slice(0,n.max)}async searchBoard(e,n=1e3){let r=[],s;for(;;){let i=await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:100,fields:["summary","status","labels","components","fixVersions"],...s?{nextPageToken:s}:{}});for(let a of i.issues??[])r.push({key:a.key,summary:a.fields?.summary??"",status:a.fields?.status?.name??"(no status)",statusId:a.fields?.status?.id??"",labels:a.fields?.labels??[],components:(a.fields?.components??[]).map(c=>c.name??"").filter(Boolean),fixVersions:(a.fields?.fixVersions??[]).filter(c=>(c.name??"").trim()).map(c=>({name:c.name??"",released:!!c.released}))});if(!i.issues?.length||r.length>=n||i.isLast||!i.nextPageToken)break;s=i.nextPageToken}return r.slice(0,n)}async boardColumns(e){try{let r=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!r)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${r}/configuration`)).columnConfig?.columns??[]).filter(a=>(a.statuses??[]).length>0&&a.name).map(a=>({name:a.name,statusIds:(a.statuses??[]).map(c=>c.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment,issuetype,parent`),r;try{r=await this.listAllComments(e)}catch{r=n.fields.comment?.comments??[]}let s=r.map(c=>({id:c.id??"",author:c.author?.displayName??"unknown",authorAccountId:c.author?.accountId??null,created:c.created,body:Ag(c.body)})),i=(n.fields.attachment??[]).filter(c=>c.id&&c.filename&&c.content).map(c=>({id:c.id,filename:c.filename,mimeType:c.mimeType??"",size:c.size??0,contentUrl:c.content})),a=tR(Ag(n.fields.description));return{key:n.key,summary:n.fields.summary??"",description:a,labels:n.fields.labels??[],status:n.fields.status?.name??"",issueType:n.fields.issuetype?.name??"",comments:s,attachments:i,parentKey:n.fields.parent?.key??""}}async listAllComments(e){let n=await this.fetchCommentPage(e,0),r=n.total??n.comments.length;if(r<=n.comments.length)return n.comments;let s=Math.max(0,r-id),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,id);){let a=await this.fetchCommentPage(e,s+i.length);if(!a.comments.length)break;i.push(...a.comments)}return i.slice(-id)}async fetchCommentPage(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){this.assertConfigured();let n=await fetch(e,{headers:this.headers()});if(!n.ok)throw new Error(`attachment download failed: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async lastEnteredStatus(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=n.toLowerCase(),i=null;for(let a of r.changelog?.histories??[])(a.items??[]).some(l=>(l.field==="status"||l.fieldId==="status")&&(l.toString??"").toLowerCase()===s)&&(!i||new Date(a.created)>new Date(i.at))&&(i={at:a.created,author:a.author?.displayName??"unknown",authorAccountId:a.author?.accountId??null});return i}async createIssue(e,n,r,s="Task",i,a=[],c={}){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:Xa(r),...i?{parent:{key:i}}:{},...a.length?{components:a.map(u=>({name:u}))}:{},...c.fixVersionIds?.length?{fixVersions:c.fixVersionIds.map(u=>({id:u}))}:{}}})).key}}async assignIssue(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}/assignee`,{accountId:n})}async listVersions(e){return(await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/versions`)??[]).map(r=>({id:String(r.id),name:r.name,released:!!r.released}))}async createVersion(e,n){let r=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}`),s=await this.request("POST","/rest/api/3/version",{name:n.slice(0,100),projectId:Number(r.id)});return{id:String(s.id),name:s.name}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:Xa(n)}})}async addAttachments(e,n){if(!n.length)return;this.assertConfigured();let r=new FormData;for(let c of n)r.append("file",new Blob([new Uint8Array(c.content)]),c.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),a=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:r});if(!a.ok)throw new Error(`Jira attachment upload failed: HTTP ${a.status}`)}async addTriggerComment(e,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Xa(n)})}async addComment(e,n){let r=`${n}
903
+ `)||" "}]});continue}let c=i.match(/^(#{1,6})\s+(.*)$/);if(c){n.push({type:"heading",attrs:{level:c[1].length},content:s(c[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let m=e[r].match(/^\s*[-*]\s+(.*)$/);if(!m)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(m[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let m=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!m)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(m[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let p=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)p.push(e[r]),r++;n.push({type:"paragraph",content:s(p.join(" "))})}return{type:"doc",version:1,content:n}}var $g,eR,jt,id,nR,Xe,To=J(()=>{"use strict";$g="Posted automatically by Allwright",eR=["Posted automatically by TicketPilot"],jt=t=>t.includes($g)||eR.some(e=>t.includes(e));id=200,nR="no Jira credentials on this runner - add them with `allwright jira set-default`";Xe=class{constructor(e,n=!0){this.auth=e;this.configured=n}auth;configured;get isConfigured(){return this.configured}assertConfigured(){if(!this.configured)throw new Error(nR)}headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,n,r){this.assertConfigured();let s=new URL(n,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:r===void 0?void 0:JSON.stringify(r)});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${n} -> ${i.status}: ${a.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,n=20){let r=await this.userSearch(e,n);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),n)}async userSearch(e,n){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${n}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let n=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of n??[])for(let a of i.statuses??[])a.name&&!r.has(a.name)&&r.set(a.name,a.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...r.entries()].sort((i,a)=>s(i[1])-s(a[1])).map(([i])=>i)}async searchEpics(e,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:n,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,n=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:n,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchHistory(e,n){let r=[],s,i=Math.min(n.pageSize??50,100);for(;;){let a=await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:i,fields:["summary","status"],...s?{nextPageToken:s}:{}});for(let c of a.issues??[])r.push({key:c.key,summary:c.fields?.summary??"",status:c.fields?.status?.name??""});if(n.onPage?.(r.length),!a.issues?.length||r.length>=n.max||a.isLast||!a.nextPageToken)break;s=a.nextPageToken}return r.slice(0,n.max)}async searchBoard(e,n=1e3){let r=[],s;for(;;){let i=await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:100,fields:["summary","status","labels","components","fixVersions"],...s?{nextPageToken:s}:{}});for(let a of i.issues??[])r.push({key:a.key,summary:a.fields?.summary??"",status:a.fields?.status?.name??"(no status)",statusId:a.fields?.status?.id??"",labels:a.fields?.labels??[],components:(a.fields?.components??[]).map(c=>c.name??"").filter(Boolean),fixVersions:(a.fields?.fixVersions??[]).filter(c=>(c.name??"").trim()).map(c=>({name:c.name??"",released:!!c.released}))});if(!i.issues?.length||r.length>=n||i.isLast||!i.nextPageToken)break;s=i.nextPageToken}return r.slice(0,n)}async boardColumns(e){try{let r=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!r)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${r}/configuration`)).columnConfig?.columns??[]).filter(a=>(a.statuses??[]).length>0&&a.name).map(a=>({name:a.name,statusIds:(a.statuses??[]).map(c=>c.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment,issuetype,parent`),r;try{r=await this.listAllComments(e)}catch{r=n.fields.comment?.comments??[]}let s=r.map(c=>({id:c.id??"",author:c.author?.displayName??"unknown",authorAccountId:c.author?.accountId??null,created:c.created,body:Ag(c.body)})),i=(n.fields.attachment??[]).filter(c=>c.id&&c.filename&&c.content).map(c=>({id:c.id,filename:c.filename,mimeType:c.mimeType??"",size:c.size??0,contentUrl:c.content})),a=tR(Ag(n.fields.description));return{key:n.key,summary:n.fields.summary??"",description:a,labels:n.fields.labels??[],status:n.fields.status?.name??"",issueType:n.fields.issuetype?.name??"",comments:s,attachments:i,parentKey:n.fields.parent?.key??""}}async listAllComments(e){let n=await this.fetchCommentPage(e,0),r=n.total??n.comments.length;if(r<=n.comments.length)return n.comments;let s=Math.max(0,r-id),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,id);){let a=await this.fetchCommentPage(e,s+i.length);if(!a.comments.length)break;i.push(...a.comments)}return i.slice(-id)}async fetchCommentPage(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){this.assertConfigured();let n=await fetch(e,{headers:this.headers()});if(!n.ok)throw new Error(`attachment download failed: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async lastEnteredStatus(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=n.toLowerCase(),i=null;for(let a of r.changelog?.histories??[])(a.items??[]).some(l=>(l.field==="status"||l.fieldId==="status")&&(l.toString??"").toLowerCase()===s)&&(!i||new Date(a.created)>new Date(i.at))&&(i={at:a.created,author:a.author?.displayName??"unknown",authorAccountId:a.author?.accountId??null});return i}async createIssue(e,n,r,s="Task",i,a=[],c={}){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:Xa(r),...i?{parent:{key:i}}:{},...a.length?{components:a.map(u=>({name:u}))}:{},...c.fixVersionIds?.length?{fixVersions:c.fixVersionIds.map(u=>({id:u}))}:{}}})).key}}async assignIssue(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}/assignee`,{accountId:n})}async listVersions(e){return(await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/versions`)??[]).map(r=>({id:String(r.id),name:r.name,released:!!r.released}))}async createVersion(e,n){let r=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}`),s=await this.request("POST","/rest/api/3/version",{name:n.slice(0,100),projectId:Number(r.id)});return{id:String(s.id),name:s.name}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:Xa(n)}})}async addAttachments(e,n){if(!n.length)return;this.assertConfigured();let r=new FormData;for(let c of n)r.append("file",new Blob([new Uint8Array(c.content)]),c.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),a=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:r});if(!a.ok)throw new Error(`Jira attachment upload failed: HTTP ${a.status}`)}async addTriggerComment(e,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Xa(n)})}async addComment(e,n){let r=`${n}
904
904
 
905
905
  ---
906
906
  _${$g} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Xa(r)})}async editLabels(e,n){let r=[...(n.add??[]).map(s=>({add:s})),...(n.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:r}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(r=>({id:r.id,name:r.name}))}async transition(e,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:n}})}async transitionByName(e,n){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===n.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}}});function cR(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=ad.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let a of i){if(a.name.startsWith(".")||aR.has(a.name))continue;let c=Qa.default.join(r,a.name);a.isDirectory()?n(c,s+1):a.isFile()&&/\.md$/i.test(a.name)&&e.push(c)}};return n(t,0),e}function ec(t){let e=[],n=0;for(let r of cR(t)){if(n>=rR||e.join(`
@@ -963,12 +963,12 @@ Should this run implement the epic ticket itself?
963
963
  ${O}${Be.NEEDS_INPUT_ASK_FENCE}
964
964
  {"options": ["${xR}", "${TR}"]}
965
965
  ${O}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let A=t.continueBranch;A&&!u&&await hu(t.repoPath,l)===!1&&(e("info",`Batch branch "${l}" is not on origin - an earlier ticket in this batch finished without pushing one. Starting it from origin/${a.baseBranch}.`),A=!1);let D=A?l:a.baseBranch;u?e("info",`Resuming the session that timed out on this ticket (timeout resume ${u.resumes}/${dd}) - same worktree, uncommitted work intact, repo context cached`):(e("info",A?`Continuing branch "${l}" from origin/${l} (autopilot batch)`:`Preparing worktree on branch "${l}" from origin/${a.baseBranch}`),await cr(t.repoPath,D),t.chain&&A||await pu(t.repoPath,l),t.chain?(e("info","Chaining onto the previous ticket's workspace - resuming its agent session (repo context cached, not re-explored)"),await wu(p,l,A?`origin/${l}`:`origin/${a.baseBranch}`)):await fu(t.repoPath,p,l,D)),m=!0;let K=Pn(a.promptTemplate,{issueKey:x.key,summary:x.summary,description:x.description||"(no description)",comments:Ss(x.comments)}),C=DR(`${x.summary}
966
- ${x.description??""}`);!u&&!C&&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 $=u?null:await Ca(p,a.baseBranch,x.key).catch(()=>null),v=!u&&!t.chain&&!$&&x.parentKey?await t.jira.epicChildren(x.parentKey).then(O=>du(p,a.baseBranch,O.map(B=>B.key).filter(B=>B!==x.key))).catch(()=>({files:[],more:0,hits:[]})):{files:[],more:0,hits:[]},P=Ve(a.agent),F=We(t.cfg,a.agent),V=!u&&!t.chain&&!C&&!v.hits.length?await OR(t.runId,P,F,t.claudeConfigDir,p,x,e):yd,te=[],L=(O,B)=>(B&&te.push({part:O,chars:B.length}),B),d=L("ticket: rule template + summary (rendered)",K)+L("attachments listing",await vi(t.jira,x.attachments,p,e))+L("design guideline pointer",bd(p))+L("knowledge: rules",kR(t.repoPath,t.project.packs??[]))+L("memory: retrieved history",hr("implement",t.repoPath,{issueKey:x.key,summary:x.summary,description:x.description,ruleName:t.rule.name}))+L("doc index",ec(p))+L("repo brief (machine-generated)",t.chain?"":Io(t.project.repoName))+L("revision: previous delivery + what is new",$?PR($,x.comments,jt):"")+L("sibling tickets: files touched",NR(v))+L("scout: likely files",zR(V.text))+L("appendix: focused reading",br.FOCUSED_READING_PROMPT)+L("appendix: protected paths",yR)+L("appendix: needs-input options",Be.NEEDS_INPUT_OPTIONS_PROMPT)+L("appendix: PR summary",bR)+L("appendix: go-live",t.project.goLiveIssueKey?wR:"")+L("appendix: write tests",a.writeTests?br.WRITE_TESTS_PROMPT:"")+L("appendix: update memory",a.updateMemory?Be.MEMORY_UPDATE_PROMPT:"")+L("epic confirmation answer",t.preflightAnswer?`
966
+ ${x.description??""}`);!u&&!C&&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 $=u?null:await Ca(p,a.baseBranch,x.key).catch(()=>null),v=!u&&!t.chain&&!$&&x.parentKey?await t.jira.epicChildren(x.parentKey).then(O=>du(p,a.baseBranch,O.map(F=>F.key).filter(F=>F!==x.key))).catch(()=>({files:[],more:0,hits:[]})):{files:[],more:0,hits:[]},N=Ve(a.agent),B=We(t.cfg,a.agent),V=!u&&!t.chain&&!C&&!v.hits.length?await OR(t.runId,N,B,t.claudeConfigDir,p,x,e):yd,te=[],L=(O,F)=>(F&&te.push({part:O,chars:F.length}),F),d=L("ticket: rule template + summary (rendered)",K)+L("attachments listing",await vi(t.jira,x.attachments,p,e))+L("design guideline pointer",bd(p))+L("knowledge: rules",kR(t.repoPath,t.project.packs??[]))+L("memory: retrieved history",hr("implement",t.repoPath,{issueKey:x.key,summary:x.summary,description:x.description,ruleName:t.rule.name}))+L("doc index",ec(p))+L("repo brief (machine-generated)",t.chain?"":Io(t.project.repoName))+L("revision: previous delivery + what is new",$?PR($,x.comments,jt):"")+L("sibling tickets: files touched",NR(v))+L("scout: likely files",zR(V.text))+L("appendix: focused reading",br.FOCUSED_READING_PROMPT)+L("appendix: protected paths",yR)+L("appendix: needs-input options",Be.NEEDS_INPUT_OPTIONS_PROMPT)+L("appendix: PR summary",bR)+L("appendix: go-live",t.project.goLiveIssueKey?wR:"")+L("appendix: write tests",a.writeTests?br.WRITE_TESTS_PROMPT:"")+L("appendix: update memory",a.updateMemory?Be.MEMORY_UPDATE_PROMPT:"")+L("epic confirmation answer",t.preflightAnswer?`
967
967
 
968
968
  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:
969
- ${t.preflightAnswer.slice(0,4e3)}`:"");x.description&&te.push({part:"\u21B3 of which ticket description",chars:x.description.length});let g=Ss(x.comments).length;g&&te.push({part:"\u21B3 of which comment history",chars:g}),t.transport.sendRunContext({runId:t.runId,pieces:u?[{part:"continuation prompt (session resumed - original context already cached)",chars:md.length}]:te,totalChars:u?md.length:d.length,sessionMode:u?"timeout-resume":t.chain?"chained":t.preflightAnswer?"preflight-resume":"fresh"}),e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${a.timeoutSeconds}s`),ks(vs.parse({runId:t.runId,issueKey:t.issueKey,projectId:t.project.id,ruleId:t.rule.id,kind:"implement",workPath:p,sessionId:f,agent:a.agent,model:a.model??"",claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,timeoutSeconds:a.timeoutSeconds,maxTurns:a.maxTurns,allowWeb:a.allowWeb,runTests:a.runTests,doneLabel:i.doneLabel,failedLabel:i.failedLabel,issueSummary:x.summary,repoName:t.project.repoName,baseRepoPath:t.repoPath,branch:l,baseBranch:a.baseBranch,jiraTransition:a.jiraTransition,jiraTransitionOnMerge:a.jiraTransitionOnMerge,requireApproval:a.requireApproval,mergeOnApprove:a.mergeOnApprove,mergeMethod:a.mergeMethod,autoMerge:a.autoMerge,batchId:t.batchId??"",startedAt:new Date().toISOString()}));let y=await wr(t.runId,P,{repoPath:p,prompt:u?md:d,timeoutSeconds:a.timeoutSeconds,bin:F,configDir:t.claudeConfigDir,mode:a.allowWeb?"edit_no_shell_web":"edit_no_shell",model:a.model||void 0,maxTurns:a.maxTurns,maxCostUsd:a.maxCostUsd,sessionId:f,resume:!!t.chain||!!u,onLog:(O,B)=>e(O,B),onUsage:r},e,()=>uo(p)),_={costUsd:y.costUsd+V.cost.costUsd,inputTokens:y.inputTokens+V.cost.inputTokens,outputTokens:y.outputTokens+V.cost.outputTokens,cacheReadTokens:(y.cacheReadTokens??0)+V.cost.cacheReadTokens,billingMode:y.billingMode,model:y.model};if(!y.ok){let O=y.error??"Claude Code failed";e("error",`Run failed: ${O}`);let B=O,Y=(y.timedOut||y.costCapped)&&!y.cancelled&&Ve(a.agent)?.capabilities.sessionResume&&(u?.resumes??0)<dd;if(y.turnLimitHit&&!Y){let N=await vd(p,l,t.runId,e);N&&(B+=kd(N))}Y&&(hd(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:l,resumes:(u?.resumes??0)+1}),w=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),B+=" - 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"),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:O.slice(0,500)}),await ki(t,B),n(y.timedOut?"timed_out":"failed",{error:B,...y.cancelled||y.costCapped?{errorKind:"guard"}:{},..._});return}let M=_i(y.resultText);if(M){S=!0,await Si({kind:"implement",allowWeb:a.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:p,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:a.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:a.agent,model:a.model,actorEmail:t.actorEmail,baseRepoPath:t.repoPath,repoName:t.project.repoName,branch:l,baseBranch:a.baseBranch,jiraTransition:a.jiraTransition,jiraTransitionOnMerge:a.jiraTransitionOnMerge,requireApproval:a.requireApproval,mergeOnApprove:a.mergeOnApprove,mergeMethod:a.mergeMethod,autoMerge:a.autoMerge,runTests:a.runTests,maxTurns:a.maxTurns,issueSummary:x.summary},M,e,n,_);return}Ln(p),await _d({runId:t.runId,issueKey:t.issueKey,issueSummary:x.summary,worktreePath:p,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:l,baseBranch:a.baseBranch,jiraTransition:a.jiraTransition,jiraTransitionOnMerge:a.jiraTransitionOnMerge,requireApproval:a.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:t.project.repoName,jira:t.jira,cfg:t.cfg,actorEmail:t.actorEmail,resultText:y.resultText,costFields:_,runTests:a.runTests,fixSession:{sessionId:f,agent:a.agent,model:a.model,timeoutSeconds:a.timeoutSeconds,maxTurns:a.maxTurns,allowWeb:a.allowWeb},sendUsage:r,mergeOnApprove:a.mergeOnApprove,mergeMethod:a.mergeMethod,autoMerge:a.autoMerge,emit:e,setStatus:n}),t.onChainSession?.({sessionId:f,worktreePath:p})}catch(T){let x=T instanceof Error?T.message:String(T);e("error",`Run failed: ${x}`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:x.slice(0,500)}),await ki(t,x),n("failed",{error:x})}finally{mn(t.runId),m&&!S&&!t.keepWorktree&&!w&&await Zt(t.repoPath,p).catch(()=>{})}}async function Sd(t,e,n,r){let{emit:s,setStatus:i,sendUsage:a,nextSeq:c}=Un(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 Po({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:c()});return}let l=t.repoPath,u=!1;if(!rc.default.existsSync(l)){i("failed",{error:`the workspace this run was parked in (${l}) 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(!po(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=hy(e)+await vi(r.jiraFor(t.repoName??""),n,l,s);ks(vs.parse({runId:t.runId,issueKey:t.issueKey,kind:"implement",workPath:l,sessionId:t.sessionId,agent:t.agent??"",model:t.model??"",claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns,allowWeb:t.allowWeb,runTests:t.runTests,doneLabel:t.doneLabel,failedLabel:t.failedLabel,issueSummary:t.issueSummary,repoName:t.repoName??"",baseRepoPath:t.baseRepoPath,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval??!0,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,startedAt:new Date().toISOString()}));let f=await wr(t.runId,Ve(t.agent),{repoPath:l,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:We(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:(S,T)=>s(S,T),onUsage:a},s,()=>uo(l)),m={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens??0,billingMode:f.billingMode,model:f.model};if(!f.ok){let S=f.error??"Claude Code failed";s("error",`Run failed: ${S}`);let T=S;if(f.turnLimitHit&&t.branch){let x=await vd(l,t.branch,t.runId,s);x&&(T+=kd(x))}await wt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,T),pn(t.runId),i(f.timedOut?"timed_out":"failed",{error:S,...f.cancelled?{errorKind:"guard"}:{},...m});return}let w=_i(f.resultText);if(w){if(t.rounds>=Yg){await py(r.jiraFor(t.repoName??""),t,s,i,m);return}u=!0,await Si({kind:"implement",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:l,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:c(),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,m);return}Ln(l),await _d({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:l,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??l,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:m,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns,allowWeb:t.allowWeb},sendUsage:a,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),pn(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await wt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),pn(t.runId),i("failed",{error:f})}finally{mn(t.runId),u||await Zt(t.baseRepoPath??l,l).catch(()=>{})}}async function _d(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:a,baseBranch:c,jiraTransition:l,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:m,repoName:w,jira:S,cfg:T,actorEmail:x,runTests:A,mergeOnApprove:D,mergeMethod:K,autoMerge:C,resultText:$,costFields:v,emit:P,setStatus:F}=t,V=await hi(s);V.deleted.length&&P("info",`Deleted ${V.deleted.length} file(s) listed in ${Nn}: `+V.deleted.slice(0,10).join(", ")+(V.deleted.length>10?", \u2026":""));for(let j of V.refused)P("warn",`${Nn} entry refused: ${j}`);let te=await yo(s);for(let j of te.notes)P("warn",j);te.regenerated.length&&P("info",`Regenerated ${te.regenerated.length} lockfile(s) for the agent's dependency change (the jail has no shell, so the runner runs the lockfile-only install): `+te.regenerated.join(", ")),P("info","Committing changes"),await ps(s,`${n}: ${r}
969
+ ${t.preflightAnswer.slice(0,4e3)}`:"");x.description&&te.push({part:"\u21B3 of which ticket description",chars:x.description.length});let g=Ss(x.comments).length;g&&te.push({part:"\u21B3 of which comment history",chars:g}),t.transport.sendRunContext({runId:t.runId,pieces:u?[{part:"continuation prompt (session resumed - original context already cached)",chars:md.length}]:te,totalChars:u?md.length:d.length,sessionMode:u?"timeout-resume":t.chain?"chained":t.preflightAnswer?"preflight-resume":"fresh"}),e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${a.timeoutSeconds}s`),ks(vs.parse({runId:t.runId,issueKey:t.issueKey,projectId:t.project.id,ruleId:t.rule.id,kind:"implement",workPath:p,sessionId:f,agent:a.agent,model:a.model??"",claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,timeoutSeconds:a.timeoutSeconds,maxTurns:a.maxTurns,allowWeb:a.allowWeb,runTests:a.runTests,doneLabel:i.doneLabel,failedLabel:i.failedLabel,issueSummary:x.summary,repoName:t.project.repoName,baseRepoPath:t.repoPath,branch:l,baseBranch:a.baseBranch,jiraTransition:a.jiraTransition,jiraTransitionOnMerge:a.jiraTransitionOnMerge,requireApproval:a.requireApproval,mergeOnApprove:a.mergeOnApprove,mergeMethod:a.mergeMethod,autoMerge:a.autoMerge,batchId:t.batchId??"",startedAt:new Date().toISOString()}));let y=await wr(t.runId,N,{repoPath:p,prompt:u?md:d,timeoutSeconds:a.timeoutSeconds,bin:B,configDir:t.claudeConfigDir,mode:a.allowWeb?"edit_no_shell_web":"edit_no_shell",model:a.model||void 0,maxTurns:a.maxTurns,maxCostUsd:a.maxCostUsd,sessionId:f,resume:!!t.chain||!!u,onLog:(O,F)=>e(O,F),onUsage:r},e,()=>uo(p)),_={costUsd:y.costUsd+V.cost.costUsd,inputTokens:y.inputTokens+V.cost.inputTokens,outputTokens:y.outputTokens+V.cost.outputTokens,cacheReadTokens:(y.cacheReadTokens??0)+V.cost.cacheReadTokens,billingMode:y.billingMode,model:y.model};if(!y.ok){let O=y.error??"Claude Code failed";e("error",`Run failed: ${O}`);let F=O,Y=(y.timedOut||y.costCapped)&&!y.cancelled&&Ve(a.agent)?.capabilities.sessionResume&&(u?.resumes??0)<dd;if(y.turnLimitHit&&!Y){let P=await vd(p,l,t.runId,e);P&&(F+=kd(P))}Y&&(hd(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:l,resumes:(u?.resumes??0)+1}),w=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),F+=" - 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"),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:O.slice(0,500)}),await ki(t,F),n(y.timedOut?"timed_out":"failed",{error:F,...y.cancelled||y.costCapped?{errorKind:"guard"}:{},..._});return}let M=_i(y.resultText);if(M){S=!0,await Si({kind:"implement",allowWeb:a.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:p,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:a.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:a.agent,model:a.model,actorEmail:t.actorEmail,baseRepoPath:t.repoPath,repoName:t.project.repoName,branch:l,baseBranch:a.baseBranch,jiraTransition:a.jiraTransition,jiraTransitionOnMerge:a.jiraTransitionOnMerge,requireApproval:a.requireApproval,mergeOnApprove:a.mergeOnApprove,mergeMethod:a.mergeMethod,autoMerge:a.autoMerge,runTests:a.runTests,maxTurns:a.maxTurns,issueSummary:x.summary},M,e,n,_);return}Ln(p),await _d({runId:t.runId,issueKey:t.issueKey,issueSummary:x.summary,worktreePath:p,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:l,baseBranch:a.baseBranch,jiraTransition:a.jiraTransition,jiraTransitionOnMerge:a.jiraTransitionOnMerge,requireApproval:a.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:t.project.repoName,jira:t.jira,cfg:t.cfg,actorEmail:t.actorEmail,resultText:y.resultText,costFields:_,runTests:a.runTests,fixSession:{sessionId:f,agent:a.agent,model:a.model,timeoutSeconds:a.timeoutSeconds,maxTurns:a.maxTurns,allowWeb:a.allowWeb},sendUsage:r,mergeOnApprove:a.mergeOnApprove,mergeMethod:a.mergeMethod,autoMerge:a.autoMerge,emit:e,setStatus:n}),t.onChainSession?.({sessionId:f,worktreePath:p})}catch(T){let x=T instanceof Error?T.message:String(T);e("error",`Run failed: ${x}`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:x.slice(0,500)}),await ki(t,x),n("failed",{error:x})}finally{mn(t.runId),m&&!S&&!t.keepWorktree&&!w&&await Zt(t.repoPath,p).catch(()=>{})}}async function Sd(t,e,n,r){let{emit:s,setStatus:i,sendUsage:a,nextSeq:c}=Un(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 Po({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:c()});return}let l=t.repoPath,u=!1;if(!rc.default.existsSync(l)){i("failed",{error:`the workspace this run was parked in (${l}) 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(!po(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=hy(e)+await vi(r.jiraFor(t.repoName??""),n,l,s);ks(vs.parse({runId:t.runId,issueKey:t.issueKey,kind:"implement",workPath:l,sessionId:t.sessionId,agent:t.agent??"",model:t.model??"",claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns,allowWeb:t.allowWeb,runTests:t.runTests,doneLabel:t.doneLabel,failedLabel:t.failedLabel,issueSummary:t.issueSummary,repoName:t.repoName??"",baseRepoPath:t.baseRepoPath,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval??!0,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,startedAt:new Date().toISOString()}));let f=await wr(t.runId,Ve(t.agent),{repoPath:l,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:We(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:(S,T)=>s(S,T),onUsage:a},s,()=>uo(l)),m={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens??0,billingMode:f.billingMode,model:f.model};if(!f.ok){let S=f.error??"Claude Code failed";s("error",`Run failed: ${S}`);let T=S;if(f.turnLimitHit&&t.branch){let x=await vd(l,t.branch,t.runId,s);x&&(T+=kd(x))}await wt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,T),pn(t.runId),i(f.timedOut?"timed_out":"failed",{error:S,...f.cancelled?{errorKind:"guard"}:{},...m});return}let w=_i(f.resultText);if(w){if(t.rounds>=Yg){await py(r.jiraFor(t.repoName??""),t,s,i,m);return}u=!0,await Si({kind:"implement",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:l,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:c(),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,m);return}Ln(l),await _d({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:l,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??l,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:m,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns,allowWeb:t.allowWeb},sendUsage:a,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),pn(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await wt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),pn(t.runId),i("failed",{error:f})}finally{mn(t.runId),u||await Zt(t.baseRepoPath??l,l).catch(()=>{})}}async function _d(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:a,baseBranch:c,jiraTransition:l,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:m,repoName:w,jira:S,cfg:T,actorEmail:x,runTests:A,mergeOnApprove:D,mergeMethod:K,autoMerge:C,resultText:$,costFields:v,emit:N,setStatus:B}=t,V=await hi(s);V.deleted.length&&N("info",`Deleted ${V.deleted.length} file(s) listed in ${Nn}: `+V.deleted.slice(0,10).join(", ")+(V.deleted.length>10?", \u2026":""));for(let j of V.refused)N("warn",`${Nn} entry refused: ${j}`);let te=await yo(s);for(let j of te.notes)N("warn",j);te.regenerated.length&&N("info",`Regenerated ${te.regenerated.length} lockfile(s) for the agent's dependency change (the jail has no shell, so the runner runs the lockfile-only install): `+te.regenerated.join(", ")),N("info","Committing changes"),await ps(s,`${n}: ${r}
970
970
 
971
- Allwright run ${e}`);let L=await lr(s,c);if(!L.ok){let j=L.forbidden.length?`refusing to push: changes touch protected paths (${L.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 (${L.files} files, ${L.countedLines} reviewable lines of ${L.insertions+L.deletions} total; limits ${or} files/${ar} lines - lockfile churn and pure deletions are exempt)`;P("error",j),await wt(S,n,e,m,j),F("failed",{error:j,errorKind:"guard",...v});return}P("info",`Diff: ${L.files} file(s), +${L.insertions}/-${L.deletions}`);let d={...v},g="",y="",_,M,O;if(A){let j=mi(s);if(!j)P("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ee=fr(rc.default.readFileSync(j,"utf8"));if(!ee.length)P("info",`${sc.default.basename(j)} lists no commands - nothing to run`);else{P("info",`Running ${ee.length} documented test command(s) - no tokens, plain shell`);let ae=await Mn(s,ee,{perCommandTimeoutMs:15*6e4,repoName:w}),pe=ae.filter(me=>me.exitCode!==0),$e=pe.length;for(let me of ae)P(me.exitCode===0?"info":"warn",Gg(me));let lt=_m(i,pe.map(me=>me.command)),oa=pe.filter(me=>!lt.has(me.command)),Ar=lt.size?`${lt.size} of ${pe.length} failing command(s) match a recurring, environment-suspected failure in this repo's run history - no automatic fix attempt ran for those; they still show as failed below. Investigate the sandbox/TEST.md itself rather than this ticket's changes.`:"";Ar&&P("info",Ar);let Ht="";if(oa.length&&t.fixSession){let me=await CR({runId:e,issueKey:n,worktreePath:s,baseBranch:c,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:T,failed:oa,emit:P,sendUsage:t.sendUsage,baseCost:d});if(d.costUsd+=me.cost.costUsd,d.inputTokens+=me.cost.inputTokens,d.outputTokens+=me.cost.outputTokens,me.outcome==="cancelled"){let se="stopped by a person during the automatic test-fix attempt - nothing was pushed";P("warn",se),Ha({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:K,autoMerge:C,repoName:w,baseRepoPath:i,branch:a,baseBranch:c,headSha:await mt(s),requireApproval:p,doneLabel:f,failedLabel:m,jiraTransition:l,jiraTransitionOnMerge:u,actorEmail:x,resultSummary:Jg($),prSummary:gd($)??"",costUsd:d.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await wt(S,n,e,m,`${se}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),F("failed",{error:se,errorKind:"guard",retryAvailable:!0,...d});return}if(me.outcome==="committed"){y=me.resultText,P("info",`Re-running ${ee.length} documented test command(s) after the fix`),ae=await Mn(s,ee,{perCommandTimeoutMs:15*6e4,repoName:w}),pe=ae.filter(se=>se.exitCode!==0);for(let se of ae)P(se.exitCode===0?"info":"warn",Gg(se));Ht=pe.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${$e} failure(s). ${me.note}`:`The first pass had ${$e} failure(s); one automatic same-session fix attempt resolved them. ${me.note}`}else Ht=me.note}_=pe.slice(0,20).map(me=>({command:me.command.slice(0,500),exitCode:me.exitCode,tail:me.tail.slice(-4e3)})),M=ae.length-pe.length,O=ae.length,g=`
971
+ Allwright run ${e}`);let L=await lr(s,c);if(!L.ok){let j=L.forbidden.length?`refusing to push: changes touch protected paths (${L.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 (${L.files} files, ${L.countedLines} reviewable lines of ${L.insertions+L.deletions} total; limits ${or} files/${ar} lines - lockfile churn and pure deletions are exempt)`;N("error",j),await wt(S,n,e,m,j),B("failed",{error:j,errorKind:"guard",...v});return}N("info",`Diff: ${L.files} file(s), +${L.insertions}/-${L.deletions}`);let d={...v},g="",y="",_,M,O;if(A){let j=mi(s);if(!j)N("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ee=fr(rc.default.readFileSync(j,"utf8"));if(!ee.length)N("info",`${sc.default.basename(j)} lists no commands - nothing to run`);else{N("info",`Running ${ee.length} documented test command(s) - no tokens, plain shell`);let ae=await Mn(s,ee,{perCommandTimeoutMs:15*6e4,repoName:w}),pe=ae.filter(me=>me.exitCode!==0),$e=pe.length;for(let me of ae)N(me.exitCode===0?"info":"warn",Gg(me));let lt=_m(i,pe.map(me=>me.command)),oa=pe.filter(me=>!lt.has(me.command)),Ar=lt.size?`${lt.size} of ${pe.length} failing command(s) match a recurring, environment-suspected failure in this repo's run history - no automatic fix attempt ran for those; they still show as failed below. Investigate the sandbox/TEST.md itself rather than this ticket's changes.`:"";Ar&&N("info",Ar);let Ht="";if(oa.length&&t.fixSession){let me=await CR({runId:e,issueKey:n,worktreePath:s,baseBranch:c,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:T,failed:oa,emit:N,sendUsage:t.sendUsage,baseCost:d});if(d.costUsd+=me.cost.costUsd,d.inputTokens+=me.cost.inputTokens,d.outputTokens+=me.cost.outputTokens,me.outcome==="cancelled"){let se="stopped by a person during the automatic test-fix attempt - nothing was pushed";N("warn",se),Ha({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:K,autoMerge:C,repoName:w,baseRepoPath:i,branch:a,baseBranch:c,headSha:await mt(s),requireApproval:p,doneLabel:f,failedLabel:m,jiraTransition:l,jiraTransitionOnMerge:u,actorEmail:x,resultSummary:Jg($),prSummary:gd($)??"",costUsd:d.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await wt(S,n,e,m,`${se}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),B("failed",{error:se,errorKind:"guard",retryAvailable:!0,...d});return}if(me.outcome==="committed"){y=me.resultText,N("info",`Re-running ${ee.length} documented test command(s) after the fix`),ae=await Mn(s,ee,{perCommandTimeoutMs:15*6e4,repoName:w}),pe=ae.filter(se=>se.exitCode!==0);for(let se of ae)N(se.exitCode===0?"info":"warn",Gg(se));Ht=pe.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${$e} failure(s). ${me.note}`:`The first pass had ${$e} failure(s); one automatic same-session fix attempt resolved them. ${me.note}`}else Ht=me.note}_=pe.slice(0,20).map(me=>({command:me.command.slice(0,500),exitCode:me.exitCode,tail:me.tail.slice(-4e3)})),M=ae.length-pe.length,O=ae.length,g=`
972
972
 
973
973
  ### Tests
974
974
  `+ae.map(me=>`- ${me.exitCode===0?"PASS":"FAIL"} \`${me.command}\``).join(`
@@ -978,30 +978,30 @@ Allwright run ${e}`);let L=await lr(s,c);if(!L.ok){let j=L.forbidden.length?`ref
978
978
 
979
979
  All ${ae.length} passed.`)+[Ar,Ht].filter(Boolean).map(me=>`
980
980
 
981
- ${me}`).join(""),pe.length&&P("warn",`${pe.length} test command(s) failed - the PR will say so; review before merging`),$e>0&&Ct(i,{issueKey:n,runId:e,title:pe.length?`TEST.md commands failing at PR (${pe.length} of ${ae.length})`:"TEST.md failures fixed by same-session retry",detail:ae.map(me=>`${me.exitCode===0?"PASS":"FAIL"} ${me.command}`).join(`
981
+ ${me}`).join(""),pe.length&&N("warn",`${pe.length} test command(s) failed - the PR will say so; review before merging`),$e>0&&Ct(i,{issueKey:n,runId:e,title:pe.length?`TEST.md commands failing at PR (${pe.length} of ${ae.length})`:"TEST.md failures fixed by same-session retry",detail:ae.map(me=>`${me.exitCode===0?"PASS":"FAIL"} ${me.command}`).join(`
982
982
  `)+(Ht?`
983
- ${Ht}`:"")})}}}let B=await ms(s),Y=Jt(B);if(!Y){let j=`origin "${B}" is not a GitHub remote - implement mode supports GitHub only`;P("error",j),await wt(S,n,e,m,j),F("failed",{error:j,...v});return}let N=await mt(s),U=Jg($),re=(y?gd(y):null)??gd($);try{await sy({gitDir:s,ownerRepo:Y,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:a,baseBranch:c,jiraTransition:l,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:m,repoName:w,jira:S,cfg:T,actorEmail:x,mergeOnApprove:D,mergeMethod:K,autoMerge:C,summary:U,prSummary:re??void 0,cost:d,testReport:g,failedTests:_,testsPassed:M,testsTotal:O,goLiveDraft:(y?Wg(y):null)??Wg($)??void 0,emit:P,setStatus:F})}catch(j){let ee=j instanceof Error?j.message:String(j);Ha({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:K,autoMerge:C,repoName:w,baseRepoPath:i,branch:a,baseBranch:c,headSha:N,requireApproval:p,doneLabel:f,failedLabel:m,jiraTransition:l,jiraTransitionOnMerge:u,actorEmail:x,resultSummary:U,prSummary:re??"",costUsd:d.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),P("error",`Run failed: ${ee}`),P("info",`The commit itself survived on the runner (branch ${a}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await wt(S,n,e,m,`${ee}
983
+ ${Ht}`:"")})}}}let F=await ms(s),Y=Jt(F);if(!Y){let j=`origin "${F}" is not a GitHub remote - implement mode supports GitHub only`;N("error",j),await wt(S,n,e,m,j),B("failed",{error:j,...v});return}let P=await mt(s),U=Jg($),re=(y?gd(y):null)??gd($);try{await sy({gitDir:s,ownerRepo:Y,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:a,baseBranch:c,jiraTransition:l,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:m,repoName:w,jira:S,cfg:T,actorEmail:x,mergeOnApprove:D,mergeMethod:K,autoMerge:C,summary:U,prSummary:re??void 0,cost:d,testReport:g,failedTests:_,testsPassed:M,testsTotal:O,goLiveDraft:(y?Wg(y):null)??Wg($)??void 0,emit:N,setStatus:B})}catch(j){let ee=j instanceof Error?j.message:String(j);Ha({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:K,autoMerge:C,repoName:w,baseRepoPath:i,branch:a,baseBranch:c,headSha:P,requireApproval:p,doneLabel:f,failedLabel:m,jiraTransition:l,jiraTransitionOnMerge:u,actorEmail:x,resultSummary:U,prSummary:re??"",costUsd:d.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),N("error",`Run failed: ${ee}`),N("info",`The commit itself survived on the runner (branch ${a}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await wt(S,n,e,m,`${ee}
984
984
 
985
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),F("failed",{error:ee,retryAvailable:!0,...d})}}async function CR(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:a,failed:c,emit:l,sendUsage:u,baseCost:p}=t,f=Ve(i.agent);if(!f?.capabilities.sessionResume){let A=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return l("info",A),{outcome:"skipped",note:A,cost:$R}}l("info",`${c.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let m=await mt(r),w=await wr(e,f,{repoPath:r,prompt:vR(c),timeoutSeconds:i.timeoutSeconds,bin:We(a,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,D)=>l(A,D),onUsage:u?A=>u({...A,inputTokens:p.inputTokens+A.inputTokens,outputTokens:p.outputTokens+A.outputTokens,costUsd:A.costUsd===void 0?void 0:p.costUsd+A.costUsd}):void 0},l),S={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:S};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 l("warn",A),{outcome:"agent_failed",note:A,cost:S}}if(_i(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 l("warn",A),{outcome:"agent_failed",note:A,cost:S}}let T=await hi(r);for(let A of T.refused)l("warn",`${Nn} entry refused: ${A}`);try{let A=await yo(r);for(let D of A.notes)l("warn",D);A.regenerated.length&&l("info",`Regenerated lockfile(s) for the fix's dependency change: ${A.regenerated.join(", ")}`)}catch(A){await ur(r,m);let D=`An automatic fix attempt changed dependencies but its lockfile could not be regenerated (${A instanceof Error?A.message:A}) - the fix was discarded; the results above are from the original work.`;return l("warn",D),{outcome:"reverted",note:D,cost:S}}try{await ps(r,`${n}: fix failing TEST.md commands
985
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),B("failed",{error:ee,retryAvailable:!0,...d})}}async function CR(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:a,failed:c,emit:l,sendUsage:u,baseCost:p}=t,f=Ve(i.agent);if(!f?.capabilities.sessionResume){let A=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return l("info",A),{outcome:"skipped",note:A,cost:$R}}l("info",`${c.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let m=await mt(r),w=await wr(e,f,{repoPath:r,prompt:vR(c),timeoutSeconds:i.timeoutSeconds,bin:We(a,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,D)=>l(A,D),onUsage:u?A=>u({...A,inputTokens:p.inputTokens+A.inputTokens,outputTokens:p.outputTokens+A.outputTokens,costUsd:A.costUsd===void 0?void 0:p.costUsd+A.costUsd}):void 0},l),S={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:S};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 l("warn",A),{outcome:"agent_failed",note:A,cost:S}}if(_i(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 l("warn",A),{outcome:"agent_failed",note:A,cost:S}}let T=await hi(r);for(let A of T.refused)l("warn",`${Nn} entry refused: ${A}`);try{let A=await yo(r);for(let D of A.notes)l("warn",D);A.regenerated.length&&l("info",`Regenerated lockfile(s) for the fix's dependency change: ${A.regenerated.join(", ")}`)}catch(A){await ur(r,m);let D=`An automatic fix attempt changed dependencies but its lockfile could not be regenerated (${A instanceof Error?A.message:A}) - the fix was discarded; the results above are from the original work.`;return l("warn",D),{outcome:"reverted",note:D,cost:S}}try{await ps(r,`${n}: fix failing TEST.md commands
986
986
 
987
- Allwright run ${e} (automatic test-fix attempt)`)}catch{let A=`An automatic fix attempt concluded no code change was warranted: ${_s(w.resultText)}`;return l("info",A),{outcome:"no_changes",note:A,cost:S}}let x=await lr(r,s);if(!x.ok){await ur(r,m);let A=x.forbidden.length?`An automatic fix attempt touched protected paths (${x.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 l("warn",A),{outcome:"reverted",note:A,cost:S}}return{outcome:"committed",note:`Fix attempt: ${_s(w.resultText)}`,resultText:w.resultText,cost:S}}async function sy(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:a,mergeMethod:c,autoMerge:l,branch:u,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:m,requireApproval:w,doneLabel:S,failedLabel:T,repoName:x,jira:A,cfg:D,actorEmail:K,summary:C,prSummary:$,cost:v,testReport:P,emit:F,setStatus:V}=t;F("info",`Pushing ${u} to origin`),await fs(e,u);let te=await Pa(e,u),d=`${$?.trim()?`${$.trim()}
987
+ Allwright run ${e} (automatic test-fix attempt)`)}catch{let A=`An automatic fix attempt concluded no code change was warranted: ${_s(w.resultText)}`;return l("info",A),{outcome:"no_changes",note:A,cost:S}}let x=await lr(r,s);if(!x.ok){await ur(r,m);let A=x.forbidden.length?`An automatic fix attempt touched protected paths (${x.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 l("warn",A),{outcome:"reverted",note:A,cost:S}}return{outcome:"committed",note:`Fix attempt: ${_s(w.resultText)}`,resultText:w.resultText,cost:S}}async function sy(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:a,mergeMethod:c,autoMerge:l,branch:u,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:m,requireApproval:w,doneLabel:S,failedLabel:T,repoName:x,jira:A,cfg:D,actorEmail:K,summary:C,prSummary:$,cost:v,testReport:N,emit:B,setStatus:V}=t;B("info",`Pushing ${u} to origin`),await fs(e,u);let te=await Pa(e,u),d=`${$?.trim()?`${$.trim()}
988
988
 
989
989
  <details>
990
990
  <summary>Technical details</summary>
991
991
 
992
992
  ${C}
993
993
 
994
- </details>`:C}${P??""}
994
+ </details>`:C}${N??""}
995
995
 
996
996
  ---
997
997
  Jira: ${new URL(`/browse/${s}`,D.jira?.baseUrl??"").toString()}
998
- _Allwright implement run \`${r}\` \xB7 cost $${v.costUsd.toFixed(4)}. `+(P?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");F("info","Opening pull request");let g=po(ke()??D,x,K);g.source==="user"&&F("info",`PR will be authored with ${K}'s own GitHub token`);let _=await new rt(g.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:d});F("info",`PR ready: ${_.url}`),og({runId:r,issueKey:s,repoName:x,owner:n.owner,repo:n.repo,prNumber:_.number,prUrl:_.url,jiraTransitionOnMerge:m??"",createdAt:new Date().toISOString()}),V("posting",v);let M={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:x,owner:n.owner,repo:n.repo,prNumber:_.number,prUrl:_.url,branch:u,headSha:te,doneLabel:S,failedLabel:T,jiraTransition:f,mergeOnApprove:a,mergeMethod:c,autoMerge:l,agentConfigDir:t.agentConfigDir};if(w)Nt(M),await A.addComment(s,`**Allwright opened a pull request for review.**
998
+ _Allwright implement run \`${r}\` \xB7 cost $${v.costUsd.toFixed(4)}. `+(N?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");B("info","Opening pull request");let g=po(ke()??D,x,K);g.source==="user"&&B("info",`PR will be authored with ${K}'s own GitHub token`);let _=await new Ye(g.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:d});B("info",`PR ready: ${_.url}`),og({runId:r,issueKey:s,repoName:x,owner:n.owner,repo:n.repo,prNumber:_.number,prUrl:_.url,jiraTransitionOnMerge:m??"",createdAt:new Date().toISOString()}),V("posting",v);let M={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:x,owner:n.owner,repo:n.repo,prNumber:_.number,prUrl:_.url,branch:u,headSha:te,doneLabel:S,failedLabel:T,jiraTransition:f,mergeOnApprove:a,mergeMethod:c,autoMerge:l,agentConfigDir:t.agentConfigDir};if(w)Nt(M),await A.addComment(s,`**Allwright opened a pull request for review.**
999
999
 
1000
1000
  PR: ${_.url}
1001
1001
 
1002
- 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}\`)`),V("awaiting_approval",{...v,prUrl:_.url,headSha:te,resultSummary:_s($?.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}:{}}),F("info",`Awaiting approval on the dashboard \xB7 $${v.costUsd.toFixed(4)}`);else{if(l){F("info",`Auto-merging PR #${_.number} (${c})`);let B=st(D,x),Y=B?await new rt(B).mergePullRequest(n.owner,n.repo,_.number,c,{sha:te,title:`${s} (#${_.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};Y.merged?F("info",`PR #${_.number} merged`):(F("warn",`Auto-merge did not go through - ${Y.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 - ${Y.reason}
1002
+ 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}\`)`),V("awaiting_approval",{...v,prUrl:_.url,headSha:te,resultSummary:_s($?.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}:{}}),B("info",`Awaiting approval on the dashboard \xB7 $${v.costUsd.toFixed(4)}`);else{if(l){B("info",`Auto-merging PR #${_.number} (${c})`);let F=st(D,x),Y=F?await new Ye(F).mergePullRequest(n.owner,n.repo,_.number,c,{sha:te,title:`${s} (#${_.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};if(Y.merged){if(B("info",`PR #${_.number} merged`),F)try{await new Ye(F).deleteBranch(n.owner,n.repo,u)}catch(P){B("warn",`PR #${_.number} merged, but its branch could not be deleted: ${P instanceof Error?P.message:String(P)}. If this ticket was chained, delete "${u}" by hand so the next PR in the stack can reach the real base.`)}}else B("warn",`Auto-merge did not go through - ${Y.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 - ${Y.reason}
1003
1003
 
1004
- PR: ${_.url}`))}let O=(ke()??D).repos[x]?.path;O&&io(O,s)&&Ct(O,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${_.url} merged/opened straight-through.`}),await iy({jira:A,issueKey:s},M,F),V("succeeded",{...v,prUrl:_.url,headSha:te,resultSummary:_s($?.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}:{}}),F("info",`Run succeeded \xB7 ${_.url} \xB7 $${v.costUsd.toFixed(4)}`)}}async function iy(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.**
1004
+ PR: ${_.url}`)}let O=(ke()??D).repos[x]?.path;O&&io(O,s)&&Ct(O,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${_.url} merged/opened straight-through.`}),await iy({jira:A,issueKey:s},M,B),V("succeeded",{...v,prUrl:_.url,headSha:te,resultSummary:_s($?.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}:{}}),B("info",`Run succeeded \xB7 ${_.url} \xB7 $${v.costUsd.toFixed(4)}`)}}async function iy(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.**
1005
1005
 
1006
1006
  PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
1007
1007
 
@@ -1011,9 +1011,9 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
1011
1011
 
1012
1012
  Note: ${r}`:"")+`
1013
1013
 
1014
- (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Be.NEEDS_INPUT_LABEL,e.failedLabel]}),r}async function No(t,e,n){let r=mr(e);if(!r){b.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=uy(t,e);try{let a=st(ke()??t.cfg,r.repoName);if(!a)throw new Error("GitHub token missing on this runner");let c=new rt(a);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let l=await c.getPullRequest(r.owner,r.repo,r.prNumber);if(!l)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(l.state==="closed"&&!l.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let u=n??r.headSha;if(l.state==="open"&&l.headSha!==u){let p=`PR #${r.prNumber} changed since review started (${u.slice(0,7)} \u2192 ${l.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",p),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:l.headSha,resultSummary:p});return}if(r.mergeOnApprove&&l.state==="open"&&!l.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let p=await c.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:u,title:`${r.issueKey} (#${r.prNumber})`});if(!p.merged){let f=`Approved, but the merge did not go through - ${p.reason}`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}
1014
+ (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Be.NEEDS_INPUT_LABEL,e.failedLabel]}),r}async function No(t,e,n){let r=mr(e);if(!r){b.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=uy(t,e);try{let a=st(ke()??t.cfg,r.repoName);if(!a)throw new Error("GitHub token missing on this runner");let c=new Ye(a);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let l=await c.getPullRequest(r.owner,r.repo,r.prNumber);if(!l)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(l.state==="closed"&&!l.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let u=n??r.headSha;if(l.state==="open"&&l.headSha!==u){let p=`PR #${r.prNumber} changed since review started (${u.slice(0,7)} \u2192 ${l.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",p),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:l.headSha,resultSummary:p});return}if(r.mergeOnApprove&&l.state==="open"&&!l.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let p=await c.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:u,title:`${r.issueKey} (#${r.prNumber})`});if(!p.merged){let f=`Approved, but the merge did not go through - ${p.reason}`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}
1015
1015
 
1016
- PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:l.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(ke()??t.cfg).repos[r.repoName??""]?.path;p&&io(p,r.issueKey)&&Ct(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await iy({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),gr(e)}catch(a){let c=a instanceof Error?a.message:String(a);s("error",`Approval handling failed: ${c}`),await dy(t,r,c),i("failed",{error:c}),gr(e)}}async function oy(t,e){let n=mr(e);if(!n){b.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=uy(t,e);try{let i=st(ke()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let a=new rt(i);r("info",`Rejection received for ${n.issueKey} - closing PR #${n.prNumber}`);let c=await a.getPullRequest(n.owner,n.repo,n.prNumber);c&&c.state==="open"&&await a.closePullRequest(n.owner,n.repo,n.prNumber),c?.merged||await a.deleteBranch(n.owner,n.repo,n.branch),await t.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright: changes rejected.**
1016
+ PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:l.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`);try{await c.deleteBranch(r.owner,r.repo,r.branch)}catch(f){s("warn",`PR #${r.prNumber} merged, but its branch could not be deleted: ${f instanceof Error?f.message:String(f)}. If this ticket was chained, delete "${r.branch}" by hand so the next PR in the stack can reach the real base.`)}}{let p=(ke()??t.cfg).repos[r.repoName??""]?.path;p&&io(p,r.issueKey)&&Ct(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await iy({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),gr(e)}catch(a){let c=a instanceof Error?a.message:String(a);s("error",`Approval handling failed: ${c}`),await dy(t,r,c),i("failed",{error:c}),gr(e)}}async function oy(t,e){let n=mr(e);if(!n){b.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=uy(t,e);try{let i=st(ke()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let a=new Ye(i);r("info",`Rejection received for ${n.issueKey} - closing PR #${n.prNumber}`);let c=await a.getPullRequest(n.owner,n.repo,n.prNumber);c&&c.state==="open"&&await a.closePullRequest(n.owner,n.repo,n.prNumber),c?.merged||await a.deleteBranch(n.owner,n.repo,n.branch),await t.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright: changes rejected.**
1017
1017
 
1018
1018
  The pull request was closed and the branch deleted. This ticket is labeled \`${n.failedLabel}\`; remove the label to try again. (run \`${n.runId}\`)`),await t.jiraFor(n.repoName??"").editLabels(n.issueKey,{add:[n.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),gr(e)}catch(i){let a=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${a}`),await dy(t,n,a),s("failed",{error:a}),gr(e)}}async function ay(t,e){let n=bi(e);if(!n){b.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:c,setStatus:l,sendUsage:u}=Un(e,t.transport,1e5);c("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),l("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:a}=Un(e,t.transport,n.nextLogSeq);try{let c=await Pa(n.baseRepoPath,n.branch);if(c!==n.headSha){r("error",`Retry push aborted: branch ${n.branch} no longer holds the commit this run produced (expected ${n.headSha.slice(0,7)}, ${c?`found ${c.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),Vu(e),s("failed",{retryAvailable:!1});return}let l=await ms(n.baseRepoPath),u=Jt(l);if(!u)throw new Error(`origin "${l}" is not a GitHub remote`);r("info",`Retry push for ${n.issueKey}: branch ${n.branch} at ${n.headSha.slice(0,7)}`);let p=t.jiraFor(n.repoName);await sy({gitDir:n.baseRepoPath,ownerRepo:u,runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:p,cfg:ke()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Vu(e),await p.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(c){let l=c instanceof Error?c.message:String(c);r("error",`Retry push failed: ${l}`),Ha({...n,nextLogSeq:a()}),s("failed",{error:l,retryAvailable:!0})}}async function cy(t,e){let{emit:n,setStatus:r,sendUsage:s,nextSeq:i}=Un(t.runId,e.transport,Qg),a=t.workPath,c=e.jiraFor(t.repoName),l=!1,u=!1;ks({...t,crashResumes:t.crashResumes+1});try{if(r("running"),n("warn",`This runner stopped mid-run (a crash or power loss, not a normal stop) - resuming the same agent session in ${a}`+(t.batchId?` (autopilot batch ${t.batchId})`:"")),!po(ke()??e.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)");let p=await wr(t.runId,Ve(t.agent),{repoPath:a,prompt:_R,timeoutSeconds:t.timeoutSeconds,bin:We(e.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:(w,S)=>n(w,S),onUsage:s},n,()=>uo(a)),f={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok){let w=`resumed after a runner crash, but the resumed session did not finish: ${p.error??"the agent failed"}`;n("error",`Run failed: ${w}`);let S=w,T=p.timedOut&&!p.cancelled&&!!t.branch;if(p.turnLimitHit&&!T&&t.branch){let x=await vd(a,t.branch,t.runId,n);x&&(S+=kd(x))}T&&(hd(t.projectId,t.issueKey,{sessionId:t.sessionId,worktreePath:a,branch:t.branch,resumes:1}),u=!0,n("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"),await wt(c,t.issueKey,t.runId,t.failedLabel,S),r(p.timedOut?"timed_out":"failed",{error:S,...p.cancelled?{errorKind:"guard"}:{},...f});return}let m=_i(p.resultText);if(m){l=!0,await Si({kind:"implement",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:a,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:c,nextLogSeq:i(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:t.agent,model:t.model,actorEmail:t.actorEmail,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},m,n,r,f);return}Ln(a),await _d({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:a,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??a,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:c,cfg:e.cfg,actorEmail:t.actorEmail,resultText:p.resultText,costFields:f,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent,model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns,allowWeb:t.allowWeb},sendUsage:s,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,emit:n,setStatus:r})}catch(p){let f=`resumed after a runner crash, but the resume failed: ${p instanceof Error?p.message:String(p)}`;n("error",`Run failed: ${f}`),await wt(c,t.issueKey,t.runId,t.failedLabel,f),r("failed",{error:f})}finally{mn(t.runId),!l&&!u&&await Zt(t.baseRepoPath??a,a).catch(()=>{})}}async function ly(t,e,n){let{emit:r,setStatus:s}=Un(t.runId,n.transport,Qg),i=`this runner stopped while the run was executing - a crash, an out-of-memory kill or a power loss, not a normal stop - and the run could not be resumed: ${e}. Re-trigger the ticket to start a fresh run.`;r("error",`Run failed: ${i}`);let a=n.jiraFor(t.repoName);t.kind==="respond"?await a.addComment(t.issueKey,`**Allwright could not answer this question.**
1019
1019
 
@@ -1083,7 +1083,7 @@ ${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed y
1083
1083
 
1084
1084
  ${i.slice(0,800)}
1085
1085
 
1086
- (run \`${t.runId}\`)`),n("failed",{error:i})}}function WR(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=cn(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let c of e.steps){for(let l of c.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(l[1]);for(let l of c.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(l[1])}let i=e.requiredSecrets.filter(c=>!s.has(c));i.length&&b.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 a=e.requiredSecrets.filter(c=>s.has(c)&&!r.has(c)&&!n[c]&&!process.env[c]);return a.length?`missing deploy secret(s) on this runner: ${a.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${a[0]}=...`:null}async function Sy(t,e,n){let r=t.environment,s=cn(t.cfg,t.project.repoName,r.name),i=Is(Object.values(s)),a=Date.now(),c=[];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=Ce(t.cfg,t.project,"assist"),$="error"in C?{ok:!1,error:C.error}:await gi({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:C,jira:t.jira});if(!$.ok)e("warn",`Pre-deploy audit could not run: ${$.error} - deploying anyway (advisory)`);else if(!$.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let v={};for(let P of $.audit.findings)v[P.severity]=(v[P.severity]??0)+1;e("warn",`Pre-deploy audit: ${$.audit.findings.length} finding(s) (`+Object.entries(v).map(([P,F])=>`${F} ${P}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let P of $.audit.findings.slice(0,5))e("warn",` [${P.severity}] ${P.title} - ${P.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:$}=await Promise.resolve().then(()=>(gy(),my));e("info",`Go-live checklist: running what can be run from ${t.project.goLiveIssueKey}`);let v=await C({jira:t.jira,issueKey:t.project.goLiveIssueKey,repoPath:t.repoPath,onProgress:P=>e("info",` ${P}`)});for(let P of $(v,t.project.goLiveIssueKey))e(v.results.some(F=>F.exitCode!==0)?"warn":"info",P)}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 $=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",$),await Mt(t,`**Allwright refused to deploy to \`${r.name}\`.**
1086
+ (run \`${t.runId}\`)`),n("failed",{error:i})}}function WR(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=cn(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let c of e.steps){for(let l of c.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(l[1]);for(let l of c.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(l[1])}let i=e.requiredSecrets.filter(c=>!s.has(c));i.length&&b.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 a=e.requiredSecrets.filter(c=>s.has(c)&&!r.has(c)&&!n[c]&&!process.env[c]);return a.length?`missing deploy secret(s) on this runner: ${a.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${a[0]}=...`:null}async function Sy(t,e,n){let r=t.environment,s=cn(t.cfg,t.project.repoName,r.name),i=Is(Object.values(s)),a=Date.now(),c=[];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=Ce(t.cfg,t.project,"assist"),$="error"in C?{ok:!1,error:C.error}:await gi({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:C,jira:t.jira});if(!$.ok)e("warn",`Pre-deploy audit could not run: ${$.error} - deploying anyway (advisory)`);else if(!$.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let v={};for(let N of $.audit.findings)v[N.severity]=(v[N.severity]??0)+1;e("warn",`Pre-deploy audit: ${$.audit.findings.length} finding(s) (`+Object.entries(v).map(([N,B])=>`${B} ${N}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let N of $.audit.findings.slice(0,5))e("warn",` [${N.severity}] ${N.title} - ${N.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:$}=await Promise.resolve().then(()=>(gy(),my));e("info",`Go-live checklist: running what can be run from ${t.project.goLiveIssueKey}`);let v=await C({jira:t.jira,issueKey:t.project.goLiveIssueKey,repoPath:t.repoPath,onProgress:N=>e("info",` ${N}`)});for(let N of $(v,t.project.goLiveIssueKey))e(v.results.some(B=>B.exitCode!==0)?"warn":"info",N)}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 $=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",$),await Mt(t,`**Allwright refused to deploy to \`${r.name}\`.**
1087
1087
 
1088
1088
  ${$}
1089
1089
 
@@ -1091,21 +1091,21 @@ ${$}
1091
1091
 
1092
1092
  Allwright run ${t.runId}`);if(!$.ok){e("error",$.reason??"merge failed"),await Mt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
1093
1093
 
1094
- ${$.reason}`),n("failed",{error:$.reason});return}$.alreadyMerged?e("info",`"${C}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Ru(l,r.branch))}let p=await mt(l).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Ed(l,r.workdir),m={...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,S=r.timeoutSeconds*1e3,T=ty(t.runId),x=()=>T.signal.aborted;try{for(let[C,$]of r.steps.entries()){if(x()){let F=`stopped from the dashboard during step ${C+1} - nothing further ran`;e("error",F),n("failed",{error:F,errorKind:"guard",deployedRef:p});return}let v=S-(Date.now()-a);if(v<=0){let F=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${C+1}`;e("error",F),await Mt(t,`**Allwright deploy to \`${r.name}\` timed out.**
1094
+ ${$.reason}`),n("failed",{error:$.reason});return}$.alreadyMerged?e("info",`"${C}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Ru(l,r.branch))}let p=await mt(l).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Ed(l,r.workdir),m={...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,S=r.timeoutSeconds*1e3,T=ty(t.runId),x=()=>T.signal.aborted;try{for(let[C,$]of r.steps.entries()){if(x()){let B=`stopped from the dashboard during step ${C+1} - nothing further ran`;e("error",B),n("failed",{error:B,errorKind:"guard",deployedRef:p});return}let v=S-(Date.now()-a);if(v<=0){let B=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${C+1}`;e("error",B),await Mt(t,`**Allwright deploy to \`${r.name}\` timed out.**
1095
1095
 
1096
- ${F}`),n("timed_out",{error:F,deployedRef:p});return}e("info",`\u25B6 step ${C+1}/${r.steps.length}: ${$.name}`);let P=await _y({command:$.run,cwd:f,env:m,timeoutMs:v,signal:T.signal,onLine:(F,V)=>{w++;let te=KR(V);te&&c.length<20&&c.push(te),w===yy&&e("warn","(output truncated - deploy log limit reached)"),!(w>=yy)&&e(F,i(V))}});if(P.timedOut){let F=`step "${$.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",F),await Mt(t,`**Allwright deploy to \`${r.name}\` timed out.**
1096
+ ${B}`),n("timed_out",{error:B,deployedRef:p});return}e("info",`\u25B6 step ${C+1}/${r.steps.length}: ${$.name}`);let N=await _y({command:$.run,cwd:f,env:m,timeoutMs:v,signal:T.signal,onLine:(B,V)=>{w++;let te=KR(V);te&&c.length<20&&c.push(te),w===yy&&e("warn","(output truncated - deploy log limit reached)"),!(w>=yy)&&e(B,i(V))}});if(N.timedOut){let B=`step "${$.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",B),await Mt(t,`**Allwright deploy to \`${r.name}\` timed out.**
1097
1097
 
1098
- ${F}`),n("timed_out",{error:F,deployedRef:p});return}if(P.code!==0){if($.continueOnError){e("warn",`step "${$.name}" exited ${P.code} - continuing (marked continue-on-error)`);continue}let F="";try{F=i(await uu(l))}catch{}let V=P.failures?i(P.failures):"",te=P.tail?i(P.tail):"",L=xf(nu(`${V}
1099
- ${te}`.trim(),{cwd:l})),d=`step ${C+1} "${$.name}" failed with exit code ${P.code}`+(V?`:
1098
+ ${B}`),n("timed_out",{error:B,deployedRef:p});return}if(N.code!==0){if($.continueOnError){e("warn",`step "${$.name}" exited ${N.code} - continuing (marked continue-on-error)`);continue}let B="";try{B=i(await uu(l))}catch{}let V=N.failures?i(N.failures):"",te=N.tail?i(N.tail):"",L=xf(nu(`${V}
1099
+ ${te}`.trim(),{cwd:l})),d=`step ${C+1} "${$.name}" failed with exit code ${N.code}`+(V?`:
1100
1100
  ${V}`:"")+(te?`${V?`
1101
1101
 
1102
1102
  how the output ended:
1103
- `:": "}${te}`:"")+L+(F?`
1103
+ `:": "}${te}`:"")+L+(B?`
1104
1104
 
1105
1105
  Checkout at failure:
1106
- ${F}`:"");e("error",d),await Mt(t,`**Allwright deploy to \`${r.name}\` failed.**
1106
+ ${B}`:"");e("error",d),await Mt(t,`**Allwright deploy to \`${r.name}\` failed.**
1107
1107
 
1108
- Step ${C+1} \`${$.name}\` exited ${P.code}.
1108
+ Step ${C+1} \`${$.name}\` exited ${N.code}.
1109
1109
 
1110
1110
  `+(V?`\`\`\`
1111
1111
  ${V}
@@ -1118,19 +1118,19 @@ ${te.slice(0,1200)}
1118
1118
 
1119
1119
  `:"")+(L?`${L.trim()}
1120
1120
 
1121
- `:"")+(F?`Checkout at failure:
1121
+ `:"")+(B?`Checkout at failure:
1122
1122
  \`\`\`
1123
- ${F.slice(0,800)}
1123
+ ${B.slice(0,800)}
1124
1124
  \`\`\`
1125
1125
 
1126
1126
  `:"")+(c.length?`**Before retrying, these still need a person:**
1127
1127
  `+c.map(g=>`- \`${g.command}\`${g.why?` - ${g.why}`:""}`).join(`
1128
1128
  `)+`
1129
1129
 
1130
- `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${C+1} "${$.name}" exit ${P.code}`+(V||te?`
1131
- ${(V||te).slice(0,500)}`:"")}),c.length&&by(e,c),n("failed",{error:d.slice(0,4e3),deployedRef:p,...c.length?{manualSteps:c}:{}});return}e("info",`\u2713 step ${C+1}/${r.steps.length}: ${$.name}`)}}finally{ny(t.runId)}if(p=await mt(l).catch(()=>"")||p,r.servePath?.trim()){let C=r.servePath.trim(),$=r.branch.trim(),v=await mt(C).catch(()=>"");if(!v)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=v;let P=$?await mu(C,$):"";if(!P)e("warn",`serving check: ${C} is at ${v.slice(0,10)}, but `+($?`origin/${$} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${$||"commit"} could not be verified`);else if(v!==P){let F=await gu(C,v,P),V=`The steps all succeeded, but the live checkout at ${C} is at ${v.slice(0,10)} while origin/${$} is at ${P.slice(0,10)}`+(F?` - ${F} commit(s) behind`:"")+`. Users are NOT getting the latest ${$}. 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: ${V}`),await Mt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
1130
+ `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${C+1} "${$.name}" exit ${N.code}`+(V||te?`
1131
+ ${(V||te).slice(0,500)}`:"")}),c.length&&by(e,c),n("failed",{error:d.slice(0,4e3),deployedRef:p,...c.length?{manualSteps:c}:{}});return}e("info",`\u2713 step ${C+1}/${r.steps.length}: ${$.name}`)}}finally{ny(t.runId)}if(p=await mt(l).catch(()=>"")||p,r.servePath?.trim()){let C=r.servePath.trim(),$=r.branch.trim(),v=await mt(C).catch(()=>"");if(!v)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=v;let N=$?await mu(C,$):"";if(!N)e("warn",`serving check: ${C} is at ${v.slice(0,10)}, but `+($?`origin/${$} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${$||"commit"} could not be verified`);else if(v!==N){let B=await gu(C,v,N),V=`The steps all succeeded, but the live checkout at ${C} is at ${v.slice(0,10)} while origin/${$} is at ${N.slice(0,10)}`+(B?` - ${B} commit(s) behind`:"")+`. Users are NOT getting the latest ${$}. 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: ${V}`),await Mt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
1132
1132
 
1133
- ${V}`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${v.slice(0,10)}, origin/${$} at ${P.slice(0,10)} (${C})`}),n("failed",{error:V,deployedRef:p});return}else e("info",`serving check: ${C} is at ${v.slice(0,10)} = origin/${$} - users get this build`)}}n("posting");let A=Math.round((Date.now()-a)/1e3),D=null;r.publicUrl?.trim()&&(D=await XR(r.publicUrl.trim()),e(D?"warn":"info",D??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Rs.BRANCH_DEPLOY_ISSUE_KEY&&await Mt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
1133
+ ${V}`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${v.slice(0,10)}, origin/${$} at ${N.slice(0,10)} (${C})`}),n("failed",{error:V,deployedRef:p});return}else e("info",`serving check: ${C} is at ${v.slice(0,10)} = origin/${$} - users get this build`)}}n("posting");let A=Math.round((Date.now()-a)/1e3),D=null;r.publicUrl?.trim()&&(D=await XR(r.publicUrl.trim()),e(D?"warn":"info",D??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Rs.BRANCH_DEPLOY_ISSUE_KEY&&await Mt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
1134
1134
 
1135
1135
  `+(D?`> **Live where?** ${D}
1136
1136
 
@@ -1148,7 +1148,7 @@ ${V}`),Ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.nam
1148
1148
 
1149
1149
  ${c}
1150
1150
 
1151
- (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await cr(t.repoPath,r),await cr(t.repoPath,n.branch)}catch(c){return s(`sync check could not fetch branches: ${c instanceof Error?c.message:String(c)}`)}let i;try{i=await Iu(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(c){return s(`sync check failed: ${c instanceof Error?c.message:String(c)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let a=st(ke()??t.cfg,t.project.repoName);if(!a)return s(`"${n.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let c=await ms(t.repoPath),l=Jt(c);if(!l)throw new Error(`could not parse a GitHub owner/repo from origin "${c}"`);let p=await new rt(a).createPullRequest(l.owner,l.repo,{title:`Sync ${n.name} (${n.branch}) with ${r}`,head:r,base:n.branch,body:`Allwright opened this automatically while trying to deploy \`${t.issueKey}\` to \`${n.name}\`: \`${n.branch}\` doesn't have everything that's on \`${r}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
1151
+ (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await cr(t.repoPath,r),await cr(t.repoPath,n.branch)}catch(c){return s(`sync check could not fetch branches: ${c instanceof Error?c.message:String(c)}`)}let i;try{i=await Iu(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(c){return s(`sync check failed: ${c instanceof Error?c.message:String(c)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let a=st(ke()??t.cfg,t.project.repoName);if(!a)return s(`"${n.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let c=await ms(t.repoPath),l=Jt(c);if(!l)throw new Error(`could not parse a GitHub owner/repo from origin "${c}"`);let p=await new Ye(a).createPullRequest(l.owner,l.repo,{title:`Sync ${n.name} (${n.branch}) with ${r}`,head:r,base:n.branch,body:`Allwright opened this automatically while trying to deploy \`${t.issueKey}\` to \`${n.name}\`: \`${n.branch}\` doesn't have everything that's on \`${r}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
1152
1152
 
1153
1153
  (run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${p.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(c){return s(`could not open a sync PR: ${c instanceof Error?c.message:String(c)}`)}}async function ZR(t){let e=cn(t.cfg,t.repoName,t.environmentName),n=Is(Object.values(e)),r=Ed(t.repoPath,t.workdir),s=await _y({command:t.step.run,cwd:r,env:{...process.env,...e,ALLWRIGHT_ENVIRONMENT:t.environmentName,ALLWRIGHT_BRANCH:t.branch,TICKETPILOT_ENVIRONMENT:t.environmentName,TICKETPILOT_BRANCH:t.branch},timeoutMs:t.timeoutMs,signal:t.signal,onLine:()=>{}}),i=[s.failures.trim()?`FAILING LINES:
1154
1154
  ${s.failures.trim()}`:"",s.tail.trim()?`LAST LINES:
@@ -1240,7 +1240,7 @@ Then set ALLWRIGHT_CONFIG_DIR to a stable data dir (e.g. %ProgramData%\\Allwrigh
1240
1240
  `+n);return}try{(0,vt.execFileSync)("systemctl",["disable","--now",Pi]),t.info(`stopped the old ${Pi} service - this one replaces it`)}catch{}let r=$i();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}yn.default.writeFileSync(Wd,n),(0,vt.execFileSync)("systemctl",["daemon-reload"]),(0,vt.execFileSync)("systemctl",["enable","--now",Sr]),(0,vt.execFileSync)("systemctl",["restart",Sr]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${Sr} -f`),t.info("Status: allwright service status")}function Cb(t){if(t.override)return[Ci.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=Ci.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function SE(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[_c.default.homedir()];return t&&e.push(Ci.default.join("/home",t)),Cb({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function Pb(){let t={removed:!1,paths:[],problems:[]};for(let e of SE())if(yn.default.existsSync(e))try{yn.default.rmSync(e),t.removed=!0,t.paths.push(e)}catch(n){t.problems.push(`could not delete ${e}: ${n instanceof Error?n.message:String(n)}`)}return t}function Zd(){return typeof process.getuid!="function"||process.getuid()===0}function Gd(t){if(Zd()){(0,vt.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,vt.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function _E(t){if(Zd()){yn.default.rmSync(t);return}(0,vt.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function Nb(){if(!Rc())return{removed:!1,absent:!0,error:""};let t=[Sr,Pi].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>yn.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{Gd(["disable",e.name])}catch{}_E(e.file)}return Gd(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:Zd()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function Ic(){if(Rc())for(let t of[Sr,Pi])try{Gd(["stop",t])}catch{}}function Ec(){let t=Nb(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${$b.RUNNER_UNINSTALL_COMMAND}`),e;let n=Pb();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function Jd(t){let e=Ec();e.serviceRemoved?(Ic(),t.info("Service stopped and removed.")):e.serviceAbsent&&t.info("No systemd service was installed here - nothing to stop.");for(let n of e.removedPaths)t.info(`Deleted ${n} - the Jira and GitHub tokens on this machine went with it.`);if(!e.configRemoved&&e.problems.length===0&&t.info("No runner config was found - there were no credentials left to delete."),t.info("Checkouts on disk were NOT touched - remove them yourself if you want them gone."),e.problems.length>0)throw new Error(e.problems.join("; "))}function Yd(t){let e=`/etc/systemd/system/${t}.service.d`;return{dir:e,file:`${e}/override.conf`,content:`[Service]
1241
1241
  KillMode=mixed
1242
1242
  TimeoutStopSec=2h
1243
- `}}function Xd(){for(let t of[Sr,Pi])try{if((0,vt.execFileSync)("systemctl",["show",t,"-p","LoadState"],{encoding:"utf8"}).includes("LoadState=loaded"))return t}catch{}return""}function Do(){let t=Xd();if(!t)return{protected:null,fixCommand:""};let e=Yd(t),n=`sudo mkdir -p ${e.dir} && printf '[Service]\\nKillMode=mixed\\nTimeoutStopSec=2h\\n' | sudo tee ${e.file} && sudo systemctl daemon-reload`;try{let r=(0,vt.execFileSync)("systemctl",["show",t,"-p","KillMode","-p","TimeoutStopUSec"],{encoding:"utf8"}),s=/KillMode=(\S+)/.exec(r)?.[1]??"",i=/TimeoutStopUSec=(\S+)/.exec(r)?.[1]??"",a=/h$/.test(i)||/^(3[0-9]|[4-9][0-9])min$/.test(i);return{protected:s==="mixed"&&a,fixCommand:n}}catch{return{protected:null,fixCommand:""}}}function xE(){let t=Do();if(t.protected!==!1)return t.protected===!0;let e=Xd();if(!e)return!1;let n=Yd(e);try{return(0,vt.execFileSync)("sudo",["-n","mkdir","-p",n.dir],{stdio:"ignore"}),(0,vt.execFileSync)("sudo",["-n","tee",n.file],{input:n.content,stdio:["pipe","ignore","ignore"]}),(0,vt.execFileSync)("sudo",["-n","systemctl","daemon-reload"],{stdio:"ignore"}),Do().protected===!0}catch{return!1}}var vt,yn,_c,Ci,$b,Sr,Wd,Pi,Ac=J(()=>{"use strict";vt=require("node:child_process"),yn=E(require("node:fs"),1),_c=E(require("node:os"),1),Ci=E(require("node:path"),1),$b=E(Me(),1);Kd();Sr="allwright",Wd=`/etc/systemd/system/${Sr}.service`,Pi="ticketpilot-runner"});var Wb={};Fe(Wb,{MAX_CHAIN_DEPTH:()=>eh,breakChain:()=>sh,breakSingleModeChain:()=>ch,chainOf:()=>nh,chainSessionFor:()=>jc,loadBatchPlan:()=>th,nextMemberWillChain:()=>lh,parsePlanAnswer:()=>uh,recordChainSession:()=>rh,recordSingleModeSession:()=>oh,saveBatchPlan:()=>RE,singleModeChainIntact:()=>ah,singleModeSessionFor:()=>ih});function RE(t){Ni.default.mkdirSync(Qd(),{recursive:!0,mode:448}),Ni.default.writeFileSync(Nc.default.join(Qd(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function th(t){if(!t)return null;try{return JSON.parse(Ni.default.readFileSync(Nc.default.join(Qd(),`${t}.json`),"utf8"))}catch{return null}}function nh(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function jc(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=Bn.get(Pc(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=eh||!Ni.default.existsSync(s.worktreePath)?null:s}function rh(t,e,n,r){let s=Bn.get(Pc(t,e));Bn.set(Pc(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function sh(t,e){Bn.delete(Pc(t,e))}function ih(t){let e=Bn.get(Lo(t));return!e||e.depth>=eh||!Ni.default.existsSync(e.worktreePath)?null:e}function oh(t,e,n,r){let s=Bn.get(Lo(t));Bn.set(Lo(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function ah(t,e){return Bn.get(Lo(t))?.lastIssue===e}function ch(t){Bn.delete(Lo(t))}function lh(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function uh(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),a=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(a.length!==e.length||!a.every(p=>i.has(p))||new Set(a).size!==a.length)return null;let c=(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),l=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:a,chains:c,dependencies:l,reasoning:u}}var Ni,Nc,eh,Qd,Bn,Pc,Lo,Mc=J(()=>{"use strict";Ni=E(require("node:fs"),1),Nc=E(require("node:path"),1);Te();eh=3,Qd=()=>Nc.default.join(X(),"autopilot-plans");Bn=new Map,Pc=(t,e)=>`${t}:${e[0]}`;Lo=t=>`${t}:__single__`});var Hn=be((EO,Nw)=>{"use strict";var Cw=["nodebuffer","arraybuffer","fragments"],Pw=typeof Blob<"u";Pw&&Cw.push("blob");Nw.exports={BINARY_TYPES:Cw,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Pw,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qo=be((AO,Fc)=>{"use strict";var{EMPTY_BUFFER:eA}=Hn(),vh=Buffer[Symbol.species];function tA(t,e){if(t.length===0)return eA;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 vh(n.buffer,n.byteOffset,r):n}function jw(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Mw(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function nA(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function kh(t){if(kh.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vh(t):ArrayBuffer.isView(t)?e=new vh(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),kh.readOnly=!1),e}Fc.exports={concat:tA,mask:jw,toArrayBuffer:nA,toBuffer:kh,unmask:Mw};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Fc.exports.mask=function(e,n,r,s,i){i<48?jw(e,n,r,s,i):t.mask(e,n,r,s,i)},Fc.exports.unmask=function(e,n){e.length<32?Mw(e,n):t.unmask(e,n)}}catch{}});var Dw=be(($O,zw)=>{"use strict";var Ow=Symbol("kDone"),Sh=Symbol("kRun"),_h=class{constructor(e){this[Ow]=()=>{this.pending--,this[Sh]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Sh]()}[Sh](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ow])}}};zw.exports=_h});var Oi=be((CO,Fw)=>{"use strict";var Fo=require("zlib"),Lw=qo(),rA=Dw(),{kStatusCode:Uw}=Hn(),sA=Buffer[Symbol.species],iA=Buffer.from([0,0,255,255]),Hc=Symbol("permessage-deflate"),Kn=Symbol("total-length"),ji=Symbol("callback"),xr=Symbol("buffers"),Mi=Symbol("error"),Bc,xh=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,!Bc){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Bc=new rA(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[ji];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){Bc.add(s=>{this._decompress(e,n,(i,a)=>{s(),r(i,a)})})}compress(e,n,r){Bc.add(s=>{this._compress(e,n,(i,a)=>{s(),r(i,a)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?Fo.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Fo.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Hc]=this,this._inflate[Kn]=0,this._inflate[xr]=[],this._inflate.on("error",aA),this._inflate.on("data",qw)}this._inflate[ji]=r,this._inflate.write(e),n&&this._inflate.write(iA),this._inflate.flush(()=>{let i=this._inflate[Mi];if(i){this._inflate.close(),this._inflate=null,r(i);return}let a=Lw.concat(this._inflate[xr],this._inflate[Kn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Kn]=0,this._inflate[xr]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,a)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?Fo.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Fo.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Kn]=0,this._deflate[xr]=[],this._deflate.on("data",oA)}this._deflate[ji]=r,this._deflate.write(e),this._deflate.flush(Fo.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Lw.concat(this._deflate[xr],this._deflate[Kn]);n&&(i=new sA(i.buffer,i.byteOffset,i.length-4)),this._deflate[ji]=null,this._deflate[Kn]=0,this._deflate[xr]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Fw.exports=xh;function oA(t){this[xr].push(t),this[Kn]+=t.length}function qw(t){if(this[Kn]+=t.length,this[Hc]._maxPayload<1||this[Kn]<=this[Hc]._maxPayload){this[xr].push(t);return}this[Mi]=new RangeError("Max payload size exceeded"),this[Mi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Mi][Uw]=1009,this.removeListener("data",qw),this.reset()}function aA(t){if(this[Hc]._inflate=null,this[Mi]){this[ji](this[Mi]);return}t[Uw]=1007,this[ji](t)}});var zi=be((PO,Kc)=>{"use strict";var{isUtf8:Bw}=require("buffer"),{hasBlob:cA}=Hn(),lA=[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 uA(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Th(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 dA(t){return cA&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Kc.exports={isBlob:dA,isValidStatusCode:uA,isValidUTF8:Th,tokenChars:lA};if(Bw)Kc.exports.isValidUTF8=function(t){return t.length<24?Th(t):Bw(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Kc.exports.isValidUTF8=function(e){return e.length<32?Th(e):t(e)}}catch{}});var $h=be((NO,Jw)=>{"use strict";var{Writable:hA}=require("stream"),Hw=Oi(),{BINARY_TYPES:pA,EMPTY_BUFFER:Kw,kStatusCode:fA,kWebSocket:mA}=Hn(),{concat:Rh,toArrayBuffer:gA,unmask:yA}=qo(),{isValidStatusCode:bA,isValidUTF8:Ww}=zi(),Wc=Buffer[Symbol.species],Dt=0,Gw=1,Vw=2,Zw=3,Ih=4,Eh=5,Gc=6,Ah=class extends hA{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pA[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[mA]=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=Dt}_write(e,n,r){if(this._opcode===8&&this._state==Dt)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 Wc(r.buffer,r.byteOffset+e,r.length-e),new Wc(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 Wc(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 Dt:this.getInfo(e);break;case Gw:this.getPayloadLength16(e);break;case Vw:this.getPayloadLength64(e);break;case Zw:this.getMask();break;case Ih:this.getData(e);break;case Eh:case Gc: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[Hw.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=Gw:this._payloadLength===127?this._state=Vw: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=Zw:this._state=Ih}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ih}getData(e){let n=Kw;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&&yA(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=Eh,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hw.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 a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(a);return}this._fragments.push(i)}this.dataMessage(n),this._state===Dt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Dt;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=Rh(r,n):this._binaryType==="arraybuffer"?s=gA(Rh(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Dt):(this._state=Gc,setImmediate(()=>{this.emit("message",s,!0),this._state=Dt,this.startLoop(e)}))}else{let s=Rh(r,n);if(!this._skipUTF8Validation&&!Ww(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Eh||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Dt):(this._state=Gc,setImmediate(()=>{this.emit("message",s,!1),this._state=Dt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kw),this.end();else{let r=e.readUInt16BE(0);if(!bA(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Wc(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ww(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=Dt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt):(this._state=Gc,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let a=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(a,this.createError),a.code=i,a[fA]=s,a}};Jw.exports=Ah});var Nh=be((MO,Qw)=>{"use strict";var{Duplex:jO}=require("stream"),{randomFillSync:wA}=require("crypto"),{types:{isUint8Array:vA}}=require("util"),Yw=Oi(),{EMPTY_BUFFER:kA,kWebSocket:SA,NOOP:_A}=Hn(),{isBlob:Di,isValidStatusCode:xA}=zi(),{mask:Xw,toBuffer:Us}=qo(),Lt=Symbol("kByteLength"),TA=Buffer.alloc(4),Vc=8*1024,qs,Li=Vc,Qt=0,RA=1,IA=2,Ch=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=Qt,this.onerror=_A,this[SA]=void 0}static frame(e,n){let r,s=!1,i=2,a=!1;n.mask&&(r=n.maskBuffer||TA,n.generateMask?n.generateMask(r):(Li===Vc&&(qs===void 0&&(qs=Buffer.alloc(Vc)),wA(qs,0,Vc),Li=0),r[0]=qs[Li++],r[1]=qs[Li++],r[2]=qs[Li++],r[3]=qs[Li++]),a=(r[0]|r[1]|r[2]|r[3])===0,i=6);let c;typeof e=="string"?(!n.mask||a)&&n[Lt]!==void 0?c=n[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,s=n.mask&&n.readOnly&&!a);let l=c;c>=65536?(i+=8,l=127):c>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(s?c+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(c,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(c,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],a?[u,e]:s?(Xw(e,r,u,i,c),[u]):(Xw(e,r,e,0,c),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=kA;else{if(typeof e!="number"||!xA(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 c=Buffer.byteLength(n);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(vA(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[Lt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Qt?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(t.frame(i,a),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Di(e)?(s=e.size,i=!1):(e=Us(e),s=e.length,i=Us.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Di(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Qt?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Di(e)?(s=e.size,i=!1):(e=Us(e),s=e.length,i=Us.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Di(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Qt?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}send(e,n,r){let s=this._extensions[Yw.extensionName],i=n.binary?2:1,a=n.compress,c,l;typeof e=="string"?(c=Buffer.byteLength(e),l=!1):Di(e)?(c=e.size,l=!1):(e=Us(e),c=e.length,l=Us.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[Lt]:c,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:a};Di(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Qt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Lt],this._state=IA,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Ph,this,c,s);return}this._bufferedBytes-=r[Lt];let a=Us(i);n?this.dispatch(a,n,r,s):(this._state=Qt,this.sendFrame(t.frame(a,r),s),this.dequeue())}).catch(i=>{process.nextTick(EA,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Yw.extensionName];this._bufferedBytes+=r[Lt],this._state=RA,i.compress(e,r.fin,(a,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ph(this,l,s);return}this._bufferedBytes-=r[Lt],this._state=Qt,r.readOnly=!1,this.sendFrame(t.frame(c,r),s),this.dequeue()})}dequeue(){for(;this._state===Qt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],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)}};Qw.exports=Ch;function Ph(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 EA(t,e,n){Ph(t,e,n),t.onerror(e)}});var cv=be((OO,av)=>{"use strict";var{kForOnEventAttribute:Bo,kListener:jh}=Hn(),ev=Symbol("kCode"),tv=Symbol("kData"),nv=Symbol("kError"),rv=Symbol("kMessage"),sv=Symbol("kReason"),Ui=Symbol("kTarget"),iv=Symbol("kType"),ov=Symbol("kWasClean"),Wn=class{constructor(e){this[Ui]=null,this[iv]=e}get target(){return this[Ui]}get type(){return this[iv]}};Object.defineProperty(Wn.prototype,"target",{enumerable:!0});Object.defineProperty(Wn.prototype,"type",{enumerable:!0});var Fs=class extends Wn{constructor(e,n={}){super(e),this[ev]=n.code===void 0?0:n.code,this[sv]=n.reason===void 0?"":n.reason,this[ov]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ev]}get reason(){return this[sv]}get wasClean(){return this[ov]}};Object.defineProperty(Fs.prototype,"code",{enumerable:!0});Object.defineProperty(Fs.prototype,"reason",{enumerable:!0});Object.defineProperty(Fs.prototype,"wasClean",{enumerable:!0});var qi=class extends Wn{constructor(e,n={}){super(e),this[nv]=n.error===void 0?null:n.error,this[rv]=n.message===void 0?"":n.message}get error(){return this[nv]}get message(){return this[rv]}};Object.defineProperty(qi.prototype,"error",{enumerable:!0});Object.defineProperty(qi.prototype,"message",{enumerable:!0});var Ho=class extends Wn{constructor(e,n={}){super(e),this[tv]=n.data===void 0?null:n.data}get data(){return this[tv]}};Object.defineProperty(Ho.prototype,"data",{enumerable:!0});var AA={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Bo]&&s[jh]===e&&!s[Bo])return;let r;if(t==="message")r=function(i,a){let c=new Ho("message",{data:a?i:i.toString()});c[Ui]=this,Zc(e,this,c)};else if(t==="close")r=function(i,a){let c=new Fs("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ui]=this,Zc(e,this,c)};else if(t==="error")r=function(i){let a=new qi("error",{error:i,message:i.message});a[Ui]=this,Zc(e,this,a)};else if(t==="open")r=function(){let i=new Wn("open");i[Ui]=this,Zc(e,this,i)};else return;r[Bo]=!!n[Bo],r[jh]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[jh]===e&&!n[Bo]){this.removeListener(t,n);break}}};av.exports={CloseEvent:Fs,ErrorEvent:qi,Event:Wn,EventTarget:AA,MessageEvent:Ho};function Zc(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jc=be((zO,lv)=>{"use strict";var{tokenChars:Ko}=zi();function bn(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function $A(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,a,c,l=-1,u=-1,p=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),a===void 0)if(p===-1&&Ko[u]===1)l===-1&&(l=f);else if(f!==0&&(u===32||u===9))p===-1&&l!==-1&&(p=f);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(l,p);u===44?(bn(e,w,n),n=Object.create(null)):a=w,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&Ko[u]===1)l===-1&&(l=f);else if(u===32||u===9)p===-1&&l!==-1&&(p=f);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),bn(n,t.slice(l,p),!0),u===44&&(bn(e,a,n),n=Object.create(null),a=void 0),l=p=-1}else if(u===61&&l!==-1&&p===-1)c=t.slice(l,f),l=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(Ko[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:r||(r=!0),s=!1}else if(i)if(Ko[u]===1)l===-1&&(l=f);else if(u===34&&l!==-1)i=!1,p=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Ko[u]===1)l===-1&&(l=f);else if(l!==-1&&(u===32||u===9))p===-1&&(p=f);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(l,p);r&&(w=w.replace(/\\/g,""),r=!1),bn(n,c,w),u===44&&(bn(e,a,n),n=Object.create(null),a=void 0),c=void 0,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=t.slice(l,p);return a===void 0?bn(e,m,n):(c===void 0?bn(n,m,!0):r?bn(n,c,m.replace(/\\/g,"")):bn(n,c,m),bn(e,a,n)),e}function CA(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(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lv.exports={format:CA,parse:$A}});var el=be((UO,kv)=>{"use strict";var PA=require("events"),NA=require("https"),jA=require("http"),hv=require("net"),MA=require("tls"),{randomBytes:OA,createHash:zA}=require("crypto"),{Duplex:DO,Readable:LO}=require("stream"),{URL:Mh}=require("url"),Tr=Oi(),DA=$h(),LA=Nh(),{isBlob:UA}=zi(),{BINARY_TYPES:uv,CLOSE_TIMEOUT:qA,EMPTY_BUFFER:Yc,GUID:FA,kForOnEventAttribute:Oh,kListener:BA,kStatusCode:HA,kWebSocket:Ze,NOOP:pv}=Hn(),{EventTarget:{addEventListener:KA,removeEventListener:WA}}=cv(),{format:GA,parse:VA}=Jc(),{toBuffer:ZA}=qo(),fv=Symbol("kAborted"),zh=[8,13],Gn=["CONNECTING","OPEN","CLOSING","CLOSED"],JA=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ne=class t extends PA{constructor(e,n,r){super(),this._binaryType=uv[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yc,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]),mv(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uv.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 DA({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 LA(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Ze]=this,i[Ze]=this,e[Ze]=this,s.on("conclude",QA),s.on("drain",e$),s.on("error",t$),s.on("message",n$),s.on("ping",r$),s.on("pong",s$),i.onerror=i$,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bv),e.on("data",Qc),e.on("end",wv),e.on("error",vv),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[Tr.extensionName]&&this._extensions[Tr.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){kt(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())}),yv(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){Dh(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yc,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){Dh(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yc,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){Dh(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Tr.extensionName]||(s.compress=!1),this._sender.send(e||Yc,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){kt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ne,"CONNECTING",{enumerable:!0,value:Gn.indexOf("CONNECTING")});Object.defineProperty(Ne.prototype,"CONNECTING",{enumerable:!0,value:Gn.indexOf("CONNECTING")});Object.defineProperty(Ne,"OPEN",{enumerable:!0,value:Gn.indexOf("OPEN")});Object.defineProperty(Ne.prototype,"OPEN",{enumerable:!0,value:Gn.indexOf("OPEN")});Object.defineProperty(Ne,"CLOSING",{enumerable:!0,value:Gn.indexOf("CLOSING")});Object.defineProperty(Ne.prototype,"CLOSING",{enumerable:!0,value:Gn.indexOf("CLOSING")});Object.defineProperty(Ne,"CLOSED",{enumerable:!0,value:Gn.indexOf("CLOSED")});Object.defineProperty(Ne.prototype,"CLOSED",{enumerable:!0,value:Gn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ne.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ne.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Oh])return e[BA];return null},set(e){for(let n of this.listeners(t))if(n[Oh]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Oh]:!0})}})});Ne.prototype.addEventListener=KA;Ne.prototype.removeEventListener=WA;kv.exports=Ne;function mv(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qA,protocolVersion:zh[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,!zh.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${zh.join(", ")})`);let i;if(e instanceof Mh)i=e;else try{i=new Mh(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 a=i.protocol==="wss:",c=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!a&&!c?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let T=new SyntaxError(l);if(t._redirects===0)throw T;Xc(t,T);return}let u=a?443:80,p=OA(16).toString("base64"),f=a?NA.request:jA.request,m=new Set,w;if(s.createConnection=s.createConnection||(a?XA:YA),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Tr({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=GA({[Tr.extensionName]:w.offer()})),n.length){for(let T of n){if(typeof T!="string"||!JA.test(T)||m.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(T)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let T=s.path.split(":");s.socketPath=T[0],s.path=T[1]}let S;if(s.followRedirects){if(t._redirects===0){t._originalIpc=c,t._originalSecure=a,t._originalHostOrSocketPath=c?s.socketPath:i.host;let T=r&&r.headers;if(r={...r,headers:{}},T)for(let[x,A]of Object.entries(T))r.headers[x.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let T=c?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!T||t._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,T||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=t._req=f(s),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=f(s);s.timeout&&S.on("timeout",()=>{kt(t,S,"Opening handshake has timed out")}),S.on("error",T=>{S===null||S[fv]||(S=t._req=null,Xc(t,T))}),S.on("response",T=>{let x=T.headers.location,A=T.statusCode;if(x&&s.followRedirects&&A>=300&&A<400){if(++t._redirects>s.maxRedirects){kt(t,S,"Maximum redirects exceeded");return}S.abort();let D;try{D=new Mh(x,e)}catch{let C=new SyntaxError(`Invalid URL: ${x}`);Xc(t,C);return}mv(t,D,n,r)}else t.emit("unexpected-response",S,T)||kt(t,S,`Unexpected server response: ${T.statusCode}`)}),S.on("upgrade",(T,x,A)=>{if(t.emit("upgrade",T),t.readyState!==Ne.CONNECTING)return;S=t._req=null;let D=T.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){kt(t,x,"Invalid Upgrade header");return}let K=zA("sha1").update(p+FA).digest("base64");if(T.headers["sec-websocket-accept"]!==K){kt(t,x,"Invalid Sec-WebSocket-Accept header");return}let C=T.headers["sec-websocket-protocol"],$;if(C!==void 0?m.size?m.has(C)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":m.size&&($="Server sent no subprotocol"),$){kt(t,x,$);return}C&&(t._protocol=C);let v=T.headers["sec-websocket-extensions"];if(v!==void 0){if(!w){kt(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let P;try{P=VA(v)}catch{kt(t,x,"Invalid Sec-WebSocket-Extensions header");return}let F=Object.keys(P);if(F.length!==1||F[0]!==Tr.extensionName){kt(t,x,"Server indicated an extension that was not requested");return}try{w.accept(P[Tr.extensionName])}catch{kt(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Tr.extensionName]=w}t.setSocket(x,A,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,t):S.end()}function Xc(t,e){t._readyState=Ne.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function YA(t){return t.path=t.socketPath,hv.connect(t)}function XA(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hv.isIP(t.host)?"":t.host),MA.connect(t)}function kt(t,e,n){t._readyState=Ne.CLOSING;let r=new Error(n);Error.captureStackTrace(r,kt),e.setHeader?(e[fv]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xc,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Dh(t,e,n){if(e){let r=UA(e)?e.size:ZA(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Gn[t.readyState]})`);process.nextTick(n,r)}}function QA(t,e){let n=this[Ze];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ze]!==void 0&&(n._socket.removeListener("data",Qc),process.nextTick(gv,n._socket),t===1005?n.close():n.close(t,e))}function e$(){let t=this[Ze];t.isPaused||t._socket.resume()}function t$(t){let e=this[Ze];e._socket[Ze]!==void 0&&(e._socket.removeListener("data",Qc),process.nextTick(gv,e._socket),e.close(t[HA])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function dv(){this[Ze].emitClose()}function n$(t,e){this[Ze].emit("message",t,e)}function r$(t){let e=this[Ze];e._autoPong&&e.pong(t,!this._isServer,pv),e.emit("ping",t)}function s$(t){this[Ze].emit("pong",t)}function gv(t){t.resume()}function i$(t){let e=this[Ze];e.readyState!==Ne.CLOSED&&(e.readyState===Ne.OPEN&&(e._readyState=Ne.CLOSING,yv(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yv(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bv(){let t=this[Ze];if(this.removeListener("close",bv),this.removeListener("data",Qc),this.removeListener("end",wv),t._readyState=Ne.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[Ze]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",dv),t._receiver.on("finish",dv))}function Qc(t){this[Ze]._receiver.write(t)||this.pause()}function wv(){let t=this[Ze];t._readyState=Ne.CLOSING,t._receiver.end(),this.end()}function vv(){let t=this[Ze];this.removeListener("error",vv),this.on("error",pv),t&&(t._readyState=Ne.CLOSING,this.destroy())}});var Tv=be((FO,xv)=>{"use strict";var qO=el(),{Duplex:o$}=require("stream");function Sv(t){t.emit("close")}function a$(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _v(t){this.removeListener("error",_v),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function c$(t,e){let n=!0,r=new o$({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,a){let c=!a&&r._readableState.objectMode?i.toString():i;r.push(c)||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(Sv,r);return}let a=!1;t.once("error",function(l){a=!0,i(l)}),t.once("close",function(){a||i(s),process.nextTick(Sv,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,a){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,a)});return}t.send(s,a)},r.on("end",a$),r.on("error",_v),r}xv.exports=c$});var Lh=be((BO,Rv)=>{"use strict";var{tokenChars:l$}=zi();function u$(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let a=t.charCodeAt(s);if(r===-1&&l$[a]===1)n===-1&&(n=s);else if(s!==0&&(a===32||a===9))r===-1&&n!==-1&&(r=s);else if(a===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let c=t.slice(n,r);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),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}Rv.exports={parse:u$}});var Nv=be((KO,Pv)=>{"use strict";var d$=require("events"),tl=require("http"),{Duplex:HO}=require("stream"),{createHash:h$}=require("crypto"),Iv=Jc(),Bs=Oi(),p$=Lh(),f$=el(),{CLOSE_TIMEOUT:m$,GUID:g$,kWebSocket:y$}=Hn(),b$=/^[+/0-9A-Za-z]{22}==$/,Ev=0,Av=1,Cv=2,Uh=class extends d${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:m$,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:f$,...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=tl.createServer((r,s)=>{let i=tl.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=w$(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,a)=>{this.handleUpgrade(s,i,a,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ev}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===Cv){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Wo,this);return}if(e&&this.once("close",e),this._state!==Av)if(this._state=Av,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(Wo,this):process.nextTick(Wo,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Wo(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",$v);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Hs(this,e,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Hs(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!b$.test(i)){Hs(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Hs(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Go(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=p$.parse(l)}catch{Hs(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 m=new Bs({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Iv.parse(p);w[Bs.extensionName]&&(m.accept(w[Bs.extensionName]),f[Bs.extensionName]=m)}catch{Hs(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(w,S,T,x)=>{if(!w)return Go(n,S||401,T,x);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(m))return Go(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[y$])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ev)return Go(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h$("sha1").update(n+g$).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Bs.extensionName]){let f=e[Bs.extensionName].params,m=Iv.format({[Bs.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
1243
+ `}}function Xd(){for(let t of[Sr,Pi])try{if((0,vt.execFileSync)("systemctl",["show",t,"-p","LoadState"],{encoding:"utf8"}).includes("LoadState=loaded"))return t}catch{}return""}function Do(){let t=Xd();if(!t)return{protected:null,fixCommand:""};let e=Yd(t),n=`sudo mkdir -p ${e.dir} && printf '[Service]\\nKillMode=mixed\\nTimeoutStopSec=2h\\n' | sudo tee ${e.file} && sudo systemctl daemon-reload`;try{let r=(0,vt.execFileSync)("systemctl",["show",t,"-p","KillMode","-p","TimeoutStopUSec"],{encoding:"utf8"}),s=/KillMode=(\S+)/.exec(r)?.[1]??"",i=/TimeoutStopUSec=(\S+)/.exec(r)?.[1]??"",a=/h$/.test(i)||/^(3[0-9]|[4-9][0-9])min$/.test(i);return{protected:s==="mixed"&&a,fixCommand:n}}catch{return{protected:null,fixCommand:""}}}function xE(){let t=Do();if(t.protected!==!1)return t.protected===!0;let e=Xd();if(!e)return!1;let n=Yd(e);try{return(0,vt.execFileSync)("sudo",["-n","mkdir","-p",n.dir],{stdio:"ignore"}),(0,vt.execFileSync)("sudo",["-n","tee",n.file],{input:n.content,stdio:["pipe","ignore","ignore"]}),(0,vt.execFileSync)("sudo",["-n","systemctl","daemon-reload"],{stdio:"ignore"}),Do().protected===!0}catch{return!1}}var vt,yn,_c,Ci,$b,Sr,Wd,Pi,Ac=J(()=>{"use strict";vt=require("node:child_process"),yn=E(require("node:fs"),1),_c=E(require("node:os"),1),Ci=E(require("node:path"),1),$b=E(Me(),1);Kd();Sr="allwright",Wd=`/etc/systemd/system/${Sr}.service`,Pi="ticketpilot-runner"});var Wb={};Fe(Wb,{MAX_CHAIN_DEPTH:()=>eh,breakChain:()=>sh,breakSingleModeChain:()=>ch,chainOf:()=>nh,chainSessionFor:()=>jc,loadBatchPlan:()=>th,nextMemberWillChain:()=>lh,parsePlanAnswer:()=>uh,recordChainSession:()=>rh,recordSingleModeSession:()=>oh,saveBatchPlan:()=>RE,singleModeChainIntact:()=>ah,singleModeSessionFor:()=>ih});function RE(t){Ni.default.mkdirSync(Qd(),{recursive:!0,mode:448}),Ni.default.writeFileSync(Nc.default.join(Qd(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function th(t){if(!t)return null;try{return JSON.parse(Ni.default.readFileSync(Nc.default.join(Qd(),`${t}.json`),"utf8"))}catch{return null}}function nh(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function jc(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=Bn.get(Pc(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=eh||!Ni.default.existsSync(s.worktreePath)?null:s}function rh(t,e,n,r){let s=Bn.get(Pc(t,e));Bn.set(Pc(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function sh(t,e){Bn.delete(Pc(t,e))}function ih(t){let e=Bn.get(Lo(t));return!e||e.depth>=eh||!Ni.default.existsSync(e.worktreePath)?null:e}function oh(t,e,n,r){let s=Bn.get(Lo(t));Bn.set(Lo(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function ah(t,e){return Bn.get(Lo(t))?.lastIssue===e}function ch(t){Bn.delete(Lo(t))}function lh(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function uh(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),a=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(a.length!==e.length||!a.every(p=>i.has(p))||new Set(a).size!==a.length)return null;let c=(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),l=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:a,chains:c,dependencies:l,reasoning:u}}var Ni,Nc,eh,Qd,Bn,Pc,Lo,Mc=J(()=>{"use strict";Ni=E(require("node:fs"),1),Nc=E(require("node:path"),1);Te();eh=3,Qd=()=>Nc.default.join(X(),"autopilot-plans");Bn=new Map,Pc=(t,e)=>`${t}:${e[0]}`;Lo=t=>`${t}:__single__`});var Hn=be((EO,Nw)=>{"use strict";var Cw=["nodebuffer","arraybuffer","fragments"],Pw=typeof Blob<"u";Pw&&Cw.push("blob");Nw.exports={BINARY_TYPES:Cw,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Pw,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qo=be((AO,Fc)=>{"use strict";var{EMPTY_BUFFER:eA}=Hn(),vh=Buffer[Symbol.species];function tA(t,e){if(t.length===0)return eA;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 vh(n.buffer,n.byteOffset,r):n}function jw(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Mw(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function nA(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function kh(t){if(kh.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vh(t):ArrayBuffer.isView(t)?e=new vh(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),kh.readOnly=!1),e}Fc.exports={concat:tA,mask:jw,toArrayBuffer:nA,toBuffer:kh,unmask:Mw};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Fc.exports.mask=function(e,n,r,s,i){i<48?jw(e,n,r,s,i):t.mask(e,n,r,s,i)},Fc.exports.unmask=function(e,n){e.length<32?Mw(e,n):t.unmask(e,n)}}catch{}});var Dw=be(($O,zw)=>{"use strict";var Ow=Symbol("kDone"),Sh=Symbol("kRun"),_h=class{constructor(e){this[Ow]=()=>{this.pending--,this[Sh]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Sh]()}[Sh](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ow])}}};zw.exports=_h});var Oi=be((CO,Fw)=>{"use strict";var Fo=require("zlib"),Lw=qo(),rA=Dw(),{kStatusCode:Uw}=Hn(),sA=Buffer[Symbol.species],iA=Buffer.from([0,0,255,255]),Hc=Symbol("permessage-deflate"),Kn=Symbol("total-length"),ji=Symbol("callback"),xr=Symbol("buffers"),Mi=Symbol("error"),Bc,xh=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,!Bc){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Bc=new rA(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[ji];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){Bc.add(s=>{this._decompress(e,n,(i,a)=>{s(),r(i,a)})})}compress(e,n,r){Bc.add(s=>{this._compress(e,n,(i,a)=>{s(),r(i,a)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?Fo.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Fo.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Hc]=this,this._inflate[Kn]=0,this._inflate[xr]=[],this._inflate.on("error",aA),this._inflate.on("data",qw)}this._inflate[ji]=r,this._inflate.write(e),n&&this._inflate.write(iA),this._inflate.flush(()=>{let i=this._inflate[Mi];if(i){this._inflate.close(),this._inflate=null,r(i);return}let a=Lw.concat(this._inflate[xr],this._inflate[Kn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Kn]=0,this._inflate[xr]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,a)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?Fo.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Fo.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Kn]=0,this._deflate[xr]=[],this._deflate.on("data",oA)}this._deflate[ji]=r,this._deflate.write(e),this._deflate.flush(Fo.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Lw.concat(this._deflate[xr],this._deflate[Kn]);n&&(i=new sA(i.buffer,i.byteOffset,i.length-4)),this._deflate[ji]=null,this._deflate[Kn]=0,this._deflate[xr]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Fw.exports=xh;function oA(t){this[xr].push(t),this[Kn]+=t.length}function qw(t){if(this[Kn]+=t.length,this[Hc]._maxPayload<1||this[Kn]<=this[Hc]._maxPayload){this[xr].push(t);return}this[Mi]=new RangeError("Max payload size exceeded"),this[Mi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Mi][Uw]=1009,this.removeListener("data",qw),this.reset()}function aA(t){if(this[Hc]._inflate=null,this[Mi]){this[ji](this[Mi]);return}t[Uw]=1007,this[ji](t)}});var zi=be((PO,Kc)=>{"use strict";var{isUtf8:Bw}=require("buffer"),{hasBlob:cA}=Hn(),lA=[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 uA(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Th(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 dA(t){return cA&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Kc.exports={isBlob:dA,isValidStatusCode:uA,isValidUTF8:Th,tokenChars:lA};if(Bw)Kc.exports.isValidUTF8=function(t){return t.length<24?Th(t):Bw(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Kc.exports.isValidUTF8=function(e){return e.length<32?Th(e):t(e)}}catch{}});var $h=be((NO,Jw)=>{"use strict";var{Writable:hA}=require("stream"),Hw=Oi(),{BINARY_TYPES:pA,EMPTY_BUFFER:Kw,kStatusCode:fA,kWebSocket:mA}=Hn(),{concat:Rh,toArrayBuffer:gA,unmask:yA}=qo(),{isValidStatusCode:bA,isValidUTF8:Ww}=zi(),Wc=Buffer[Symbol.species],Dt=0,Gw=1,Vw=2,Zw=3,Ih=4,Eh=5,Gc=6,Ah=class extends hA{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pA[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[mA]=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=Dt}_write(e,n,r){if(this._opcode===8&&this._state==Dt)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 Wc(r.buffer,r.byteOffset+e,r.length-e),new Wc(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 Wc(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 Dt:this.getInfo(e);break;case Gw:this.getPayloadLength16(e);break;case Vw:this.getPayloadLength64(e);break;case Zw:this.getMask();break;case Ih:this.getData(e);break;case Eh:case Gc: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[Hw.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=Gw:this._payloadLength===127?this._state=Vw: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=Zw:this._state=Ih}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ih}getData(e){let n=Kw;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&&yA(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=Eh,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hw.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 a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(a);return}this._fragments.push(i)}this.dataMessage(n),this._state===Dt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Dt;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=Rh(r,n):this._binaryType==="arraybuffer"?s=gA(Rh(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Dt):(this._state=Gc,setImmediate(()=>{this.emit("message",s,!0),this._state=Dt,this.startLoop(e)}))}else{let s=Rh(r,n);if(!this._skipUTF8Validation&&!Ww(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Eh||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Dt):(this._state=Gc,setImmediate(()=>{this.emit("message",s,!1),this._state=Dt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kw),this.end();else{let r=e.readUInt16BE(0);if(!bA(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Wc(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ww(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=Dt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt):(this._state=Gc,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let a=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(a,this.createError),a.code=i,a[fA]=s,a}};Jw.exports=Ah});var Nh=be((MO,Qw)=>{"use strict";var{Duplex:jO}=require("stream"),{randomFillSync:wA}=require("crypto"),{types:{isUint8Array:vA}}=require("util"),Yw=Oi(),{EMPTY_BUFFER:kA,kWebSocket:SA,NOOP:_A}=Hn(),{isBlob:Di,isValidStatusCode:xA}=zi(),{mask:Xw,toBuffer:Us}=qo(),Lt=Symbol("kByteLength"),TA=Buffer.alloc(4),Vc=8*1024,qs,Li=Vc,Qt=0,RA=1,IA=2,Ch=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=Qt,this.onerror=_A,this[SA]=void 0}static frame(e,n){let r,s=!1,i=2,a=!1;n.mask&&(r=n.maskBuffer||TA,n.generateMask?n.generateMask(r):(Li===Vc&&(qs===void 0&&(qs=Buffer.alloc(Vc)),wA(qs,0,Vc),Li=0),r[0]=qs[Li++],r[1]=qs[Li++],r[2]=qs[Li++],r[3]=qs[Li++]),a=(r[0]|r[1]|r[2]|r[3])===0,i=6);let c;typeof e=="string"?(!n.mask||a)&&n[Lt]!==void 0?c=n[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,s=n.mask&&n.readOnly&&!a);let l=c;c>=65536?(i+=8,l=127):c>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(s?c+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(c,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(c,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],a?[u,e]:s?(Xw(e,r,u,i,c),[u]):(Xw(e,r,e,0,c),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=kA;else{if(typeof e!="number"||!xA(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 c=Buffer.byteLength(n);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(vA(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[Lt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Qt?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(t.frame(i,a),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Di(e)?(s=e.size,i=!1):(e=Us(e),s=e.length,i=Us.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Di(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Qt?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Di(e)?(s=e.size,i=!1):(e=Us(e),s=e.length,i=Us.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Di(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Qt?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}send(e,n,r){let s=this._extensions[Yw.extensionName],i=n.binary?2:1,a=n.compress,c,l;typeof e=="string"?(c=Buffer.byteLength(e),l=!1):Di(e)?(c=e.size,l=!1):(e=Us(e),c=e.length,l=Us.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[Lt]:c,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:a};Di(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Qt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Lt],this._state=IA,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Ph,this,c,s);return}this._bufferedBytes-=r[Lt];let a=Us(i);n?this.dispatch(a,n,r,s):(this._state=Qt,this.sendFrame(t.frame(a,r),s),this.dequeue())}).catch(i=>{process.nextTick(EA,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Yw.extensionName];this._bufferedBytes+=r[Lt],this._state=RA,i.compress(e,r.fin,(a,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ph(this,l,s);return}this._bufferedBytes-=r[Lt],this._state=Qt,r.readOnly=!1,this.sendFrame(t.frame(c,r),s),this.dequeue()})}dequeue(){for(;this._state===Qt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],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)}};Qw.exports=Ch;function Ph(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 EA(t,e,n){Ph(t,e,n),t.onerror(e)}});var cv=be((OO,av)=>{"use strict";var{kForOnEventAttribute:Bo,kListener:jh}=Hn(),ev=Symbol("kCode"),tv=Symbol("kData"),nv=Symbol("kError"),rv=Symbol("kMessage"),sv=Symbol("kReason"),Ui=Symbol("kTarget"),iv=Symbol("kType"),ov=Symbol("kWasClean"),Wn=class{constructor(e){this[Ui]=null,this[iv]=e}get target(){return this[Ui]}get type(){return this[iv]}};Object.defineProperty(Wn.prototype,"target",{enumerable:!0});Object.defineProperty(Wn.prototype,"type",{enumerable:!0});var Fs=class extends Wn{constructor(e,n={}){super(e),this[ev]=n.code===void 0?0:n.code,this[sv]=n.reason===void 0?"":n.reason,this[ov]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ev]}get reason(){return this[sv]}get wasClean(){return this[ov]}};Object.defineProperty(Fs.prototype,"code",{enumerable:!0});Object.defineProperty(Fs.prototype,"reason",{enumerable:!0});Object.defineProperty(Fs.prototype,"wasClean",{enumerable:!0});var qi=class extends Wn{constructor(e,n={}){super(e),this[nv]=n.error===void 0?null:n.error,this[rv]=n.message===void 0?"":n.message}get error(){return this[nv]}get message(){return this[rv]}};Object.defineProperty(qi.prototype,"error",{enumerable:!0});Object.defineProperty(qi.prototype,"message",{enumerable:!0});var Ho=class extends Wn{constructor(e,n={}){super(e),this[tv]=n.data===void 0?null:n.data}get data(){return this[tv]}};Object.defineProperty(Ho.prototype,"data",{enumerable:!0});var AA={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Bo]&&s[jh]===e&&!s[Bo])return;let r;if(t==="message")r=function(i,a){let c=new Ho("message",{data:a?i:i.toString()});c[Ui]=this,Zc(e,this,c)};else if(t==="close")r=function(i,a){let c=new Fs("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ui]=this,Zc(e,this,c)};else if(t==="error")r=function(i){let a=new qi("error",{error:i,message:i.message});a[Ui]=this,Zc(e,this,a)};else if(t==="open")r=function(){let i=new Wn("open");i[Ui]=this,Zc(e,this,i)};else return;r[Bo]=!!n[Bo],r[jh]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[jh]===e&&!n[Bo]){this.removeListener(t,n);break}}};av.exports={CloseEvent:Fs,ErrorEvent:qi,Event:Wn,EventTarget:AA,MessageEvent:Ho};function Zc(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jc=be((zO,lv)=>{"use strict";var{tokenChars:Ko}=zi();function bn(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function $A(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,a,c,l=-1,u=-1,p=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),a===void 0)if(p===-1&&Ko[u]===1)l===-1&&(l=f);else if(f!==0&&(u===32||u===9))p===-1&&l!==-1&&(p=f);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(l,p);u===44?(bn(e,w,n),n=Object.create(null)):a=w,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&Ko[u]===1)l===-1&&(l=f);else if(u===32||u===9)p===-1&&l!==-1&&(p=f);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),bn(n,t.slice(l,p),!0),u===44&&(bn(e,a,n),n=Object.create(null),a=void 0),l=p=-1}else if(u===61&&l!==-1&&p===-1)c=t.slice(l,f),l=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(Ko[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:r||(r=!0),s=!1}else if(i)if(Ko[u]===1)l===-1&&(l=f);else if(u===34&&l!==-1)i=!1,p=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Ko[u]===1)l===-1&&(l=f);else if(l!==-1&&(u===32||u===9))p===-1&&(p=f);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(l,p);r&&(w=w.replace(/\\/g,""),r=!1),bn(n,c,w),u===44&&(bn(e,a,n),n=Object.create(null),a=void 0),c=void 0,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=t.slice(l,p);return a===void 0?bn(e,m,n):(c===void 0?bn(n,m,!0):r?bn(n,c,m.replace(/\\/g,"")):bn(n,c,m),bn(e,a,n)),e}function CA(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(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lv.exports={format:CA,parse:$A}});var el=be((UO,kv)=>{"use strict";var PA=require("events"),NA=require("https"),jA=require("http"),hv=require("net"),MA=require("tls"),{randomBytes:OA,createHash:zA}=require("crypto"),{Duplex:DO,Readable:LO}=require("stream"),{URL:Mh}=require("url"),Tr=Oi(),DA=$h(),LA=Nh(),{isBlob:UA}=zi(),{BINARY_TYPES:uv,CLOSE_TIMEOUT:qA,EMPTY_BUFFER:Yc,GUID:FA,kForOnEventAttribute:Oh,kListener:BA,kStatusCode:HA,kWebSocket:Ze,NOOP:pv}=Hn(),{EventTarget:{addEventListener:KA,removeEventListener:WA}}=cv(),{format:GA,parse:VA}=Jc(),{toBuffer:ZA}=qo(),fv=Symbol("kAborted"),zh=[8,13],Gn=["CONNECTING","OPEN","CLOSING","CLOSED"],JA=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ne=class t extends PA{constructor(e,n,r){super(),this._binaryType=uv[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yc,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]),mv(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uv.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 DA({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 LA(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Ze]=this,i[Ze]=this,e[Ze]=this,s.on("conclude",QA),s.on("drain",e$),s.on("error",t$),s.on("message",n$),s.on("ping",r$),s.on("pong",s$),i.onerror=i$,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bv),e.on("data",Qc),e.on("end",wv),e.on("error",vv),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[Tr.extensionName]&&this._extensions[Tr.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){kt(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())}),yv(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){Dh(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yc,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){Dh(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yc,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){Dh(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Tr.extensionName]||(s.compress=!1),this._sender.send(e||Yc,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){kt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ne,"CONNECTING",{enumerable:!0,value:Gn.indexOf("CONNECTING")});Object.defineProperty(Ne.prototype,"CONNECTING",{enumerable:!0,value:Gn.indexOf("CONNECTING")});Object.defineProperty(Ne,"OPEN",{enumerable:!0,value:Gn.indexOf("OPEN")});Object.defineProperty(Ne.prototype,"OPEN",{enumerable:!0,value:Gn.indexOf("OPEN")});Object.defineProperty(Ne,"CLOSING",{enumerable:!0,value:Gn.indexOf("CLOSING")});Object.defineProperty(Ne.prototype,"CLOSING",{enumerable:!0,value:Gn.indexOf("CLOSING")});Object.defineProperty(Ne,"CLOSED",{enumerable:!0,value:Gn.indexOf("CLOSED")});Object.defineProperty(Ne.prototype,"CLOSED",{enumerable:!0,value:Gn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ne.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ne.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Oh])return e[BA];return null},set(e){for(let n of this.listeners(t))if(n[Oh]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Oh]:!0})}})});Ne.prototype.addEventListener=KA;Ne.prototype.removeEventListener=WA;kv.exports=Ne;function mv(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qA,protocolVersion:zh[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,!zh.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${zh.join(", ")})`);let i;if(e instanceof Mh)i=e;else try{i=new Mh(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 a=i.protocol==="wss:",c=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!a&&!c?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let T=new SyntaxError(l);if(t._redirects===0)throw T;Xc(t,T);return}let u=a?443:80,p=OA(16).toString("base64"),f=a?NA.request:jA.request,m=new Set,w;if(s.createConnection=s.createConnection||(a?XA:YA),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Tr({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=GA({[Tr.extensionName]:w.offer()})),n.length){for(let T of n){if(typeof T!="string"||!JA.test(T)||m.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(T)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let T=s.path.split(":");s.socketPath=T[0],s.path=T[1]}let S;if(s.followRedirects){if(t._redirects===0){t._originalIpc=c,t._originalSecure=a,t._originalHostOrSocketPath=c?s.socketPath:i.host;let T=r&&r.headers;if(r={...r,headers:{}},T)for(let[x,A]of Object.entries(T))r.headers[x.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let T=c?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!T||t._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,T||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=t._req=f(s),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=f(s);s.timeout&&S.on("timeout",()=>{kt(t,S,"Opening handshake has timed out")}),S.on("error",T=>{S===null||S[fv]||(S=t._req=null,Xc(t,T))}),S.on("response",T=>{let x=T.headers.location,A=T.statusCode;if(x&&s.followRedirects&&A>=300&&A<400){if(++t._redirects>s.maxRedirects){kt(t,S,"Maximum redirects exceeded");return}S.abort();let D;try{D=new Mh(x,e)}catch{let C=new SyntaxError(`Invalid URL: ${x}`);Xc(t,C);return}mv(t,D,n,r)}else t.emit("unexpected-response",S,T)||kt(t,S,`Unexpected server response: ${T.statusCode}`)}),S.on("upgrade",(T,x,A)=>{if(t.emit("upgrade",T),t.readyState!==Ne.CONNECTING)return;S=t._req=null;let D=T.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){kt(t,x,"Invalid Upgrade header");return}let K=zA("sha1").update(p+FA).digest("base64");if(T.headers["sec-websocket-accept"]!==K){kt(t,x,"Invalid Sec-WebSocket-Accept header");return}let C=T.headers["sec-websocket-protocol"],$;if(C!==void 0?m.size?m.has(C)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":m.size&&($="Server sent no subprotocol"),$){kt(t,x,$);return}C&&(t._protocol=C);let v=T.headers["sec-websocket-extensions"];if(v!==void 0){if(!w){kt(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=VA(v)}catch{kt(t,x,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(N);if(B.length!==1||B[0]!==Tr.extensionName){kt(t,x,"Server indicated an extension that was not requested");return}try{w.accept(N[Tr.extensionName])}catch{kt(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Tr.extensionName]=w}t.setSocket(x,A,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,t):S.end()}function Xc(t,e){t._readyState=Ne.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function YA(t){return t.path=t.socketPath,hv.connect(t)}function XA(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hv.isIP(t.host)?"":t.host),MA.connect(t)}function kt(t,e,n){t._readyState=Ne.CLOSING;let r=new Error(n);Error.captureStackTrace(r,kt),e.setHeader?(e[fv]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xc,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Dh(t,e,n){if(e){let r=UA(e)?e.size:ZA(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Gn[t.readyState]})`);process.nextTick(n,r)}}function QA(t,e){let n=this[Ze];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ze]!==void 0&&(n._socket.removeListener("data",Qc),process.nextTick(gv,n._socket),t===1005?n.close():n.close(t,e))}function e$(){let t=this[Ze];t.isPaused||t._socket.resume()}function t$(t){let e=this[Ze];e._socket[Ze]!==void 0&&(e._socket.removeListener("data",Qc),process.nextTick(gv,e._socket),e.close(t[HA])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function dv(){this[Ze].emitClose()}function n$(t,e){this[Ze].emit("message",t,e)}function r$(t){let e=this[Ze];e._autoPong&&e.pong(t,!this._isServer,pv),e.emit("ping",t)}function s$(t){this[Ze].emit("pong",t)}function gv(t){t.resume()}function i$(t){let e=this[Ze];e.readyState!==Ne.CLOSED&&(e.readyState===Ne.OPEN&&(e._readyState=Ne.CLOSING,yv(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yv(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bv(){let t=this[Ze];if(this.removeListener("close",bv),this.removeListener("data",Qc),this.removeListener("end",wv),t._readyState=Ne.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[Ze]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",dv),t._receiver.on("finish",dv))}function Qc(t){this[Ze]._receiver.write(t)||this.pause()}function wv(){let t=this[Ze];t._readyState=Ne.CLOSING,t._receiver.end(),this.end()}function vv(){let t=this[Ze];this.removeListener("error",vv),this.on("error",pv),t&&(t._readyState=Ne.CLOSING,this.destroy())}});var Tv=be((FO,xv)=>{"use strict";var qO=el(),{Duplex:o$}=require("stream");function Sv(t){t.emit("close")}function a$(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _v(t){this.removeListener("error",_v),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function c$(t,e){let n=!0,r=new o$({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,a){let c=!a&&r._readableState.objectMode?i.toString():i;r.push(c)||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(Sv,r);return}let a=!1;t.once("error",function(l){a=!0,i(l)}),t.once("close",function(){a||i(s),process.nextTick(Sv,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,a){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,a)});return}t.send(s,a)},r.on("end",a$),r.on("error",_v),r}xv.exports=c$});var Lh=be((BO,Rv)=>{"use strict";var{tokenChars:l$}=zi();function u$(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let a=t.charCodeAt(s);if(r===-1&&l$[a]===1)n===-1&&(n=s);else if(s!==0&&(a===32||a===9))r===-1&&n!==-1&&(r=s);else if(a===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let c=t.slice(n,r);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),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}Rv.exports={parse:u$}});var Nv=be((KO,Pv)=>{"use strict";var d$=require("events"),tl=require("http"),{Duplex:HO}=require("stream"),{createHash:h$}=require("crypto"),Iv=Jc(),Bs=Oi(),p$=Lh(),f$=el(),{CLOSE_TIMEOUT:m$,GUID:g$,kWebSocket:y$}=Hn(),b$=/^[+/0-9A-Za-z]{22}==$/,Ev=0,Av=1,Cv=2,Uh=class extends d${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:m$,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:f$,...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=tl.createServer((r,s)=>{let i=tl.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=w$(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,a)=>{this.handleUpgrade(s,i,a,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ev}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===Cv){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Wo,this);return}if(e&&this.once("close",e),this._state!==Av)if(this._state=Av,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(Wo,this):process.nextTick(Wo,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Wo(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",$v);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Hs(this,e,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Hs(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!b$.test(i)){Hs(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Hs(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Go(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=p$.parse(l)}catch{Hs(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 m=new Bs({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Iv.parse(p);w[Bs.extensionName]&&(m.accept(w[Bs.extensionName]),f[Bs.extensionName]=m)}catch{Hs(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(w,S,T,x)=>{if(!w)return Go(n,S||401,T,x);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(m))return Go(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[y$])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ev)return Go(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h$("sha1").update(n+g$).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Bs.extensionName]){let f=e[Bs.extensionName].params,m=Iv.format({[Bs.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
1244
1244
  `).join(`\r
1245
1245
  `)),i.removeListener("error",$v),p.setSocket(i,a,{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(Wo,this)})),c(p,s)}};Pv.exports=Uh;function w$(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 Wo(t){t._state=Cv,t.emit("close")}function $v(){this.destroy()}function Go(t,e,n,r){n=n||tl.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} ${tl.STATUS_CODES[e]}\r
1246
1246
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
@@ -1331,7 +1331,7 @@ ${p}`)}Le(["systemctl","reload","nginx"]),b.info(`\u2713 nginx: ${t.hostname} \u
1331
1331
  `).slice(0,6e4),tables:n.length}}var Rr,cl,nk,V$,ik=J(()=>{"use strict";Rr=E(require("node:fs"),1),cl=E(require("node:path"),1),nk=E(require("node:zlib"),1),V$=128*1024*1024});var ep={};Fe(ep,{BREAKDOWN_CONTRACT:()=>hl,MAX_JIRA_ISSUES:()=>lk,PROVENANCE_RULE:()=>Qh,extractNamedBlock:()=>Ir,profileDump:()=>uk,profileSqlDump:()=>dk,rebirthStudyInFlight:()=>X$,runRebirthDesign:()=>pC,runRebirthStudy:()=>aC,scopeAllows:()=>hk,sendRunFinished:()=>oC,shrinkWarning:()=>Hi,splitDesign:()=>ul,splitSpec:()=>Xh});function X$(t){return ll.has(t)}function uk(t){try{if(Ws.default.statSync(t).isDirectory())return rk(t)?sk(t):{ok:!1,markdown:`\`${t}\` is a directory but holds no .bson collections - point at a SQL dump file or a mongodump folder`,tables:0}}catch{return{ok:!1,markdown:`Could not read the dump at \`${t}\``,tables:0}}return dk(t)}function dk(t){if(/\.(rar|zip|7z|tar|tgz|bz2|xz)$/i.test(t))return{ok:!1,markdown:`\`${t}\` is an archive, not a SQL dump - extract the .sql inside it and use that (plain .sql or .dump text; the profiler reads text, it does not unpack archives)`,tables:0};let e;try{let n=Ws.default.openSync(t,"r"),r=Ws.default.fstatSync(n).size,s=Math.min(r,32*1024*1024),i=Buffer.alloc(s);if(Ws.default.readSync(n,i,0,s,0),Ws.default.closeSync(n),/\.gz$/i.test(t))try{i=ck.default.gunzipSync(Ws.default.readFileSync(t),{maxOutputLength:64*1024*1024})}catch{return{ok:!1,markdown:`Could not decompress \`${t}\` (or it is larger than 64MB unpacked) - gunzip it and give the .sql`,tables:0}}if(e=i.toString("utf8"),i.subarray(0,Math.min(s,65536)).includes(0))return{ok:!1,markdown:`\`${t}\` is binary, not SQL text - export a plain-text dump (pg_dump / mysqldump default output) and use that`,tables:0};let a=r>s,c=[];for(let u of e.matchAll(/CREATE TABLE[^`"\w]*[`"]?([\w.]+)[`"]?\s*\(([\s\S]*?)\)\s*;/gi)){let f=u[2].split(`
1332
1332
  `).map(m=>m.trim()).filter(m=>m&&!/^(PRIMARY|UNIQUE|KEY|CONSTRAINT|FOREIGN|INDEX)/i.test(m)).map(m=>m.split(/\s+/)[0].replace(/[`",]/g,"")).filter(Boolean);c.push({name:u[1],columns:f,rows:0})}for(let u of c){let p=u.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),f=0;for(let w of e.matchAll(new RegExp(`INSERT INTO [\`"]?${p}[\`"]?[^;]*;`,"gi")))f+=(w[0].match(/\),\s*\(/g)?.length??0)+1;let m=e.match(new RegExp(`COPY [\`"]?${p}[\`"]?[^\\n]*FROM stdin;\\n([\\s\\S]*?)\\n\\\\\\.`,"i"));m&&(f+=m[1].split(`
1333
1333
  `).filter(Boolean).length),u.rows=f}let l=["# Data profile (from the dump, by code - no database was connected)","",`${c.length} table(s) found in \`${t}\`${a?" (large dump - schema read from its head; row counts are minimums)":""}.`,"",`| Table | Columns | Rows${a?" (\u2265)":""} |`,"| --- | --- | --- |",...c.sort((u,p)=>p.rows-u.rows).map(u=>`| ${u.name} | ${u.columns.length} | ${u.rows.toLocaleString()} |`),"","## Columns",...c.map(u=>`- **${u.name}**: ${u.columns.join(", ")||"(none parsed)"}`)];return{ok:c.length>0,markdown:l.join(`
1334
- `).slice(0,6e4),tables:c.length}}catch(n){return{ok:!1,markdown:`Could not read the dump at \`${t}\`: ${n instanceof Error?n.message:n}`,tables:0}}}function Hi(t,e){let n=t.trim().length,r=e.trim().length;return n<2e3||r>=n*.9?"":` WARNING: it came back ${Math.round(100-r/n*100)}% smaller than the current version - check the diff for lost detail before approving.`}function hk(t,e){return t==="all"?!0:t.startsWith("except:")?e!==t.slice(7):t===e}function Ir(t,e){let r=new RegExp("```"+e+"\\n([\\s\\S]*?)```","").exec(t);return r?{block:r[1].trim(),rest:t.replace(r[0],"").trim()}:{block:"",rest:t}}function oC(t,e,n,r){t.send({type:"rebirth.study.update",rebirthId:e,stageNumber:1,status:"in_progress",note:"",progressDone:0,progressTotal:0,artifact:"",items:[],buildOrder:[],brief:"",runFinished:{kind:n,ok:r.ok,error:(r.error??"").slice(0,2e3)},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}})}async function aC(t){let{msg:e,transport:n}=t;if(ll.has(e.rebirthId))return{ok:!1,error:"a study is already running for this rebirth - it reports as it goes"};ll.add(e.rebirthId);let r={inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0},s=i=>{let a=r;r={inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0},n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:i.stageNumber,status:i.status,note:i.note??"",progressDone:i.progressDone??0,progressTotal:i.progressTotal??0,artifact:i.artifact??"",items:i.items??[],buildOrder:i.buildOrder??[],brief:i.brief??"",...i.proposal?{proposal:i.proposal}:{},usageDelta:a})};try{let i=Ce(t.cfg,t.project,"assist");if("error"in i)return{ok:!1,error:i.error};let a=(0,dl.randomUUID)(),c=!1,l=e.refineMessage.trim()?"rebirth_refold":"rebirth_study",u=async(A,D,K=60)=>{let C=await i.adapter.run({repoPath:t.repoPath,prompt:A,timeoutSeconds:D*60,bin:i.bin,mode:"read_only",maxTurns:K,sessionId:a,resume:c,onLog:()=>{}});return c=!0,Se({surface:l,projectId:t.project.id,agentId:i.adapter.id,refKind:"rebirth",refId:e.rebirthId,...ve(C)}),r={inputTokens:r.inputTokens+(C.inputTokens??0),outputTokens:r.outputTokens+(C.outputTokens??0),cacheReadTokens:r.cacheReadTokens+(C.cacheReadTokens??0),costUsd:r.costUsd+(C.costUsd??0)},C};if(e.refineMessage.trim()){let A=e.refineScope,D=(L,d)=>s({stageNumber:4,status:"in_progress",note:d,proposal:{message:e.refineMessage,scope:A,docs:L.docs??[],tickets:L.tickets??[],buildOrder:L.buildOrder??[],working:L.working??!1,error:L.error??""}});if(!e.currentDocsIncluded){let L="refine refused: this control plane does not send the current documents with a correction, so the refine would rewrite the plan from scratch and lose everything the correction does not mention. Update the control plane, then refine again.";return s({stageNumber:4,status:"failed",note:L}),{ok:!1,error:L}}D({working:!0},"Folding your correction into the plan - the result comes back as proposed changes for your review\u2026"),c=!1;let K=await u(iC(e.refineMessage,{brief:e.currentBrief,understanding:e.currentUnderstanding,requirements:e.currentRequirements,spec:e.currentSpec},A),60,150);if(!K.ok||!K.resultText.trim())return D({error:K.error??"the refine pass produced nothing"},"The refold failed - nothing was changed"),{ok:!1,error:K.error??"the refine pass produced nothing"};let C=Ir(K.resultText,"brief"),$=Ir(C.rest,"understanding"),v=Ir($.rest,"requirements"),P=L=>hk(A,L),F=[],V=[],te=[];if(P("brief")&&C.block&&F.push({doc:"brief",proposed:C.block.slice(0,1e5)}),P("understanding")&&$.block&&F.push({doc:"understanding",proposed:$.block.slice(0,2e5)}),P("requirements")&&v.block&&F.push({doc:"requirements",proposed:v.block.slice(0,2e5)}),P("spec")&&v.rest.trim()){let L=Xh(v.rest);L.spec.trim()&&(F.push({doc:"spec",proposed:L.spec}),V=L.tickets,te=L.order)}return F.length?(D({docs:F,tickets:V,buildOrder:te},"Refold ready - review the proposed changes (nothing applied yet)"),{ok:!0}):(D({error:"the refold answer held no usable document block - try again"},"The refold failed - nothing was changed"),{ok:!1,error:"no usable document block in the refold answer"})}let p=[];if(t.repoAvailable){s({stageNumber:1,status:"in_progress",note:e.newBuild?"Reading the documents provided - this is the long part":"Reading the codebase - this is the long part"});let A=await u(eC(e.currentUnderstanding),20);!A.ok||!A.resultText.trim()?(s({stageNumber:1,status:"failed",note:A.error??"the study pass produced nothing"}),p.push("the code study failed - its findings are not in this plan")):s({stageNumber:1,status:"done",note:(e.newBuild?"Documents studied":"Codebase studied")+Hi(e.currentUnderstanding,A.resultText),artifact:A.resultText.trim().slice(0,1e5)})}else s({stageNumber:1,status:"skipped",note:e.newBuild?"no material yet - upload the proposal/documents under Add material and re-run the study":"no code yet - map the legacy checkout on the runner (allwright repo add) and re-run the study to fold it in"}),p.push(e.newBuild?"no DOCUMENTS were provided - nothing here is based on reading them":"the CODE was not available - nothing here is based on reading it");if(e.dbDumpPath.trim()){s({stageNumber:2,status:"in_progress",note:`Profiling the dump at ${e.dbDumpPath}`});let A=uk(e.dbDumpPath.trim());s({stageNumber:2,status:A.ok?"done":"failed",note:A.ok?`${A.tables} table(s) profiled`:"the dump could not be profiled",artifact:A.markdown})}else e.newBuild||(s({stageNumber:2,status:"skipped",note:"no DB dump given - add one and re-run the study to profile the data"}),p.push("the DATABASE was not profiled - data shapes in this plan are inferred, not read"));let f=!1;if(e.legacyJiraKey.trim()&&t.jira){let A=e.legacyJiraKey.trim().toUpperCase(),D=Math.min(2e3,Math.max(50,e.maxJiraIssues||lk));s({stageNumber:3,status:"in_progress",note:`Reading ${A} tickets - 0/?`,progressDone:0});try{let C=(await t.jira.searchHistory(`project = ${A} ORDER BY created DESC`,{max:D,pageSize:Q$,onPage:$=>s({stageNumber:3,status:"in_progress",note:`Reading ${A} tickets - ${$} read (max ${D})`,progressDone:$,progressTotal:D})})).map($=>`${$.key} [${$.status}] ${$.summary}`);if(C.length){s({stageNumber:3,status:"in_progress",note:`Distilling ${C.length} tickets into the requirements ledger\u2026`,progressDone:C.length,progressTotal:C.length});let $=await u(tC(C.join(`
1334
+ `).slice(0,6e4),tables:c.length}}catch(n){return{ok:!1,markdown:`Could not read the dump at \`${t}\`: ${n instanceof Error?n.message:n}`,tables:0}}}function Hi(t,e){let n=t.trim().length,r=e.trim().length;return n<2e3||r>=n*.9?"":` WARNING: it came back ${Math.round(100-r/n*100)}% smaller than the current version - check the diff for lost detail before approving.`}function hk(t,e){return t==="all"?!0:t.startsWith("except:")?e!==t.slice(7):t===e}function Ir(t,e){let r=new RegExp("```"+e+"\\n([\\s\\S]*?)```","").exec(t);return r?{block:r[1].trim(),rest:t.replace(r[0],"").trim()}:{block:"",rest:t}}function oC(t,e,n,r){t.send({type:"rebirth.study.update",rebirthId:e,stageNumber:1,status:"in_progress",note:"",progressDone:0,progressTotal:0,artifact:"",items:[],buildOrder:[],brief:"",runFinished:{kind:n,ok:r.ok,error:(r.error??"").slice(0,2e3)},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}})}async function aC(t){let{msg:e,transport:n}=t;if(ll.has(e.rebirthId))return{ok:!1,error:"a study is already running for this rebirth - it reports as it goes"};ll.add(e.rebirthId);let r={inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0},s=i=>{let a=r;r={inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0},n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:i.stageNumber,status:i.status,note:i.note??"",progressDone:i.progressDone??0,progressTotal:i.progressTotal??0,artifact:i.artifact??"",items:i.items??[],buildOrder:i.buildOrder??[],brief:i.brief??"",...i.proposal?{proposal:i.proposal}:{},usageDelta:a})};try{let i=Ce(t.cfg,t.project,"assist");if("error"in i)return{ok:!1,error:i.error};let a=(0,dl.randomUUID)(),c=!1,l=e.refineMessage.trim()?"rebirth_refold":"rebirth_study",u=async(A,D,K=60)=>{let C=await i.adapter.run({repoPath:t.repoPath,prompt:A,timeoutSeconds:D*60,bin:i.bin,mode:"read_only",maxTurns:K,sessionId:a,resume:c,onLog:()=>{}});return c=!0,Se({surface:l,projectId:t.project.id,agentId:i.adapter.id,refKind:"rebirth",refId:e.rebirthId,...ve(C)}),r={inputTokens:r.inputTokens+(C.inputTokens??0),outputTokens:r.outputTokens+(C.outputTokens??0),cacheReadTokens:r.cacheReadTokens+(C.cacheReadTokens??0),costUsd:r.costUsd+(C.costUsd??0)},C};if(e.refineMessage.trim()){let A=e.refineScope,D=(L,d)=>s({stageNumber:4,status:"in_progress",note:d,proposal:{message:e.refineMessage,scope:A,docs:L.docs??[],tickets:L.tickets??[],buildOrder:L.buildOrder??[],working:L.working??!1,error:L.error??""}});if(!e.currentDocsIncluded){let L="refine refused: this control plane does not send the current documents with a correction, so the refine would rewrite the plan from scratch and lose everything the correction does not mention. Update the control plane, then refine again.";return s({stageNumber:4,status:"failed",note:L}),{ok:!1,error:L}}D({working:!0},"Folding your correction into the plan - the result comes back as proposed changes for your review\u2026"),c=!1;let K=await u(iC(e.refineMessage,{brief:e.currentBrief,understanding:e.currentUnderstanding,requirements:e.currentRequirements,spec:e.currentSpec},A),60,150);if(!K.ok||!K.resultText.trim())return D({error:K.error??"the refine pass produced nothing"},"The refold failed - nothing was changed"),{ok:!1,error:K.error??"the refine pass produced nothing"};let C=Ir(K.resultText,"brief"),$=Ir(C.rest,"understanding"),v=Ir($.rest,"requirements"),N=L=>hk(A,L),B=[],V=[],te=[];if(N("brief")&&C.block&&B.push({doc:"brief",proposed:C.block.slice(0,1e5)}),N("understanding")&&$.block&&B.push({doc:"understanding",proposed:$.block.slice(0,2e5)}),N("requirements")&&v.block&&B.push({doc:"requirements",proposed:v.block.slice(0,2e5)}),N("spec")&&v.rest.trim()){let L=Xh(v.rest);L.spec.trim()&&(B.push({doc:"spec",proposed:L.spec}),V=L.tickets,te=L.order)}return B.length?(D({docs:B,tickets:V,buildOrder:te},"Refold ready - review the proposed changes (nothing applied yet)"),{ok:!0}):(D({error:"the refold answer held no usable document block - try again"},"The refold failed - nothing was changed"),{ok:!1,error:"no usable document block in the refold answer"})}let p=[];if(t.repoAvailable){s({stageNumber:1,status:"in_progress",note:e.newBuild?"Reading the documents provided - this is the long part":"Reading the codebase - this is the long part"});let A=await u(eC(e.currentUnderstanding),20);!A.ok||!A.resultText.trim()?(s({stageNumber:1,status:"failed",note:A.error??"the study pass produced nothing"}),p.push("the code study failed - its findings are not in this plan")):s({stageNumber:1,status:"done",note:(e.newBuild?"Documents studied":"Codebase studied")+Hi(e.currentUnderstanding,A.resultText),artifact:A.resultText.trim().slice(0,1e5)})}else s({stageNumber:1,status:"skipped",note:e.newBuild?"no material yet - upload the proposal/documents under Add material and re-run the study":"no code yet - map the legacy checkout on the runner (allwright repo add) and re-run the study to fold it in"}),p.push(e.newBuild?"no DOCUMENTS were provided - nothing here is based on reading them":"the CODE was not available - nothing here is based on reading it");if(e.dbDumpPath.trim()){s({stageNumber:2,status:"in_progress",note:`Profiling the dump at ${e.dbDumpPath}`});let A=uk(e.dbDumpPath.trim());s({stageNumber:2,status:A.ok?"done":"failed",note:A.ok?`${A.tables} table(s) profiled`:"the dump could not be profiled",artifact:A.markdown})}else e.newBuild||(s({stageNumber:2,status:"skipped",note:"no DB dump given - add one and re-run the study to profile the data"}),p.push("the DATABASE was not profiled - data shapes in this plan are inferred, not read"));let f=!1;if(e.legacyJiraKey.trim()&&t.jira){let A=e.legacyJiraKey.trim().toUpperCase(),D=Math.min(2e3,Math.max(50,e.maxJiraIssues||lk));s({stageNumber:3,status:"in_progress",note:`Reading ${A} tickets - 0/?`,progressDone:0});try{let C=(await t.jira.searchHistory(`project = ${A} ORDER BY created DESC`,{max:D,pageSize:Q$,onPage:$=>s({stageNumber:3,status:"in_progress",note:`Reading ${A} tickets - ${$} read (max ${D})`,progressDone:$,progressTotal:D})})).map($=>`${$.key} [${$.status}] ${$.summary}`);if(C.length){s({stageNumber:3,status:"in_progress",note:`Distilling ${C.length} tickets into the requirements ledger\u2026`,progressDone:C.length,progressTotal:C.length});let $=await u(tC(C.join(`
1335
1335
  `).slice(0,12e4),e.currentRequirements),12);$.ok&&$.resultText.trim()?(s({stageNumber:3,status:"done",note:`${C.length} tickets distilled`+Hi(e.currentRequirements,$.resultText),artifact:$.resultText.trim().slice(0,1e5),progressDone:C.length,progressTotal:C.length}),f=!0):s({stageNumber:3,status:"failed",note:$.error??"the distill pass produced nothing"})}else s({stageNumber:3,status:"skipped",note:`${A} returned no readable tickets - either the board is empty, or this server's Jira account cannot see it (wrong site or not invited). Check the credential, then run the study again`}),p.push(`the JIRA HISTORY came back EMPTY for ${A} - requirements are not based on the old board`)}catch(K){s({stageNumber:3,status:"failed",note:`Jira read failed: ${K instanceof Error?K.message:K}`})}}else if(e.newBuild){s({stageNumber:3,status:"in_progress",note:"Distilling requirements from the documents\u2026"});let A=await u(nC(e.currentRequirements),12);A.ok&&A.resultText.trim()?(s({stageNumber:3,status:"done",note:"Requirements distilled from the documents"+Hi(e.currentRequirements,A.resultText),artifact:A.resultText.trim().slice(0,1e5)}),f=!0):(s({stageNumber:3,status:"failed",note:A.error??"the distill pass produced nothing"}),p.push("the requirements pass failed - the SPEC leans on the documents directly"))}else s({stageNumber:3,status:"skipped",note:e.legacyJiraKey?"no Jira credential on this runner":"no legacy Jira key given"}),p.push("the JIRA HISTORY was not read - requirements come only from what else was provided");s({stageNumber:4,status:"in_progress",note:"Writing the SPEC from everything studied\u2026"});let m=await u(rC(e.extraContext.trim(),p,e.currentSpec,e.gdprRequired,e.newBuild),15);if(!m.ok||!m.resultText.trim())return s({stageNumber:4,status:"failed",note:m.error??"the SPEC pass produced nothing"}),{ok:!1,error:m.error??"SPEC generation failed"};let{spec:w,tickets:S,order:T}=Xh(m.resultText);s({stageNumber:4,status:"done",note:"SPEC drafted - review it, refine it in your words if something is missing, then approve"+Hi(e.currentSpec,w),artifact:w}),s({stageNumber:1,status:"done",note:"Writing the project understanding (plain language)\u2026"});let x=await u(sC(e.currentBrief),8);return x.ok&&x.resultText.trim()&&s({stageNumber:1,status:"done",note:"Project understanding ready - read and verify it"+Hi(e.currentBrief,x.resultText),brief:x.resultText.trim().slice(0,1e5)}),S.length&&s({stageNumber:6,status:"in_progress",note:`${S.length} tickets proposed by the SPEC - created on Jira after you approve`,items:S,buildOrder:T}),b.info(`rebirth study done for ${e.rebirthId}: code \u2713, data ${e.dbDumpPath?"\u2713":"skipped"}, requirements ${f?"\u2713":"skipped/failed"}, SPEC \u2713 (${S.length} tickets proposed)`),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{ll.delete(e.rebirthId)}}function Xh(t){let e=/```json\s*\n([\s\S]*?)```/.exec(t),n=[],r=[];if(e)try{let s=JSON.parse(e[1]);n=(s.tickets??[]).filter(i=>typeof i.title=="string"&&i.title.trim()).slice(0,60).map(i=>({title:i.title.trim().slice(0,300),detail:typeof i.detail=="string"?i.detail.trim().slice(0,4e3):"",area:typeof i.area=="string"&&cC.has(i.area.trim().toLowerCase())?i.area.trim().toLowerCase():"",screens:Array.isArray(i.screens)?i.screens.filter(a=>typeof a=="string"&&a.trim().length>0).slice(0,12).map(a=>a.trim().slice(0,80)):[]})),r=(s.order??[]).filter(i=>typeof i.title=="string"&&i.title.trim()&&Array.isArray(i.tickets)).slice(0,16).map(i=>({title:i.title.trim().slice(0,120),mode:i.mode==="separate"?"separate":"chain",tickets:i.tickets.filter(a=>Number.isInteger(a)&&a>=0&&a<n.length).slice(0,60)})).filter(i=>i.tickets.length>0)}catch{}return{spec:t.replace(/```json\s*\n[\s\S]*?```/g,"").trim().slice(0,15e4),tickets:n,order:r}}function ul(t){let e=Ir(t,"direction").block,n=[],r=/```screen:([^\n]+)\n([\s\S]*?)```/g,s;for(;(s=r.exec(t))&&n.length<8;)n.push({name:s[1].trim().slice(0,80),html:s[2].trim().slice(0,2e5)});let i=[];try{let a=JSON.parse(Ir(t,"inventory").block||"[]");Array.isArray(a)&&(i=a.filter(c=>!!c&&typeof c=="object").map(c=>({name:String(c.name??"").slice(0,80),note:String(c.note??"").slice(0,200)})).filter(c=>c.name).slice(0,40))}catch{}return{direction:e,screens:n,inventory:i}}async function pC(t){let{msg:e,transport:n}=t,r=s=>n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:4,status:"in_progress",note:s,progressDone:0,progressTotal:0,artifact:"",items:[],buildOrder:[],brief:"",design:{direction:"",screens:[],inventory:[],specs:[],partial:!0},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}});try{let s=Ce(t.cfg,t.project,"assist");if("error"in s)return{ok:!1,error:s.error};let i=!!e.screenName;r(e.stackOnly?e.refineMessage?"Revising the tech stack recommendation with your reasoning\u2026":"Working out the tech stack recommendation from the SPEC and the legacy code\u2026":e.specOnly?`Reading the legacy code for "${e.screenName}" - fields, filters, conditions\u2026`:i?`Designing the "${e.screenName}" screen\u2026`:e.refineMessage?"Revising the UI design with your correction\u2026":"Designing the UI - direction first, then the screens\u2026");let a=await s.adapter.run({repoPath:t.repoPath,prompt:e.stackOnly?hC(e.spec,e.brief,e.refineMessage,e.currentStack,e.newBuild):e.specOnly?dC(e.screenName,"",e.screenBrief,e.screenSpec):i?ak(e.screenName,e.screenBrief,e.currentDirection,e.currentScreenHtml,e.screenSpec,e.referenceScreenHtml):lC(e.spec,e.brief,e.refineMessage,e.currentDirection),timeoutSeconds:1200,bin:s.bin,mode:"read_only",maxTurns:60,sessionId:(0,dl.randomUUID)(),onLog:()=>{}});if(Se({surface:e.stackOnly?"rebirth_techstack":"rebirth_design",projectId:t.project.id,agentId:s.adapter.id,refKind:"rebirth",refId:e.rebirthId,refLabel:e.specOnly||i?e.screenName:"",...ve(a)}),!a.ok||!a.resultText.trim())return r(`UI design failed: ${a.error??"no answer"}`),{ok:!1,error:a.error??"the design pass produced nothing"};if(e.stackOnly){let D=Ir(a.resultText,"techstack").block.slice(0,4e4);return D?(n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:6,status:"in_progress",note:"Tech stack recommendation ready - review it, reason with it, then confirm to unlock Build.",progressDone:0,progressTotal:0,artifact:"",items:[],buildOrder:[],brief:"",techStack:D,usageDelta:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cacheReadTokens:a.cacheReadTokens??0,costUsd:a.costUsd??0}}),{ok:!0}):(r("The tech stack recommendation did not come back - try again"),{ok:!1,error:"no techstack block in the answer"})}if(e.specOnly){let D=Ir(a.resultText,"screenspec").block.slice(0,3e4);return D?(n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:4,status:"in_progress",note:`The "${e.screenName}" details are ready.`,progressDone:0,progressTotal:0,artifact:"",items:[],buildOrder:[],brief:"",design:{direction:"",screens:[],inventory:[],specs:[{name:e.screenName,doc:D}],partial:!0},usageDelta:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cacheReadTokens:a.cacheReadTokens??0,costUsd:a.costUsd??0}}),{ok:!0}):(r(`The "${e.screenName}" details did not come back - try again`),{ok:!1,error:"no screenspec block in the answer"})}let c=D=>({inputTokens:D.inputTokens??0,outputTokens:D.outputTokens??0,cacheReadTokens:D.cacheReadTokens??0,costUsd:D.costUsd??0}),l=(D,K,C)=>n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:4,status:"in_progress",note:K,progressDone:0,progressTotal:0,artifact:"",items:[],buildOrder:[],brief:"",design:D,usageDelta:C});if(i){let K=ul(a.resultText).screens.filter(C=>C.name===e.screenName).slice(0,1);return K.length?(l({direction:"",screens:K,inventory:[],specs:[],partial:!0},`The "${e.screenName}" screen is ready.`,c(a)),{ok:!0}):(r(`The "${e.screenName}" screen did not come back named right - try again`),{ok:!1,error:"the screen block was missing from the answer"})}let u=ul(a.resultText);if(!u.inventory.length)return r("The design plan came back without a screen inventory - run it again"),{ok:!1,error:"no inventory in the plan answer"};l({direction:u.direction,screens:[],inventory:u.inventory,specs:[],partial:!0},`Screen list ready - ${u.inventory.length} screen(s) mapped. Drawing the missing ones\u2026`,c(a));let p=u.direction||e.currentDirection,f=new Set(e.existingScreenNames),m=u.inventory.filter(D=>!f.has(D.name)),S=m.slice(0,6),T=0,x=e.referenceScreenHtml;for(let[D,K]of S.entries()){r(`Drawing "${K.name}" (${D+1}/${S.length})\u2026`);let C=await s.adapter.run({repoPath:t.repoPath,prompt:ak(K.name,K.note,p,"","",x),timeoutSeconds:900,bin:s.bin,mode:"read_only",maxTurns:40,sessionId:(0,dl.randomUUID)(),onLog:()=>{}});Se({surface:"rebirth_design",projectId:t.project.id,agentId:s.adapter.id,refKind:"rebirth",refId:e.rebirthId,refLabel:K.name,...ve(C)});let $=C.ok?ul(C.resultText).screens.find(v=>v.name===K.name):void 0;$?(T+=1,x||(x=$.html),l({direction:"",screens:[$],inventory:[],specs:[],partial:!0},`"${K.name}" is ready (${T}/${S.length}). ${D+1<S.length?"Drawing the next\u2026":""}`,c(C))):l({direction:"",screens:[],inventory:[],specs:[],partial:!0},`"${K.name}" did not come back usable - skipped (ask for it again per-screen).`,c(C))}let A=m.length-S.length;return r(`UI design ready - ${T} screen(s) drawn this run`+(A>0?`, ${A} still to design (open each and click Design, or run this again)`:"")+". Open the studio to review."),{ok:!0}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}var Ws,ck,dl,ll,lk,Q$,ea,eC,Qh,tC,nC,rC,hl,sC,ok,iC,cC,lC,uC,dC,hC,ak,tp=J(()=>{"use strict";Ws=E(require("node:fs"),1),ck=E(require("node:zlib"),1),dl=require("node:crypto");Pt();ot();Vt();ik();ll=new Set;lk=500,Q$=50;ea=(t,e)=>e.trim()?`A reviewed ${t} already exists - it is below. UPDATE IT IN PLACE rather than writing a new one: keep every still-true sentence VERBATIM (same words, same order, same headings - the reviewer reads a green/red diff of your answer against this text, and every needless rewording costs them a re-review of something that never changed), fold in only what this fresh read adds or corrects, and never drop or compress detail the document already records. Any word limit below applies to a FRESH document - an updated one may exceed it, and trimming existing detail to fit a limit is the failure, not the fix.
1336
1336
 
1337
1337
  --- CURRENT ${t.toUpperCase()} ---
@@ -1525,8 +1525,8 @@ ${s.slice(0,2e4)}
1525
1525
  "${e}"
1526
1526
  Their words win.
1527
1527
 
1528
- `:"")+(r?"Its CURRENT mockup is below - EDIT it to address what was asked, keep everything else as it is (a tweak is a tweak, not a reinvention):\n\n```html\n"+r.slice(0,15e4)+"\n```\n\n":"")+"Answer with exactly one fenced block:\n```screen:"+t+"\n<!doctype html>\u2026\n```\n"+uC});var na={};Fe(na,{appendRebirthUploadChunk:()=>wC,beginRebirthUpload:()=>yC,rebirthUploadsDir:()=>ta,uploadedCodeDir:()=>fC,uploadedDumpPath:()=>mC});function ta(t){return Xe.default.join(X(),"rebirth-uploads",t.replace(/[^\w-]/g,""))}function fC(t){let e=Xe.default.join(ta(t),"code");try{return Ee.default.readdirSync(e).length>0?e:null}catch{return null}}function mC(t){let e=Xe.default.join(ta(t),"db");try{let n=Ee.default.readdirSync(e).filter(r=>!/\.(rar|zip|7z|tar|tgz|bz2|xz)$/i.test(r)||Ee.default.statSync(Xe.default.join(e,r)).isDirectory()).map(r=>({f:r,at:Ee.default.statSync(Xe.default.join(e,r)).mtimeMs})).sort((r,s)=>s.at-r.at);return n.length?Xe.default.join(e,n[0].f):null}catch{return null}}function gC(){let t=Date.now();for(let[e,n]of Gs)if(t-n.startedAt>36e5){try{Ee.default.closeSync(n.fd),Ee.default.rmSync(n.filePath,{force:!0})}catch{}Gs.delete(e)}}function yC(t){gC();let e=Xe.default.basename(t.name).replace(/[^\w.-]/g,"_").slice(0,120);if(!e)return{ok:!1,error:"the file needs a usable name"};if((t.kind==="frontend"||t.kind==="backend")&&!/\.(zip|tar\.gz|tgz)$/i.test(e))return{ok:!1,error:"code uploads must be a .zip or .tar.gz archive"};if(t.kind==="dump"&&/\.rar$/i.test(e))return{ok:!1,error:"RAR is not a database dump - extract the .sql (or .sql.gz) from it and upload that"};let n=Xe.default.join(ta(t.rebirthId),"incoming");Ee.default.mkdirSync(n,{recursive:!0});let r=(0,fk.randomUUID)(),s=Xe.default.join(n,`${r}-${e}`),i=Ee.default.openSync(s,"w");return Gs.set(r,{rebirthId:t.rebirthId,kind:t.kind,name:e,filePath:s,fd:i,nextSeq:0,startedAt:Date.now()}),{ok:!0,uploadId:r}}async function pk(t){let e=/\.zip$/i.test(t),{stdout:n}=e?await Vn("unzip",["-Z1",t],{maxBuffer:2e7}):await Vn("tar",["-tzf",t],{maxBuffer:2e7});for(let r of n.split(`
1529
- `)){let s=r.trim();if(s&&(s.startsWith("/")||s.split("/").includes("..")))throw new Error(`archive entry "${s.slice(0,80)}" escapes the extraction directory - refused`)}}async function bC(t){Ee.default.closeSync(t.fd);let e=ta(t.rebirthId);if(t.kind==="dump"){let r=Xe.default.join(e,"db");if(Ee.default.mkdirSync(r,{recursive:!0}),/\.(zip|tar\.gz|tgz)$/i.test(t.name)){await pk(t.filePath);let i=Xe.default.join(r,t.name.replace(/\.(zip|tar\.gz|tgz)$/i,""));return Ee.default.rmSync(i,{recursive:!0,force:!0}),Ee.default.mkdirSync(i,{recursive:!0}),/\.zip$/i.test(t.name)?await Vn("unzip",["-q",t.filePath,"-d",i],{maxBuffer:1e7,timeout:3e5}):await Vn("tar",["-xzf",t.filePath,"-C",i],{maxBuffer:1e7,timeout:3e5}),Ee.default.rmSync(t.filePath,{force:!0}),{storedPath:i,note:"dump archive extracted - the next study run profiles it (MongoDB dumps supported)"}}let s=Xe.default.join(r,t.name);return Ee.default.renameSync(t.filePath,s),{storedPath:s,note:"dump stored - the next study run profiles it"}}if(t.kind==="docs"&&!/\.(zip|tar\.gz|tgz)$/i.test(t.name)){let r=Xe.default.join(e,"code","docs");Ee.default.mkdirSync(r,{recursive:!0});let s=Xe.default.join(r,t.name);return Ee.default.renameSync(t.filePath,s),{storedPath:s,note:"document stored - the next study run reads it"}}await pk(t.filePath);let n=Xe.default.join(e,"code",t.kind==="docs"?"docs":t.kind);if(Ee.default.rmSync(n,{recursive:!0,force:!0}),Ee.default.mkdirSync(n,{recursive:!0}),/\.zip$/i.test(t.filePath)?await Vn("unzip",["-q",t.filePath,"-d",n],{maxBuffer:1e7,timeout:3e5}):await Vn("tar",["-xzf",t.filePath,"-C",n],{maxBuffer:1e7,timeout:3e5}),Ee.default.rmSync(t.filePath,{force:!0}),!Ee.default.existsSync(Xe.default.join(n,".git")))try{await Vn("git",["init","-q"],{cwd:n}),await Vn("git",["add","-A"],{cwd:n,maxBuffer:1e7}),await Vn("git",["-c","user.email=rebirth@allwright","-c","user.name=Rebirth upload","commit","-q","-m","legacy snapshot (uploaded)"],{cwd:n,maxBuffer:1e7})}catch(r){b.warn(`rebirth upload: git init of ${n} failed: ${r instanceof Error?r.message:r}`)}return{storedPath:n,note:`${t.kind} code extracted - the next study run reads it`}}async function wC(t){let e=Gs.get(t.uploadId);if(!e)return{ok:!1,error:"unknown or expired upload - start it again"};if(t.seq!==e.nextSeq){Gs.delete(t.uploadId);try{Ee.default.closeSync(e.fd),Ee.default.rmSync(e.filePath,{force:!0})}catch{}return{ok:!1,error:`chunk ${t.seq} arrived where ${e.nextSeq} was expected - upload aborted, start again`}}try{return Ee.default.writeSync(e.fd,Buffer.from(t.dataBase64,"base64")),e.nextSeq+=1,t.last?(Gs.delete(t.uploadId),{ok:!0,...await bC(e)}):{ok:!0,storedPath:"",note:""}}catch(n){Gs.delete(t.uploadId);try{Ee.default.closeSync(e.fd)}catch{}Ee.default.rmSync(e.filePath,{force:!0});let r=n instanceof Error?n.message:String(n);return{ok:!1,error:/unzip|ENOENT/.test(r)&&r.includes("unzip")?"this server has no `unzip` - install it (apt install unzip) and upload again":r}}}var Ee,Xe,fk,mk,gk,Vn,Gs,ra=J(()=>{"use strict";Ee=E(require("node:fs"),1),Xe=E(require("node:path"),1),fk=require("node:crypto"),mk=require("node:child_process"),gk=require("node:util");Te();ot();Vn=(0,gk.promisify)(mk.execFile),Gs=new Map});var np={};Fe(np,{databasesFromEnvFiles:()=>vk,executeDecommission:()=>RC,guardPath:()=>wk,planDecommission:()=>kk});async function vn(t,e,n=kC){try{let{stdout:r}=await vC(t,e,{timeout:n,maxBuffer:4e6});return r}catch{return""}}function wk(t,e){let n=St.default.resolve(e);if(!St.default.isAbsolute(e)||n==="/"||n.split("/").length<3)return{ok:!1,error:`refusing "${e}" - give the absolute path of one checkout`};for(let[i,a]of Object.entries(t.repos)){let c=St.default.resolve(a.path);if(n===c||n.startsWith(c+St.default.sep)||c.startsWith(n+St.default.sep))return{ok:!1,error:`${n} is (or contains) the mapped checkout of "${i}" - remove or move that project first`}}let r;try{r=Ft.default.statSync(n)}catch{return{ok:!1,error:`${n} does not exist on this machine`}}if(!r.isDirectory())return{ok:!1,error:`${n} is not a directory`};if(!Ft.default.existsSync(St.default.join(n,".git")))return{ok:!1,error:`${n} is not a git checkout - this flow removes checkouts only`};let s=St.default.resolve(process.cwd());return s===n||s.startsWith(n+St.default.sep)?{ok:!1,error:`${n} contains this runner itself - not removable from here`}:{ok:!0,dir:n}}async function SC(t){let e=[];for(let n of["/etc/systemd/system","/usr/lib/systemd/system","/lib/systemd/system"]){let r=[];try{r=Ft.default.readdirSync(n).filter(s=>s.endsWith(".service"))}catch{continue}for(let s of r.slice(0,400)){try{if(Ft.default.readFileSync(St.default.join(n,s),"utf8").includes(t)){let a=(await vn("systemctl",["is-active",s])).trim()||"unknown";e.push({name:s.replace(/\.service$/,""),detail:`${n}/${s} \xB7 ${a}`})}}catch{}if(e.length>=30)return e}}return e}async function _C(t){let e=new Map;for(let i of vr(await vn("ss",["-tlnpH"])))i.pid>0&&e.set(i.pid,[...e.get(i.pid)??[],i.port]);let n=[],r=[];try{r=Ft.default.readdirSync("/proc").filter(i=>/^\d+$/.test(i))}catch{return n}let s=process.pid;for(let i of r){let a=Number(i);if(a!==s)try{let c=Ft.default.readlinkSync(`/proc/${a}/cwd`),l=Ft.default.readFileSync(`/proc/${a}/cmdline`,"utf8").replaceAll("\0"," ").trim();if((c===t||c.startsWith(t+St.default.sep)||l.includes(t+St.default.sep)||l.endsWith(t))&&(n.push({pid:a,command:l.slice(0,160),ports:e.get(a)??[]}),n.length>=50))break}catch{}}return n}async function xC(t){let e=(await vn("docker",["ps","-a","--format","{{.Names}}"])).split(`
1528
+ `:"")+(r?"Its CURRENT mockup is below - EDIT it to address what was asked, keep everything else as it is (a tweak is a tweak, not a reinvention):\n\n```html\n"+r.slice(0,15e4)+"\n```\n\n":"")+"Answer with exactly one fenced block:\n```screen:"+t+"\n<!doctype html>\u2026\n```\n"+uC});var na={};Fe(na,{appendRebirthUploadChunk:()=>wC,beginRebirthUpload:()=>yC,rebirthUploadsDir:()=>ta,uploadedCodeDir:()=>fC,uploadedDumpPath:()=>mC});function ta(t){return Qe.default.join(X(),"rebirth-uploads",t.replace(/[^\w-]/g,""))}function fC(t){let e=Qe.default.join(ta(t),"code");try{return Ee.default.readdirSync(e).length>0?e:null}catch{return null}}function mC(t){let e=Qe.default.join(ta(t),"db");try{let n=Ee.default.readdirSync(e).filter(r=>!/\.(rar|zip|7z|tar|tgz|bz2|xz)$/i.test(r)||Ee.default.statSync(Qe.default.join(e,r)).isDirectory()).map(r=>({f:r,at:Ee.default.statSync(Qe.default.join(e,r)).mtimeMs})).sort((r,s)=>s.at-r.at);return n.length?Qe.default.join(e,n[0].f):null}catch{return null}}function gC(){let t=Date.now();for(let[e,n]of Gs)if(t-n.startedAt>36e5){try{Ee.default.closeSync(n.fd),Ee.default.rmSync(n.filePath,{force:!0})}catch{}Gs.delete(e)}}function yC(t){gC();let e=Qe.default.basename(t.name).replace(/[^\w.-]/g,"_").slice(0,120);if(!e)return{ok:!1,error:"the file needs a usable name"};if((t.kind==="frontend"||t.kind==="backend")&&!/\.(zip|tar\.gz|tgz)$/i.test(e))return{ok:!1,error:"code uploads must be a .zip or .tar.gz archive"};if(t.kind==="dump"&&/\.rar$/i.test(e))return{ok:!1,error:"RAR is not a database dump - extract the .sql (or .sql.gz) from it and upload that"};let n=Qe.default.join(ta(t.rebirthId),"incoming");Ee.default.mkdirSync(n,{recursive:!0});let r=(0,fk.randomUUID)(),s=Qe.default.join(n,`${r}-${e}`),i=Ee.default.openSync(s,"w");return Gs.set(r,{rebirthId:t.rebirthId,kind:t.kind,name:e,filePath:s,fd:i,nextSeq:0,startedAt:Date.now()}),{ok:!0,uploadId:r}}async function pk(t){let e=/\.zip$/i.test(t),{stdout:n}=e?await Vn("unzip",["-Z1",t],{maxBuffer:2e7}):await Vn("tar",["-tzf",t],{maxBuffer:2e7});for(let r of n.split(`
1529
+ `)){let s=r.trim();if(s&&(s.startsWith("/")||s.split("/").includes("..")))throw new Error(`archive entry "${s.slice(0,80)}" escapes the extraction directory - refused`)}}async function bC(t){Ee.default.closeSync(t.fd);let e=ta(t.rebirthId);if(t.kind==="dump"){let r=Qe.default.join(e,"db");if(Ee.default.mkdirSync(r,{recursive:!0}),/\.(zip|tar\.gz|tgz)$/i.test(t.name)){await pk(t.filePath);let i=Qe.default.join(r,t.name.replace(/\.(zip|tar\.gz|tgz)$/i,""));return Ee.default.rmSync(i,{recursive:!0,force:!0}),Ee.default.mkdirSync(i,{recursive:!0}),/\.zip$/i.test(t.name)?await Vn("unzip",["-q",t.filePath,"-d",i],{maxBuffer:1e7,timeout:3e5}):await Vn("tar",["-xzf",t.filePath,"-C",i],{maxBuffer:1e7,timeout:3e5}),Ee.default.rmSync(t.filePath,{force:!0}),{storedPath:i,note:"dump archive extracted - the next study run profiles it (MongoDB dumps supported)"}}let s=Qe.default.join(r,t.name);return Ee.default.renameSync(t.filePath,s),{storedPath:s,note:"dump stored - the next study run profiles it"}}if(t.kind==="docs"&&!/\.(zip|tar\.gz|tgz)$/i.test(t.name)){let r=Qe.default.join(e,"code","docs");Ee.default.mkdirSync(r,{recursive:!0});let s=Qe.default.join(r,t.name);return Ee.default.renameSync(t.filePath,s),{storedPath:s,note:"document stored - the next study run reads it"}}await pk(t.filePath);let n=Qe.default.join(e,"code",t.kind==="docs"?"docs":t.kind);if(Ee.default.rmSync(n,{recursive:!0,force:!0}),Ee.default.mkdirSync(n,{recursive:!0}),/\.zip$/i.test(t.filePath)?await Vn("unzip",["-q",t.filePath,"-d",n],{maxBuffer:1e7,timeout:3e5}):await Vn("tar",["-xzf",t.filePath,"-C",n],{maxBuffer:1e7,timeout:3e5}),Ee.default.rmSync(t.filePath,{force:!0}),!Ee.default.existsSync(Qe.default.join(n,".git")))try{await Vn("git",["init","-q"],{cwd:n}),await Vn("git",["add","-A"],{cwd:n,maxBuffer:1e7}),await Vn("git",["-c","user.email=rebirth@allwright","-c","user.name=Rebirth upload","commit","-q","-m","legacy snapshot (uploaded)"],{cwd:n,maxBuffer:1e7})}catch(r){b.warn(`rebirth upload: git init of ${n} failed: ${r instanceof Error?r.message:r}`)}return{storedPath:n,note:`${t.kind} code extracted - the next study run reads it`}}async function wC(t){let e=Gs.get(t.uploadId);if(!e)return{ok:!1,error:"unknown or expired upload - start it again"};if(t.seq!==e.nextSeq){Gs.delete(t.uploadId);try{Ee.default.closeSync(e.fd),Ee.default.rmSync(e.filePath,{force:!0})}catch{}return{ok:!1,error:`chunk ${t.seq} arrived where ${e.nextSeq} was expected - upload aborted, start again`}}try{return Ee.default.writeSync(e.fd,Buffer.from(t.dataBase64,"base64")),e.nextSeq+=1,t.last?(Gs.delete(t.uploadId),{ok:!0,...await bC(e)}):{ok:!0,storedPath:"",note:""}}catch(n){Gs.delete(t.uploadId);try{Ee.default.closeSync(e.fd)}catch{}Ee.default.rmSync(e.filePath,{force:!0});let r=n instanceof Error?n.message:String(n);return{ok:!1,error:/unzip|ENOENT/.test(r)&&r.includes("unzip")?"this server has no `unzip` - install it (apt install unzip) and upload again":r}}}var Ee,Qe,fk,mk,gk,Vn,Gs,ra=J(()=>{"use strict";Ee=E(require("node:fs"),1),Qe=E(require("node:path"),1),fk=require("node:crypto"),mk=require("node:child_process"),gk=require("node:util");Te();ot();Vn=(0,gk.promisify)(mk.execFile),Gs=new Map});var np={};Fe(np,{databasesFromEnvFiles:()=>vk,executeDecommission:()=>RC,guardPath:()=>wk,planDecommission:()=>kk});async function vn(t,e,n=kC){try{let{stdout:r}=await vC(t,e,{timeout:n,maxBuffer:4e6});return r}catch{return""}}function wk(t,e){let n=St.default.resolve(e);if(!St.default.isAbsolute(e)||n==="/"||n.split("/").length<3)return{ok:!1,error:`refusing "${e}" - give the absolute path of one checkout`};for(let[i,a]of Object.entries(t.repos)){let c=St.default.resolve(a.path);if(n===c||n.startsWith(c+St.default.sep)||c.startsWith(n+St.default.sep))return{ok:!1,error:`${n} is (or contains) the mapped checkout of "${i}" - remove or move that project first`}}let r;try{r=Ft.default.statSync(n)}catch{return{ok:!1,error:`${n} does not exist on this machine`}}if(!r.isDirectory())return{ok:!1,error:`${n} is not a directory`};if(!Ft.default.existsSync(St.default.join(n,".git")))return{ok:!1,error:`${n} is not a git checkout - this flow removes checkouts only`};let s=St.default.resolve(process.cwd());return s===n||s.startsWith(n+St.default.sep)?{ok:!1,error:`${n} contains this runner itself - not removable from here`}:{ok:!0,dir:n}}async function SC(t){let e=[];for(let n of["/etc/systemd/system","/usr/lib/systemd/system","/lib/systemd/system"]){let r=[];try{r=Ft.default.readdirSync(n).filter(s=>s.endsWith(".service"))}catch{continue}for(let s of r.slice(0,400)){try{if(Ft.default.readFileSync(St.default.join(n,s),"utf8").includes(t)){let a=(await vn("systemctl",["is-active",s])).trim()||"unknown";e.push({name:s.replace(/\.service$/,""),detail:`${n}/${s} \xB7 ${a}`})}}catch{}if(e.length>=30)return e}}return e}async function _C(t){let e=new Map;for(let i of vr(await vn("ss",["-tlnpH"])))i.pid>0&&e.set(i.pid,[...e.get(i.pid)??[],i.port]);let n=[],r=[];try{r=Ft.default.readdirSync("/proc").filter(i=>/^\d+$/.test(i))}catch{return n}let s=process.pid;for(let i of r){let a=Number(i);if(a!==s)try{let c=Ft.default.readlinkSync(`/proc/${a}/cwd`),l=Ft.default.readFileSync(`/proc/${a}/cmdline`,"utf8").replaceAll("\0"," ").trim();if((c===t||c.startsWith(t+St.default.sep)||l.includes(t+St.default.sep)||l.endsWith(t))&&(n.push({pid:a,command:l.slice(0,160),ports:e.get(a)??[]}),n.length>=50))break}catch{}}return n}async function xC(t){let e=(await vn("docker",["ps","-a","--format","{{.Names}}"])).split(`
1530
1530
  `).filter(Boolean).slice(0,60),n=[];for(let r of e){let s=await vn("docker",["inspect","--format",'{{.Config.Image}} {{range .Mounts}}{{.Source}} {{end}} {{index .Config.Labels "com.docker.compose.project.working_dir"}}',r]),[i="",a="",c=""]=s.trim().split(" ");if((a.includes(t)||c&&c.startsWith(t))&&(n.push({name:r,image:i.slice(0,120)}),n.length>=30))break}return n}function vk(t){let e=[],n=[],r=new Set,s=[];try{s=Ft.default.readdirSync(t).filter(i=>i===".env"||i.startsWith(".env."))}catch{return{databases:e,warnings:n}}for(let i of s.slice(0,10)){let a="";try{a=Ft.default.readFileSync(St.default.join(t,i),"utf8").slice(0,64e3)}catch{continue}for(let c of a.matchAll(/(?:DATABASE_URL|DB_URL)\s*=\s*"?(postgres(?:ql)?|mysql):\/\/([^\s"']+)/gi)){let l=c[1].toLowerCase().startsWith("postgres")?"postgres":"mysql";try{let u=new URL(`${c[1]}://${c[2]}`),p=u.pathname.replace(/^\//,"").split("?")[0];if(!p||r.has(`${l}:${p}`))continue;TC.has(u.hostname)?(r.add(`${l}:${p}`),e.push({name:p,engine:l,source:i})):n.push(`${i} names a REMOTE ${l} database "${p}" on ${u.hostname} - not offered here, clean it up where it lives`)}catch{}}}return{databases:e,warnings:n}}async function kk(t,e){let n={path:"",sizeMb:0,services:[],processes:[],containers:[],databases:[],warnings:[]},r=wk(t,e);if(!r.ok)return{ok:!1,error:r.error,...n};let s=r.dir,[i,a,c,l]=await Promise.all([vn("du",["-sm",s],3e4),SC(s),_C(s),xC(s)]),{databases:u,warnings:p}=vk(s);return{ok:!0,path:s,sizeMb:Number(i.split(" ")[0])||0,services:a,processes:c,containers:l,databases:u,warnings:p}}async function RC(t,e,n){let r=await kk(t,e.path);if(!r.ok){n({label:"Check the path",ok:!1,detail:r.error??"refused"});return}let s=r.path,i=(f,m)=>f.filter(w=>m.includes(w)),a=i(e.services,r.services.map(f=>f.name)),c=e.services.filter(f=>!a.includes(f));for(let f of c)n({label:`Stop service ${f}`,ok:!1,detail:"not in this checkout's plan - refused"});for(let f of a){let m=await vn("sudo",["-n","systemctl","disable","--now",`${f}.service`]).then(async()=>(await vn("systemctl",["is-active",`${f}.service`])).trim());n(m==="inactive"||m==="failed"||m==="unknown"||m===""?{label:`Stop service ${f}`,ok:!0,detail:"stopped and disabled"}:{label:`Stop service ${f}`,ok:!1,detail:`still ${m} - sudo likely refused; run: sudo systemctl disable --now ${f}`})}let l=new Set(r.processes.map(f=>f.pid));for(let f of e.pids){if(!l.has(f)){n({label:`Stop process ${f}`,ok:!1,detail:"not in this checkout's plan - refused"});continue}let m=r.processes.find(w=>w.pid===f)?.ports??[];try{process.kill(f,"SIGTERM"),await new Promise(w=>setTimeout(w,2e3));try{process.kill(f,0),process.kill(f,"SIGKILL")}catch{}n({label:`Stop process ${f}`,ok:!0,detail:m.length?`stopped - port${m.length>1?"s":""} ${m.join(", ")} freed`:"stopped"})}catch(w){n({label:`Stop process ${f}`,ok:!1,detail:w instanceof Error?w.message:String(w)})}}let u=i(e.containers,r.containers.map(f=>f.name));for(let f of e.containers.filter(m=>!u.includes(m)))n({label:`Remove container ${f}`,ok:!1,detail:"not in this checkout's plan - refused"});for(let f of u){let m=await vn("docker",["rm","-f",f]);n({label:`Remove container ${f}`,ok:m.trim()===f,detail:m.trim()===f?"removed":"docker refused - remove it by hand"})}let p=new Map(r.databases.map(f=>[f.name,f]));for(let f of e.databases){let m=p.get(f);if(!m){n({label:`Drop database ${f}`,ok:!1,detail:"not named by this checkout's own env files - refused"});continue}if(m.engine==="postgres"){let S=(await vn("sudo",["-n","-u","postgres","psql","-c",`DROP DATABASE IF EXISTS "${f}"`])).includes("DROP DATABASE");n({label:`Drop database ${f}`,ok:S,detail:S?"dropped":`could not drop it from here - run: sudo -u postgres psql -c 'DROP DATABASE "${f}"'`})}else{let S=(await vn("sudo",["-n","mysql","-N","-e",`DROP DATABASE IF EXISTS \`${f}\`; SELECT 'dropped'`])).includes("dropped");n({label:`Drop database ${f}`,ok:S,detail:S?"dropped":`could not drop it from here - run: sudo mysql -e 'DROP DATABASE \`${f}\`'`})}}if(e.deleteFolder)try{Ft.default.rmSync(s,{recursive:!0,force:!0});let f=!Ft.default.existsSync(s);n({label:`Delete ${s}`,ok:f,detail:f?`${r.sizeMb} MB freed`:"still there - permissions? delete it by hand"})}catch(f){n({label:`Delete ${s}`,ok:!1,detail:f instanceof Error?f.message:String(f)})}}var Ft,St,yk,bk,vC,kC,TC,rp=J(()=>{"use strict";Ft=E(require("node:fs"),1),St=E(require("node:path"),1),yk=require("node:child_process"),bk=require("node:util");Oo();vC=(0,bk.promisify)(yk.execFile),kC=15e3;TC=new Set(["localhost","127.0.0.1","::1","0.0.0.0"])});function Sk(t,...e){try{return JSON.parse(fl.default.readFileSync(ml.default.join(t,...e),"utf8"))}catch{return null}}function pl(t,...e){try{return fl.default.readFileSync(ml.default.join(t,...e),"utf8")}catch{return""}}function $C(t){for(let e of["prisma/schema.prisma","schema.prisma","apps/api/prisma/schema.prisma"]){let n=/provider\s*=\s*"(postgresql|mysql|sqlite|mongodb|sqlserver|cockroachdb)"/.exec(pl(t,e));if(n)return`${{postgresql:"PostgreSQL",mysql:"MySQL",sqlite:"SQLite",mongodb:"MongoDB",sqlserver:"SQL Server",cockroachdb:"CockroachDB"}[n[1]]} (Prisma)`}return""}function _k(t){let e={languages:[],frameworks:[],databases:[],docker:Ue(t,"Dockerfile"),dockerCompose:Ue(t,"docker-compose.yml")||Ue(t,"docker-compose.yaml")||Ue(t,"compose.yml")||Ue(t,"compose.yaml"),packageManager:"",monorepo:""},n=(i,a)=>{a&&!i.includes(a)&&i.push(a)},r=Sk(t,"package.json");if(r){n(e.languages,Ue(t,"tsconfig.json")?"TypeScript":"JavaScript");let i={...r.dependencies,...r.devDependencies};for(let[a,c]of IC)i[a]&&n(e.frameworks,c);n(e.databases,i.prisma||i["@prisma/client"]?$C(t):"");for(let[a,c]of EC)i[a]&&n(e.databases,c);e.packageManager=Ue(t,"pnpm-lock.yaml")?"pnpm":Ue(t,"yarn.lock")?"yarn":Ue(t,"package-lock.json")?"npm":"",e.monorepo=Ue(t,"pnpm-workspace.yaml")?"pnpm workspaces":Ue(t,"turbo.json")?"turborepo":r.workspaces?"npm/yarn workspaces":""}let s=(pl(t,"requirements.txt")+pl(t,"pyproject.toml")).toLowerCase();if(s||Ue(t,"manage.py")){n(e.languages,"Python");for(let[i,a]of AC)(s.includes(i)||i==="django"&&Ue(t,"manage.py"))&&n(e.frameworks,a);s.includes("psycopg")&&n(e.databases,"PostgreSQL"),s.includes("pymongo")&&n(e.databases,"MongoDB"),(s.includes("mysqlclient")||s.includes("pymysql"))&&n(e.databases,"MySQL"),e.packageManager||(e.packageManager=Ue(t,"poetry.lock")?"poetry":Ue(t,"requirements.txt")?"pip":"")}return Ue(t,"go.mod")&&n(e.languages,"Go"),Ue(t,"Cargo.toml")&&n(e.languages,"Rust"),Ue(t,"composer.json")&&(n(e.languages,"PHP"),(Sk(t,"composer.json")?.require??{})["laravel/framework"]&&n(e.frameworks,"Laravel")),Ue(t,"Gemfile")&&(n(e.languages,"Ruby"),pl(t,"Gemfile").includes("rails")&&n(e.frameworks,"Rails")),(Ue(t,"pom.xml")||Ue(t,"build.gradle")||Ue(t,"build.gradle.kts"))&&n(e.languages,"Java/Kotlin"),e.languages=e.languages.slice(0,4),e.frameworks=e.frameworks.slice(0,6),e.databases=e.databases.slice(0,4),e}var fl,ml,Ue,IC,EC,AC,xk=J(()=>{"use strict";fl=E(require("node:fs"),1),ml=E(require("node:path"),1),Ue=(t,...e)=>fl.default.existsSync(ml.default.join(t,...e));IC=[["next","Next.js"],["@nestjs/core","NestJS"],["nuxt","Nuxt"],["@angular/core","Angular"],["vue","Vue"],["svelte","Svelte"],["react","React"],["express","Express"],["fastify","Fastify"],["@remix-run/react","Remix"],["astro","Astro"],["electron","Electron"],["react-native","React Native"],["tailwindcss","Tailwind"]],EC=[["mongoose","MongoDB"],["mongodb","MongoDB"],["pg","PostgreSQL"],["postgres","PostgreSQL"],["mysql2","MySQL"],["mysql","MySQL"],["better-sqlite3","SQLite"],["sqlite3","SQLite"],["redis","Redis"],["ioredis","Redis"]],AC=[["django","Django"],["flask","Flask"],["fastapi","FastAPI"]]});var jk={};Fe(jk,{buildAgentReport:()=>Nk,buildSetupReport:()=>jC,claudeLoggedIn:()=>$k,codexLoggedIn:()=>Ck,kimiLoggedIn:()=>Pk,repoCurrentBranch:()=>Ek,repoDefaultBranch:()=>Ak});function Ek(t){try{let e=(0,sa.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Ak(t){let e=(...s)=>{try{return(0,sa.execFileSync)("git",["-C",t,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},n=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(n?.startsWith("origin/"))return n.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function $k(t=ia.default.homedir()){if(tn.default.existsSync(kn.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(tn.default.readFileSync(kn.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}function PC(t){try{return tn.default.readdirSync(t).length>0}catch{return!1}}function Ck(t=ia.default.homedir()){return tn.default.existsSync(kn.default.join(t,".codex","auth.json"))}function Pk(t=ia.default.homedir()){return PC(kn.default.join(t,".kimi","credentials"))||tn.default.existsSync(kn.default.join(t,".kimi","credentials.json"))}async function NC(t){let e=Rk.get(t);if(e&&Date.now()-e.at<6e4)return{installed:e.installed,version:e.version};let n=!1,r="";try{let{stdout:s}=await CC(t,["--version"],{timeout:1e4});n=!0,r=s.trim().slice(0,60)}catch{n=!1}return Rk.set(t,{at:Date.now(),installed:n,version:r}),{installed:n,version:r}}async function Nk(t){let e=gl.REGISTERED_AGENTS.filter(r=>Tk[r.id]),n=await Promise.all(e.map(async r=>{let{installed:s,version:i}=await NC(We(t,r.id)),a=Tk[r.id](ia.default.homedir());return[r.id,{installed:s,version:i,loggedIn:a}]}));return Object.fromEntries(n)}async function jC(t,e,n){let r=await Nk(t),s=e.map(a=>{let c=t.repos[a];if(!c)return{repoName:a,path:"",mapped:!1,liveMapped:!!n?.repos?.[a],pathExists:!1,isGit:!1,currentBranch:"",claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let l=tn.default.existsSync(c.path);return{repoName:a,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[a]:!0,pathExists:l,isGit:l&&tn.default.existsSync(kn.default.join(c.path,".git")),currentBranch:l?Ek(c.path):"",claudeMd:l&&tn.default.existsSync(kn.default.join(c.path,"CLAUDE.md")),deployMd:l&&tn.default.existsSync(kn.default.join(c.path,"DEPLOY.md")),testMd:l&&tn.default.existsSync(kn.default.join(c.path,"TEST.md")),githubToken:!!st(t,a),githubTokenOwn:!!c.github?.token,defaultBranch:l?Ak(c.path):"",architecture:l?_k(c.path):void 0}}),i=Object.values(t.repos).find(a=>a.github?.token);return{jiraConfigured:!!t.jira,...(()=>{let a=Do();return{serviceProtected:a.protected,serviceProtectFix:a.protected===!1?a.fixCommand:""}})(),jiraEmail:t.jira?.email??"",agents:r,claude:r[gl.DEFAULT_AGENT_ID]??{installed:!1,version:"",loggedIn:!1},githubTokenSet:!!(t.github?.token||i),githubLogin:t.github?.login??i?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:s}}var sa,tn,ia,kn,Ik,gl,CC,Tk,Rk,Mk=J(()=>{"use strict";sa=require("node:child_process");Ac();tn=E(require("node:fs"),1),ia=E(require("node:os"),1),kn=E(require("node:path"),1),Ik=require("node:util"),gl=E(Me(),1);Pt();ys();xk();CC=(0,Ik.promisify)(sa.execFile);Tk={"claude-code":$k,codex:Ck,kimi:Pk},Rk=new Map});var qk={};Fe(qk,{discoverForMonitoring:()=>ip});async function zk(t,e){try{let{stdout:n}=await MC(t,e,{timeout:OC,maxBuffer:4e6});return n}catch{return""}}function qC(t){let e;try{e=yl.default.readdirSync(t)}catch{return null}let n=null;for(let r of e.slice(0,500))if(LC.some(s=>r.endsWith(s)))try{let s=yl.default.statSync(sp.default.join(t,r));if(!s.isFile())continue;(!n||s.mtimeMs>n.mtimeMs)&&(n={name:r,mtimeMs:s.mtimeMs,size:s.size})}catch{}return n?{newestFile:n.name,newestAgeHours:Math.round((Date.now()-n.mtimeMs)/36e5),sizeMB:Number((n.size/1024/1024).toFixed(1))}:null}async function ip(){let[t,e]=await Promise.all([zk("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain","--no-pager"]),zk("ss",["-tlnpH"])]),n=[];for(let c of lc(t)){let l=c.name.replace(/\.service$/,""),u=Object.keys(Ok).find(p=>l===p||l.startsWith(p+"@")||l.startsWith(p+"-"));if(u&&n.push({name:l,kind:Ok[u]}),n.length>=40)break}let r=[...new Set(n.filter(c=>c.kind==="web").map(c=>c.name.split("@")[0].split("-")[0]))],s=[];for(let c of vr(e)){let l=zC[c.port];l&&!s.some(u=>u.kind===l)&&s.push({kind:l,port:c.port})}let i=[...DC];try{for(let c of yl.default.readdirSync("/home").slice(0,20))i.push(sp.default.join("/home",c,"backups"))}catch{}let a=[];for(let c of i){if(a.length>=UC)break;let l=qC(c);l&&a.push({path:c,...l})}return{os:{platform:process.platform,arch:process.arch,release:Dk.default.release().slice(0,60)},services:n,webServers:r,backupCandidates:a,dbHints:s}}var yl,Dk,sp,Lk,Uk,MC,OC,Ok,zC,DC,LC,UC,op=J(()=>{"use strict";yl=E(require("node:fs"),1),Dk=E(require("node:os"),1),sp=E(require("node:path"),1),Lk=require("node:child_process"),Uk=require("node:util");Oo();MC=(0,Uk.promisify)(Lk.execFile),OC=8e3,Ok={nginx:"web",caddy:"web",apache2:"web",httpd:"web",postgresql:"db",mysql:"db",mariadb:"db",mongod:"db",redis:"cache",docker:"containers",allwright:"runner","ticketpilot-runner":"runner"},zC={5432:"postgres",3306:"mysql",27017:"mongodb",6379:"redis"},DC=["/backups","/backup","/var/backups","/root/backups","/opt/backups","/srv/backups"],LC=[".sql",".sql.gz",".dump",".tar.gz",".tgz",".zip",".gz",".bak"],UC=20});var Hk={};Fe(Hk,{parseSuggestion:()=>Bk,suggestMonitorCheck:()=>BC});function Bk(t){let e=[...t.matchAll(/```json\s*\n([\s\S]*?)```/g)];for(let n=e.length-1;n>=0;n--)try{let r=FC.safeParse(JSON.parse(e[n][1]));if(r.success)return r.data}catch{}return null}async function BC(t){let e={name:"",commands:[],parseRules:{amberPattern:"",redPattern:"",greenRequires:""},notes:""},n=await ip().catch(()=>null),r=n?[`- OS: ${n.os.platform}/${n.os.arch} ${n.os.release}`,n.services.length?`- running services: ${n.services.map(l=>l.name).join(", ")}`:"",n.webServers.length?`- web servers: ${n.webServers.join(", ")}`:"",n.dbHints.length?`- databases listening: ${n.dbHints.map(l=>`${l.kind}:${l.port}`).join(", ")}`:"",n.backupCandidates.length?`- backup-looking directories: ${n.backupCandidates.map(l=>`${l.path} (newest ${l.newestFile||"?"}, ${l.newestAgeHours}h old)`).join("; ")}`:""].filter(Boolean):["- (machine discovery failed - propose from the request alone and say so in notes)"],s="```",i=`Propose ONE monitoring check for this server as shell commands. The person asked:
1531
1531
  "${t.notes.slice(0,2e3)}"
1532
1532
 
@@ -1578,7 +1578,7 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
1578
1578
  Answer with ONLY a fenced json block, nothing after it:
1579
1579
  \`\`\`json
1580
1580
  {"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
1581
- \`\`\``}function Db(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():"",a=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:a||"(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"}}}Ba();mo();za();var _r=E(Me(),1);Te();To();var Zb=E(require("node:fs"),1);xs();Es();dn();So();fd();xs();Yt();ys();Ba();Pt();var $c=E(require("node:fs"),1),Lb=E(require("node:path"),1);Te();var TE=1440*6e4,Ub=()=>Lb.default.join(X(),"agent-overrides.json");function qb(){try{return JSON.parse($c.default.readFileSync(Ub(),"utf8"))}catch{return{}}}function Fb(t){$c.default.mkdirSync(X(),{recursive:!0,mode:448}),$c.default.writeFileSync(Ub(),JSON.stringify(t,null,2),{mode:384})}var Bb=(t,e)=>`${t}:${e}`;function Hb(t,e,n){let r=(n??"").trim();if(!r)return;let s=qb();s[Bb(t,e)]={agentId:r,at:new Date().toISOString()},Fb(s)}function Kb(t,e){let n=qb(),r=Bb(t,e),s=n[r];return!s||(delete n[r],Fb(n),Date.now()-Date.parse(s.at)>TE)?"":s.agentId}function Cc(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}}}za();ot();Mc();var Gb=24*3600*1e3,Oc=14,IE=Oc*24*3600*1e3,EE=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]);function Vb(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 zc=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!!Qi(this.cfg,e)}get jiraless(){return eo(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,b.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),b.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),b.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.`}),b.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(a=>a.enabled).length;b.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(b.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():b.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}recoverCrashedRuns(){let e=Object.values(nc());if(!e.length)return[];let n=[],r={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};for(let s of e){let i=Kg(s,{worktreeExists:Zb.default.existsSync(s.workPath),adapterCanResume:!!Ve(s.agent)?.capabilities.sessionResume,parkedForInput:!!Ju(s.runId),awaitingApproval:!!mr(s.runId),awaitingPushRetry:!!bi(s.runId)});if(i.action==="forget"){b.info(`crash sweep: run ${s.runId} (${s.issueKey}) - ${i.reason}`),mn(s.runId);continue}let a=`resume:${s.runId}`;if(!this.inFlight.has(a)){if(this.inFlight.add(a),i.action==="fail"){b.warn(`crash sweep: run ${s.runId} (${s.issueKey}) cannot be resumed - failing it loudly (${i.reason})`),ly(s,i.reason,r).catch(c=>b.error(`crash-failure report for ${s.runId} failed: ${c}`)).finally(()=>this.inFlight.delete(a));continue}n.push(s.workPath),b.warn(`crash sweep: run ${s.runId} (${s.issueKey}) was orphaned by a crash - resuming its agent session in ${s.workPath}`),this.enqueueForRepo(s.baseRepoPath??s.workPath,async()=>{try{await cy(s,r)}finally{this.inFlight.delete(a)}})}}return n}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=om(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{b.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Ce(this.cfg,n,"assist");if("error"in s){b.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await gi({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 a=i.audit.findings.length;b.info(`Scheduled audit done: ${a} finding(s) - drift visible on the Audits page`)}else b.warn(`Scheduled audit failed: ${i.error}`)}catch(s){b.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){b.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){b.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 v=Date.parse(e.pausedUntil);Number.isFinite(v)&&(this.autopilotPausedUntil=v);return}let n=e.item;if(!n)return;let r=this.rules.find(v=>v.id===n.ruleId&&v.enabled),s=this.projects.find(v=>v.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=Cc(s,[]),a="project"in i?i.project:s,c=this.cfg.repos[a.repoName];if(!c){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${a.repoName}" on this machine`});return}if(!this.hasJira(a.repoName)){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no Jira credential for "${a.repoName}" on this machine - run \`allwright jira set-default\` there (or \`allwright jira set "${a.repoName}"\`)`});return}let l=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,u=Vb(l,n.agentId);b.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:"")+(u.agentId?` -> agent ${u.agentId}`:""));let p=this.jiraOf(a),f="";try{f=(await p.getIssue(n.issueKey))?.summary??""}catch(v){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${v instanceof Error?v.message:String(v)}`});return}let m=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!m.accepted||!m.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:m.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:m.runId});let w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let S=this.resolveClaudeProfile(m.runId,m.claudeProfile),T=!!(n.batchId&&n.branchOverride),x=n.batchId?th(n.batchId):null,A=!n.continueBranch&&!T?nh(x,n.issueKey):null,D=A?jc(n.batchId,A,n.issueKey):null,K=T&&n.continueBranch?ih(n.batchId):null,C=D??K,$=lh(A,n.issueKey)||T&&n.remainingInBatch>0;this.enqueueForRepo(c.path,async()=>{try{await Po({runId:m.runId,rule:u.rule,project:a,issueKey:n.issueKey,repoPath:c.path,cfg:this.cfg,jira:p,transport:this.transport,claudeConfigDir:S,actorEmail:m.actorEmail,continueBranch:n.continueBranch,batchId:n.batchId,...C?{chain:{sessionId:C.sessionId,worktreePath:C.worktreePath}}:{},keepWorktree:$,onChainSession:A?v=>rh(n.batchId,A,n.issueKey,v):T&&$?v=>oh(n.batchId,n.issueKey,v,!!K):void 0}),A&&!jc(n.batchId,A,A[A.indexOf(n.issueKey)+1]??"")&&A.indexOf(n.issueKey)<A.length-1&&sh(n.batchId,A),T&&!ah(n.batchId,n.issueKey)&&ch(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(ko());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let a=st(n,i);if(!a)return null;let c=r.get(a);return c||r.set(a,c=new rt(a)),c};for(let i of e.slice(0,10)){let a=s(i.repoName);if(!a)continue;if(!this.hasJira(i.repoName)){this.warnNoJiraForRepo(i.repoName);continue}let c=`gh-approve:${i.runId}`;if(this.inFlight.has(c))continue;let l,u;try{[l,u]=await Promise.all([a.getReviews(i.owner,i.repo,i.prNumber),a.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){b.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!u){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.`;b.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.**
1581
+ \`\`\``}function Db(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():"",a=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:a||"(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"}}}Ba();mo();za();var _r=E(Me(),1);Te();To();var Zb=E(require("node:fs"),1);xs();Es();dn();So();fd();xs();Yt();ys();Ba();Pt();var $c=E(require("node:fs"),1),Lb=E(require("node:path"),1);Te();var TE=1440*6e4,Ub=()=>Lb.default.join(X(),"agent-overrides.json");function qb(){try{return JSON.parse($c.default.readFileSync(Ub(),"utf8"))}catch{return{}}}function Fb(t){$c.default.mkdirSync(X(),{recursive:!0,mode:448}),$c.default.writeFileSync(Ub(),JSON.stringify(t,null,2),{mode:384})}var Bb=(t,e)=>`${t}:${e}`;function Hb(t,e,n){let r=(n??"").trim();if(!r)return;let s=qb();s[Bb(t,e)]={agentId:r,at:new Date().toISOString()},Fb(s)}function Kb(t,e){let n=qb(),r=Bb(t,e),s=n[r];return!s||(delete n[r],Fb(n),Date.now()-Date.parse(s.at)>TE)?"":s.agentId}function Cc(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}}}za();ot();Mc();var Gb=24*3600*1e3,Oc=14,IE=Oc*24*3600*1e3,EE=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]);function Vb(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 zc=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!!Qi(this.cfg,e)}get jiraless(){return eo(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,b.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),b.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),b.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.`}),b.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(a=>a.enabled).length;b.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(b.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():b.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}recoverCrashedRuns(){let e=Object.values(nc());if(!e.length)return[];let n=[],r={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};for(let s of e){let i=Kg(s,{worktreeExists:Zb.default.existsSync(s.workPath),adapterCanResume:!!Ve(s.agent)?.capabilities.sessionResume,parkedForInput:!!Ju(s.runId),awaitingApproval:!!mr(s.runId),awaitingPushRetry:!!bi(s.runId)});if(i.action==="forget"){b.info(`crash sweep: run ${s.runId} (${s.issueKey}) - ${i.reason}`),mn(s.runId);continue}let a=`resume:${s.runId}`;if(!this.inFlight.has(a)){if(this.inFlight.add(a),i.action==="fail"){b.warn(`crash sweep: run ${s.runId} (${s.issueKey}) cannot be resumed - failing it loudly (${i.reason})`),ly(s,i.reason,r).catch(c=>b.error(`crash-failure report for ${s.runId} failed: ${c}`)).finally(()=>this.inFlight.delete(a));continue}n.push(s.workPath),b.warn(`crash sweep: run ${s.runId} (${s.issueKey}) was orphaned by a crash - resuming its agent session in ${s.workPath}`),this.enqueueForRepo(s.baseRepoPath??s.workPath,async()=>{try{await cy(s,r)}finally{this.inFlight.delete(a)}})}}return n}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=om(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{b.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Ce(this.cfg,n,"assist");if("error"in s){b.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await gi({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 a=i.audit.findings.length;b.info(`Scheduled audit done: ${a} finding(s) - drift visible on the Audits page`)}else b.warn(`Scheduled audit failed: ${i.error}`)}catch(s){b.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){b.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){b.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 v=Date.parse(e.pausedUntil);Number.isFinite(v)&&(this.autopilotPausedUntil=v);return}let n=e.item;if(!n)return;let r=this.rules.find(v=>v.id===n.ruleId&&v.enabled),s=this.projects.find(v=>v.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=Cc(s,[]),a="project"in i?i.project:s,c=this.cfg.repos[a.repoName];if(!c){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${a.repoName}" on this machine`});return}if(!this.hasJira(a.repoName)){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no Jira credential for "${a.repoName}" on this machine - run \`allwright jira set-default\` there (or \`allwright jira set "${a.repoName}"\`)`});return}let l=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,u=Vb(l,n.agentId);b.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:"")+(u.agentId?` -> agent ${u.agentId}`:""));let p=this.jiraOf(a),f="";try{f=(await p.getIssue(n.issueKey))?.summary??""}catch(v){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${v instanceof Error?v.message:String(v)}`});return}let m=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!m.accepted||!m.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:m.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:m.runId});let w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let S=this.resolveClaudeProfile(m.runId,m.claudeProfile),T=!!(n.batchId&&n.branchOverride),x=n.batchId?th(n.batchId):null,A=!n.continueBranch&&!T?nh(x,n.issueKey):null,D=A?jc(n.batchId,A,n.issueKey):null,K=T&&n.continueBranch?ih(n.batchId):null,C=D??K,$=lh(A,n.issueKey)||T&&n.remainingInBatch>0;this.enqueueForRepo(c.path,async()=>{try{await Po({runId:m.runId,rule:u.rule,project:a,issueKey:n.issueKey,repoPath:c.path,cfg:this.cfg,jira:p,transport:this.transport,claudeConfigDir:S,actorEmail:m.actorEmail,continueBranch:n.continueBranch,batchId:n.batchId,...C?{chain:{sessionId:C.sessionId,worktreePath:C.worktreePath}}:{},keepWorktree:$,onChainSession:A?v=>rh(n.batchId,A,n.issueKey,v):T&&$?v=>oh(n.batchId,n.issueKey,v,!!K):void 0}),A&&!jc(n.batchId,A,A[A.indexOf(n.issueKey)+1]??"")&&A.indexOf(n.issueKey)<A.length-1&&sh(n.batchId,A),T&&!ah(n.batchId,n.issueKey)&&ch(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(ko());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let a=st(n,i);if(!a)return null;let c=r.get(a);return c||r.set(a,c=new Ye(a)),c};for(let i of e.slice(0,10)){let a=s(i.repoName);if(!a)continue;if(!this.hasJira(i.repoName)){this.warnNoJiraForRepo(i.repoName);continue}let c=`gh-approve:${i.runId}`;if(this.inFlight.has(c))continue;let l,u;try{[l,u]=await Promise.all([a.getReviews(i.owner,i.repo,i.prNumber),a.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){b.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!u){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.`;b.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.**
1582
1582
 
1583
1583
  ${w}
1584
1584
 
@@ -1598,7 +1598,7 @@ PR: ${i.prUrl} (run \`${i.runId}\`)`).catch(()=>{}),Nt({...i,headSha:u.headSha})
1598
1598
 
1599
1599
  PR: ${i.prUrl}
1600
1600
 
1601
- Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),Nt({...i,changesRequestedNotified:!0}),b.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(m.commitId===u.headSha){b.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${m.user} - completing the run`),this.inFlight.add(c);try{await No(p,i.runId,m.commitId)}catch(w){b.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(c)}}}}}async sweepMergedPRs(){let e=Object.values(Ka());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=c=>{let l=st(n,c);if(!l)return null;let u=r.get(l);return u||r.set(l,u=new rt(l)),u},i=20,a=720*3600*1e3;for(let c of e.slice(0,i)){let l=s(c.repoName);if(!l)continue;if(!this.hasJira(c.repoName)){this.warnNoJiraForRepo(c.repoName);continue}if(Date.now()-new Date(c.createdAt).getTime()>a){b.warn(`merge watch for ${c.issueKey} PR #${c.prNumber} is over 30 days old - dropping`),vo(c.runId);continue}let u;try{u=await l.getPullRequest(c.owner,c.repo,c.prNumber)}catch(m){b.warn(`merge check failed for ${c.owner}/${c.repo}#${c.prNumber}: ${m instanceof Error?m.message:m}`);continue}if(!u){vo(c.runId);continue}if(u.state==="open")continue;if(!u.merged){vo(c.runId);continue}let p=this.jiraFor(c.repoName),f="";if(c.jiraTransitionOnMerge)try{f=await p.transitionByName(c.issueKey,c.jiraTransitionOnMerge)?`
1601
+ Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),Nt({...i,changesRequestedNotified:!0}),b.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(m.commitId===u.headSha){b.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${m.user} - completing the run`),this.inFlight.add(c);try{await No(p,i.runId,m.commitId)}catch(w){b.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(c)}}}}}async sweepMergedPRs(){let e=Object.values(Ka());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=c=>{let l=st(n,c);if(!l)return null;let u=r.get(l);return u||r.set(l,u=new Ye(l)),u},i=20,a=720*3600*1e3;for(let c of e.slice(0,i)){let l=s(c.repoName);if(!l)continue;if(!this.hasJira(c.repoName)){this.warnNoJiraForRepo(c.repoName);continue}if(Date.now()-new Date(c.createdAt).getTime()>a){b.warn(`merge watch for ${c.issueKey} PR #${c.prNumber} is over 30 days old - dropping`),vo(c.runId);continue}let u;try{u=await l.getPullRequest(c.owner,c.repo,c.prNumber)}catch(m){b.warn(`merge check failed for ${c.owner}/${c.repo}#${c.prNumber}: ${m instanceof Error?m.message:m}`);continue}if(!u){vo(c.runId);continue}if(u.state==="open")continue;if(!u.merged){vo(c.runId);continue}let p=this.jiraFor(c.repoName),f="";if(c.jiraTransitionOnMerge)try{f=await p.transitionByName(c.issueKey,c.jiraTransitionOnMerge)?`
1602
1602
 
1603
1603
  Ticket moved to **${c.jiraTransitionOnMerge}**.`:`
1604
1604
 
@@ -1629,7 +1629,7 @@ Rules:
1629
1629
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
1630
1630
 
1631
1631
  Conflicted files:
1632
- `;async function Xb(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:a}=t,c=Yb.default.join(jn(),`conflict-${(0,dh.randomUUID)().slice(0,8)}`),l=!1;try{a("info",`Preparing a worktree for ${r} to merge ${s} into it`),await ho(n,c,r),l=!0;let u=await Su(c,s);if(u.ok&&u.alreadyUpToDate)return a("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!u.ok&&u.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${u.reason}`};let p={},f=!1;if(!u.ok){let S=u.conflicts;a("info",`git merged everything except ${S.length} file(s): ${S.slice(0,20).join(", ")}`+(S.length>20?", \u2026":""));let T=Ve(t.agentId);if(!T)return await dr(c),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let x=ir(t.agentId,"edit_no_shell");if(x)return await dr(c),{ok:!1,note:`${x} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};a("info",`Asking ${T.displayName} to resolve only those files`);let A=-1,D=setInterval(()=>{Tu(c,S).then($=>{let v=S.filter(P=>!$.includes(P));v.length!==A&&(A=v.length,a("info",`Conflict progress: ${v.length}/${S.length} resolved`+(v.length?` \xB7 clean: ${v.join(", ")}`:"")+($.length?` \xB7 still conflicted: ${$.join(", ")}`:"")))}).catch(()=>{})},12e3),K=await Co(T,{repoPath:c,prompt:$E+S.map($=>`- ${$}`).join(`
1632
+ `;async function Xb(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:a}=t,c=Yb.default.join(jn(),`conflict-${(0,dh.randomUUID)().slice(0,8)}`),l=!1;try{a("info",`Preparing a worktree for ${r} to merge ${s} into it`),await ho(n,c,r),l=!0;let u=await Su(c,s);if(u.ok&&u.alreadyUpToDate)return a("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!u.ok&&u.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${u.reason}`};let p={},f=!1;if(!u.ok){let S=u.conflicts;a("info",`git merged everything except ${S.length} file(s): ${S.slice(0,20).join(", ")}`+(S.length>20?", \u2026":""));let T=Ve(t.agentId);if(!T)return await dr(c),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let x=ir(t.agentId,"edit_no_shell");if(x)return await dr(c),{ok:!1,note:`${x} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};a("info",`Asking ${T.displayName} to resolve only those files`);let A=-1,D=setInterval(()=>{Tu(c,S).then($=>{let v=S.filter(N=>!$.includes(N));v.length!==A&&(A=v.length,a("info",`Conflict progress: ${v.length}/${S.length} resolved`+(v.length?` \xB7 clean: ${v.join(", ")}`:"")+($.length?` \xB7 still conflicted: ${$.join(", ")}`:"")))}).catch(()=>{})},12e3),K=await Co(T,{repoPath:c,prompt:$E+S.map($=>`- ${$}`).join(`
1633
1633
  `),timeoutSeconds:t.timeoutSeconds,bin:We(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,dh.randomUUID)(),onLog:($,v)=>a($,v)},($,v)=>a($==="warn"?"warn":$,v));if(clearInterval(D),p={costUsd:K.costUsd,inputTokens:K.inputTokens,outputTokens:K.outputTokens},Se({surface:"run_conflict_resolve",agentId:t.agentId,refKind:"run",refLabel:t.issueKey,...ve(K)}),!K.ok)return await dr(c),{ok:!1,...p,note:`The agent could not do the resolution: ${K.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let C=await ja(c);if(C.length)return await dr(c),{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 _u(c,`${i}: merge ${s}, conflicts resolved by the agent
1634
1634
 
1635
1635
  Resolved via Allwright`)}try{let S=await Pm(c);for(let T of S.notes)a("warn",T);S.regenerated.length&&(await xu(c),a("info","Regenerated lockfile(s) the merge left stale and folded them into the merge commit: "+S.regenerated.join(", ")))}catch(S){return{ok:!1,...p,note:`Nothing was pushed: the merge changed dependencies but the lockfile could not be regenerated - ${S instanceof Error?S.message:String(S)}. Resolve it by hand on ${r}, or use Rebuild on current base.`}}let m=await lr(c,s);if(!m.ok){let S=m.forbidden.length?`the merged result touches protected paths (${m.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${m.files} files, ${m.insertions+m.deletions} lines; limits ${or}/${ar})`;return await dr(c),{ok:!1,...p,note:`Nothing was pushed: ${S}. The merge was rolled back.`}}await fs(c,r);let w=await mt(c);return a("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(u){return await dr(c).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{l&&(await Zt(n,c).catch(()=>{}),Jb.default.rmSync(c,{recursive:!0,force:!0}))}}var hh=E(require("node:fs"),1),Qb=E(require("node:path"),1),ph=require("node:crypto");dn();bo();Pt();xs();Vt();wo();function CE(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
@@ -1657,12 +1657,12 @@ Your ONLY job is to address that finding, with the smallest change possible.
1657
1657
  - 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.
1658
1658
  - Do not ask questions; if you cannot fix it safely, say what you found and stop.
1659
1659
  - You have no shell; the runner re-runs the documented tests after you finish.
1660
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function ew(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:a,onLog:c}=t,l=Qb.default.join(jn(),`testfix-${(0,ph.randomUUID)().slice(0,8)}`),u=!1;try{let p=Ve(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=ir(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};c("info",`Preparing a worktree on ${r} for the test fix`),await cr(n,r),await ho(n,l,r),u=!0,await ur(l,`origin/${r}`);let m=await mt(l);c("info",`Asking ${p.displayName} to fix ${a.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await Co(p,{repoPath:l,prompt:t.finding?PE(i,t.finding):CE(i,a),timeoutSeconds:t.timeoutSeconds,bin:We(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,ph.randomUUID)(),onLog:(P,F)=>c(P,F)},(P,F)=>c(P==="warn"?"warn":P,F)),S={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(Se({surface:"run_testfix",agentId:t.agentId,refKind:"run",refLabel:i,...ve(w)}),!w.ok)return{ok:!1,...S,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let T=await hi(l);for(let P of T.refused)c("warn",`${Nn} entry refused: ${P}`);try{let P=await yo(l);for(let F of P.notes)c("warn",F);P.regenerated.length&&c("info",`Regenerated lockfile(s) for the fix's dependency change: ${P.regenerated.join(", ")}`)}catch(P){return await ur(l,m),{ok:!1,...S,note:`Nothing was pushed: the fix changed dependencies but its lockfile could not be regenerated - ${P instanceof Error?P.message:String(P)}. The fix was discarded; the PR is unchanged.`}}let x=!0;try{await ps(l,t.finding?`${i}: ${t.finding.title.slice(0,60)}
1660
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function ew(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:a,onLog:c}=t,l=Qb.default.join(jn(),`testfix-${(0,ph.randomUUID)().slice(0,8)}`),u=!1;try{let p=Ve(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=ir(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};c("info",`Preparing a worktree on ${r} for the test fix`),await cr(n,r),await ho(n,l,r),u=!0,await ur(l,`origin/${r}`);let m=await mt(l);c("info",`Asking ${p.displayName} to fix ${a.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await Co(p,{repoPath:l,prompt:t.finding?PE(i,t.finding):CE(i,a),timeoutSeconds:t.timeoutSeconds,bin:We(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,ph.randomUUID)(),onLog:(N,B)=>c(N,B)},(N,B)=>c(N==="warn"?"warn":N,B)),S={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(Se({surface:"run_testfix",agentId:t.agentId,refKind:"run",refLabel:i,...ve(w)}),!w.ok)return{ok:!1,...S,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let T=await hi(l);for(let N of T.refused)c("warn",`${Nn} entry refused: ${N}`);try{let N=await yo(l);for(let B of N.notes)c("warn",B);N.regenerated.length&&c("info",`Regenerated lockfile(s) for the fix's dependency change: ${N.regenerated.join(", ")}`)}catch(N){return await ur(l,m),{ok:!1,...S,note:`Nothing was pushed: the fix changed dependencies but its lockfile could not be regenerated - ${N instanceof Error?N.message:String(N)}. The fix was discarded; the PR is unchanged.`}}let x=!0;try{await ps(l,t.finding?`${i}: ${t.finding.title.slice(0,60)}
1661
1661
 
1662
1662
  Allwright finding-fix run`:`${i}: fix failing TEST.md commands
1663
1663
 
1664
- Allwright test-fix run`)}catch{x=!1}if(!x){let P=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return c("info",P),{ok:!0,...S,remaining:a,note:P}}let A=await lr(l,s);if(!A.ok){await ur(l,m);let P=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 ${or}/${ar})`;return{ok:!1,...S,note:`Nothing was pushed: ${P}. The fix commit was discarded; the PR is unchanged.`}}let D=a,K,C,$=mi(l);if($){let P=fr(hh.default.readFileSync($,"utf8"));if(P.length){c("info",`Re-running ${P.length} documented test command(s)`);let F=await Mn(l,P,{perCommandTimeoutMs:15*6e4});for(let V of F)c(V.exitCode===0?"info":"warn",`${V.exitCode===0?"PASS":"FAIL"} ${V.command} (exit ${V.exitCode})`+(V.exitCode===0?"":`
1665
- ${V.tail.slice(-1500)}`));D=F.filter(V=>V.exitCode!==0).slice(0,20).map(V=>({command:V.command.slice(0,500),exitCode:V.exitCode,tail:V.tail.slice(-4e3)})),C=F.length,K=F.length-D.length}}await fs(l,r);let v=await mt(l);return c("info",`Pushed the fix to ${r} (${v.slice(0,7)})`),{ok:!0,...S,headSha:v,remaining:D,testsPassed:K,testsTotal:C,note:D.length?`The fix was pushed, but ${D.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{u&&(await Zt(n,l).catch(()=>{}),hh.default.rmSync(l,{recursive:!0,force:!0}))}}ui();Yt();var js=E(require("node:fs"),1),tw=E(require("node:path"),1);ht();Te();var NE=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)}),jE=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(NE).default([]),createdTickets:k.array(k.object({key:k.string(),summary:k.string()})).default([])}),ME=k.record(jE),OE=40,zE=200,fh=2e4,DE=30,LE=2e3,nw=8,rw=255;function sw(){return tw.default.join(X(),"chat-sessions.json")}function Ms(){let t=sw();if(!js.default.existsSync(t))return{};try{return ME.parse(JSON.parse(js.default.readFileSync(t,"utf8")))}catch{return{}}}function mh(t){js.default.mkdirSync(X(),{recursive:!0,mode:448});let e=sw(),n=e+".tmp";js.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1664
+ Allwright test-fix run`)}catch{x=!1}if(!x){let N=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return c("info",N),{ok:!0,...S,remaining:a,note:N}}let A=await lr(l,s);if(!A.ok){await ur(l,m);let N=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 ${or}/${ar})`;return{ok:!1,...S,note:`Nothing was pushed: ${N}. The fix commit was discarded; the PR is unchanged.`}}let D=a,K,C,$=mi(l);if($){let N=fr(hh.default.readFileSync($,"utf8"));if(N.length){c("info",`Re-running ${N.length} documented test command(s)`);let B=await Mn(l,N,{perCommandTimeoutMs:15*6e4});for(let V of B)c(V.exitCode===0?"info":"warn",`${V.exitCode===0?"PASS":"FAIL"} ${V.command} (exit ${V.exitCode})`+(V.exitCode===0?"":`
1665
+ ${V.tail.slice(-1500)}`));D=B.filter(V=>V.exitCode!==0).slice(0,20).map(V=>({command:V.command.slice(0,500),exitCode:V.exitCode,tail:V.tail.slice(-4e3)})),C=B.length,K=B.length-D.length}}await fs(l,r);let v=await mt(l);return c("info",`Pushed the fix to ${r} (${v.slice(0,7)})`),{ok:!0,...S,headSha:v,remaining:D,testsPassed:K,testsTotal:C,note:D.length?`The fix was pushed, but ${D.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{u&&(await Zt(n,l).catch(()=>{}),hh.default.rmSync(l,{recursive:!0,force:!0}))}}ui();Yt();var js=E(require("node:fs"),1),tw=E(require("node:path"),1);ht();Te();var NE=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)}),jE=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(NE).default([]),createdTickets:k.array(k.object({key:k.string(),summary:k.string()})).default([])}),ME=k.record(jE),OE=40,zE=200,fh=2e4,DE=30,LE=2e3,nw=8,rw=255;function sw(){return tw.default.join(X(),"chat-sessions.json")}function Ms(){let t=sw();if(!js.default.existsSync(t))return{};try{return ME.parse(JSON.parse(js.default.readFileSync(t,"utf8")))}catch{return{}}}function mh(t){js.default.mkdirSync(X(),{recursive:!0,mode:448});let e=sw(),n=e+".tmp";js.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1666
1666
  `,{mode:384}),js.default.renameSync(n,e),js.default.chmodSync(e,384)}function gh(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function iw(t,e){e.messages=e.messages.slice(-zE),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(OE))delete t[r.sessionId];mh(t)}function ow(t,e,n,r=[],s=new Date().toISOString(),i="",a=""){let c=Ms(),l=c[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:s,ownerUserId:i,agentId:a,messages:[]};!l.ownerUserId&&i&&(l.ownerUserId=i),!l.agentId&&a&&(l.agentId=a),gh(l),l.messages.push({role:"user",text:n.slice(0,fh),steps:[],files:r.slice(0,nw).map(u=>u.slice(0,rw)),at:s,ms:0,tokens:0}),iw(c,l)}function Dc(t){let e=Ms(),n=e[t];if(!n)return;let r=n.messages.length;gh(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,mh(e))}function aw(t,e,n,r,s=[],i=[],a={},c="",l=""){let u=Ms(),f=u[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),ownerUserId:c,agentId:l,messages:[]};!f.ownerUserId&&c&&(f.ownerUserId=c),!f.agentId&&l&&(f.agentId=l),gh(f),f.messages.push({role:"user",text:n.slice(0,fh),steps:[],files:i.slice(0,nw).map(m=>m.slice(0,rw)),at:a.askedAt||new Date().toISOString(),ms:0,tokens:0},{role:"agent",text:r.slice(0,fh),steps:s.slice(0,DE).map(m=>m.slice(0,LE)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(a.ms??0)),tokens:Math.max(0,Math.round(a.tokens??0))}),iw(u,f)}function cw(t){return Object.values(Ms()).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 Os(t){return Ms()[t]??null}function Lc(t,e){if(!t||!e.length)return;let n=Ms(),r=n[t];if(!r)return;let s=new Set(r.createdTickets.map(i=>i.key));for(let i of e)s.has(i.key)||r.createdTickets.push({key:i.key,summary:i.summary.slice(0,250)});r.updatedAt=new Date().toISOString(),mh(n)}function lw(t){if(!t)return"";let e=Ms()[t];return e?.createdTickets.length?`
1667
1667
 
1668
1668
  Tickets ALREADY CREATED on Jira from this conversation: `+e.createdTickets.map(n=>`${n.key} ("${n.summary}")`).join(", ")+". These exist - never include one of them (or a re-worded copy of it) in a new ```ticket block. A new block drafts ONLY what is being asked for now; when the ask is a change to an existing ticket, say so in prose and name its key instead.":""}Pt();Vt();ot();var uw=36,dw=60;function hw(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 UE=`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:
@@ -1694,7 +1694,7 @@ Never emit both blocks in one reply, and never let either replace the actual ans
1694
1694
  `,{mode:384}),Uo.default.renameSync(n+".tmp",n)}function vw(){return bw()}var zs=E(require("node:fs"),1),zt=E(require("node:path"),1),yh=300,KE=4,kw=512*1024,WE=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Sw=/\.mdx?$/i;function _w(t){let e=zt.default.resolve(t),n=[],r=(s,i)=>{if(i>KE||n.length>=yh)return;let a;try{a=zs.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=yh)return;if(!c.isFile()||!Sw.test(c.name))continue;let l=zt.default.join(s,c.name);try{let u=zs.default.statSync(l);n.push({path:zt.default.relative(e,l).split(zt.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let c of a){if(n.length>=yh)return;!c.isDirectory()||c.isSymbolicLink()||WE.has(c.name)||c.name.startsWith(".")||r(zt.default.join(s,c.name),i+1)}};return r(e,0),n}function xw(t,e){let n=zt.default.resolve(t);if(!Sw.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=zt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+zt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=zs.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return zs.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+zt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let a;try{a=zs.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!a.isFile())return{ok:!1,error:"that path is not a file"};try{let c=zs.default.readFileSync(s,"utf8"),l=Buffer.byteLength(c,"utf8")>kw;return{ok:!0,path:zt.default.relative(i,s).split(zt.default.sep).join("/"),content:l?c.slice(0,kw):c,truncated:l}}catch(c){return{ok:!1,error:c instanceof Error?c.message:"could not read the file"}}}var _e=E(Me(),1);var qc=E(require("node:fs"),1),Tw=E(require("node:path"),1);ht();Te();var GE=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),VE=k.array(GE);function Rw(){return Tw.default.join(X(),"synced-projects.json")}function Iw(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));qc.default.mkdirSync(X(),{recursive:!0}),qc.default.writeFileSync(Rw(),JSON.stringify(e,null,2),{mode:384})}catch{}}function ZE(){try{let t=VE.safeParse(JSON.parse(qc.default.readFileSync(Rw(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Ew(t){return ZE().find(e=>e.repoName===t)??null}xs();So();Es();var wh=E(require("node:fs"),1),Ds=E(require("node:path"),1),Aw=require("node:child_process"),Ls=E(Me(),1);Te();Es();var JE=15e4,bh=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function YE(t){let e=Ds.default.join(t,"node_modules",".bin","prisma");return wh.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function XE(t,e){if(!(0,Ls.isSelfMigrationFilename)(e))return null;let n=Ds.default.join(t,Ls.SELF_MIGRATION_DIR),r=Ds.default.resolve(n,e),s=Ds.default.relative(n,r);return s!==e||s.startsWith("..")||Ds.default.isAbsolute(s)?null:r}async function $w(t){let{file:e}=t,n=XE(t.repoPath,e);if(!n)return bh(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!wh.default.existsSync(n))return bh(e,{name:"file",ok:!1,detail:`${Ls.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Ls.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=cn(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return bh(e,{name:"database url",ok:!1,detail:`no ${t.urlSecret} in this runner's secret store for "${t.repoName}:${t.environmentName}" - the value stays on this machine`,fix:[`allwright env set ${t.repoName} ${t.environmentName} "${t.urlSecret}=postgresql://\u2026"`]},`this runner has no ${t.urlSecret} for "${t.environmentName}"`);let i=Ds.default.join(t.repoPath,"apps","api"),{bin:a,prefix:c}=YE(i),l=Is([s]),u=await QE(a,[...c,"db","execute","--url",s,"--file",n],i),p=l(u.output).slice(-8e3);return u.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${u.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${u.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Ls.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function QE(t,e,n){return new Promise(r=>{(0,Aw.execFile)(t,e,{cwd:n,timeout:JE,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,a)=>{let c=[i,a].filter(Boolean).join(`
1695
1695
  `).trim();if(!s)return r({code:0,output:c});let l=typeof s.code=="number"?s.code:1;r({code:l||1,output:c||s.message})})})}var v$=E(Tv(),1),k$=E(Jc(),1),S$=E(Oi(),1),_$=E($h(),1),x$=E(Nh(),1),T$=E(Lh(),1),jv=E(el(),1),R$=E(Nv(),1);var qh=jv.default;var Vo=E(require("node:crypto"),1),Ut=E(Me(),1);ot();function I$(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function nl(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function E$(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let u=Ut.ProjectConfig.safeParse(l);u.success?r.push(u.data):nl(n,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let u=Ut.RuleConfig.safeParse(l);u.success?s.push(u.data):nl(n,"rule",I$(l),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let u=Ut.EnvironmentConfig.safeParse(l);u.success?i.push(u.data):nl(n,"environment","",u.error.issues[0]?.message??"invalid shape")}let a=[];for(let l of Array.isArray(e.monitors)?e.monitors:[]){let u=Ut.MonitorCheckConfig.safeParse(l);u.success?a.push(u.data):nl(n,"monitor check","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,monitors:a,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var A$=2e4,$$=6e4,C$=5e3,rl=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===qh.OPEN}connect(){if(this.closed)return;b.info(`connecting to control plane at ${this.wsUrl}`);let e=new qh(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Ut.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},A$)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){b.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Ut.parseServerMsg)(r)}catch(i){let a=E$(r);if(!a){b.warn(`ignoring malformed server message: ${i}`);return}for(let c of a.warnings)b.warn(c);b.warn(`config push had ${a.warnings.length} ${a.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=a.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)b.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){b.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);b.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,$$)}),e.on("error",n=>{b.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,b.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="selfmigration.apply")return this.events.onSelfMigrationApply(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.explain")return this.events.onAuditExplain(e);if(e.type==="chat.cancel")return this.events.onChatCancel(e);if(e.type==="chat.diagnostic")return this.events.onChatDiagnostic(e);if(e.type==="chat.step.run")return this.events.onChatStepRun(e);if(e.type==="autopilot.plan")return this.events.onAutopilotPlan(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="jira.versions")return this.events.onJiraVersions(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="server.inventory")return this.events.onServerInventory(e);if(e.type==="server.decommission.plan")return this.events.onServerDecommissionPlan(e);if(e.type==="site.audit")return this.events.onSiteAudit(e);if(e.type==="rebirth.upload.begin")return this.events.onRebirthUploadBegin(e);if(e.type==="rebirth.design")return this.events.onRebirthDesign(e);if(e.type==="rebirth.upload.chunk")return this.events.onRebirthUploadChunk(e);if(e.type==="server.decommission.execute")return this.events.onServerDecommissionExecute(e);if(e.type==="timeline.digest")return this.events.onTimelineDigest(e);if(e.type==="rebirth.study")return this.events.onRebirthStudy(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.ask")return this.events.onSetupAsk(e);if(e.type==="setup.recheck")return this.events.onSetupRecheck(e);if(e.type==="repo.unmap")return this.events.onRepoUnmap(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="runner.uninstall")return this.events.onRunnerUninstall(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="run.answer")return this.events.onRunAnswer(e);if(e.type==="audit.stats")return this.events.onAuditStats(e);if(e.type==="monitor.run")return this.events.onMonitorRun(e);if(e.type==="monitor.discover")return this.events.onMonitorDiscover(e);if(e.type==="monitor.rebaseline")return this.events.onMonitorRebaseline(e);if(e.type==="monitor.suggest")return this.events.onMonitorSuggest(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=C$){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Vo.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Vo.default.randomUUID(),n=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:Vo.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Vo.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??"",fixTicketSummary:n.fixTicketSummary??"",fixTicketDescription:n.fixTicketDescription??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,outputTruncated:n.outputTruncated??!1,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,ownerUserId:n.ownerUserId??"",agentId:n.agentId??"",messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??0,tokens:r.tokens??0}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,ok:n.ok,browseBaseUrl:n.browseBaseUrl??"",columns:n.columns.map(r=>({name:r.name,issues:r.issues.map(s=>({key:s.key,summary:s.summary,labels:s.labels,components:s.components??[],fixVersions:s.fixVersions??[]}))})),...n.error!==void 0?{error:n.error}:{}})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical",costUsd:r.costUsd??0,inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0}))})}sendChatStepRunResult(e,n){this.send({type:"chat.step.run.result",requestId:e,ok:n.ok,stepName:n.stepName??"",commandLine:n.commandLine??"",exitCode:n.exitCode??0,timedOut:n.timedOut??!1,output:n.output??"",error:n.error??""})}sendChatDiagnosticResult(e,n){this.send({type:"chat.diagnostic.result",requestId:e,ok:n.ok,commandLine:n.commandLine??"",output:n.output??""})}sendAutopilotPlanResult(e,n){this.send({type:"autopilot.plan.result",requestId:e,ok:n.ok,error:n.error??"",order:n.order??[],chains:n.chains??[],dependencies:n.dependencies??[],reasoning:n.reasoning??""})}sendAuditExplainResult(e,n){this.send({type:"audit.explain.result",requestId:e,ok:n.ok,error:n.error??"",explanation:n.explanation??""})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendRunnerUninstallResult(e,n){this.send({type:"runner.uninstall.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",serviceRemoved:n.serviceRemoved??!1,configRemoved:n.configRemoved??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??"",truncated:n.truncated??!1})}sendRunContext(e){this.send({type:"run.context",runId:e.runId,pieces:e.pieces.slice(0,30),totalChars:e.totalChars,sessionMode:e.sessionMode})}sendSetupAskResult(e,n){this.send({type:"setup.ask.result",requestId:e,ok:n.ok,error:n.error,answer:n.answer??""})}sendRepoUnmapResult(e,n){this.send({type:"repo.unmap.result",requestId:e,ok:n.ok,error:n.error??"",removedPath:n.removedPath??""})}sendSetupRecheckResult(e,n){this.send({type:"setup.recheck.result",requestId:e,ok:n.ok,error:n.error??"",checks:(n.checks??[]).map(r=>({environment:r.environment??"",question:r.question,ok:r.ok,detail:r.detail??"",blocking:r.blocking??!0}))})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendServerInventoryResult(e,n){this.send({type:"server.inventory.result",requestId:e,...n})}sendRebirthStudyResult(e,n){this.send({type:"rebirth.study.result",requestId:e,...n})}sendSiteAuditResult(e,n){this.send({type:"site.audit.result",requestId:e,...n})}sendRebirthDesignResult(e,n){this.send({type:"rebirth.design.result",requestId:e,...n})}sendRebirthUploadBeginResult(e,n){this.send({type:"rebirth.upload.begin.result",requestId:e,uploadId:"",...n})}sendRebirthUploadChunkResult(e,n){this.send({type:"rebirth.upload.chunk.result",requestId:e,storedPath:"",note:"",...n})}sendServerDecommissionPlanResult(e,n){this.send({type:"server.decommission.plan.result",requestId:e,...n})}sendServerDecommissionResult(e,n){this.send({type:"server.decommission.result",requestId:e,...n})}sendServerDecommissionProgress(e){this.send({type:"server.decommission.progress",...e})}sendTimelineDigestResult(e,n){this.send({type:"timeline.digest.result",requestId:e,...n})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,serviceProtected:n.serviceProtected,serviceProtectFix:n.serviceProtectFix??"",jiraEmail:n.jiraEmail??"",agents:n.agents??{},claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}sendJiraVersionsResult(e,n){this.send({type:"jira.versions.result",requestId:e,ok:n.ok,error:n.error??"",versions:n.versions})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var sl=E(require("node:fs"),1),Fi=E(require("node:path"),1),Fh=require("node:child_process"),P$=/\.mdx?$/i,Mv=6,N$=/^[\w.\- ()]+$/;function j$(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Fi.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!P$.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Mv)return{ok:!1,error:`path deeper than ${Mv} levels`};for(let a of r)if(a==="."||a===".."||!N$.test(a))return{ok:!1,error:`invalid path segment "${a}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Fi.default.resolve(t),i=Fi.default.resolve(s,n);return i!==s&&!i.startsWith(s+Fi.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Bh(t){let e=j$(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(sl.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};sl.default.mkdirSync(Fi.default.dirname(e.abs),{recursive:!0}),sl.default.writeFileSync(e.abs,t.content.endsWith(`
1696
1696
  `)?t.content:t.content+`
1697
- `);let n=i=>new Promise((a,c)=>{(0,Fh.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(l,u,p)=>l?c(new Error(p||l.message)):a())}),r="";try{r=await new Promise((i,a)=>(0,Fh.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(c,l,u)=>c?a(new Error(u||c.message)):i(l.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var Ks=E(require("node:fs"),1),Hh=E(require("node:path"),1),il=require("node:child_process"),zv=require("node:util");Te();To();Es();ys();Pt();dn();var Dv=E(Me(),1),Ov=(0,zv.promisify)(il.execFile);function M$(t){try{return new URL(t).host}catch{return t}}function O$(t){try{return(0,il.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function ol(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,a=i??t.jira,c=(e.jiraSiteUrl??"").trim().toLowerCase();if(!a)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner",fix:["allwright jira set-default"],fixNote:"A server set up with `allwright init --no-jira` has none on purpose - that is fine for a machine that only deploys, but this project polls a board, so it needs one. The command asks for the Jira base URL, an account email and an API token (id.atlassian.com -> Security -> API tokens), and applies live."});else if(!c)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let f=M$(a.baseUrl),m=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(f!==c)s.push({name:"jira-site",ok:!1,detail:`this project is on ${c}, but ${m} is for ${f}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${c}: the base URL (https://${c}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Ye(a);try{let S=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${S.displayName} on ${f} (${m})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(T){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Zo(T)}`})}}catch(S){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Zo(S)}`})}}}let l=t.repos[e.repoName];if(l&&Ks.default.existsSync(l.path)){let f=Hh.default.join(l.path,"CLAUDE.md"),m=Ks.default.existsSync(f)&&Ks.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:m,detail:m?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...m?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Mo(l.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!l)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Ks.default.existsSync(l.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${l.path}`});else{let f=Ks.default.existsSync(Hh.default.join(l.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${l.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let m=We(t,f),w=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:S}=await Ov(m,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:S.trim().slice(0,100)})}catch(S){s.push({name:w,ok:!1,detail:`cannot run "${m}" for agent "${f}": ${Zo(S)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await Ov("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:f.trim().slice(0,100)})}catch(f){s.push({name:"git",ok:!1,detail:`cannot run git: ${Zo(f)}`})}let p=st(t,e.repoName);if(!p)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${Dv.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:f}=await Promise.resolve().then(()=>(Yt(),gs)),m=new f(p),w=await m.whoami(),S=l&&Ks.default.existsSync(l.path)?O$(l.path):null,T=S?Jt(S):null;if(!T)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let x=await m.repoAccess(T.owner,T.repo);s.push({name:"github-token",ok:x.ok&&x.canPush,detail:x.ok?x.canPush?`${w} has push access to ${T.owner}/${T.repo}`:`${w} can read ${T.owner}/${T.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${T.owner}/${T.repo}: ${x.error}`,...x.ok&&x.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${T.owner}/${T.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:Zo(f)})}if(n.length){t.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let f of n){let m=cn(t,e.repoName,f.name),w=f.requiredSecrets.filter(S=>!m[S]&&!process.env[S]);s.push({name:`env:${f.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${w[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function Zo(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}ot();Ja();Mc();Zh();var HC=300,Wk=9e5,KC=45e3,Gk=6,WC="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls. You are close to the end of the budget for this question, so ANSWER NOW with what you have, marking anything you could not verify - a useful partial answer beats none. Finish exactly as the original instructions asked.",GC="You stopped because the session hit its turn limit - nothing failed, and there is still time on this question. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls, and go where the evidence is rather than reading broadly. Finish exactly as the original instructions asked.",VC=15e4,ZC=3e5;function JC(t){try{let{packs:e,lessons:n}=fi("compose",t),r=[e.map(s=>`### ${s.name}
1697
+ `);let n=i=>new Promise((a,c)=>{(0,Fh.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(l,u,p)=>l?c(new Error(p||l.message)):a())}),r="";try{r=await new Promise((i,a)=>(0,Fh.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(c,l,u)=>c?a(new Error(u||c.message)):i(l.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var Ks=E(require("node:fs"),1),Hh=E(require("node:path"),1),il=require("node:child_process"),zv=require("node:util");Te();To();Es();ys();Pt();dn();var Dv=E(Me(),1),Ov=(0,zv.promisify)(il.execFile);function M$(t){try{return new URL(t).host}catch{return t}}function O$(t){try{return(0,il.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function ol(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,a=i??t.jira,c=(e.jiraSiteUrl??"").trim().toLowerCase();if(!a)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner",fix:["allwright jira set-default"],fixNote:"A server set up with `allwright init --no-jira` has none on purpose - that is fine for a machine that only deploys, but this project polls a board, so it needs one. The command asks for the Jira base URL, an account email and an API token (id.atlassian.com -> Security -> API tokens), and applies live."});else if(!c)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let f=M$(a.baseUrl),m=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(f!==c)s.push({name:"jira-site",ok:!1,detail:`this project is on ${c}, but ${m} is for ${f}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${c}: the base URL (https://${c}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Xe(a);try{let S=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${S.displayName} on ${f} (${m})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(T){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Zo(T)}`})}}catch(S){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Zo(S)}`})}}}let l=t.repos[e.repoName];if(l&&Ks.default.existsSync(l.path)){let f=Hh.default.join(l.path,"CLAUDE.md"),m=Ks.default.existsSync(f)&&Ks.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:m,detail:m?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...m?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Mo(l.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!l)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Ks.default.existsSync(l.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${l.path}`});else{let f=Ks.default.existsSync(Hh.default.join(l.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${l.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let m=We(t,f),w=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:S}=await Ov(m,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:S.trim().slice(0,100)})}catch(S){s.push({name:w,ok:!1,detail:`cannot run "${m}" for agent "${f}": ${Zo(S)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await Ov("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:f.trim().slice(0,100)})}catch(f){s.push({name:"git",ok:!1,detail:`cannot run git: ${Zo(f)}`})}let p=st(t,e.repoName);if(!p)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${Dv.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:f}=await Promise.resolve().then(()=>(Yt(),gs)),m=new f(p),w=await m.whoami(),S=l&&Ks.default.existsSync(l.path)?O$(l.path):null,T=S?Jt(S):null;if(!T)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let x=await m.repoAccess(T.owner,T.repo);s.push({name:"github-token",ok:x.ok&&x.canPush,detail:x.ok?x.canPush?`${w} has push access to ${T.owner}/${T.repo}`:`${w} can read ${T.owner}/${T.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${T.owner}/${T.repo}: ${x.error}`,...x.ok&&x.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${T.owner}/${T.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:Zo(f)})}if(n.length){t.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let f of n){let m=cn(t,e.repoName,f.name),w=f.requiredSecrets.filter(S=>!m[S]&&!process.env[S]);s.push({name:`env:${f.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${w[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function Zo(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}ot();Ja();Mc();Zh();var HC=300,Wk=9e5,KC=45e3,Gk=6,WC="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls. You are close to the end of the budget for this question, so ANSWER NOW with what you have, marking anything you could not verify - a useful partial answer beats none. Finish exactly as the original instructions asked.",GC="You stopped because the session hit its turn limit - nothing failed, and there is still time on this question. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls, and go where the evidence is rather than reading broadly. Finish exactly as the original instructions asked.",VC=15e4,ZC=3e5;function JC(t){try{let{packs:e,lessons:n}=fi("compose",t),r=[e.map(s=>`### ${s.name}
1698
1698
  ${s.content}`).join(`
1699
1699
 
1700
1700
  `).slice(0,4e3),n.trim().slice(-4e3)].filter(Boolean).join(`
@@ -1708,8 +1708,8 @@ ${r}
1708
1708
 
1709
1709
  ${e.length>8e3?`\u2026
1710
1710
 
1711
- ${e.slice(-8e3)}`:e}`}var Ke=new Tp;Ke.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(Sc);function Vk(t){b.info(`Create the token at ${_e.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of _e.GITHUB_TOKEN_PERMISSIONS.steps)b.info(` - ${e}`);b.info(_e.GITHUB_TOKEN_PERMISSIONS.note),b.info(`Then paste it below for ${t}.`)}Ke.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",Vs.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=Er.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let a=await e.question(`${r}: `);if(!a.trim())throw new Error(`${r} is required`);return a.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=Ib(t),a=i==="skip";i==="offer-skip"&&(b.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."),a=Eb(await e.question('Connect Jira now? [Enter = yes, or type "skip" for a deploy-only server]: ')));let c=a?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)},l=Fl.parse({controlPlaneUrl:r,runnerName:t.name,jira:c});if(l.jira){let u=await new Ye(l.jira).myself();b.info(`Jira credential OK - authenticated as ${u.displayName}`)}l=await Tb(l,s),b.info(`Enrolled as runner "${l.runnerName}" (${l.runnerId})`),b.info(`Credentials saved to ${En()} (mode 600, this machine only)`),l.jira||b.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)."),b.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var ap=Ke.command("repo").description("Map control-plane repo names to local checkouts");ap.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=ge(),s=nn.default.resolve(e.replace(/^~(?=\/|$)/,Vs.default.homedir()));if(!n.force){if(!Ge.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(!Ge.default.existsSync(nn.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},xe(r),b.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(dn(),Gf));b.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{b.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}Bt()||b.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.`)});ap.command("list").description("Show configured repo mappings").action(()=>{let t=ge(),e=Object.entries(t.repos);if(!e.length)return b.info("no repos mapped yet");for(let[n,r]of e)b.info(`${n} -> ${r.path}`)});var Zk=Ke.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Zk.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=ge(),n=e.claudeProfiles[t]?.configDir??`${En().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ge.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},xe(e),b.info(`profile "${t}" -> ${n}`),b.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),b.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,rn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),b.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),Bt()});Zk.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ge(),e=Object.entries(t.claudeProfiles);if(b.info("default: this OS user's own Claude login (no profile)"),!e.length)return b.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=Ge.default.existsSync(r.configDir)&&Ge.default.readdirSync(r.configDir).length>0;b.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});ap.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=ge();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),xe(e),b.info(`Removed "${t}" (was ${n})`),r.length&&b.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&b.info("Also removed its audit schedule(s)"),b.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),b.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var cp=Ke.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");cp.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){b.info(`
1712
- `+Tc(xc()));return}Vd(b)});cp.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(()=>Jd(b));cp.command("status").description("systemctl status for the runner service").action(()=>{(0,rn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Ke.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()=>{b.info("Updating: npm install -g allwright@latest");let t=(0,rn.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)}),b.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Wi=Ke.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Wi.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=ge();if(!e.repos[t]){let c=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${c}. Run \`allwright repo add\` first.`)}let n=Ew(t),r=(n?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let c={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let l=await new Ye(c).myself();if(e.repos[t].jira=c,xe(e),b.info(`The token already on this server works on ${r} - authenticated as ${l.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Ye(c).search(`project = "${n.jiraProjectKey}"`,1),b.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{b.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.`)}Bt();return}catch{b.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let a=Er.default.createInterface({input:process.stdin,output:process.stdout});try{let l=(await a.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await a.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await a.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!l||!p||!f)throw new Error("all three values are required");let m={baseUrl:l,email:p,apiToken:f},w=await new Ye(m).myself();b.info(`Jira credential OK - authenticated as ${w.displayName} on ${l}`),e.repos[t].jira=m,xe(e),b.info(`Saved: repo "${t}" now polls ${l} (other repos keep the runner-wide credential)`),Bt()}finally{a.close()}});Wi.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=ge(),e=Er.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,a=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!a)throw new Error("all three values are required");let c={baseUrl:s,email:i,apiToken:a},l=await new Ye(c).myself();t.jira=c,xe(t),b.info(`Jira credential OK - authenticated as ${l.displayName} on ${s}`),b.info(`Saved to ${En()} (mode 600, this machine only). Repo overrides are untouched.`),Bt()}finally{e.close()}});Wi.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ge();b.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))b.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Wi.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=ge(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Er.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 a=[e.jira,...Object.values(e.repos).map(u=>u.jira)].filter(u=>!!u),c=new Set,l=!1;for(let u of a)if(!c.has(u.baseUrl)){c.add(u.baseUrl);try{let p=await new Ye({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();b.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),l=!0}catch{b.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!l)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},xe(e),b.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Wi.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ge(),e=Object.entries(t.jiraUsers);if(!e.length)return b.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)b.info(`${n} -> posts to Jira as ${r.email}`)});Wi.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ge(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],xe(e),b.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Gi=Ke.command("github").description("GitHub credential for implement-mode rules");Gi.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=Er.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Vk("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(()=>(Yt(),gs)),s=await new r(n).whoami(),i=ge();i.github={token:n,login:s},xe(i),b.info(`GitHub token OK - authenticated as ${s}`),b.info(`Saved to ${En()} (mode 600, this machine only)`)}finally{e.close()}});Gi.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=ge();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&&Ge.default.existsSync(r))try{let i=(0,rn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),a=Jt(i);if(a){let{GitHubClient:c}=await Promise.resolve().then(()=>(Yt(),gs)),l=new c(n),u=await l.repoAccess(a.owner,a.repo);if(u.ok&&u.canPush){let p=await l.whoami();b.info(`The shared token on this server already has push access to ${a.owner}/${a.repo} as ${p} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),b.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Er.default.createInterface({input:process.stdin,output:process.stdout});try{Vk(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){b.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:a}=await Promise.resolve().then(()=>(Yt(),gs)),c=await new a(i).whoami();e.repos[t].github={token:i,login:c},xe(e),b.info(`GitHub token OK - authenticated as ${c}`),b.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Gi.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=ge(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Er.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(()=>(Yt(),gs)),a=await new i(s).whoami();e.githubUsers[n]={token:s,login:a},xe(e),b.info(`GitHub token OK - authenticated as ${a}`),b.info(`Saved. Implement runs triggered by ${n} now open PRs as ${a}. No restart needed.`)}finally{r.close()}});Gi.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ge(),e=Object.entries(t.githubUsers);if(!e.length)return b.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)b.info(`${n} -> own GitHub token stored`)});Gi.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ge(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],xe(e),b.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Gi.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ge();b.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))b.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);b.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var lp=Ke.command("audit").description("Recurring specialist audits on this runner");lp.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=ge();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}],xe(r),b.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});lp.command("schedules").description("List scheduled audits").action(()=>{let t=ge();if(!t.auditSchedules.length)return b.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)b.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});lp.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ge(),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");xe(n),b.info("Removed. Restart the runner to apply.")});var up=Ke.command("deploy").description("Deployment settings for this machine");up.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=ge();t.deploy={enabled:!0},xe(t),b.info("deployments ENABLED on this runner"),b.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),Bt()});up.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ge();t.deploy={enabled:!1},xe(t),b.info("deployments DISABLED on this runner"),Bt()});up.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ge();b.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return b.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);b.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var bl=Ke.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");bl.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=ge(),s=ba(t,e),i=r.environments[s]??{secrets:{}},a=[];for(let c of n){let l=c.indexOf("=");if(l<=0)throw new Error(`expected KEY=VALUE, got "${c}"`);let u=c.slice(0,l).trim();i.secrets[u]=c.slice(l+1),a.push(u)}r.environments[s]=i,xe(r),b.info(`stored ${a.length} secret(s) for ${s}: ${a.join(", ")}`),b.info(`Saved to ${En()} (mode 600, this machine only)`),Bt()});bl.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=ge().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:a}=await Promise.resolve().then(()=>(tk(),ek));await a({repoName:t,envName:e,dir:nn.default.resolve(i.replace(/^~(?=\/|$)/,Vs.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});bl.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ge(),s=ba(t,e),i=r.environments[s];if(!i)return b.info(`nothing stored for ${s}`);for(let a of n)delete i.secrets[a];r.environments[s]=i,xe(r),b.info(`removed ${n.join(", ")} from ${s}`)});bl.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ge(),e=Object.entries(t.environments);if(!e.length)return b.info("no environment secrets stored");for(let[n,r]of e)b.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Ke.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=qp(t);b.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),b.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),b.info(`Restore on any machine with: allwright import ${nn.default.basename(e.file)}`)}catch(e){b.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Ke.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Ps();if(e&&Ns(e)){b.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=Fp(t);b.info(`Restored ${n.restored.length} entries into ${X()}`),n.previousDir&&b.info(`Previous config kept at ${n.previousDir}`),b.info("Start the runner and it will reconnect with the restored identity.")}catch(n){b.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Ke.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=ge(),s=_e.REGISTERED_AGENTS.map(a=>a.id);if(t==="list"){for(let a of _e.REGISTERED_AGENTS){let c=We(r,a.id),l=r.agents[a.id]?.bin?" (set here)":" (default: its own id)",u="";try{u=(0,rn.execFileSync)(c,["--version"],{timeout:1e4,encoding:"utf8"}).trim().slice(0,60)}catch{u="not runnable on this machine"}b.info(`${a.id}: ${c}${l} - ${u}`)}return}if(!e||!s.includes(e)){b.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],xe(r),b.info(`${e} is back to its default binary ("${e}" on PATH).`),Bt();return}if(t!=="set-bin"||!n){b.error("usage: allwright agent list | set-bin <agentId> <path> | clear-bin <agentId>"),process.exitCode=1;return}let i="";try{i=(0,rn.execFileSync)(n,["--version"],{timeout:15e3,encoding:"utf8"}).trim()}catch(a){b.error(`"${n}" did not answer \`--version\` (${a instanceof Error?a.message:a}) - nothing was saved. Check the path, or that the binary is executable by this user.`),process.exitCode=1;return}r.agents[e]={bin:n},xe(r),b.info(`${e} now runs as "${n}" (${i.slice(0,60)}) on this machine.`),Bt()});Ke.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=ge();if(t==="on"||t==="off"){e.operatorEnabled=t==="on",xe(e),t==="on"?b.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`."):b.info("operator mode DISABLED on this machine - Compose is back to read-only here."),Bt();return}if(t==="status"){b.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=vw();if(!n.length){b.info("no operator turns have run on this machine.");return}for(let r of n){b.info(`${r.at} ${r.userName||r.userId||"someone"} [${r.sessionId}] asked: ${r.ask}`);for(let s of r.commands)b.info(` - ${s}`)}return}b.error(`unknown action "${t}" - use on | off | status | log`),process.exitCode=1});Ke.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ge(),e=Object.keys(t.repos),n=eo(t);n&&b.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 a=await ol(t,i),c=!Qi(t,i.repoName);for(let l of a){if(i.jiraProjectKey==="*"&&l.name==="jira-project")continue;if(c&&l.name==="jira-credentials"){n||b.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=l.ok?"PASS":"FAIL";(l.ok?b.info:b.error)(`[${u}] ${l.name}: ${l.detail}`),s&&=l.ok}}s||(process.exitCode=1)});function Bt(){let t=Ps()??$i();if(t&&Ns(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),b.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?_b(t):null;return b.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 XC(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Sb();e.ok||(b.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",Hd);let n=t.jira?new Ye(t.jira):od(),r=new Map,s=d=>{let g=t.repos[d]?.jira;if(!g)return n;let y=r.get(d);return y||(y=new Ye(g),r.set(d,y)),y},i=new Map,a=(d,g)=>{let y=Rb(ke()??t,d,g);switch(y.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:y.error};case"user":{let _=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,M=i.get(_);return M||(M=new Ye(y.creds),i.set(_,M)),{jira:M,authored:!0}}}},c=new URL("/api/runner/ws",t.controlPlaneUrl);c.protocol=c.protocol==="https:"?"wss:":"ws:";let l=[],u=[],p=[],f,m=null,w={cfg:t,jiraFor:s,transport:null},S=new Set,T=async(d,g,y)=>{if(!(g.length<2))for(let _=0;_<g.length;_++){let{text:M,changed:O}=Ab(y[_]??"",g);O&&await d.updateDescription(g[_],M).then(()=>b.info(`Compose: rewrote sibling ticket refs in ${g[_]} to real keys`)).catch(B=>b.warn(`Compose: could not rewrite refs in ${g[_]}: ${B instanceof Error?B.message:B}`))}},x=d=>{let g=l.find(_=>_.id===d),y=g&&t.repos[g.repoName];return g&&y?{project:g,repoPath:y.path}:null},A=d=>{let g=l.find(M=>M.id===d),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!g)return`${y} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let _=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${g.name}" (repo "${g.repoName}"). Repos mapped here: ${_}. 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 ${g.repoName} /path/to/checkout`},D={cfg:t,jiraFor:s,get transport(){return w.transport},lookup:(d,g)=>{let y=x(d),_=p.find(M=>M.projectId===d&&M.name===g);return y&&_?{...y,environment:_}:null}},K=new Map,C=new Set,$=null,v=new rl(c.toString(),t.runnerToken,{runnerVersion:Sc},{onConfig:d=>{l=d.projects,Iw(d.projects),u=d.rules,p=d.environments,wg(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments),$?.setMonitors(d.monitors)},onDeployFix:async d=>{let g=x(d.projectId);if(!g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let _=await Pd({agent:y,repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,_)},onProjectTest:async d=>{let g=l.find(_=>_.id===d.projectId);if(!g){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}b.info(`running connection test for project "${g.name}"`);let y=await ol(ke()??t,g,p.filter(_=>_.projectId===g.id),u.filter(_=>_.projectId===g.id).map(_=>"agent"in _.action?_.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,y.every(_=>_.ok),y)},onRuleDiagnose:async d=>{let g=u.find(N=>N.id===d.ruleId),y=g&&l.find(N=>N.id===g.projectId);if(!g||!y){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}b.info(`diagnosing rule "${g.name}"`);let _=await ol(ke()??t,y,g.action.type==="deploy"?p.filter(N=>N.projectId===y.id):[]),M=g.action.type==="implement"?_:_.filter(N=>N.name!=="github-token"),{matchedCount:O,excludedCount:B,excludedSample:Y}=await f.diagnoseRule(g,y);v.sendRuleDiagnoseResult(d.requestId,{checks:M,matchedCount:O,excludedCount:B,excludedSample:Y})},onCancel:d=>{ey(d)?b.info(`run ${d} stopped from the dashboard`):b.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,g)=>{if(ac(d)){Ad(D,d).catch(y=>b.error(`deploy approval crashed for ${d}: ${y instanceof Error?y.stack:y}`));return}No(w,d,g).catch(y=>b.error(`approval handling crashed for ${d}: ${y instanceof Error?y.stack:y}`))},onRetryPush:d=>{let g=bi(d),y=()=>ay(w,d).catch(_=>b.error(`retry push crashed for ${d}: ${_ instanceof Error?_.stack:_}`));g?f.runOnRepoQueue(g.baseRepoPath,y):y()},onRejected:d=>{if(ac(d)){$d(D,d).catch(g=>b.error(`deploy rejection crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}oy(w,d).catch(g=>b.error(`rejection handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onDeployStart:d=>{let g=`${d.runId}#${d.attempt}`;if(S.has(g))return;S.add(g);let y=x(d.projectId);if(!y){let _=A(d.projectId);b.error(`deploy ${d.runId}: ${_}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:_});return}b.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>jo({runId:d.runId,project:y.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(_=>b.error(`deploy crashed for ${d.runId}: ${_ instanceof Error?_.stack:_}`)))},onDeploySuggest:async d=>{let g=x(d.projectId);if(!g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`asking ${y.adapter.displayName} for "${d.environmentName}" deploy steps in ${g.repoPath}`);let _=await Nd({agent:y,repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,_)},onEnvPreflight:async d=>{let g=x(d.projectId);if(!g){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await Cd({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});v.sendEnvPreflightResult(d.requestId,y)},onSelfMigrationApply:async d=>{let g=x(d.projectId);if(!g){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(d.projectId)});return}b.info(`applying migration ${d.file} for "${d.environmentName}"`);let y=await $w({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});b.info(y.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${y.error}`),v.sendSelfMigrationApplyResult(d.requestId,y)},onAutopilotPlan:async d=>{try{let g=x(d.projectId);if(!g){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let y=s(g.project.repoName),_=[];for(let U of d.issueKeys)try{let re=await y.getIssue(U);_.push(`${U}: ${re.summary}
1711
+ ${e.slice(-8e3)}`:e}`}var Ke=new Tp;Ke.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(Sc);function Vk(t){b.info(`Create the token at ${_e.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of _e.GITHUB_TOKEN_PERMISSIONS.steps)b.info(` - ${e}`);b.info(_e.GITHUB_TOKEN_PERMISSIONS.note),b.info(`Then paste it below for ${t}.`)}Ke.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",Vs.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=Er.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let a=await e.question(`${r}: `);if(!a.trim())throw new Error(`${r} is required`);return a.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=Ib(t),a=i==="skip";i==="offer-skip"&&(b.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."),a=Eb(await e.question('Connect Jira now? [Enter = yes, or type "skip" for a deploy-only server]: ')));let c=a?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)},l=Fl.parse({controlPlaneUrl:r,runnerName:t.name,jira:c});if(l.jira){let u=await new Xe(l.jira).myself();b.info(`Jira credential OK - authenticated as ${u.displayName}`)}l=await Tb(l,s),b.info(`Enrolled as runner "${l.runnerName}" (${l.runnerId})`),b.info(`Credentials saved to ${En()} (mode 600, this machine only)`),l.jira||b.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)."),b.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var ap=Ke.command("repo").description("Map control-plane repo names to local checkouts");ap.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=ge(),s=nn.default.resolve(e.replace(/^~(?=\/|$)/,Vs.default.homedir()));if(!n.force){if(!Ge.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(!Ge.default.existsSync(nn.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},xe(r),b.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(dn(),Gf));b.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{b.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}Bt()||b.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.`)});ap.command("list").description("Show configured repo mappings").action(()=>{let t=ge(),e=Object.entries(t.repos);if(!e.length)return b.info("no repos mapped yet");for(let[n,r]of e)b.info(`${n} -> ${r.path}`)});var Zk=Ke.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Zk.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=ge(),n=e.claudeProfiles[t]?.configDir??`${En().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ge.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},xe(e),b.info(`profile "${t}" -> ${n}`),b.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),b.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,rn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),b.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),Bt()});Zk.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ge(),e=Object.entries(t.claudeProfiles);if(b.info("default: this OS user's own Claude login (no profile)"),!e.length)return b.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=Ge.default.existsSync(r.configDir)&&Ge.default.readdirSync(r.configDir).length>0;b.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});ap.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=ge();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),xe(e),b.info(`Removed "${t}" (was ${n})`),r.length&&b.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&b.info("Also removed its audit schedule(s)"),b.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),b.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var cp=Ke.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");cp.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){b.info(`
1712
+ `+Tc(xc()));return}Vd(b)});cp.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(()=>Jd(b));cp.command("status").description("systemctl status for the runner service").action(()=>{(0,rn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Ke.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()=>{b.info("Updating: npm install -g allwright@latest");let t=(0,rn.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)}),b.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Wi=Ke.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Wi.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=ge();if(!e.repos[t]){let c=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${c}. Run \`allwright repo add\` first.`)}let n=Ew(t),r=(n?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let c={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let l=await new Xe(c).myself();if(e.repos[t].jira=c,xe(e),b.info(`The token already on this server works on ${r} - authenticated as ${l.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Xe(c).search(`project = "${n.jiraProjectKey}"`,1),b.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{b.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.`)}Bt();return}catch{b.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let a=Er.default.createInterface({input:process.stdin,output:process.stdout});try{let l=(await a.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await a.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await a.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!l||!p||!f)throw new Error("all three values are required");let m={baseUrl:l,email:p,apiToken:f},w=await new Xe(m).myself();b.info(`Jira credential OK - authenticated as ${w.displayName} on ${l}`),e.repos[t].jira=m,xe(e),b.info(`Saved: repo "${t}" now polls ${l} (other repos keep the runner-wide credential)`),Bt()}finally{a.close()}});Wi.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=ge(),e=Er.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,a=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!a)throw new Error("all three values are required");let c={baseUrl:s,email:i,apiToken:a},l=await new Xe(c).myself();t.jira=c,xe(t),b.info(`Jira credential OK - authenticated as ${l.displayName} on ${s}`),b.info(`Saved to ${En()} (mode 600, this machine only). Repo overrides are untouched.`),Bt()}finally{e.close()}});Wi.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ge();b.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))b.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Wi.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=ge(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Er.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 a=[e.jira,...Object.values(e.repos).map(u=>u.jira)].filter(u=>!!u),c=new Set,l=!1;for(let u of a)if(!c.has(u.baseUrl)){c.add(u.baseUrl);try{let p=await new Xe({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();b.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),l=!0}catch{b.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!l)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},xe(e),b.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Wi.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ge(),e=Object.entries(t.jiraUsers);if(!e.length)return b.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)b.info(`${n} -> posts to Jira as ${r.email}`)});Wi.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ge(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],xe(e),b.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Gi=Ke.command("github").description("GitHub credential for implement-mode rules");Gi.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=Er.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Vk("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(()=>(Yt(),gs)),s=await new r(n).whoami(),i=ge();i.github={token:n,login:s},xe(i),b.info(`GitHub token OK - authenticated as ${s}`),b.info(`Saved to ${En()} (mode 600, this machine only)`)}finally{e.close()}});Gi.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=ge();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&&Ge.default.existsSync(r))try{let i=(0,rn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),a=Jt(i);if(a){let{GitHubClient:c}=await Promise.resolve().then(()=>(Yt(),gs)),l=new c(n),u=await l.repoAccess(a.owner,a.repo);if(u.ok&&u.canPush){let p=await l.whoami();b.info(`The shared token on this server already has push access to ${a.owner}/${a.repo} as ${p} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),b.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Er.default.createInterface({input:process.stdin,output:process.stdout});try{Vk(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){b.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:a}=await Promise.resolve().then(()=>(Yt(),gs)),c=await new a(i).whoami();e.repos[t].github={token:i,login:c},xe(e),b.info(`GitHub token OK - authenticated as ${c}`),b.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Gi.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=ge(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Er.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(()=>(Yt(),gs)),a=await new i(s).whoami();e.githubUsers[n]={token:s,login:a},xe(e),b.info(`GitHub token OK - authenticated as ${a}`),b.info(`Saved. Implement runs triggered by ${n} now open PRs as ${a}. No restart needed.`)}finally{r.close()}});Gi.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ge(),e=Object.entries(t.githubUsers);if(!e.length)return b.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)b.info(`${n} -> own GitHub token stored`)});Gi.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ge(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],xe(e),b.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Gi.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ge();b.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))b.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);b.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var lp=Ke.command("audit").description("Recurring specialist audits on this runner");lp.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=ge();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}],xe(r),b.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});lp.command("schedules").description("List scheduled audits").action(()=>{let t=ge();if(!t.auditSchedules.length)return b.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)b.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});lp.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ge(),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");xe(n),b.info("Removed. Restart the runner to apply.")});var up=Ke.command("deploy").description("Deployment settings for this machine");up.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=ge();t.deploy={enabled:!0},xe(t),b.info("deployments ENABLED on this runner"),b.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),Bt()});up.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ge();t.deploy={enabled:!1},xe(t),b.info("deployments DISABLED on this runner"),Bt()});up.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ge();b.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return b.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);b.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var bl=Ke.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");bl.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=ge(),s=ba(t,e),i=r.environments[s]??{secrets:{}},a=[];for(let c of n){let l=c.indexOf("=");if(l<=0)throw new Error(`expected KEY=VALUE, got "${c}"`);let u=c.slice(0,l).trim();i.secrets[u]=c.slice(l+1),a.push(u)}r.environments[s]=i,xe(r),b.info(`stored ${a.length} secret(s) for ${s}: ${a.join(", ")}`),b.info(`Saved to ${En()} (mode 600, this machine only)`),Bt()});bl.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=ge().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:a}=await Promise.resolve().then(()=>(tk(),ek));await a({repoName:t,envName:e,dir:nn.default.resolve(i.replace(/^~(?=\/|$)/,Vs.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});bl.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ge(),s=ba(t,e),i=r.environments[s];if(!i)return b.info(`nothing stored for ${s}`);for(let a of n)delete i.secrets[a];r.environments[s]=i,xe(r),b.info(`removed ${n.join(", ")} from ${s}`)});bl.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ge(),e=Object.entries(t.environments);if(!e.length)return b.info("no environment secrets stored");for(let[n,r]of e)b.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Ke.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=qp(t);b.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),b.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),b.info(`Restore on any machine with: allwright import ${nn.default.basename(e.file)}`)}catch(e){b.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Ke.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Ps();if(e&&Ns(e)){b.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=Fp(t);b.info(`Restored ${n.restored.length} entries into ${X()}`),n.previousDir&&b.info(`Previous config kept at ${n.previousDir}`),b.info("Start the runner and it will reconnect with the restored identity.")}catch(n){b.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Ke.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=ge(),s=_e.REGISTERED_AGENTS.map(a=>a.id);if(t==="list"){for(let a of _e.REGISTERED_AGENTS){let c=We(r,a.id),l=r.agents[a.id]?.bin?" (set here)":" (default: its own id)",u="";try{u=(0,rn.execFileSync)(c,["--version"],{timeout:1e4,encoding:"utf8"}).trim().slice(0,60)}catch{u="not runnable on this machine"}b.info(`${a.id}: ${c}${l} - ${u}`)}return}if(!e||!s.includes(e)){b.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],xe(r),b.info(`${e} is back to its default binary ("${e}" on PATH).`),Bt();return}if(t!=="set-bin"||!n){b.error("usage: allwright agent list | set-bin <agentId> <path> | clear-bin <agentId>"),process.exitCode=1;return}let i="";try{i=(0,rn.execFileSync)(n,["--version"],{timeout:15e3,encoding:"utf8"}).trim()}catch(a){b.error(`"${n}" did not answer \`--version\` (${a instanceof Error?a.message:a}) - nothing was saved. Check the path, or that the binary is executable by this user.`),process.exitCode=1;return}r.agents[e]={bin:n},xe(r),b.info(`${e} now runs as "${n}" (${i.slice(0,60)}) on this machine.`),Bt()});Ke.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=ge();if(t==="on"||t==="off"){e.operatorEnabled=t==="on",xe(e),t==="on"?b.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`."):b.info("operator mode DISABLED on this machine - Compose is back to read-only here."),Bt();return}if(t==="status"){b.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=vw();if(!n.length){b.info("no operator turns have run on this machine.");return}for(let r of n){b.info(`${r.at} ${r.userName||r.userId||"someone"} [${r.sessionId}] asked: ${r.ask}`);for(let s of r.commands)b.info(` - ${s}`)}return}b.error(`unknown action "${t}" - use on | off | status | log`),process.exitCode=1});Ke.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ge(),e=Object.keys(t.repos),n=eo(t);n&&b.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 a=await ol(t,i),c=!Qi(t,i.repoName);for(let l of a){if(i.jiraProjectKey==="*"&&l.name==="jira-project")continue;if(c&&l.name==="jira-credentials"){n||b.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=l.ok?"PASS":"FAIL";(l.ok?b.info:b.error)(`[${u}] ${l.name}: ${l.detail}`),s&&=l.ok}}s||(process.exitCode=1)});function Bt(){let t=Ps()??$i();if(t&&Ns(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),b.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?_b(t):null;return b.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 XC(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Sb();e.ok||(b.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",Hd);let n=t.jira?new Xe(t.jira):od(),r=new Map,s=d=>{let g=t.repos[d]?.jira;if(!g)return n;let y=r.get(d);return y||(y=new Xe(g),r.set(d,y)),y},i=new Map,a=(d,g)=>{let y=Rb(ke()??t,d,g);switch(y.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:y.error};case"user":{let _=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,M=i.get(_);return M||(M=new Xe(y.creds),i.set(_,M)),{jira:M,authored:!0}}}},c=new URL("/api/runner/ws",t.controlPlaneUrl);c.protocol=c.protocol==="https:"?"wss:":"ws:";let l=[],u=[],p=[],f,m=null,w={cfg:t,jiraFor:s,transport:null},S=new Set,T=async(d,g,y)=>{if(!(g.length<2))for(let _=0;_<g.length;_++){let{text:M,changed:O}=Ab(y[_]??"",g);O&&await d.updateDescription(g[_],M).then(()=>b.info(`Compose: rewrote sibling ticket refs in ${g[_]} to real keys`)).catch(F=>b.warn(`Compose: could not rewrite refs in ${g[_]}: ${F instanceof Error?F.message:F}`))}},x=d=>{let g=l.find(_=>_.id===d),y=g&&t.repos[g.repoName];return g&&y?{project:g,repoPath:y.path}:null},A=d=>{let g=l.find(M=>M.id===d),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!g)return`${y} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let _=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${g.name}" (repo "${g.repoName}"). Repos mapped here: ${_}. 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 ${g.repoName} /path/to/checkout`},D={cfg:t,jiraFor:s,get transport(){return w.transport},lookup:(d,g)=>{let y=x(d),_=p.find(M=>M.projectId===d&&M.name===g);return y&&_?{...y,environment:_}:null}},K=new Map,C=new Set,$=null,v=new rl(c.toString(),t.runnerToken,{runnerVersion:Sc},{onConfig:d=>{l=d.projects,Iw(d.projects),u=d.rules,p=d.environments,wg(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments),$?.setMonitors(d.monitors)},onDeployFix:async d=>{let g=x(d.projectId);if(!g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let _=await Pd({agent:y,repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,_)},onProjectTest:async d=>{let g=l.find(_=>_.id===d.projectId);if(!g){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}b.info(`running connection test for project "${g.name}"`);let y=await ol(ke()??t,g,p.filter(_=>_.projectId===g.id),u.filter(_=>_.projectId===g.id).map(_=>"agent"in _.action?_.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,y.every(_=>_.ok),y)},onRuleDiagnose:async d=>{let g=u.find(P=>P.id===d.ruleId),y=g&&l.find(P=>P.id===g.projectId);if(!g||!y){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}b.info(`diagnosing rule "${g.name}"`);let _=await ol(ke()??t,y,g.action.type==="deploy"?p.filter(P=>P.projectId===y.id):[]),M=g.action.type==="implement"?_:_.filter(P=>P.name!=="github-token"),{matchedCount:O,excludedCount:F,excludedSample:Y}=await f.diagnoseRule(g,y);v.sendRuleDiagnoseResult(d.requestId,{checks:M,matchedCount:O,excludedCount:F,excludedSample:Y})},onCancel:d=>{ey(d)?b.info(`run ${d} stopped from the dashboard`):b.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,g)=>{if(ac(d)){Ad(D,d).catch(y=>b.error(`deploy approval crashed for ${d}: ${y instanceof Error?y.stack:y}`));return}No(w,d,g).catch(y=>b.error(`approval handling crashed for ${d}: ${y instanceof Error?y.stack:y}`))},onRetryPush:d=>{let g=bi(d),y=()=>ay(w,d).catch(_=>b.error(`retry push crashed for ${d}: ${_ instanceof Error?_.stack:_}`));g?f.runOnRepoQueue(g.baseRepoPath,y):y()},onRejected:d=>{if(ac(d)){$d(D,d).catch(g=>b.error(`deploy rejection crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}oy(w,d).catch(g=>b.error(`rejection handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onDeployStart:d=>{let g=`${d.runId}#${d.attempt}`;if(S.has(g))return;S.add(g);let y=x(d.projectId);if(!y){let _=A(d.projectId);b.error(`deploy ${d.runId}: ${_}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:_});return}b.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>jo({runId:d.runId,project:y.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(_=>b.error(`deploy crashed for ${d.runId}: ${_ instanceof Error?_.stack:_}`)))},onDeploySuggest:async d=>{let g=x(d.projectId);if(!g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`asking ${y.adapter.displayName} for "${d.environmentName}" deploy steps in ${g.repoPath}`);let _=await Nd({agent:y,repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,_)},onEnvPreflight:async d=>{let g=x(d.projectId);if(!g){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await Cd({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});v.sendEnvPreflightResult(d.requestId,y)},onSelfMigrationApply:async d=>{let g=x(d.projectId);if(!g){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(d.projectId)});return}b.info(`applying migration ${d.file} for "${d.environmentName}"`);let y=await $w({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});b.info(y.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${y.error}`),v.sendSelfMigrationApplyResult(d.requestId,y)},onAutopilotPlan:async d=>{try{let g=x(d.projectId);if(!g){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let y=s(g.project.repoName),_=[];for(let U of d.issueKeys)try{let re=await y.getIssue(U);_.push(`${U}: ${re.summary}
1713
1713
  ${(re.description||"").slice(0,500)}`)}catch{_.push(`${U}: (could not read from Jira)`)}let M=Ce(t,g.project,"assist");if("error"in M){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:M.error});return}let O=`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.
1714
1714
 
1715
1715
  `+_.join(`
@@ -1723,12 +1723,12 @@ Rules:
1723
1723
  - "order": every key exactly once. Prerequisites before the work that needs them.
1724
1724
  - "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.
1725
1725
  - "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
1726
- - "reasoning": 2-3 short lines a person can check your plan against.`,B=await M.adapter.run({repoPath:g.repoPath,prompt:O,timeoutSeconds:90,bin:M.bin,mode:"read_only",maxTurns:3,model:M.adapter.fastModel,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"autopilot_plan",projectId:g.project.id,agentId:M.adapter.id,refKind:"none",refLabel:`${d.issueKeys.length} tickets`,...ve(B)});let Y=uh(B.resultText,d.issueKeys);if(!Y){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:N}=await Promise.resolve().then(()=>(Mc(),Wb));N({batchId:d.batchId,projectId:d.projectId,order:Y.order,chains:Y.chains,dependencies:Y.dependencies,reasoning:Y.reasoning}),v.sendAutopilotPlanResult(d.requestId,{ok:!0,...Y})}catch(g){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatDiagnostic:async d=>{try{let{runDiagnostic:g}=await Promise.resolve().then(()=>(Zh(),Fv)),y=await g({command:d.command,args:d.args});b.info(`chat diagnostic (user-approved): ${y.commandLine}`),v.sendChatDiagnosticResult(d.requestId,y)}catch(g){v.sendChatDiagnosticResult(d.requestId,{ok:!1,output:g instanceof Error?g.message:String(g)})}},onChatStepRun:async d=>{let g=D.lookup(d.projectId,d.environmentName);if(!g){v.sendChatStepRunResult(d.requestId,{ok:!1,error:`this runner has no environment "${d.environmentName}" for that project`});return}let{environment:y}=g,_=y.steps[d.stepIndex];if(!_||_.name!==d.stepName){v.sendChatStepRunResult(d.requestId,{ok:!1,error:`step ${d.stepIndex+1} of "${y.name}" is ${_?`"${_.name}"`:"not there"} on this machine, not "${d.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let M=`${d.projectId}:${y.name}:${d.stepIndex}`;if(C.has(M)){v.sendChatStepRunResult(d.requestId,{ok:!1,stepName:_.name,error:"that step is already running here - wait for it to finish"});return}C.add(M),b.info(`chat step re-run (user-approved): [${y.name}] ${_.name}`);try{let{runSavedStep:O}=await Promise.resolve().then(()=>(Es(),Iy)),B=await O({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:y.name,workdir:y.workdir,branch:y.branch,step:_,cfg:t,timeoutMs:Math.min(y.timeoutSeconds*1e3,ZC)});v.sendChatStepRunResult(d.requestId,{ok:!0,stepName:_.name,...B})}catch(O){v.sendChatStepRunResult(d.requestId,{ok:!1,stepName:_.name,error:O instanceof Error?O.message:String(O)})}finally{C.delete(M)}},onChatCancel:d=>{let g=K.get(d.turnId);g&&(g.abort(),b.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let g=x(d.projectId);if(!g){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:A(d.projectId)});return}let y=d.sessionId||(0,Zn.randomUUID)(),_=!d.sessionId,M=d.sessionId?Os(d.sessionId):null,O=M?.agentId||d.agentId||g.project.defaultAgent||_e.DEFAULT_AGENT_ID;if(!_&&d.userId){let qe=M?.ownerUserId??"";if(qe&&qe!==d.userId){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 B=d.operator===!0;if(B&&!t.operatorEnabled){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 Y=_?0:M?.messages.length??0,N=!1,U=0,re="";if(!_&&Y>=uw){let qe=await pw(g,y,t);if(qe)N=!0,U=Y,re=qe,y=(0,Zn.randomUUID)(),_=!0,b.info(`chat compacted: ${Y} message(s) summarized into a fresh session`);else if(Y>=dw){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let j=d.files.length?Eg(g.repoPath,d.requestId,d.files):null,ee=(0,_e.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,_e.pendingMigrationsAppendix)(d.pendingMigrations)+(0,_e.monitorChecksAppendix)(d.monitorChecks)+(0,_e.deployTargetsAppendix)(d.environments)+(0,_e.savedStepChecksAppendix)(d.environmentSteps)+(0,_e.composeCommandAppendix)(d.command)+lw(d.sessionId??""),ae=JC(g.repoPath)+hr("compose",g.repoPath,{summary:d.message,ruleName:""});tc(g,t);let pe="```",$e=_?`You are the project assistant for "${g.project.name}" - this working directory is its repository, and you have read-only access.
1726
+ - "reasoning": 2-3 short lines a person can check your plan against.`,F=await M.adapter.run({repoPath:g.repoPath,prompt:O,timeoutSeconds:90,bin:M.bin,mode:"read_only",maxTurns:3,model:M.adapter.fastModel,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"autopilot_plan",projectId:g.project.id,agentId:M.adapter.id,refKind:"none",refLabel:`${d.issueKeys.length} tickets`,...ve(F)});let Y=uh(F.resultText,d.issueKeys);if(!Y){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:P}=await Promise.resolve().then(()=>(Mc(),Wb));P({batchId:d.batchId,projectId:d.projectId,order:Y.order,chains:Y.chains,dependencies:Y.dependencies,reasoning:Y.reasoning}),v.sendAutopilotPlanResult(d.requestId,{ok:!0,...Y})}catch(g){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatDiagnostic:async d=>{try{let{runDiagnostic:g}=await Promise.resolve().then(()=>(Zh(),Fv)),y=await g({command:d.command,args:d.args});b.info(`chat diagnostic (user-approved): ${y.commandLine}`),v.sendChatDiagnosticResult(d.requestId,y)}catch(g){v.sendChatDiagnosticResult(d.requestId,{ok:!1,output:g instanceof Error?g.message:String(g)})}},onChatStepRun:async d=>{let g=D.lookup(d.projectId,d.environmentName);if(!g){v.sendChatStepRunResult(d.requestId,{ok:!1,error:`this runner has no environment "${d.environmentName}" for that project`});return}let{environment:y}=g,_=y.steps[d.stepIndex];if(!_||_.name!==d.stepName){v.sendChatStepRunResult(d.requestId,{ok:!1,error:`step ${d.stepIndex+1} of "${y.name}" is ${_?`"${_.name}"`:"not there"} on this machine, not "${d.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let M=`${d.projectId}:${y.name}:${d.stepIndex}`;if(C.has(M)){v.sendChatStepRunResult(d.requestId,{ok:!1,stepName:_.name,error:"that step is already running here - wait for it to finish"});return}C.add(M),b.info(`chat step re-run (user-approved): [${y.name}] ${_.name}`);try{let{runSavedStep:O}=await Promise.resolve().then(()=>(Es(),Iy)),F=await O({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:y.name,workdir:y.workdir,branch:y.branch,step:_,cfg:t,timeoutMs:Math.min(y.timeoutSeconds*1e3,ZC)});v.sendChatStepRunResult(d.requestId,{ok:!0,stepName:_.name,...F})}catch(O){v.sendChatStepRunResult(d.requestId,{ok:!1,stepName:_.name,error:O instanceof Error?O.message:String(O)})}finally{C.delete(M)}},onChatCancel:d=>{let g=K.get(d.turnId);g&&(g.abort(),b.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let g=x(d.projectId);if(!g){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:A(d.projectId)});return}let y=d.sessionId||(0,Zn.randomUUID)(),_=!d.sessionId,M=d.sessionId?Os(d.sessionId):null,O=M?.agentId||d.agentId||g.project.defaultAgent||_e.DEFAULT_AGENT_ID;if(!_&&d.userId){let qe=M?.ownerUserId??"";if(qe&&qe!==d.userId){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 F=d.operator===!0;if(F&&!t.operatorEnabled){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 Y=_?0:M?.messages.length??0,P=!1,U=0,re="";if(!_&&Y>=uw){let qe=await pw(g,y,t);if(qe)P=!0,U=Y,re=qe,y=(0,Zn.randomUUID)(),_=!0,b.info(`chat compacted: ${Y} message(s) summarized into a fresh session`);else if(Y>=dw){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let j=d.files.length?Eg(g.repoPath,d.requestId,d.files):null,ee=(0,_e.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,_e.pendingMigrationsAppendix)(d.pendingMigrations)+(0,_e.monitorChecksAppendix)(d.monitorChecks)+(0,_e.deployTargetsAppendix)(d.environments)+(0,_e.savedStepChecksAppendix)(d.environmentSteps)+(0,_e.composeCommandAppendix)(d.command)+lw(d.sessionId??""),ae=JC(g.repoPath)+hr("compose",g.repoPath,{summary:d.message,ruleName:""});tc(g,t);let pe="```",$e=_?`You are the project assistant for "${g.project.name}" - this working directory is its repository, and you have read-only access.
1727
1727
 
1728
1728
  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.
1729
1729
  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.
1730
1730
 
1731
- `+(B?"":`You cannot run commands - but you can ASK to. When the answer genuinely needs machine state (is a service up, what is in its log, what is listening), request ONE read-only diagnostic by ending your reply with:
1731
+ `+(F?"":`You cannot run commands - but you can ASK to. When the answer genuinely needs machine state (is a service up, what is in its log, what is listening), request ONE read-only diagnostic by ending your reply with:
1732
1732
  ${pe}diagnose
1733
1733
  {"command": "<id>", "args": {...}, "why": "one line the user reads before approving"}
1734
1734
  ${pe}
@@ -1744,26 +1744,26 @@ ${re}
1744
1744
  ${d.userName||"The user"} says: ${d.message}`+(j?.section??""):ee+_e.TICKET_RULES_APPENDIX+`
1745
1745
 
1746
1746
  `+ae+`
1747
- ${d.userName||"The user"} says: ${d.message}`+(j?.section??""),lt=0,oa=0,Ar=new Date;ow(d.projectId,y,d.message,d.files.map(qe=>qe.name),Ar.toISOString(),d.userId,O),v.send({type:"chat.session",requestId:d.requestId,sessionId:y});let Ht=[],me=[],se;try{let qe=Ce(t,g.project,B?"operator":"chat",O);if("error"in qe){Dc(y),v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:qe.error});return}let $r=new AbortController;K.set(d.requestId,$r);let Yk=Date.now(),dp={repoPath:g.repoPath,prompt:$e,signal:$r.signal,timeoutSeconds:HC,bin:qe.bin,mode:B?"operator":"read_only_web",maxTurns:25,model:d.model||qe.adapter.fastModel,sessionId:y,resume:!_,onLog:(Qe,_t)=>{Qe==="agent"&&(Ht.push(_t.slice(0,4e3)),v.send({type:"chat.stream",requestId:d.requestId,seq:lt++,text:_t.slice(0,8e3)}))},onTool:(Qe,_t)=>{B&&(me.push(`${Qe}: ${_t}`),Ht.push(`${Qe}: ${_t}`.slice(0,4e3))),v.send({type:"chat.activity",requestId:d.requestId,seq:oa++,verb:Qe,target:_t})},onUsage:Qe=>{v.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(Qe.inputTokens),outputTokens:Math.round(Qe.outputTokens),cacheReadTokens:Qe.cacheReadTokens===void 0?void 0:Math.round(Qe.cacheReadTokens),turns:Qe.turns})}};se=await qe.adapter.run(dp);let wl=0;for(;!se.ok&&se.turnLimitHit&&!se.cancelled&&qe.adapter.capabilities.sessionResume&&wl<Gk;){let Qe=Wk-(Date.now()-Yk);if(Qe<KC)break;wl++,b.info(`chat turn ${d.requestId}: turn limit hit - resuming the same session (resume ${wl}/${Gk}, ${Math.round(Qe/1e3)}s left)`);let _t=await qe.adapter.run({...dp,prompt:Qe<=VC?WC:GC,resume:!0,timeoutSeconds:Math.floor(Qe/1e3)});_t.costUsd+=se.costUsd,_t.inputTokens+=se.inputTokens,_t.outputTokens+=se.outputTokens,_t.cacheReadTokens+=se.cacheReadTokens,se=_t}!se.ok&&(se.turnLimitHit||se.timedOut)&&!se.resultText.trim()&&Ht.length&&(se.resultText=YC(Ht))}finally{if(K.delete(d.requestId),j&&Ge.default.rmSync(j.dir,{recursive:!0,force:!0}),B&&me.length)try{ww({projectId:d.projectId,sessionId:y,userId:d.userId,userName:d.userName,ask:d.message,commands:me})}catch(qe){b.warn(`operator ledger write failed: ${qe instanceof Error?qe.message:qe}`)}}if(se.cancelled){Dc(y),v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:se.inputTokens,outputTokens:se.outputTokens,cacheReadTokens:se.cacheReadTokens});return}if(!se.ok&&se.timedOut&&(se.error=`this has been running for ${Math.round(Wk/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 qe=Ht.filter($r=>$r.trim()&&!se.resultText.trim().startsWith($r.trim()));se.ok||(se.resultText=`${se.resultText.trim()}
1747
+ ${d.userName||"The user"} says: ${d.message}`+(j?.section??""),lt=0,oa=0,Ar=new Date;ow(d.projectId,y,d.message,d.files.map(qe=>qe.name),Ar.toISOString(),d.userId,O),v.send({type:"chat.session",requestId:d.requestId,sessionId:y});let Ht=[],me=[],se;try{let qe=Ce(t,g.project,F?"operator":"chat",O);if("error"in qe){Dc(y),v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:qe.error});return}let $r=new AbortController;K.set(d.requestId,$r);let Yk=Date.now(),dp={repoPath:g.repoPath,prompt:$e,signal:$r.signal,timeoutSeconds:HC,bin:qe.bin,mode:F?"operator":"read_only_web",maxTurns:25,model:d.model||qe.adapter.fastModel,sessionId:y,resume:!_,onLog:(et,_t)=>{et==="agent"&&(Ht.push(_t.slice(0,4e3)),v.send({type:"chat.stream",requestId:d.requestId,seq:lt++,text:_t.slice(0,8e3)}))},onTool:(et,_t)=>{F&&(me.push(`${et}: ${_t}`),Ht.push(`${et}: ${_t}`.slice(0,4e3))),v.send({type:"chat.activity",requestId:d.requestId,seq:oa++,verb:et,target:_t})},onUsage:et=>{v.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(et.inputTokens),outputTokens:Math.round(et.outputTokens),cacheReadTokens:et.cacheReadTokens===void 0?void 0:Math.round(et.cacheReadTokens),turns:et.turns})}};se=await qe.adapter.run(dp);let wl=0;for(;!se.ok&&se.turnLimitHit&&!se.cancelled&&qe.adapter.capabilities.sessionResume&&wl<Gk;){let et=Wk-(Date.now()-Yk);if(et<KC)break;wl++,b.info(`chat turn ${d.requestId}: turn limit hit - resuming the same session (resume ${wl}/${Gk}, ${Math.round(et/1e3)}s left)`);let _t=await qe.adapter.run({...dp,prompt:et<=VC?WC:GC,resume:!0,timeoutSeconds:Math.floor(et/1e3)});_t.costUsd+=se.costUsd,_t.inputTokens+=se.inputTokens,_t.outputTokens+=se.outputTokens,_t.cacheReadTokens+=se.cacheReadTokens,se=_t}!se.ok&&(se.turnLimitHit||se.timedOut)&&!se.resultText.trim()&&Ht.length&&(se.resultText=YC(Ht))}finally{if(K.delete(d.requestId),j&&Ge.default.rmSync(j.dir,{recursive:!0,force:!0}),F&&me.length)try{ww({projectId:d.projectId,sessionId:y,userId:d.userId,userName:d.userName,ask:d.message,commands:me})}catch(qe){b.warn(`operator ledger write failed: ${qe instanceof Error?qe.message:qe}`)}}if(se.cancelled){Dc(y),v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:se.inputTokens,outputTokens:se.outputTokens,cacheReadTokens:se.cacheReadTokens});return}if(!se.ok&&se.timedOut&&(se.error=`this has been running for ${Math.round(Wk/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 qe=Ht.filter($r=>$r.trim()&&!se.resultText.trim().startsWith($r.trim()));se.ok||(se.resultText=`${se.resultText.trim()}
1748
1748
 
1749
1749
  ---
1750
- _Unfinished: ${se.error||"the turn ended early"}._`),aw(d.projectId,y,d.message,se.resultText,qe,d.files.map($r=>$r.name),{askedAt:Ar.toISOString(),ms:Date.now()-Ar.getTime(),tokens:(se.inputTokens??0)+(se.outputTokens??0)},d.userId,O)}else Dc(y);let Jk=(se.inputTokens??0)+(se.cacheReadTokens??0);v.sendChatTurnResult(d.requestId,{contextTokens:Jk,contextLimit:hw(se.model||d.model||""),compacted:N,compactedMessages:U,ok:se.ok,sessionId:y,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:d=>{v.sendChatListResult(d.requestId,cw(d.projectId))},onRepoDocs:d=>{let g=x(d.projectId);if(!g){v.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:A(d.projectId)});return}v.sendRepoDocsResult(d.requestId,{ok:!0,docs:_w(g.repoPath)})},onRepoDocRead:d=>{let g=x(d.projectId);if(!g){v.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:A(d.projectId)});return}let y=xw(g.repoPath,d.path);v.sendRepoDocReadResult(d.requestId,{ok:y.ok,path:y.ok?y.path:d.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:d=>{let g=Os(d.sessionId);v.sendChatLoadResult(d.requestId,{ok:g!==null,projectId:g?.projectId??"",ownerUserId:g?.ownerUserId??"",agentId:g?.agentId??"",messages:g?.messages??[],error:g?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async d=>{let g=x(d.projectId);if(!g){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:A(d.projectId)});return}try{let y=s(g.project.repoName),_;try{_=await y.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY Rank ASC`,1e3)}catch{_=await y.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY updated DESC`,1e3)}let M=await y.boardColumns(g.project.jiraProjectKey),O;if(M){O=M.map(N=>({name:N.name,issues:[]}));let Y=new Map;for(let N of _){let U=M.findIndex(j=>j.statusIds.includes(N.statusId)),re={key:N.key,summary:N.summary,labels:N.labels,components:N.components,fixVersions:N.fixVersions};if(U>=0)O[U].issues.push(re);else{let j=Y.get(N.status)??[];j.push(re),Y.set(N.status,j)}}for(let[N,U]of Y)O.push({name:N,issues:U})}else{let Y=ee=>ee.trim().toLowerCase(),N=new Map,U=new Map;for(let ee of _){let ae=Y(ee.status);N.has(ae)||N.set(ae,ee.status.trim());let pe=U.get(ae)??[];pe.push({key:ee.key,summary:ee.summary,labels:ee.labels,components:ee.components,fixVersions:ee.fixVersions}),U.set(ae,pe)}let re=[];try{re=await y.projectStatuses(g.project.jiraProjectKey)}catch{}let j=[];for(let ee of re){let ae=Y(ee);!j.includes(ae)&&U.has(ae)&&j.push(ae)}for(let ee of U.keys())j.includes(ee)||j.push(ee);O=j.map(ee=>({name:N.get(ee)??ee,issues:U.get(ee)??[]}))}let B=t.repos[g.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(B?.baseUrl??"").replace(/\/+$/,""),columns:O})}catch(y){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async d=>{let g=x(d.projectId);if(!g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(g.project.repoName);d.agentId&&Hb(d.projectId,d.issueKey,d.agentId);let _=d.comment.trim()?a(g.project.repoName,d.requestedByEmail):{jira:y,authored:!1};if(_.error!==void 0){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:_.error});return}if(d.reimplement){let M=await y.getIssue(d.issueKey),O=M.comments.filter(N=>jt(N.body)),B=O.length?Math.max(...O.map(N=>new Date(N.created).getTime())):0;if(!M.comments.some(N=>!jt(N.body)&&new Date(N.created).getTime()>B)){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await y.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await y.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await _.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!_.authored&&d.requestedBy?`
1750
+ _Unfinished: ${se.error||"the turn ended early"}._`),aw(d.projectId,y,d.message,se.resultText,qe,d.files.map($r=>$r.name),{askedAt:Ar.toISOString(),ms:Date.now()-Ar.getTime(),tokens:(se.inputTokens??0)+(se.outputTokens??0)},d.userId,O)}else Dc(y);let Jk=(se.inputTokens??0)+(se.cacheReadTokens??0);v.sendChatTurnResult(d.requestId,{contextTokens:Jk,contextLimit:hw(se.model||d.model||""),compacted:P,compactedMessages:U,ok:se.ok,sessionId:y,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:d=>{v.sendChatListResult(d.requestId,cw(d.projectId))},onRepoDocs:d=>{let g=x(d.projectId);if(!g){v.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:A(d.projectId)});return}v.sendRepoDocsResult(d.requestId,{ok:!0,docs:_w(g.repoPath)})},onRepoDocRead:d=>{let g=x(d.projectId);if(!g){v.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:A(d.projectId)});return}let y=xw(g.repoPath,d.path);v.sendRepoDocReadResult(d.requestId,{ok:y.ok,path:y.ok?y.path:d.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:d=>{let g=Os(d.sessionId);v.sendChatLoadResult(d.requestId,{ok:g!==null,projectId:g?.projectId??"",ownerUserId:g?.ownerUserId??"",agentId:g?.agentId??"",messages:g?.messages??[],error:g?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async d=>{let g=x(d.projectId);if(!g){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:A(d.projectId)});return}try{let y=s(g.project.repoName),_;try{_=await y.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY Rank ASC`,1e3)}catch{_=await y.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY updated DESC`,1e3)}let M=await y.boardColumns(g.project.jiraProjectKey),O;if(M){O=M.map(P=>({name:P.name,issues:[]}));let Y=new Map;for(let P of _){let U=M.findIndex(j=>j.statusIds.includes(P.statusId)),re={key:P.key,summary:P.summary,labels:P.labels,components:P.components,fixVersions:P.fixVersions};if(U>=0)O[U].issues.push(re);else{let j=Y.get(P.status)??[];j.push(re),Y.set(P.status,j)}}for(let[P,U]of Y)O.push({name:P,issues:U})}else{let Y=ee=>ee.trim().toLowerCase(),P=new Map,U=new Map;for(let ee of _){let ae=Y(ee.status);P.has(ae)||P.set(ae,ee.status.trim());let pe=U.get(ae)??[];pe.push({key:ee.key,summary:ee.summary,labels:ee.labels,components:ee.components,fixVersions:ee.fixVersions}),U.set(ae,pe)}let re=[];try{re=await y.projectStatuses(g.project.jiraProjectKey)}catch{}let j=[];for(let ee of re){let ae=Y(ee);!j.includes(ae)&&U.has(ae)&&j.push(ae)}for(let ee of U.keys())j.includes(ee)||j.push(ee);O=j.map(ee=>({name:P.get(ee)??ee,issues:U.get(ee)??[]}))}let F=t.repos[g.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(F?.baseUrl??"").replace(/\/+$/,""),columns:O})}catch(y){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async d=>{let g=x(d.projectId);if(!g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(g.project.repoName);d.agentId&&Hb(d.projectId,d.issueKey,d.agentId);let _=d.comment.trim()?a(g.project.repoName,d.requestedByEmail):{jira:y,authored:!1};if(_.error!==void 0){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:_.error});return}if(d.reimplement){let M=await y.getIssue(d.issueKey),O=M.comments.filter(P=>jt(P.body)),F=O.length?Math.max(...O.map(P=>new Date(P.created).getTime())):0;if(!M.comments.some(P=>!jt(P.body)&&new Date(P.created).getTime()>F)){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await y.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await y.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await _.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!_.authored&&d.requestedBy?`
1751
1751
 
1752
- _(requested by ${d.requestedBy} via Allwright)_`:"")),b.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.agentId?` agent ${d.agentId}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(y){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async d=>{let g=l.find(_=>_.id===d.projectId);if(!g||!g.jiraProjectKey){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g?"this project has no Jira board key yet - set it in project settings first":A(d.projectId)});return}let y={project:g,repoPath:t.repos[g.repoName]?.path??""};try{let _=a(y.project.repoName,d.requestedByEmail);if(_.error!==void 0){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:_.error});return}let M=[];if(d.newVersionName.trim()){let j=await _.jira.createVersion(y.project.jiraProjectKey,d.newVersionName.trim());M=[j.id],b.info(`Compose created release "${j.name}" (${j.id})`)}else d.fixVersionId.trim()&&(M=[d.fixVersionId.trim()]);let O={fixVersionIds:M},B=async j=>{let ee=d.assigneeAccountId.trim();if(ee)try{await _.jira.assignIssue(j,ee)}catch(ae){b.warn(`could not assign ${j}: ${ae instanceof Error?ae.message:ae}`)}},Y=`
1752
+ _(requested by ${d.requestedBy} via Allwright)_`:"")),b.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.agentId?` agent ${d.agentId}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(y){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async d=>{let g=l.find(_=>_.id===d.projectId);if(!g||!g.jiraProjectKey){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g?"this project has no Jira board key yet - set it in project settings first":A(d.projectId)});return}let y={project:g,repoPath:t.repos[g.repoName]?.path??""};try{let _=a(y.project.repoName,d.requestedByEmail);if(_.error!==void 0){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:_.error});return}let M=[];if(d.newVersionName.trim()){let j=await _.jira.createVersion(y.project.jiraProjectKey,d.newVersionName.trim());M=[j.id],b.info(`Compose created release "${j.name}" (${j.id})`)}else d.fixVersionId.trim()&&(M=[d.fixVersionId.trim()]);let O={fixVersionIds:M},F=async j=>{let ee=d.assigneeAccountId.trim();if(ee)try{await _.jira.assignIssue(j,ee)}catch(ae){b.warn(`could not assign ${j}: ${ae instanceof Error?ae.message:ae}`)}},Y=`
1753
1753
 
1754
1754
  ---
1755
- _Created via Allwright Compose`+(!_.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._",N="";if(y.repoPath&&d.chatSessionId&&(!d.asEpic||d.createAs==="epic_with_children")){let j=Os(d.chatSessionId)?.ownerUserId??"";if(!j||!d.userId||j===d.userId){let ee=await fw(y,d.chatSessionId,t);ee&&(N=`
1755
+ _Created via Allwright Compose`+(!_.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._",P="";if(y.repoPath&&d.chatSessionId&&(!d.asEpic||d.createAs==="epic_with_children")){let j=Os(d.chatSessionId)?.ownerUserId??"";if(!j||!d.userId||j===d.userId){let ee=await fw(y,d.chatSessionId,t);ee&&(P=`
1756
1756
 
1757
1757
  ----
1758
1758
  *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):*
1759
1759
 
1760
- ${ee}`)}}if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let j=d.createAs==="separate_epics"?"Epic":"Task",ee=[],ae=[];for(let pe of d.children){let $e=(pe.description||"(no description)")+Y,lt=await _.jira.createIssue(y.project.jiraProjectKey,pe.summary,$e,j,void 0,d.component?[d.component]:[],O);await B(lt.key),ee.push(lt.key),ae.push($e)}await T(_.jira,ee,ae),Lc(d.chatSessionId,ee.map((pe,$e)=>({key:pe,summary:d.children[$e]?.summary??""}))),b.info(`Compose created ${ee.length} standalone ${j.toLowerCase()}(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:ee[0]??"",childKeys:ee});return}let{key:U}=await _.jira.createIssue(y.project.jiraProjectKey,d.summary,(d.description||"(no description)")+N+Y,d.asEpic?"Epic":"Task",void 0,d.component?[d.component]:[],O);await B(U),d.files.length&&await _.jira.addAttachments(U,d.files.map(j=>({name:j.name,content:Buffer.from(j.contentBase64,"base64")}))).then(()=>b.info(`Compose attached ${d.files.length} file(s) to ${U}`)).catch(j=>b.warn(`Compose could not attach files to ${U}: ${j instanceof Error?j.message:j}`));let re=[];if(d.asEpic){let j=[];for(let ee of d.children){let ae=(ee.description||"(no description)")+Y,pe=await _.jira.createIssue(y.project.jiraProjectKey,ee.summary,ae,"Task",U,d.component?[d.component]:[],O);await B(pe.key),re.push(pe.key),j.push(ae)}await T(_.jira,re,j),Lc(d.chatSessionId,[{key:U,summary:d.summary},...re.map((ee,ae)=>({key:ee,summary:d.children[ae]?.summary??""}))]),b.info(`Compose created epic ${U} with ${re.length} child ticket(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U,childKeys:re});return}d.triggerComment.trim()&&await _.jira.addTriggerComment(U,`${d.triggerComment.trim()}`+(!_.authored&&d.requestedBy?`
1760
+ ${ee}`)}}if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let j=d.createAs==="separate_epics"?"Epic":"Task",ee=[],ae=[];for(let pe of d.children){let $e=(pe.description||"(no description)")+Y,lt=await _.jira.createIssue(y.project.jiraProjectKey,pe.summary,$e,j,void 0,d.component?[d.component]:[],O);await F(lt.key),ee.push(lt.key),ae.push($e)}await T(_.jira,ee,ae),Lc(d.chatSessionId,ee.map((pe,$e)=>({key:pe,summary:d.children[$e]?.summary??""}))),b.info(`Compose created ${ee.length} standalone ${j.toLowerCase()}(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:ee[0]??"",childKeys:ee});return}let{key:U}=await _.jira.createIssue(y.project.jiraProjectKey,d.summary,(d.description||"(no description)")+P+Y,d.asEpic?"Epic":"Task",void 0,d.component?[d.component]:[],O);await F(U),d.files.length&&await _.jira.addAttachments(U,d.files.map(j=>({name:j.name,content:Buffer.from(j.contentBase64,"base64")}))).then(()=>b.info(`Compose attached ${d.files.length} file(s) to ${U}`)).catch(j=>b.warn(`Compose could not attach files to ${U}: ${j instanceof Error?j.message:j}`));let re=[];if(d.asEpic){let j=[];for(let ee of d.children){let ae=(ee.description||"(no description)")+Y,pe=await _.jira.createIssue(y.project.jiraProjectKey,ee.summary,ae,"Task",U,d.component?[d.component]:[],O);await F(pe.key),re.push(pe.key),j.push(ae)}await T(_.jira,re,j),Lc(d.chatSessionId,[{key:U,summary:d.summary},...re.map((ee,ae)=>({key:ee,summary:d.children[ae]?.summary??""}))]),b.info(`Compose created epic ${U} with ${re.length} child ticket(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U,childKeys:re});return}d.triggerComment.trim()&&await _.jira.addTriggerComment(U,`${d.triggerComment.trim()}`+(!_.authored&&d.requestedBy?`
1761
1761
 
1762
- _(requested by ${d.requestedBy} via Allwright)_`:"")),Lc(d.chatSessionId,[{key:U,summary:d.summary}]),b.info(`Compose created ${U}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U})}catch(_){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:_ instanceof Error?_.message:String(_)})}},onAuditStart:async d=>{let g=x(d.projectId);if(!g){v.sendAuditStartResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{b.info(`Audit (${d.role}) starting on ${g.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let y=Ce(t,g.project,"assist");if("error"in y){v.sendAuditStartResult(d.requestId,{ok:!1,error:y.error});return}let _=await gi({projectId:d.projectId,repoPath:g.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:y,jira:s(g.project.repoName),baseUrl:d.baseUrl,brief:d.brief,packs:g.project.packs??[]});if(!_.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:_.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:_.audit})}catch(y){v.sendAuditStartResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:sm(d.projectId)})}catch(g){v.sendAuditListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditExplain:async d=>{try{let g=Cu(d.projectId,d.auditId),y=g?.findings.find(N=>N.id===d.findingId);if(!g||!y){v.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let _=x(d.projectId);if(!_){v.sendAuditExplainResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let M=Ce(t,_.project,"assist");if("error"in M){v.sendAuditExplainResult(d.requestId,{ok:!1,error:M.error});return}let O=`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.
1762
+ _(requested by ${d.requestedBy} via Allwright)_`:"")),Lc(d.chatSessionId,[{key:U,summary:d.summary}]),b.info(`Compose created ${U}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U})}catch(_){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:_ instanceof Error?_.message:String(_)})}},onAuditStart:async d=>{let g=x(d.projectId);if(!g){v.sendAuditStartResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{b.info(`Audit (${d.role}) starting on ${g.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let y=Ce(t,g.project,"assist");if("error"in y){v.sendAuditStartResult(d.requestId,{ok:!1,error:y.error});return}let _=await gi({projectId:d.projectId,repoPath:g.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:y,jira:s(g.project.repoName),baseUrl:d.baseUrl,brief:d.brief,packs:g.project.packs??[]});if(!_.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:_.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:_.audit})}catch(y){v.sendAuditStartResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:sm(d.projectId)})}catch(g){v.sendAuditListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditExplain:async d=>{try{let g=Cu(d.projectId,d.auditId),y=g?.findings.find(P=>P.id===d.findingId);if(!g||!y){v.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let _=x(d.projectId);if(!_){v.sendAuditExplainResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let M=Ce(t,_.project,"assist");if("error"in M){v.sendAuditExplainResult(d.requestId,{ok:!1,error:M.error});return}let O=`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.
1763
1763
 
1764
1764
  FINDING (${y.severity}${y.ruleId?`, rule ${y.ruleId}`:""}):
1765
1765
  ${y.title}
1766
- `+y.evidence.map(N=>`- ${N.file}${N.line?`:${N.line}`:""} ${N.note}`.trim()).join(`
1766
+ `+y.evidence.map(P=>`- ${P.file}${P.line?`:${P.line}`:""} ${P.note}`.trim()).join(`
1767
1767
  `)+(y.fix?`
1768
1768
  Proposed fix: ${y.fix}`:"")+`
1769
1769
 
@@ -1774,7 +1774,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
1774
1774
  **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.
1775
1775
  **How urgent:** now / before the next release / when convenient - and why.
1776
1776
  **What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
1777
- Nothing else - no preamble, no code.`,B=await M.adapter.run({repoPath:_.repoPath,prompt:O,timeoutSeconds:120,bin:M.bin,mode:"read_only",maxTurns:8,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"audit_explain",projectId:d.projectId,agentId:M.adapter.id,refKind:"audit",refId:d.auditId,...ve(B)});let Y=B.resultText.trim();if(!B.ok||!Y){v.sendAuditExplainResult(d.requestId,{ok:!1,error:B.error??"the agent returned nothing - try again"});return}v.sendAuditExplainResult(d.requestId,{ok:!0,explanation:Y})}catch(g){v.sendAuditExplainResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async d=>{try{let g=Cu(d.projectId,d.auditId);if(!g){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:g})}catch(g){v.sendAuditGetResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async d=>{try{let g=$u(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!g){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=x(d.projectId);if(y&&d.verdicts.length){let _=[];for(let M of d.verdicts){if(M.verdict==="valid"||g.lessonsWritten.includes(M.findingId))continue;let O=g.findings.find(B=>B.id===M.findingId);O&&(ju(y.repoPath,g.role,mm(O,M.verdict,M.note,d.verdictBy)),_.push(M.findingId),b.info(`Lesson written (${g.role}): ${M.verdict} - ${O.title.slice(0,60)}`))}_.length&&(g=$u(d.projectId,d.auditId,{markLessonsWritten:_})??g)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:g})}catch(g){v.sendAuditReviewResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async d=>{let g=x(d.projectId);if(!g){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:ym(g.repoPath)})}catch(y){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async d=>{let g=x(d.projectId);if(!g){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{d.append?ju(g.repoPath,d.role,gm(d.content,d.by),d.level):bm(g.repoPath,d.role,d.level,d.source,d.name,d.content),b.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(y){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async d=>{let g=x(d.projectId);if(!g){v.sendEpicListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(g.project.repoName);if(d.epicKey){let _=await y.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:_})}else{let _=await y.searchEpics(g.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:_})}}catch(y){v.sendEpicListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async d=>{let g=x(d.projectId);if(!g){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(g.project.repoName),_=await y.epicChildren(d.epicKey),M=Ob(_);if(!M.length){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(M.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:M[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let O=await Promise.all(M.slice(0,12).map(async re=>{try{let j=await y.getIssue(re.key);return{...re,description:j.description}}catch{return{...re,description:""}}})),B=(await y.getIssue(d.epicKey).catch(()=>null))?.summary??"";b.info(`Epic suggest: weighing ${O.length} pending children of ${d.epicKey}`);let Y=Ce(t,g.project,"assist");if("error"in Y){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:Y.error});return}let N=await Y.adapter.run({repoPath:g.repoPath,prompt:zb(d.epicKey,B,O),timeoutSeconds:150,bin:Y.bin,mode:"read_only",maxTurns:20,sessionId:(0,Zn.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}});Se({surface:"epic_suggest",projectId:g.project.id,agentId:Y.adapter.id,refKind:"none",refLabel:d.epicKey,...ve(N)});let U=Db(N.resultText,O.map(re=>re.key));if("error"in U){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:U.error});return}b.info(`Epic suggest: ${d.epicKey} -> do ${U.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:U.issueKey,reason:U.reason,considered:O.length})}catch(y){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async d=>{try{let g=ke()??t;if(g.github?.token&&!g.github.login)try{let{GitHubClient:_}=await Promise.resolve().then(()=>(Yt(),gs));g.github.login=await new _(g.github.token).whoami(),xe(g)}catch{}let y=Vf(g,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...y})}catch(g){v.sendTeamCredsResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRepoUnmap:d=>{try{let g=ke();if(!g){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let y=g.repos[d.repoName];if(!y){v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let _=y.path;delete g.repos[d.repoName];for(let M of Object.keys(g.environments).filter(O=>O.startsWith(`${d.repoName}:`)))delete g.environments[M];g.auditSchedules=g.auditSchedules.filter(M=>M.repoName!==d.repoName),xe(g),Bt(),b.info(`Unmapped "${d.repoName}" (was ${_}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:_})}catch(g){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupRecheck:d=>{try{let g=x(d.projectId);if(!g){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:A(d.projectId)});return}v.sendSetupRecheckResult(d.requestId,{ok:!0,checks:yg({repoPath:g.repoPath,environments:d.environments})})}catch(g){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRebirthStudy:async d=>{let g=l.find($e=>$e.id===d.projectId&&!$e.repoName),y=g?{project:g,repoPath:""}:x(d.projectId);if(!y){v.sendRebirthStudyResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let{runRebirthStudy:_,rebirthStudyInFlight:M,sendRunFinished:O}=await Promise.resolve().then(()=>(tp(),ep));if(M(d.rebirthId)){v.sendRebirthStudyResult(d.requestId,{ok:!1,error:"a study is already running for this rebirth - it reports progress as it goes"});return}let{uploadedCodeDir:B,uploadedDumpPath:Y}=await Promise.resolve().then(()=>(ra(),na)),N=Ge.default.existsSync(y.repoPath),U=N?null:B(d.rebirthId),re=N||!!U,j=(d.legacyJiraSiteUrl??"").trim(),ee=eo(t)&&!t.repos[y.project.repoName]?.jira?null:s(y.project.repoName);if(j){let $e="";try{$e=new URL(j.includes("://")?j:`https://${j}`).origin}catch{v.sendRebirthStudyResult(d.requestId,{ok:!1,error:`"${j}" is not a usable Jira site - give a host like oldco.atlassian.net`});return}let lt=Qi(t,y.project.repoName);ee=lt?new Ye({...lt,baseUrl:$e}):null}let ae=N?y.repoPath:U??Ge.default.mkdtempSync(nn.default.join(Vs.default.tmpdir(),"rebirth-")),pe=d.dbDumpPath.trim()||Y(d.rebirthId)||"";v.sendRebirthStudyResult(d.requestId,{ok:!0}),_({msg:{...d,dbDumpPath:pe},cfg:t,project:y.project,repoPath:ae,repoAvailable:re,jira:ee,transport:v}).then($e=>{$e.ok||b.warn(`rebirth study ${d.rebirthId} failed: ${$e.error}`),O(v,d.rebirthId,d.refineMessage?"refine":"study",$e)}).catch($e=>{let lt=$e instanceof Error?$e.message:String($e);b.warn(`rebirth study ${d.rebirthId} threw: ${lt}`),O(v,d.rebirthId,d.refineMessage?"refine":"study",{ok:!1,error:lt})}).finally(()=>{!N&&!U&&Ge.default.rmSync(ae,{recursive:!0,force:!0})})},onTimelineDigest:async d=>{let g=x(d.projectId);if(!g){v.sendTimelineDigestResult(d.requestId,{ok:!1,text:"",error:A(d.projectId)});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendTimelineDigestResult(d.requestId,{ok:!1,text:"",error:y.error});return}try{let _=await y.adapter.run({repoPath:g.repoPath,prompt:d.prompt,timeoutSeconds:90,bin:y.bin,mode:"read_only",maxTurns:2,model:y.adapter.fastModel,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"timeline_digest",projectId:g.project.id,agentId:y.adapter.id,refKind:"none",...ve(_)}),v.sendTimelineDigestResult(d.requestId,{ok:_.ok&&!!_.resultText.trim(),text:_.resultText.trim().slice(0,8e3),error:_.ok?void 0:_.error||"the agent did not answer"})}catch(_){v.sendTimelineDigestResult(d.requestId,{ok:!1,text:"",error:_ instanceof Error?_.message:String(_)})}},onServerInventory:async d=>{try{let{collectServerInventory:g}=await Promise.resolve().then(()=>(Oo(),Wy)),y=await g(ke()??t);v.sendServerInventoryResult(d.requestId,{ok:!0,...y})}catch(g){v.sendServerInventoryResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g),checkouts:[],services:[],containers:[],ports:[],processes:[]})}},onRebirthDesign:async d=>{let g=l.find(re=>re.id===d.projectId&&!re.repoName),y=g?{project:g,repoPath:""}:x(d.projectId);if(!y){v.sendRebirthDesignResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let{uploadedCodeDir:_}=await Promise.resolve().then(()=>(ra(),na)),M=!!y.repoPath&&Ge.default.existsSync(y.repoPath),O=M?null:_(d.rebirthId),B=M?y.repoPath:O??Ge.default.mkdtempSync(nn.default.join(Vs.default.tmpdir(),"rebirth-design-"));v.sendRebirthDesignResult(d.requestId,{ok:!0});let{runRebirthDesign:Y,sendRunFinished:N}=await Promise.resolve().then(()=>(tp(),ep)),U=d.stackOnly?"techstack":d.screenName?"screen":"design";Y({msg:d,cfg:t,project:y.project,repoPath:B,transport:v}).then(re=>{re.ok||b.warn(`rebirth design ${d.rebirthId} failed: ${re.error}`),N(v,d.rebirthId,U,re)}).catch(re=>{let j=re instanceof Error?re.message:String(re);b.warn(`rebirth design ${d.rebirthId} threw: ${j}`),N(v,d.rebirthId,U,{ok:!1,error:j})}).finally(()=>{!M&&!O&&Ge.default.rmSync(B,{recursive:!0,force:!0})})},onRebirthUploadBegin:async d=>{let{beginRebirthUpload:g}=await Promise.resolve().then(()=>(ra(),na)),y=g({rebirthId:d.rebirthId,kind:d.kind,name:d.name});v.sendRebirthUploadBeginResult(d.requestId,y.ok?{ok:!0,uploadId:y.uploadId}:y)},onRebirthUploadChunk:async d=>{let{appendRebirthUploadChunk:g}=await Promise.resolve().then(()=>(ra(),na)),y=await g({uploadId:d.uploadId,seq:d.seq,dataBase64:d.dataBase64,last:d.last});v.sendRebirthUploadChunkResult(d.requestId,y)},onSiteAudit:async d=>{let{probeSite:g}=await Promise.resolve().then(()=>(qu(),Uu)),y=await g(d.url);v.sendSiteAuditResult(d.requestId,y)},onServerDecommissionPlan:async d=>{let{planDecommission:g}=await Promise.resolve().then(()=>(rp(),np)),y=await g(ke()??t,d.path);v.sendServerDecommissionPlanResult(d.requestId,y)},onServerDecommissionExecute:async d=>{let{executeDecommission:g}=await Promise.resolve().then(()=>(rp(),np));v.sendServerDecommissionResult(d.requestId,{ok:!0});try{await g(ke()??t,{path:d.path,deleteFolder:d.deleteFolder,services:d.services,pids:d.pids,containers:d.containers,databases:d.databases},y=>{b.info(`decommission ${d.path}: ${y.label} - ${y.ok?"ok":"FAILED"} ${y.detail}`),v.sendServerDecommissionProgress({opToken:d.opToken,step:y,done:!1,error:""})}),v.sendServerDecommissionProgress({opToken:d.opToken,done:!0,error:""})}catch(y){v.sendServerDecommissionProgress({opToken:d.opToken,done:!0,error:y instanceof Error?y.message:String(y)})}},onSetupStatus:async d=>{try{let g=ke()??t,{buildSetupReport:y}=await Promise.resolve().then(()=>(Mk(),jk)),_=await y(g,d.repoNames,t);v.sendSetupStatusResult(d.requestId,{ok:!0,..._})}catch(g){v.sendSetupStatusResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupClaudeMdGenerate:async d=>{try{let g=x(d.projectId);if(!g){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";b.info(`Setup: drafting ${y} for ${g.project.repoName}`);let _="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.",M=`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.
1777
+ Nothing else - no preamble, no code.`,F=await M.adapter.run({repoPath:_.repoPath,prompt:O,timeoutSeconds:120,bin:M.bin,mode:"read_only",maxTurns:8,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"audit_explain",projectId:d.projectId,agentId:M.adapter.id,refKind:"audit",refId:d.auditId,...ve(F)});let Y=F.resultText.trim();if(!F.ok||!Y){v.sendAuditExplainResult(d.requestId,{ok:!1,error:F.error??"the agent returned nothing - try again"});return}v.sendAuditExplainResult(d.requestId,{ok:!0,explanation:Y})}catch(g){v.sendAuditExplainResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async d=>{try{let g=Cu(d.projectId,d.auditId);if(!g){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:g})}catch(g){v.sendAuditGetResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async d=>{try{let g=$u(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!g){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=x(d.projectId);if(y&&d.verdicts.length){let _=[];for(let M of d.verdicts){if(M.verdict==="valid"||g.lessonsWritten.includes(M.findingId))continue;let O=g.findings.find(F=>F.id===M.findingId);O&&(ju(y.repoPath,g.role,mm(O,M.verdict,M.note,d.verdictBy)),_.push(M.findingId),b.info(`Lesson written (${g.role}): ${M.verdict} - ${O.title.slice(0,60)}`))}_.length&&(g=$u(d.projectId,d.auditId,{markLessonsWritten:_})??g)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:g})}catch(g){v.sendAuditReviewResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async d=>{let g=x(d.projectId);if(!g){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:ym(g.repoPath)})}catch(y){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async d=>{let g=x(d.projectId);if(!g){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{d.append?ju(g.repoPath,d.role,gm(d.content,d.by),d.level):bm(g.repoPath,d.role,d.level,d.source,d.name,d.content),b.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(y){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async d=>{let g=x(d.projectId);if(!g){v.sendEpicListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(g.project.repoName);if(d.epicKey){let _=await y.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:_})}else{let _=await y.searchEpics(g.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:_})}}catch(y){v.sendEpicListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async d=>{let g=x(d.projectId);if(!g){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(g.project.repoName),_=await y.epicChildren(d.epicKey),M=Ob(_);if(!M.length){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(M.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:M[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let O=await Promise.all(M.slice(0,12).map(async re=>{try{let j=await y.getIssue(re.key);return{...re,description:j.description}}catch{return{...re,description:""}}})),F=(await y.getIssue(d.epicKey).catch(()=>null))?.summary??"";b.info(`Epic suggest: weighing ${O.length} pending children of ${d.epicKey}`);let Y=Ce(t,g.project,"assist");if("error"in Y){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:Y.error});return}let P=await Y.adapter.run({repoPath:g.repoPath,prompt:zb(d.epicKey,F,O),timeoutSeconds:150,bin:Y.bin,mode:"read_only",maxTurns:20,sessionId:(0,Zn.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}});Se({surface:"epic_suggest",projectId:g.project.id,agentId:Y.adapter.id,refKind:"none",refLabel:d.epicKey,...ve(P)});let U=Db(P.resultText,O.map(re=>re.key));if("error"in U){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:U.error});return}b.info(`Epic suggest: ${d.epicKey} -> do ${U.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:U.issueKey,reason:U.reason,considered:O.length})}catch(y){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async d=>{try{let g=ke()??t;if(g.github?.token&&!g.github.login)try{let{GitHubClient:_}=await Promise.resolve().then(()=>(Yt(),gs));g.github.login=await new _(g.github.token).whoami(),xe(g)}catch{}let y=Vf(g,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...y})}catch(g){v.sendTeamCredsResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRepoUnmap:d=>{try{let g=ke();if(!g){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let y=g.repos[d.repoName];if(!y){v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let _=y.path;delete g.repos[d.repoName];for(let M of Object.keys(g.environments).filter(O=>O.startsWith(`${d.repoName}:`)))delete g.environments[M];g.auditSchedules=g.auditSchedules.filter(M=>M.repoName!==d.repoName),xe(g),Bt(),b.info(`Unmapped "${d.repoName}" (was ${_}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:_})}catch(g){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupRecheck:d=>{try{let g=x(d.projectId);if(!g){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:A(d.projectId)});return}v.sendSetupRecheckResult(d.requestId,{ok:!0,checks:yg({repoPath:g.repoPath,environments:d.environments})})}catch(g){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRebirthStudy:async d=>{let g=l.find($e=>$e.id===d.projectId&&!$e.repoName),y=g?{project:g,repoPath:""}:x(d.projectId);if(!y){v.sendRebirthStudyResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let{runRebirthStudy:_,rebirthStudyInFlight:M,sendRunFinished:O}=await Promise.resolve().then(()=>(tp(),ep));if(M(d.rebirthId)){v.sendRebirthStudyResult(d.requestId,{ok:!1,error:"a study is already running for this rebirth - it reports progress as it goes"});return}let{uploadedCodeDir:F,uploadedDumpPath:Y}=await Promise.resolve().then(()=>(ra(),na)),P=Ge.default.existsSync(y.repoPath),U=P?null:F(d.rebirthId),re=P||!!U,j=(d.legacyJiraSiteUrl??"").trim(),ee=eo(t)&&!t.repos[y.project.repoName]?.jira?null:s(y.project.repoName);if(j){let $e="";try{$e=new URL(j.includes("://")?j:`https://${j}`).origin}catch{v.sendRebirthStudyResult(d.requestId,{ok:!1,error:`"${j}" is not a usable Jira site - give a host like oldco.atlassian.net`});return}let lt=Qi(t,y.project.repoName);ee=lt?new Xe({...lt,baseUrl:$e}):null}let ae=P?y.repoPath:U??Ge.default.mkdtempSync(nn.default.join(Vs.default.tmpdir(),"rebirth-")),pe=d.dbDumpPath.trim()||Y(d.rebirthId)||"";v.sendRebirthStudyResult(d.requestId,{ok:!0}),_({msg:{...d,dbDumpPath:pe},cfg:t,project:y.project,repoPath:ae,repoAvailable:re,jira:ee,transport:v}).then($e=>{$e.ok||b.warn(`rebirth study ${d.rebirthId} failed: ${$e.error}`),O(v,d.rebirthId,d.refineMessage?"refine":"study",$e)}).catch($e=>{let lt=$e instanceof Error?$e.message:String($e);b.warn(`rebirth study ${d.rebirthId} threw: ${lt}`),O(v,d.rebirthId,d.refineMessage?"refine":"study",{ok:!1,error:lt})}).finally(()=>{!P&&!U&&Ge.default.rmSync(ae,{recursive:!0,force:!0})})},onTimelineDigest:async d=>{let g=x(d.projectId);if(!g){v.sendTimelineDigestResult(d.requestId,{ok:!1,text:"",error:A(d.projectId)});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendTimelineDigestResult(d.requestId,{ok:!1,text:"",error:y.error});return}try{let _=await y.adapter.run({repoPath:g.repoPath,prompt:d.prompt,timeoutSeconds:90,bin:y.bin,mode:"read_only",maxTurns:2,model:y.adapter.fastModel,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"timeline_digest",projectId:g.project.id,agentId:y.adapter.id,refKind:"none",...ve(_)}),v.sendTimelineDigestResult(d.requestId,{ok:_.ok&&!!_.resultText.trim(),text:_.resultText.trim().slice(0,8e3),error:_.ok?void 0:_.error||"the agent did not answer"})}catch(_){v.sendTimelineDigestResult(d.requestId,{ok:!1,text:"",error:_ instanceof Error?_.message:String(_)})}},onServerInventory:async d=>{try{let{collectServerInventory:g}=await Promise.resolve().then(()=>(Oo(),Wy)),y=await g(ke()??t);v.sendServerInventoryResult(d.requestId,{ok:!0,...y})}catch(g){v.sendServerInventoryResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g),checkouts:[],services:[],containers:[],ports:[],processes:[]})}},onRebirthDesign:async d=>{let g=l.find(re=>re.id===d.projectId&&!re.repoName),y=g?{project:g,repoPath:""}:x(d.projectId);if(!y){v.sendRebirthDesignResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let{uploadedCodeDir:_}=await Promise.resolve().then(()=>(ra(),na)),M=!!y.repoPath&&Ge.default.existsSync(y.repoPath),O=M?null:_(d.rebirthId),F=M?y.repoPath:O??Ge.default.mkdtempSync(nn.default.join(Vs.default.tmpdir(),"rebirth-design-"));v.sendRebirthDesignResult(d.requestId,{ok:!0});let{runRebirthDesign:Y,sendRunFinished:P}=await Promise.resolve().then(()=>(tp(),ep)),U=d.stackOnly?"techstack":d.screenName?"screen":"design";Y({msg:d,cfg:t,project:y.project,repoPath:F,transport:v}).then(re=>{re.ok||b.warn(`rebirth design ${d.rebirthId} failed: ${re.error}`),P(v,d.rebirthId,U,re)}).catch(re=>{let j=re instanceof Error?re.message:String(re);b.warn(`rebirth design ${d.rebirthId} threw: ${j}`),P(v,d.rebirthId,U,{ok:!1,error:j})}).finally(()=>{!M&&!O&&Ge.default.rmSync(F,{recursive:!0,force:!0})})},onRebirthUploadBegin:async d=>{let{beginRebirthUpload:g}=await Promise.resolve().then(()=>(ra(),na)),y=g({rebirthId:d.rebirthId,kind:d.kind,name:d.name});v.sendRebirthUploadBeginResult(d.requestId,y.ok?{ok:!0,uploadId:y.uploadId}:y)},onRebirthUploadChunk:async d=>{let{appendRebirthUploadChunk:g}=await Promise.resolve().then(()=>(ra(),na)),y=await g({uploadId:d.uploadId,seq:d.seq,dataBase64:d.dataBase64,last:d.last});v.sendRebirthUploadChunkResult(d.requestId,y)},onSiteAudit:async d=>{let{probeSite:g}=await Promise.resolve().then(()=>(qu(),Uu)),y=await g(d.url);v.sendSiteAuditResult(d.requestId,y)},onServerDecommissionPlan:async d=>{let{planDecommission:g}=await Promise.resolve().then(()=>(rp(),np)),y=await g(ke()??t,d.path);v.sendServerDecommissionPlanResult(d.requestId,y)},onServerDecommissionExecute:async d=>{let{executeDecommission:g}=await Promise.resolve().then(()=>(rp(),np));v.sendServerDecommissionResult(d.requestId,{ok:!0});try{await g(ke()??t,{path:d.path,deleteFolder:d.deleteFolder,services:d.services,pids:d.pids,containers:d.containers,databases:d.databases},y=>{b.info(`decommission ${d.path}: ${y.label} - ${y.ok?"ok":"FAILED"} ${y.detail}`),v.sendServerDecommissionProgress({opToken:d.opToken,step:y,done:!1,error:""})}),v.sendServerDecommissionProgress({opToken:d.opToken,done:!0,error:""})}catch(y){v.sendServerDecommissionProgress({opToken:d.opToken,done:!0,error:y instanceof Error?y.message:String(y)})}},onSetupStatus:async d=>{try{let g=ke()??t,{buildSetupReport:y}=await Promise.resolve().then(()=>(Mk(),jk)),_=await y(g,d.repoNames,t);v.sendSetupStatusResult(d.requestId,{ok:!0,..._})}catch(g){v.sendSetupStatusResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupClaudeMdGenerate:async d=>{try{let g=x(d.projectId);if(!g){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";b.info(`Setup: drafting ${y} for ${g.project.repoName}`);let _="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.",M=`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.
1778
1778
 
1779
1779
  Ten things decide whether this document can actually be run:
1780
1780
  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.
@@ -1793,7 +1793,7 @@ Reply with ONLY the file content - no preamble, no fences around the whole thing
1793
1793
  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:
1794
1794
  `+d.environments.map(j=>`- ${j.name}`+(j.branch?` (branch ${j.branch})`:"")+(j.publicUrl?` serves ${j.publicUrl}`:" - no URL given")+(j.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(j.workdir?`${j.workdir}`:j.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(`
1795
1795
  `)+`
1796
- If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?Xu({repoPath:g.repoPath,urls:d.environments.map(j=>j.publicUrl).filter(Boolean)})+xo(g.repoPath):""),O=`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.`,B=hr("implement",g.repoPath,{summary:d.blockers.join(" "),description:d.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.
1796
+ If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?Xu({repoPath:g.repoPath,urls:d.environments.map(j=>j.publicUrl).filter(Boolean)})+xo(g.repoPath):""),O=`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.`,F=hr("implement",g.repoPath,{summary:d.blockers.join(" "),description:d.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.
1797
1797
 
1798
1798
  BLOCKERS AS REPORTED:
1799
1799
  `+d.blockers.map((j,ee)=>`${ee+1}. ${j}`).join(`
@@ -1833,7 +1833,7 @@ Reply with ONLY the guide - no preamble.`+(d.environments.length?`
1833
1833
 
1834
1834
  THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
1835
1835
  `+d.environments.map(j=>`- ${j.name}`+(j.branch?` (branch ${j.branch})`:"")+(j.publicUrl?` serves ${j.publicUrl}`:"")+(j.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(j.workdir?j.workdir:j.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(`
1836
- `):"")+Xu({repoPath:g.repoPath,urls:d.environments.map(j=>j.publicUrl).filter(Boolean)})+xo(g.repoPath),Y=Ce(t,g.project,"assist");if("error"in Y){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:Y.error});return}let N=0,U=await Y.adapter.run({repoPath:g.repoPath,prompt:d.kind==="deploy"?M:d.kind==="design"?O:d.kind==="unblock"?B:_,timeoutSeconds:600,bin:Y.bin,mode:"read_only",maxTurns:40,sessionId:(0,Zn.randomUUID)(),onLog:(j,ee)=>{j==="agent"&&d.streamId&&v.send({type:"chat.stream",requestId:d.streamId,seq:N++,text:ee.slice(0,8e3)})}});Se({surface:"setup_docs",projectId:d.projectId,agentId:Y.adapter.id,refKind:"none",refLabel:y,...ve(U)});let re=U.resultText.trim();if(!re){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}U.outputTruncated&&b.warn(`Setup: the ${y} draft was cut off at the agent's output limit - ${re.length} chars, incomplete`),v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:re,truncated:!!U.outputTruncated})}catch(g){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupAsk:async d=>{try{let g=x(d.projectId);if(!g){v.sendSetupAskResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendSetupAskResult(d.requestId,{ok:!1,error:y.error});return}b.info(`Setup: question about "${d.subject.slice(0,60)}" (${g.project.repoName})`);let _="Someone is at a terminal on THIS machine, part-way through fixing one setup problem in Allwright, and has a question about it. Answer that question and stop."+(d.subject?`
1836
+ `):"")+Xu({repoPath:g.repoPath,urls:d.environments.map(j=>j.publicUrl).filter(Boolean)})+xo(g.repoPath),Y=Ce(t,g.project,"assist");if("error"in Y){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:Y.error});return}let P=0,U=await Y.adapter.run({repoPath:g.repoPath,prompt:d.kind==="deploy"?M:d.kind==="design"?O:d.kind==="unblock"?F:_,timeoutSeconds:600,bin:Y.bin,mode:"read_only",maxTurns:40,sessionId:(0,Zn.randomUUID)(),onLog:(j,ee)=>{j==="agent"&&d.streamId&&v.send({type:"chat.stream",requestId:d.streamId,seq:P++,text:ee.slice(0,8e3)})}});Se({surface:"setup_docs",projectId:d.projectId,agentId:Y.adapter.id,refKind:"none",refLabel:y,...ve(U)});let re=U.resultText.trim();if(!re){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}U.outputTruncated&&b.warn(`Setup: the ${y} draft was cut off at the agent's output limit - ${re.length} chars, incomplete`),v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:re,truncated:!!U.outputTruncated})}catch(g){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupAsk:async d=>{try{let g=x(d.projectId);if(!g){v.sendSetupAskResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=Ce(t,g.project,"assist");if("error"in y){v.sendSetupAskResult(d.requestId,{ok:!1,error:y.error});return}b.info(`Setup: question about "${d.subject.slice(0,60)}" (${g.project.repoName})`);let _="Someone is at a terminal on THIS machine, part-way through fixing one setup problem in Allwright, and has a question about it. Answer that question and stop."+(d.subject?`
1837
1837
 
1838
1838
  WHAT THEY ARE WORKING ON:
1839
1839
  ${d.subject}`:"")+(d.command?`
@@ -1842,11 +1842,11 @@ THE COMMAND THE SCREEN GAVE THEM:
1842
1842
  ${d.command}`:"")+(d.machineState.length?`
1843
1843
 
1844
1844
  WHAT THIS MACHINE ANSWERED AT THE LAST CHECK - seconds ago, and more reliable than anything you infer from the repository. If it disagrees with what you would have guessed, it wins:
1845
- `+d.machineState.map(B=>`- ${B}`).join(`
1845
+ `+d.machineState.map(F=>`- ${F}`).join(`
1846
1846
  `):"")+(d.history.length?`
1847
1847
 
1848
1848
  EARLIER IN THIS SAME BOX:
1849
- `+d.history.map(B=>`${B.role==="user"?"THEM":"YOU"}: ${B.text}`).join(`
1849
+ `+d.history.map(F=>`${F.role==="user"?"THEM":"YOU"}: ${F.text}`).join(`
1850
1850
 
1851
1851
  `):"")+`
1852
1852
 
@@ -1855,6 +1855,6 @@ ${d.question}
1855
1855
 
1856
1856
  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.
1857
1857
 
1858
- 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.`,M=await y.adapter.run({repoPath:g.repoPath,prompt:_,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"setup_ask",projectId:d.projectId,agentId:y.adapter.id,refKind:"none",...ve(M)});let O=M.resultText.trim();v.sendSetupAskResult(d.requestId,O?{ok:!0,answer:O}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(g){v.sendSetupAskResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupClaudeMdSave:async d=>{try{let g=x(d.projectId);if(!g){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",_=await Bh({repoPath:g.repoPath,relPath:y,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});_.ok&&b.info(`Setup: wrote human-approved ${y} to ${g.repoPath} - ${_.note}`),v.sendSetupClaudeMdSaveResult(d.requestId,_)}catch(g){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRepoDocSave:async d=>{try{let g=x(d.projectId);if(!g){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Bh({repoPath:g.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&b.info(`Saved approved doc ${d.relPath} into ${g.repoPath}`),v.sendRepoDocSaveResult(d.requestId,y)}catch(g){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:im(d.projectIds,d.since)})}catch(g){v.sendAuditStatsResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let g=()=>{let _=d.version?.trim()?`allwright@${d.version.trim()}`:"allwright@latest";b.info(`Installing ${_}`);let M=nn.default.dirname(process.execPath),O=Ge.default.existsSync(nn.default.join(M,"npm"))?nn.default.join(M,"npm"):"npm";(0,rn.execFile)(O,["install","-g",_],{timeout:18e4,env:{...process.env,PATH:`${M}:${process.env.PATH??""}`}},(B,Y,N)=>{if(B){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(N||B.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),b.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){g();return}if(m){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),b.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s)/chat turn(s) to finish`),m=setInterval(()=>{f.idle&&(clearInterval(m),m=null,g())},5e3)},onRunnerUninstall:d=>{if(!f.idle){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let g;try{g=Ec()}catch(_){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:_ instanceof Error?_.message:String(_)});return}let y=g.problems.length===0;if(v.sendRunnerUninstallResult(d.requestId,{ok:y,error:y?void 0:g.problems.join("; "),note:y?[g.serviceRemoved?"service stopped and removed":"no systemd service was installed here",g.configRemoved?`config deleted (${g.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:g.serviceRemoved||g.serviceAbsent,configRemoved:g.configRemoved}),!y){b.info("Uninstall requested from the dashboard, but it could not complete here");return}b.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{Ic(),process.exit(0)},1500)},onTestFix:async d=>{let g=y=>v.sendTestFixResult(d.requestId,{ok:!1,note:y});try{let y=mr(d.runId);if(!y){g("this runner no longer has that PR on file - it may have been decided already");return}let _=t.repos[y.repoName];if(!_){g(`no local checkout mapped for "${y.repoName}" on this machine`);return}let M=st(t,y.repoName);if(!M){g("no GitHub token on this runner for that repo");return}let O=await new rt(M).getPullRequest(y.owner,y.repo,y.prNumber);if(!O){g("that pull request no longer exists on GitHub");return}if(O.merged||O.state==="closed"){g("that pull request is already merged or closed - there is nothing left to fix");return}let B=l.find(re=>re.repoName===y.repoName),Y=y.nextDecisionSeq??1e5,N=(re,j)=>{v.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:j}),y.nextDecisionSeq=Y,Nt(y)},U=await ew({cfg:t,repoPath:_.path,branch:y.branch,baseBranch:O.baseRef||"main",issueKey:y.issueKey,agentId:B?.defaultAgent||_e.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:d.failedTests,...d.finding?{finding:{title:d.finding.title,detail:d.finding.detail}}:{},timeoutSeconds:900,onLog:N});U.ok&&U.headSha&&(y.headSha=U.headSha,Nt(y),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:U.headSha,failedTests:U.remaining??[],...U.testsPassed!==void 0?{testsPassed:U.testsPassed}:{},...U.testsTotal!==void 0?{testsTotal:U.testsTotal}:{}})),Ct(_.path,{issueKey:y.issueKey,runId:d.runId,title:d.finding?U.ok?U.headSha?`finding fixed on the PR: ${d.finding.title.slice(0,80)}`:`finding declined by the agent: ${d.finding.title.slice(0,80)}`:"dashboard finding fix failed":U.ok?U.headSha?(U.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:U.note.slice(0,500)}),v.sendTestFixResult(d.requestId,U)}catch(y){g(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async d=>{try{let g=await f.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,g)}catch(g){v.sendRunAnswerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message.slice(0,300):String(g)})}},onResolveConflict:async d=>{let g=y=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:y});try{let y=mr(d.runId);if(!y){g("this runner no longer has that PR on file - it may have been decided already");return}let _=t.repos[y.repoName];if(!_){g(`no local checkout mapped for "${y.repoName}" on this machine`);return}let M=st(t,y.repoName);if(!M){g("no GitHub token on this runner for that repo");return}let O=await new rt(M).getPullRequest(y.owner,y.repo,y.prNumber);if(!O){g("that pull request no longer exists on GitHub");return}if(!O.baseRef){g("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let B=l.find(re=>re.repoName===y.repoName),Y=y.nextDecisionSeq??1e5,N=(re,j)=>{v.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:j}),y.nextDecisionSeq=Y,Nt(y)},U=await Xb({cfg:t,repoPath:_.path,branch:y.branch,baseBranch:O.baseRef,issueKey:y.issueKey,agentId:B?.defaultAgent||_e.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:N});U.ok&&U.headSha&&(y.headSha=U.headSha,y.conflictNotified=!1,Nt(y),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:U.headSha})),v.sendResolveConflictResult(d.requestId,U)}catch(y){g(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:d=>{try{let g=_=>{try{return Ge.default.existsSync(_)&&Ge.default.readdirSync(_).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([_,M])=>({agent:"claude-code",name:_,loggedIn:g(M.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:y,defaultLoggedIn:g(nn.default.join(Vs.default.homedir(),".claude")),agentsWithoutProfiles:_e.REGISTERED_AGENTS.filter(_=>!_.capabilities.loginProfiles).map(_=>_.id)})}catch(g){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onJiraUsers:async d=>{try{let g=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:g})}catch(g){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}},onJiraVersions:async d=>{let g=l.find(y=>y.id===d.projectId);if(!g?.jiraProjectKey){v.sendJiraVersionsResult(d.requestId,{ok:!1,versions:[],error:g?"this project has no Jira board key yet - set it in project settings first":A(d.projectId)});return}try{let y=await s(g.repoName).listVersions(g.jiraProjectKey);v.sendJiraVersionsResult(d.requestId,{ok:!0,versions:y})}catch(y){v.sendJiraVersionsResult(d.requestId,{ok:!1,versions:[],error:y instanceof Error?y.message:String(y)})}},onMonitorRun:async d=>{let g=$?await $.runNow(d.checkId):{ok:!1,error:"monitoring is not ready yet on this runner"};v.send({type:"monitor.run.result",requestId:d.requestId,ok:g.ok,...g.error?{error:g.error}:{}})},onMonitorRebaseline:async d=>{try{let{clearBaseline:g}=await Promise.resolve().then(()=>(Ud(),Ld));g(d.checkId),v.send({type:"monitor.rebaseline.result",requestId:d.requestId,ok:!0}),$&&$.runNow(d.checkId)}catch(g){v.send({type:"monitor.rebaseline.result",requestId:d.requestId,ok:!1,error:g instanceof Error?g.message:String(g)})}},onMonitorSuggest:async d=>{let g=y=>v.send({type:"monitor.suggest.result",requestId:d.requestId,ok:!1,error:y,name:"",commands:[],parseRules:{amberPattern:"",redPattern:"",greenRequires:""},notes:""});try{let y=x(d.projectId);if(!y)return g(A(d.projectId));let _=Ce(t,y.project,"assist");if("error"in _)return g(_.error);let{suggestMonitorCheck:M}=await Promise.resolve().then(()=>(Kk(),Hk)),O=await M({agent:_,repoPath:y.repoPath,projectId:d.projectId,notes:d.notes});v.send({type:"monitor.suggest.result",requestId:d.requestId,ok:O.ok,...O.error?{error:O.error}:{},name:O.name,commands:O.commands,parseRules:O.parseRules,...O.schedule?{schedule:O.schedule}:{},notes:O.notes})}catch(y){g(y instanceof Error?y.message:String(y))}},onMonitorDiscover:async d=>{try{let{discoverForMonitoring:g}=await Promise.resolve().then(()=>(op(),qk)),y=await g();v.send({type:"monitor.discover.result",requestId:d.requestId,ok:!0,...y})}catch(g){v.send({type:"monitor.discover.result",requestId:d.requestId,ok:!1,error:g instanceof Error?g.message:String(g),os:{platform:"",arch:"",release:""},services:[],webServers:[],backupCandidates:[],dbHints:[]})}}});w.transport=v,f=new zc(t,s,v),f.setExternalBusy(()=>K.size);let P=f.recoverCrashedRuns(),F=Object.values(bs()).filter(d=>d.kind==="implement").map(d=>d.repoPath);yu(Object.values(t.repos).map(d=>d.path),[...F,...P]).catch(()=>{}),$=new bc(v,()=>ke()??t,(d,g)=>{let y=l.find(_=>_.id===d.projectId);if(!y){b.warn(`monitor ${d.name}: jiraNotify is on but no linked project - no ticket filed`);return}(async()=>{try{let _=await s(y.repoName).createIssue(y.jiraProjectKey,`[Monitoring] ${d.name} is ${g.status.toUpperCase()}`,`${g.summary}
1858
+ 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.`,M=await y.adapter.run({repoPath:g.repoPath,prompt:_,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Zn.randomUUID)(),onLog:()=>{}});Se({surface:"setup_ask",projectId:d.projectId,agentId:y.adapter.id,refKind:"none",...ve(M)});let O=M.resultText.trim();v.sendSetupAskResult(d.requestId,O?{ok:!0,answer:O}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(g){v.sendSetupAskResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupClaudeMdSave:async d=>{try{let g=x(d.projectId);if(!g){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",_=await Bh({repoPath:g.repoPath,relPath:y,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});_.ok&&b.info(`Setup: wrote human-approved ${y} to ${g.repoPath} - ${_.note}`),v.sendSetupClaudeMdSaveResult(d.requestId,_)}catch(g){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRepoDocSave:async d=>{try{let g=x(d.projectId);if(!g){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Bh({repoPath:g.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&b.info(`Saved approved doc ${d.relPath} into ${g.repoPath}`),v.sendRepoDocSaveResult(d.requestId,y)}catch(g){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:im(d.projectIds,d.since)})}catch(g){v.sendAuditStatsResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let g=()=>{let _=d.version?.trim()?`allwright@${d.version.trim()}`:"allwright@latest";b.info(`Installing ${_}`);let M=nn.default.dirname(process.execPath),O=Ge.default.existsSync(nn.default.join(M,"npm"))?nn.default.join(M,"npm"):"npm";(0,rn.execFile)(O,["install","-g",_],{timeout:18e4,env:{...process.env,PATH:`${M}:${process.env.PATH??""}`}},(F,Y,P)=>{if(F){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(P||F.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),b.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){g();return}if(m){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),b.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s)/chat turn(s) to finish`),m=setInterval(()=>{f.idle&&(clearInterval(m),m=null,g())},5e3)},onRunnerUninstall:d=>{if(!f.idle){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let g;try{g=Ec()}catch(_){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:_ instanceof Error?_.message:String(_)});return}let y=g.problems.length===0;if(v.sendRunnerUninstallResult(d.requestId,{ok:y,error:y?void 0:g.problems.join("; "),note:y?[g.serviceRemoved?"service stopped and removed":"no systemd service was installed here",g.configRemoved?`config deleted (${g.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:g.serviceRemoved||g.serviceAbsent,configRemoved:g.configRemoved}),!y){b.info("Uninstall requested from the dashboard, but it could not complete here");return}b.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{Ic(),process.exit(0)},1500)},onTestFix:async d=>{let g=y=>v.sendTestFixResult(d.requestId,{ok:!1,note:y});try{let y=mr(d.runId);if(!y){g("this runner no longer has that PR on file - it may have been decided already");return}let _=t.repos[y.repoName];if(!_){g(`no local checkout mapped for "${y.repoName}" on this machine`);return}let M=st(t,y.repoName);if(!M){g("no GitHub token on this runner for that repo");return}let O=await new Ye(M).getPullRequest(y.owner,y.repo,y.prNumber);if(!O){g("that pull request no longer exists on GitHub");return}if(O.merged||O.state==="closed"){g("that pull request is already merged or closed - there is nothing left to fix");return}let F=l.find(re=>re.repoName===y.repoName),Y=y.nextDecisionSeq??1e5,P=(re,j)=>{v.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:j}),y.nextDecisionSeq=Y,Nt(y)},U=await ew({cfg:t,repoPath:_.path,branch:y.branch,baseBranch:O.baseRef||"main",issueKey:y.issueKey,agentId:F?.defaultAgent||_e.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:d.failedTests,...d.finding?{finding:{title:d.finding.title,detail:d.finding.detail}}:{},timeoutSeconds:900,onLog:P});U.ok&&U.headSha&&(y.headSha=U.headSha,Nt(y),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:U.headSha,failedTests:U.remaining??[],...U.testsPassed!==void 0?{testsPassed:U.testsPassed}:{},...U.testsTotal!==void 0?{testsTotal:U.testsTotal}:{}})),Ct(_.path,{issueKey:y.issueKey,runId:d.runId,title:d.finding?U.ok?U.headSha?`finding fixed on the PR: ${d.finding.title.slice(0,80)}`:`finding declined by the agent: ${d.finding.title.slice(0,80)}`:"dashboard finding fix failed":U.ok?U.headSha?(U.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:U.note.slice(0,500)}),v.sendTestFixResult(d.requestId,U)}catch(y){g(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async d=>{try{let g=await f.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,g)}catch(g){v.sendRunAnswerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message.slice(0,300):String(g)})}},onResolveConflict:async d=>{let g=y=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:y});try{let y=mr(d.runId);if(!y){g("this runner no longer has that PR on file - it may have been decided already");return}let _=t.repos[y.repoName];if(!_){g(`no local checkout mapped for "${y.repoName}" on this machine`);return}let M=st(t,y.repoName);if(!M){g("no GitHub token on this runner for that repo");return}let O=await new Ye(M).getPullRequest(y.owner,y.repo,y.prNumber);if(!O){g("that pull request no longer exists on GitHub");return}if(!O.baseRef){g("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let F=l.find(re=>re.repoName===y.repoName),Y=y.nextDecisionSeq??1e5,P=(re,j)=>{v.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:j}),y.nextDecisionSeq=Y,Nt(y)},U=await Xb({cfg:t,repoPath:_.path,branch:y.branch,baseBranch:O.baseRef,issueKey:y.issueKey,agentId:F?.defaultAgent||_e.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:P});U.ok&&U.headSha&&(y.headSha=U.headSha,y.conflictNotified=!1,Nt(y),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:U.headSha})),v.sendResolveConflictResult(d.requestId,U)}catch(y){g(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:d=>{try{let g=_=>{try{return Ge.default.existsSync(_)&&Ge.default.readdirSync(_).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([_,M])=>({agent:"claude-code",name:_,loggedIn:g(M.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:y,defaultLoggedIn:g(nn.default.join(Vs.default.homedir(),".claude")),agentsWithoutProfiles:_e.REGISTERED_AGENTS.filter(_=>!_.capabilities.loginProfiles).map(_=>_.id)})}catch(g){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onJiraUsers:async d=>{try{let g=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:g})}catch(g){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}},onJiraVersions:async d=>{let g=l.find(y=>y.id===d.projectId);if(!g?.jiraProjectKey){v.sendJiraVersionsResult(d.requestId,{ok:!1,versions:[],error:g?"this project has no Jira board key yet - set it in project settings first":A(d.projectId)});return}try{let y=await s(g.repoName).listVersions(g.jiraProjectKey);v.sendJiraVersionsResult(d.requestId,{ok:!0,versions:y})}catch(y){v.sendJiraVersionsResult(d.requestId,{ok:!1,versions:[],error:y instanceof Error?y.message:String(y)})}},onMonitorRun:async d=>{let g=$?await $.runNow(d.checkId):{ok:!1,error:"monitoring is not ready yet on this runner"};v.send({type:"monitor.run.result",requestId:d.requestId,ok:g.ok,...g.error?{error:g.error}:{}})},onMonitorRebaseline:async d=>{try{let{clearBaseline:g}=await Promise.resolve().then(()=>(Ud(),Ld));g(d.checkId),v.send({type:"monitor.rebaseline.result",requestId:d.requestId,ok:!0}),$&&$.runNow(d.checkId)}catch(g){v.send({type:"monitor.rebaseline.result",requestId:d.requestId,ok:!1,error:g instanceof Error?g.message:String(g)})}},onMonitorSuggest:async d=>{let g=y=>v.send({type:"monitor.suggest.result",requestId:d.requestId,ok:!1,error:y,name:"",commands:[],parseRules:{amberPattern:"",redPattern:"",greenRequires:""},notes:""});try{let y=x(d.projectId);if(!y)return g(A(d.projectId));let _=Ce(t,y.project,"assist");if("error"in _)return g(_.error);let{suggestMonitorCheck:M}=await Promise.resolve().then(()=>(Kk(),Hk)),O=await M({agent:_,repoPath:y.repoPath,projectId:d.projectId,notes:d.notes});v.send({type:"monitor.suggest.result",requestId:d.requestId,ok:O.ok,...O.error?{error:O.error}:{},name:O.name,commands:O.commands,parseRules:O.parseRules,...O.schedule?{schedule:O.schedule}:{},notes:O.notes})}catch(y){g(y instanceof Error?y.message:String(y))}},onMonitorDiscover:async d=>{try{let{discoverForMonitoring:g}=await Promise.resolve().then(()=>(op(),qk)),y=await g();v.send({type:"monitor.discover.result",requestId:d.requestId,ok:!0,...y})}catch(g){v.send({type:"monitor.discover.result",requestId:d.requestId,ok:!1,error:g instanceof Error?g.message:String(g),os:{platform:"",arch:"",release:""},services:[],webServers:[],backupCandidates:[],dbHints:[]})}}});w.transport=v,f=new zc(t,s,v),f.setExternalBusy(()=>K.size);let N=f.recoverCrashedRuns(),B=Object.values(bs()).filter(d=>d.kind==="implement").map(d=>d.repoPath);yu(Object.values(t.repos).map(d=>d.path),[...B,...N]).catch(()=>{}),$=new bc(v,()=>ke()??t,(d,g)=>{let y=l.find(_=>_.id===d.projectId);if(!y){b.warn(`monitor ${d.name}: jiraNotify is on but no linked project - no ticket filed`);return}(async()=>{try{let _=await s(y.repoName).createIssue(y.jiraProjectKey,`[Monitoring] ${d.name} is ${g.status.toUpperCase()}`,`${g.summary}
1859
1859
 
1860
- `+(g.excerpt?"```\n"+g.excerpt.slice(0,3e3)+"\n```\n\n":"")+"Filed automatically by monitoring (one ticket per red episode). The check keeps running; see the Monitoring page for recovery.");b.info(`monitor ${d.name}: red episode filed as ${_.key}`)}catch(_){b.warn(`monitor ${d.name}: could not file the red-episode ticket: ${_ instanceof Error?_.message:_}`)}})()}),Sf(v),v.start(),f.start(),$.start();let V=()=>{b.info("shutting down"),m&&clearInterval(m),v.stop(),vb(process.pid),Hd(),process.exit(0)},te=!1,L=()=>{if(te){b.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),V();return}if(te=!0,f.stop(),f.idle){V();return}b.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{f.idle&&(clearInterval(d),V())},3e3)};process.on("SIGINT",L),process.on("SIGTERM",L),process.on("SIGHUP",()=>{try{let d=ge();for(let g of Object.keys(t))delete t[g];Object.assign(t,d),n=d.jira?new Ye(d.jira):od(),r.clear(),b.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){b.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Ke.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=ge();if(t.foreground){XC(e);return}let n=Ps();if(n&&Ns(n)){b.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=$i();if(r){b.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=yb(),i=(0,rn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),wb(i.pid),b.info(`Runner started in the background (pid ${i.pid}).`),b.info(`Logs: ${wc()}`),b.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.");try{let{serviceProtection:a,selfHealServiceProtection:c}=await Promise.resolve().then(()=>(Ac(),jb)),l=a();l.protected===!1&&(c()?b.info("service unit hardened: restarts now wait for live runs (KillMode=mixed)"):b.warn("this service unit would kill live runs on restart - fix once with: "+l.fixCommand))}catch{}});Ke.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=Ps();if(!e||!Ns(e)){b.info("no background runner is running"),e&&Ge.default.rmSync(Ai(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ge.default.rmSync(Ai(),{force:!0}),b.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),b.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Ke.command("status").description("Check whether the background runner is running").action(()=>{let t=Ps();t&&Ns(t)?b.info(`running in the background (pid ${t})`):b.info("not running")});Ke.parseAsync().catch(t=>{b.error(t instanceof Error?t.message:String(t)),process.exit(1)});
1860
+ `+(g.excerpt?"```\n"+g.excerpt.slice(0,3e3)+"\n```\n\n":"")+"Filed automatically by monitoring (one ticket per red episode). The check keeps running; see the Monitoring page for recovery.");b.info(`monitor ${d.name}: red episode filed as ${_.key}`)}catch(_){b.warn(`monitor ${d.name}: could not file the red-episode ticket: ${_ instanceof Error?_.message:_}`)}})()}),Sf(v),v.start(),f.start(),$.start();let V=()=>{b.info("shutting down"),m&&clearInterval(m),v.stop(),vb(process.pid),Hd(),process.exit(0)},te=!1,L=()=>{if(te){b.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),V();return}if(te=!0,f.stop(),f.idle){V();return}b.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{f.idle&&(clearInterval(d),V())},3e3)};process.on("SIGINT",L),process.on("SIGTERM",L),process.on("SIGHUP",()=>{try{let d=ge();for(let g of Object.keys(t))delete t[g];Object.assign(t,d),n=d.jira?new Xe(d.jira):od(),r.clear(),b.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){b.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Ke.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=ge();if(t.foreground){XC(e);return}let n=Ps();if(n&&Ns(n)){b.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=$i();if(r){b.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=yb(),i=(0,rn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),wb(i.pid),b.info(`Runner started in the background (pid ${i.pid}).`),b.info(`Logs: ${wc()}`),b.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.");try{let{serviceProtection:a,selfHealServiceProtection:c}=await Promise.resolve().then(()=>(Ac(),jb)),l=a();l.protected===!1&&(c()?b.info("service unit hardened: restarts now wait for live runs (KillMode=mixed)"):b.warn("this service unit would kill live runs on restart - fix once with: "+l.fixCommand))}catch{}});Ke.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=Ps();if(!e||!Ns(e)){b.info("no background runner is running"),e&&Ge.default.rmSync(Ai(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ge.default.rmSync(Ai(),{force:!0}),b.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),b.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Ke.command("status").description("Check whether the background runner is running").action(()=>{let t=Ps();t&&Ns(t)?b.info(`running in the background (pid ${t})`):b.info("not running")});Ke.parseAsync().catch(t=>{b.error(t instanceof Error?t.message:String(t)),process.exit(1)});