allwright 1.111.0 → 1.112.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 +146 -183
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -21,7 +21,7 @@ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
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=>dk(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=gn.basename(e,gn.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=Me.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
23
  `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Lh(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})}Uh.Command=ml});var Kh=me(wt=>{var{Argument:Fh}=Uo(),{Command:gl}=qh(),{CommanderError:pk,InvalidArgumentError:Bh}=Mi(),{Help:fk}=al(),{Option:Hh}=ul();wt.program=new gl;wt.createCommand=t=>new gl(t);wt.createOption=(t,e)=>new Hh(t,e);wt.createArgument=(t,e)=>new Fh(t,e);wt.Command=gl;wt.Option=Hh;wt.Argument=Fh;wt.Help=fk;wt.CommanderError=pk;wt.InvalidArgumentError=Bh;wt.InvalidOptionArgumentError=Bh});var ue,yl,G,Yt,ji=X(()=>{(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})(ue||(ue={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(yl||(yl={}));G=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yt=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 O,mk,it,qo=X(()=>{ji();O=ue.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),mk=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),it=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 d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],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,ue.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};it.create=t=>new it(t)});var gk,yn,bl=X(()=>{qo();ji();gk=(t,e)=>{let n;switch(t.code){case O.invalid_type:t.received===G.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:n=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case O.invalid_union:n="Invalid input";break;case O.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case O.invalid_enum_value:n=`Invalid enum value. Expected ${ue.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:n="Invalid function arguments";break;case O.invalid_return_type:n="Invalid function return type";break;case O.invalid_date:n="Invalid date";break;case O.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ue.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case O.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 O.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 O.custom:n="Invalid input";break;case O.invalid_intersection_types:n="Intersection results could not be merged";break;case O.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:n="Number must be finite";break;default:n=e.defaultError,ue.assertNever(t)}return{message:n}},yn=gk});function yk(t){Zh=t}function js(){return Zh}var Zh,Fo=X(()=>{bl();Zh=yn});function K(t,e){let n=js(),r=Oi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===yn?void 0:yn].filter(s=>!!s)});t.common.issues.push(r)}var Oi,bk,Ke,ne,wr,Ve,Bo,Ho,Fn,Os,wl=X(()=>{Fo();bl();Oi=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(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}},bk=[];Ke=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 ne;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 ne;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}}},ne=Object.freeze({status:"aborted"}),wr=t=>({status:"dirty",value:t}),Ve=t=>({status:"valid",value:t}),Bo=t=>t.status==="aborted",Ho=t=>t.status==="dirty",Fn=t=>t.status==="valid",Os=t=>typeof Promise<"u"&&t instanceof Promise});var Vh=X(()=>{});var Q,Yh=X(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Q||(Q={}))});function ae(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 ep(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 jk(t){return new RegExp(`^${ep(t)}$`)}function tp(t){let e=`${Qh}T${ep(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 Ok(t,e){return!!((e==="v4"||!e)&&Ek.test(t)||(e==="v6"||!e)&&$k.test(t))}function zk(t,e){if(!xk.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 Dk(t,e){return!!((e==="v4"||!e)&&Ak.test(t)||(e==="v6"||!e)&&Ck.test(t))}function Lk(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 zs(t){if(t instanceof ot){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=vt.create(zs(r))}return new ot({...t._def,shape:()=>e})}else return t instanceof vn?new vn({...t._def,type:zs(t.element)}):t instanceof vt?vt.create(zs(t.unwrap())):t instanceof Xt?Xt.create(zs(t.unwrap())):t instanceof Jt?Jt.create(t.items.map(e=>zs(e))):t}function kl(t,e){let n=Yt(t),r=Yt(e);if(t===e)return{valid:!0,data:t};if(n===G.object&&r===G.object){let s=ue.objectKeys(e),i=ue.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=kl(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=kl(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 np(t,e){return new $r({values:t,typeName:re.ZodEnum,...ae(e)})}function Xh(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function rp(t,e={},n){return t?Hn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=Xh(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=Xh(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Hn.create()}var kt,Jh,de,wk,vk,kk,Sk,_k,xk,Tk,Rk,Ik,vl,Ek,Ak,$k,Ck,Pk,Nk,Qh,Mk,Bn,vr,kr,Sr,_r,Ds,xr,Tr,Hn,wn,Ut,Ls,vn,ot,Rr,bn,Ko,Ir,Jt,Wo,Us,qs,Go,Er,Ar,$r,Cr,Kn,St,vt,Xt,Pr,Nr,Fs,Uk,zi,Di,Mr,qk,re,Fk,sp,ip,Bk,Hk,op,Kk,Wk,Gk,Zk,Vk,Yk,Jk,Xk,Qk,e0,t0,n0,r0,s0,i0,o0,a0,c0,l0,d0,u0,h0,p0,f0,m0,g0,y0,b0,w0,v0,k0,S0,_0,x0,ap=X(()=>{qo();Fo();Yh();wl();ji();kt=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}},Jh=(t,e)=>{if(Fn(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 it(t.common.issues);return this._error=n,this._error}}};de=class{get description(){return this._def.description}_getType(e){return Yt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ke,ctx:{common:e.parent.common,data:e.data,parsedType:Yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Os(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:Yt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Jh(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Fn(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=>Fn(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:Yt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Os(s)?s:Promise.resolve(s));return Jh(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:O.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 St({schema:this,typeName:re.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 vt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vn.create(this)}promise(){return Kn.create(this,this._def)}or(e){return Rr.create([this,e],this._def)}and(e){return Ir.create(this,e,this._def)}transform(e){return new St({...ae(this._def),schema:this,typeName:re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Pr({...ae(this._def),innerType:this,defaultValue:n,typeName:re.ZodDefault})}brand(){return new zi({typeName:re.ZodBranded,type:this,...ae(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Nr({...ae(this._def),innerType:this,catchValue:n,typeName:re.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Di.create(this,e)}readonly(){return Mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wk=/^c[^\s-]{8,}$/i,vk=/^[0-9a-z]+$/,kk=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Sk=/^[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,_k=/^[a-z0-9_-]{21}$/i,xk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tk=/^[-+]?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)?)??$/,Rk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ik="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ek=/^(?:(?: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])$/,Ak=/^(?:(?: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])$/,$k=/^(([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]))$/,Ck=/^(([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])$/,Pk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qh="((\\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])))",Mk=new RegExp(`^${Qh}$`);Bn=class t extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==G.string){let i=this._getOrReturnCtx(e);return K(i,{code:O.invalid_type,expected:G.string,received:i.parsedType}),ne}let r=new Ke,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:O.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),K(s,{code:O.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?K(s,{code:O.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&K(s,{code:O.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Rk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"email",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")vl||(vl=new RegExp(Ik,"u")),vl.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"emoji",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Sk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"uuid",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")_k.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"nanoid",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")wk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cuid",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")vk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cuid2",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")kk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"ulid",code:O.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),K(s,{validation:"url",code:O.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),K(s,{validation:"regex",code:O.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),K(s,{code:O.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),K(s,{code:O.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),K(s,{code:O.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?tp(i).test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:O.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Mk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:O.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?jk(i).test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:O.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Tk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"duration",code:O.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Ok(e.data,i.version)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"ip",code:O.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?zk(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"jwt",code:O.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Dk(e.data,i.version)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cidr",code:O.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Pk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"base64",code:O.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Nk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"base64url",code:O.invalid_string,message:i.message}),r.dirty()):ue.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:O.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}};Bn.create=t=>new Bn({checks:[],typeName:re.ZodString,coerce:t?.coerce??!1,...ae(t)});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)!==G.number){let i=this._getOrReturnCtx(e);return K(i,{code:O.invalid_type,expected:G.number,received:i.parsedType}),ne}let r,s=new Ke;for(let i of this._def.checks)i.kind==="int"?ue.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),K(r,{code:O.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),K(r,{code:O.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),K(r,{code:O.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Lk(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),K(r,{code:O.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),K(r,{code:O.not_finite,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,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"&&ue.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};vr.create=t=>new vr({checks:[],typeName:re.ZodNumber,coerce:t?.coerce||!1,...ae(t)});kr=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)!==G.bigint)return this._getInvalidInput(e);let r,s=new Ke;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),K(r,{code:O.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),K(r,{code:O.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),K(r,{code:O.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return K(n,{code:O.invalid_type,expected:G.bigint,received:n.parsedType}),ne}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}};kr.create=t=>new kr({checks:[],typeName:re.ZodBigInt,coerce:t?.coerce??!1,...ae(t)});Sr=class extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==G.boolean){let r=this._getOrReturnCtx(e);return K(r,{code:O.invalid_type,expected:G.boolean,received:r.parsedType}),ne}return Ve(e.data)}};Sr.create=t=>new Sr({typeName:re.ZodBoolean,coerce:t?.coerce||!1,...ae(t)});_r=class t extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==G.date){let i=this._getOrReturnCtx(e);return K(i,{code:O.invalid_type,expected:G.date,received:i.parsedType}),ne}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return K(i,{code:O.invalid_date}),ne}let r=new Ke,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:O.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),K(s,{code:O.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ue.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message: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}};_r.create=t=>new _r({checks:[],coerce:t?.coerce||!1,typeName:re.ZodDate,...ae(t)});Ds=class extends de{_parse(e){if(this._getType(e)!==G.symbol){let r=this._getOrReturnCtx(e);return K(r,{code:O.invalid_type,expected:G.symbol,received:r.parsedType}),ne}return Ve(e.data)}};Ds.create=t=>new Ds({typeName:re.ZodSymbol,...ae(t)});xr=class extends de{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return K(r,{code:O.invalid_type,expected:G.undefined,received:r.parsedType}),ne}return Ve(e.data)}};xr.create=t=>new xr({typeName:re.ZodUndefined,...ae(t)});Tr=class extends de{_parse(e){if(this._getType(e)!==G.null){let r=this._getOrReturnCtx(e);return K(r,{code:O.invalid_type,expected:G.null,received:r.parsedType}),ne}return Ve(e.data)}};Tr.create=t=>new Tr({typeName:re.ZodNull,...ae(t)});Hn=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return Ve(e.data)}};Hn.create=t=>new Hn({typeName:re.ZodAny,...ae(t)});wn=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ve(e.data)}};wn.create=t=>new wn({typeName:re.ZodUnknown,...ae(t)});Ut=class extends de{_parse(e){let n=this._getOrReturnCtx(e);return K(n,{code:O.invalid_type,expected:G.never,received:n.parsedType}),ne}};Ut.create=t=>new Ut({typeName:re.ZodNever,...ae(t)});Ls=class extends de{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return K(r,{code:O.invalid_type,expected:G.void,received:r.parsedType}),ne}return Ve(e.data)}};Ls.create=t=>new Ls({typeName:re.ZodVoid,...ae(t)});vn=class t extends de{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==G.array)return K(n,{code:O.invalid_type,expected:G.array,received:n.parsedType}),ne;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(K(n,{code:a?O.too_big:O.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&&(K(n,{code:O.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&&(K(n,{code:O.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 kt(n,a,n.path,c)))).then(a=>Ke.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new kt(n,a,n.path,c)));return Ke.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)}};vn.create=(t,e)=>new vn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:re.ZodArray,...ae(e)});ot=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=ue.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==G.object){let d=this._getOrReturnCtx(e);return K(d,{code:O.invalid_type,expected:G.object,received:d.parsedType}),ne}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ut&&this._def.unknownKeys==="strip"))for(let d in s.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let p=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:p._parse(new kt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof Ut){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")c.length>0&&(K(s,{code:O.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:d._parse(new kt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of l){let f=await p.key,g=await p.value;d.push({key:f,value:g,alwaysSet:p.alwaysSet})}return d}).then(d=>Ke.mergeObjectSync(r,d)):Ke.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:re.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ue.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ue.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return zs(this)}partial(e){let n={};for(let r of ue.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ue.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof vt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return np(ue.objectKeys(this.shape))}};ot.create=(t,e)=>new ot({shape:()=>t,unknownKeys:"strip",catchall:Ut.create(),typeName:re.ZodObject,...ae(e)});ot.strictCreate=(t,e)=>new ot({shape:()=>t,unknownKeys:"strict",catchall:Ut.create(),typeName:re.ZodObject,...ae(e)});ot.lazycreate=(t,e)=>new ot({shape:t,unknownKeys:"strip",catchall:Ut.create(),typeName:re.ZodObject,...ae(e)});Rr=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 it(c.ctx.common.issues));return K(n,{code:O.invalid_union,unionErrors:a}),ne}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 d={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(l=>new it(l));return K(n,{code:O.invalid_union,unionErrors:c}),ne}}get options(){return this._def.options}};Rr.create=(t,e)=>new Rr({options:t,typeName:re.ZodUnion,...ae(e)});bn=t=>t instanceof Er?bn(t.schema):t instanceof St?bn(t.innerType()):t instanceof Ar?[t.value]:t instanceof $r?t.options:t instanceof Cr?ue.objectValues(t.enum):t instanceof Pr?bn(t._def.innerType):t instanceof xr?[void 0]:t instanceof Tr?[null]:t instanceof vt?[void 0,...bn(t.unwrap())]:t instanceof Xt?[null,...bn(t.unwrap())]:t instanceof zi||t instanceof Mr?bn(t.unwrap()):t instanceof Nr?bn(t._def.innerType):[],Ko=class t extends de{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.object)return K(n,{code:O.invalid_type,expected:G.object,received:n.parsedType}),ne;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}):(K(n,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ne)}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=bn(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:re.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ae(r)})}};Ir=class extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(Bo(i)||Bo(a))return ne;let c=kl(i.value,a.value);return c.valid?((Ho(i)||Ho(a))&&n.dirty(),{status:n.value,value:c.data}):(K(r,{code:O.invalid_intersection_types}),ne)};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}))}};Ir.create=(t,e,n)=>new Ir({left:t,right:e,typeName:re.ZodIntersection,...ae(n)});Jt=class t extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.array)return K(r,{code:O.invalid_type,expected:G.array,received:r.parsedType}),ne;if(r.data.length<this._def.items.length)return K(r,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ne;!this._def.rest&&r.data.length>this._def.items.length&&(K(r,{code:O.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 kt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Ke.mergeArray(n,a)):Ke.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Jt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jt({items:t,typeName:re.ZodTuple,rest:null,...ae(e)})};Wo=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!==G.object)return K(r,{code:O.invalid_type,expected:G.object,received:r.parsedType}),ne;let s=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)s.push({key:i._parse(new kt(r,c,r.path,c)),value:a._parse(new kt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Ke.mergeObjectAsync(n,s):Ke.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:re.ZodRecord,...ae(r)}):new t({keyType:Bn.create(),valueType:e,typeName:re.ZodRecord,...ae(n)})}},Us=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!==G.map)return K(r,{code:O.invalid_type,expected:G.map,received:r.parsedType}),ne;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new kt(r,c,r.path,[d,"key"])),value:i._parse(new kt(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,p=await l.value;if(d.status==="aborted"||p.status==="aborted")return ne;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(d.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,p=l.value;if(d.status==="aborted"||p.status==="aborted")return ne;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(d.value,p.value)}return{status:n.value,value:c}}}};Us.create=(t,e,n)=>new Us({valueType:e,keyType:t,typeName:re.ZodMap,...ae(n)});qs=class t extends de{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.set)return K(r,{code:O.invalid_type,expected:G.set,received:r.parsedType}),ne;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(K(r,{code:O.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&&(K(r,{code:O.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 d=new Set;for(let p of l){if(p.status==="aborted")return ne;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let c=[...r.data.values()].map((l,d)=>i._parse(new kt(r,l,r.path,d)));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)}};qs.create=(t,e)=>new qs({valueType:t,minSize:null,maxSize:null,typeName:re.ZodSet,...ae(e)});Go=class t extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.function)return K(n,{code:O.invalid_type,expected:G.function,received:n.parsedType}),ne;function r(c,l){return Oi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),yn].filter(d=>!!d),issueData:{code:O.invalid_arguments,argumentsError:l}})}function s(c,l){return Oi({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),yn].filter(d=>!!d),issueData:{code:O.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Kn){let c=this;return Ve(async function(...l){let d=new it([]),p=await c._def.args.parseAsync(l,i).catch(v=>{throw d.addIssue(r(l,v)),d}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let c=this;return Ve(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new it([r(l,d.error)]);let p=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(p,i);if(!f.success)throw new it([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:Jt.create(e).rest(wn.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||Jt.create([]).rest(wn.create()),returns:n||wn.create(),typeName:re.ZodFunction,...ae(r)})}},Er=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})}};Er.create=(t,e)=>new Er({getter:t,typeName:re.ZodLazy,...ae(e)});Ar=class extends de{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return K(n,{received:n.data,code:O.invalid_literal,expected:this._def.value}),ne}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ar.create=(t,e)=>new Ar({value:t,typeName:re.ZodLiteral,...ae(e)});$r=class t extends de{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return K(n,{expected:ue.joinValues(r),received:n.parsedType,code:O.invalid_type}),ne}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 K(n,{received:n.data,code:O.invalid_enum_value,options:r}),ne}return Ve(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.create=np;Cr=class extends de{_parse(e){let n=ue.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==G.string&&r.parsedType!==G.number){let s=ue.objectValues(n);return K(r,{expected:ue.joinValues(s),received:r.parsedType,code:O.invalid_type}),ne}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ue.objectValues(n);return K(r,{received:r.data,code:O.invalid_enum_value,options:s}),ne}return Ve(e.data)}get enum(){return this._def.values}};Cr.create=(t,e)=>new Cr({values:t,typeName:re.ZodNativeEnum,...ae(e)});Kn=class extends de{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==G.promise&&n.common.async===!1)return K(n,{code:O.invalid_type,expected:G.promise,received:n.parsedType}),ne;let r=n.parsedType===G.promise?n.data:Promise.resolve(n.data);return Ve(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Kn.create=(t,e)=>new Kn({type:t,typeName:re.ZodPromise,...ae(e)});St=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===re.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=>{K(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 ne;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?ne:l.status==="dirty"?wr(l.value):n.value==="dirty"?wr(l.value):l});{if(n.value==="aborted")return ne;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ne:c.status==="dirty"?wr(c.value):n.value==="dirty"?wr(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"?ne:(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"?ne:(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(!Fn(a))return ne;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=>Fn(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):ne);ue.assertNever(s)}};St.create=(t,e,n)=>new St({schema:t,typeName:re.ZodEffects,effect:e,...ae(n)});St.createWithPreprocess=(t,e,n)=>new St({schema:e,effect:{type:"preprocess",transform:t},typeName:re.ZodEffects,...ae(n)});vt=class extends de{_parse(e){return this._getType(e)===G.undefined?Ve(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vt.create=(t,e)=>new vt({innerType:t,typeName:re.ZodOptional,...ae(e)});Xt=class extends de{_parse(e){return this._getType(e)===G.null?Ve(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xt.create=(t,e)=>new Xt({innerType:t,typeName:re.ZodNullable,...ae(e)});Pr=class extends de{_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}};Pr.create=(t,e)=>new Pr({innerType:t,typeName:re.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ae(e)});Nr=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 Os(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new it(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new it(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:re.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ae(e)});Fs=class extends de{_parse(e){if(this._getType(e)!==G.nan){let r=this._getOrReturnCtx(e);return K(r,{code:O.invalid_type,expected:G.nan,received:r.parsedType}),ne}return{status:"valid",value:e.data}}};Fs.create=t=>new Fs({typeName:re.ZodNaN,...ae(t)});Uk=Symbol("zod_brand"),zi=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}},Di=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"?ne:i.status==="dirty"?(n.dirty(),wr(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"?ne: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:re.ZodPipeline})}},Mr=class extends de{_parse(e){let n=this._def.innerType._parse(e),r=s=>(Fn(s)&&(s.value=Object.freeze(s.value)),s);return Os(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:re.ZodReadonly,...ae(e)});qk={object:ot.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"})(re||(re={}));Fk=(t,e={message:`Input not instance of ${t.name}`})=>rp(n=>n instanceof t,e),sp=Bn.create,ip=vr.create,Bk=Fs.create,Hk=kr.create,op=Sr.create,Kk=_r.create,Wk=Ds.create,Gk=xr.create,Zk=Tr.create,Vk=Hn.create,Yk=wn.create,Jk=Ut.create,Xk=Ls.create,Qk=vn.create,e0=ot.create,t0=ot.strictCreate,n0=Rr.create,r0=Ko.create,s0=Ir.create,i0=Jt.create,o0=Wo.create,a0=Us.create,c0=qs.create,l0=Go.create,d0=Er.create,u0=Ar.create,h0=$r.create,p0=Cr.create,f0=Kn.create,m0=St.create,g0=vt.create,y0=Xt.create,b0=St.createWithPreprocess,w0=Di.create,v0=()=>sp().optional(),k0=()=>ip().optional(),S0=()=>op().optional(),_0={string:(t=>Bn.create({...t,coerce:!0})),number:(t=>vr.create({...t,coerce:!0})),boolean:(t=>Sr.create({...t,coerce:!0})),bigint:(t=>kr.create({...t,coerce:!0})),date:(t=>_r.create({...t,coerce:!0}))},x0=ne});var S={};De(S,{BRAND:()=>Uk,DIRTY:()=>wr,EMPTY_PATH:()=>bk,INVALID:()=>ne,NEVER:()=>x0,OK:()=>Ve,ParseStatus:()=>Ke,Schema:()=>de,ZodAny:()=>Hn,ZodArray:()=>vn,ZodBigInt:()=>kr,ZodBoolean:()=>Sr,ZodBranded:()=>zi,ZodCatch:()=>Nr,ZodDate:()=>_r,ZodDefault:()=>Pr,ZodDiscriminatedUnion:()=>Ko,ZodEffects:()=>St,ZodEnum:()=>$r,ZodError:()=>it,ZodFirstPartyTypeKind:()=>re,ZodFunction:()=>Go,ZodIntersection:()=>Ir,ZodIssueCode:()=>O,ZodLazy:()=>Er,ZodLiteral:()=>Ar,ZodMap:()=>Us,ZodNaN:()=>Fs,ZodNativeEnum:()=>Cr,ZodNever:()=>Ut,ZodNull:()=>Tr,ZodNullable:()=>Xt,ZodNumber:()=>vr,ZodObject:()=>ot,ZodOptional:()=>vt,ZodParsedType:()=>G,ZodPipeline:()=>Di,ZodPromise:()=>Kn,ZodReadonly:()=>Mr,ZodRecord:()=>Wo,ZodSchema:()=>de,ZodSet:()=>qs,ZodString:()=>Bn,ZodSymbol:()=>Ds,ZodTransformer:()=>St,ZodTuple:()=>Jt,ZodType:()=>de,ZodUndefined:()=>xr,ZodUnion:()=>Rr,ZodUnknown:()=>wn,ZodVoid:()=>Ls,addIssueToContext:()=>K,any:()=>Vk,array:()=>Qk,bigint:()=>Hk,boolean:()=>op,coerce:()=>_0,custom:()=>rp,date:()=>Kk,datetimeRegex:()=>tp,defaultErrorMap:()=>yn,discriminatedUnion:()=>r0,effect:()=>m0,enum:()=>h0,function:()=>l0,getErrorMap:()=>js,getParsedType:()=>Yt,instanceof:()=>Fk,intersection:()=>s0,isAborted:()=>Bo,isAsync:()=>Os,isDirty:()=>Ho,isValid:()=>Fn,late:()=>qk,lazy:()=>d0,literal:()=>u0,makeIssue:()=>Oi,map:()=>a0,nan:()=>Bk,nativeEnum:()=>p0,never:()=>Jk,null:()=>Zk,nullable:()=>y0,number:()=>ip,object:()=>e0,objectUtil:()=>yl,oboolean:()=>S0,onumber:()=>k0,optional:()=>g0,ostring:()=>v0,pipeline:()=>w0,preprocess:()=>b0,promise:()=>f0,quotelessJson:()=>mk,record:()=>o0,set:()=>c0,setErrorMap:()=>yk,strictObject:()=>t0,string:()=>sp,symbol:()=>Wk,transformer:()=>m0,tuple:()=>i0,undefined:()=>Gk,union:()=>n0,unknown:()=>Yk,util:()=>ue,void:()=>Xk});var Sl=X(()=>{Fo();wl();Vh();ji();ap();qo()});var _t=X(()=>{Sl();Sl()});function te(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=Vo.default.join(Zo.default.homedir(),".config","allwright"),n=Vo.default.join(Zo.default.homedir(),".config","ticketpilot");return!kn.default.existsSync(e)&&kn.default.existsSync(n)?n:e}function Sn(){return Vo.default.join(te(),"runner.json")}function _e(){let t=Sn();if(!kn.default.existsSync(t))return null;let e=JSON.parse(kn.default.readFileSync(t,"utf8"));return _l.parse(e)}function xe(t){let e=te();kn.default.mkdirSync(e,{recursive:!0,mode:448});let n=Sn(),r=n+".tmp";kn.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384}),kn.default.renameSync(r,n),kn.default.chmodSync(n,384)}function Yo(t,e){return`${t}:${e}`}function Qt(t,e,n){return t.environments[Yo(e,n)]?.secrets??{}}function Li(t,e){return t.repos[e]?.jira??t.jira}function Ui(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function he(){let t=_e();if(!t)throw new Error(`No runner config found at ${Sn()}. Run \`allwright init\` first.`);return t}var kn,Zo,Vo,cp,_l,Ae=X(()=>{"use strict";kn=E(require("node:fs"),1),Zo=E(require("node:os"),1),Vo=E(require("node:path"),1);_t();cp=S.object({baseUrl:S.string().url(),email:S.string().email(),apiToken:S.string().min(1)}),_l=S.object({controlPlaneUrl:S.string().url(),runnerId:S.string().optional(),runnerToken:S.string().optional(),runnerName:S.string().default(Zo.default.hostname()),jira:cp.optional(),repos:S.record(S.object({path:S.string(),jira:cp.optional(),github:S.object({token:S.string().min(1),login:S.string().optional()}).optional()})).default({}),github:S.object({token:S.string().min(1),login:S.string().optional()}).optional(),githubUsers:S.record(S.object({token:S.string().min(1),login:S.string().optional()})).default({}),deploy:S.object({enabled:S.boolean().default(!1)}).default({enabled:!1}),environments:S.record(S.object({secrets:S.record(S.string()).default({})})).default({}),claudeProfiles:S.record(S.object({configDir:S.string()})).default({}),claudeBin:S.string().default("claude"),agents:S.record(S.object({bin:S.string()})).default({}),jiraUsers:S.record(S.object({email:S.string().email(),apiToken:S.string().min(1)})).default({}),auditSchedules:S.array(S.object({repoName:S.string(),role:S.enum(["security","testing"]),intervalHours:S.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:S.number().int().min(10).max(600).default(30),operatorEnabled:S.boolean().default(!1)})});var qi=me(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getParsedType=Te.ZodParsedType=Te.objectUtil=Te.util=void 0;var xl;(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})(xl||(Te.util=xl={}));var up;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(up||(Te.objectUtil=up={}));Te.ZodParsedType=xl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var I0=t=>{switch(typeof t){case"undefined":return Te.ZodParsedType.undefined;case"string":return Te.ZodParsedType.string;case"number":return Number.isNaN(t)?Te.ZodParsedType.nan:Te.ZodParsedType.number;case"boolean":return Te.ZodParsedType.boolean;case"function":return Te.ZodParsedType.function;case"bigint":return Te.ZodParsedType.bigint;case"symbol":return Te.ZodParsedType.symbol;case"object":return Array.isArray(t)?Te.ZodParsedType.array:t===null?Te.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Te.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?Te.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?Te.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?Te.ZodParsedType.date:Te.ZodParsedType.object;default:return Te.ZodParsedType.unknown}};Te.getParsedType=I0});var Qo=me(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.ZodError=Wn.quotelessJson=Wn.ZodIssueCode=void 0;var hp=qi();Wn.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 E0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");Wn.quotelessJson=E0;var Fi=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 d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],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()}};Wn.ZodError=Fi;Fi.create=t=>new Fi(t)});var Rl=me(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var Ye=Qo(),jr=qi(),A0=(t,e)=>{let n;switch(t.code){case Ye.ZodIssueCode.invalid_type:t.received===jr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Ye.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,jr.util.jsonStringifyReplacer)}`;break;case Ye.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${jr.util.joinValues(t.keys,", ")}`;break;case Ye.ZodIssueCode.invalid_union:n="Invalid input";break;case Ye.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${jr.util.joinValues(t.options)}`;break;case Ye.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${jr.util.joinValues(t.options)}, received '${t.received}'`;break;case Ye.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Ye.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Ye.ZodIssueCode.invalid_date:n="Invalid date";break;case Ye.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}"`:jr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Ye.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 Ye.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 Ye.ZodIssueCode.custom:n="Invalid input";break;case Ye.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Ye.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Ye.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,jr.util.assertNever(t)}return{message:n}};Tl.default=A0});var ea=me(Gn=>{"use strict";var $0=Gn&&Gn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Gn,"__esModule",{value:!0});Gn.defaultErrorMap=void 0;Gn.setErrorMap=C0;Gn.getErrorMap=P0;var pp=$0(Rl());Gn.defaultErrorMap=pp.default;var fp=pp.default;function C0(t){fp=t}function P0(){return fp}});var El=me(ye=>{"use strict";var N0=ye&&ye.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ye,"__esModule",{value:!0});ye.isAsync=ye.isValid=ye.isDirty=ye.isAborted=ye.OK=ye.DIRTY=ye.INVALID=ye.ParseStatus=ye.EMPTY_PATH=ye.makeIssue=void 0;ye.addIssueToContext=O0;var M0=ea(),mp=N0(Rl()),j0=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(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}};ye.makeIssue=j0;ye.EMPTY_PATH=[];function O0(t,e){let n=(0,M0.getErrorMap)(),r=(0,ye.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===mp.default?void 0:mp.default].filter(s=>!!s)});t.common.issues.push(r)}var Il=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 ye.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 ye.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}}};ye.ParseStatus=Il;ye.INVALID=Object.freeze({status:"aborted"});var z0=t=>({status:"dirty",value:t});ye.DIRTY=z0;var D0=t=>({status:"valid",value:t});ye.OK=D0;var L0=t=>t.status==="aborted";ye.isAborted=L0;var U0=t=>t.status==="dirty";ye.isDirty=U0;var q0=t=>t.status==="valid";ye.isValid=q0;var F0=t=>typeof Promise<"u"&&t instanceof Promise;ye.isAsync=F0});var yp=me(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0})});var wp=me(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.errorUtil=void 0;var bp;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(bp||(ta.errorUtil=bp={}))});var Cp=me(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=xp;R.custom=Rp;var q=Qo(),na=ea(),ee=wp(),I=El(),B=qi(),Tt=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}},vp=(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 ce(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 le=class{get description(){return this._def.description}_getType(e){return(0,B.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,B.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,B.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,B.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return vp(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,B.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,B.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,I.isAsync)(s)?s:Promise.resolve(s));return vp(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 ht({schema:this,typeName:se.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 xt.create(this,this._def)}nullable(){return tn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tn.create(this)}promise(){return Yn.create(this,this._def)}or(e){return Fr.create([this,e],this._def)}and(e){return Br.create(this,e,this._def)}transform(e){return new ht({...ce(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Zr({...ce(this._def),innerType:this,defaultValue:n,typeName:se.ZodDefault})}brand(){return new Bi({typeName:se.ZodBranded,type:this,...ce(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Vr({...ce(this._def),innerType:this,catchValue:n,typeName:se.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Hi.create(this,e)}readonly(){return Yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};R.ZodType=le;R.Schema=le;R.ZodSchema=le;var B0=/^c[^\s-]{8,}$/i,H0=/^[0-9a-z]+$/,K0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,W0=/^[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,G0=/^[a-z0-9_-]{21}$/i,Z0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,V0=/^[-+]?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)?)??$/,Y0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Al,X0=/^(?:(?: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])$/,Q0=/^(?:(?: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])$/,eS=/^(([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]))$/,tS=/^(([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])$/,nS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sp="((\\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])))",sS=new RegExp(`^${Sp}$`);function _p(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 iS(t){return new RegExp(`^${_p(t)}$`)}function xp(t){let e=`${Sp}T${_p(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 oS(t,e){return!!((e==="v4"||!e)&&X0.test(t)||(e==="v6"||!e)&&eS.test(t))}function aS(t,e){if(!Z0.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 cS(t,e){return!!((e==="v4"||!e)&&Q0.test(t)||(e==="v6"||!e)&&tS.test(t))}var Zn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==B.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:B.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")Y0.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")Al||(Al=new RegExp(J0,"u")),Al.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")W0.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")G0.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")B0.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")H0.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")K0.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"?xp(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"?sS.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"?iS(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"?V0.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"?oS(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"?aS(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"?cS(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"?nS.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"?rS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"base64url",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):B.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,...ee.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ee.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ee.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ee.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ee.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ee.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ee.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ee.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ee.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ee.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ee.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ee.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ee.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ee.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,...ee.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,...ee.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ee.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...ee.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...ee.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...ee.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...ee.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...ee.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...ee.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...ee.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,ee.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=Zn;Zn.create=t=>new Zn({checks:[],typeName:se.ZodString,coerce:t?.coerce??!1,...ce(t)});function lS(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 Or=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==B.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.number,received:i.parsedType}),I.INVALID}let r,s=new I.ParseStatus;for(let i of this._def.checks)i.kind==="int"?B.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"?lS(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()):B.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,ee.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ee.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ee.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ee.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ee.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ee.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ee.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ee.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ee.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ee.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ee.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:ee.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ee.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ee.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"&&B.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=Or;Or.create=t=>new Or({checks:[],typeName:se.ZodNumber,coerce:t?.coerce||!1,...ce(t)});var zr=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==B.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()):B.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:B.ZodParsedType.bigint,received:n.parsedType}),I.INVALID}gte(e,n){return this.setLimit("min",e,!0,ee.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ee.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ee.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ee.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ee.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:ee.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ee.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ee.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ee.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ee.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:se.ZodBigInt,coerce:t?.coerce??!1,...ce(t)});var Dr=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==B.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.boolean,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodBoolean=Dr;Dr.create=t=>new Dr({typeName:se.ZodBoolean,coerce:t?.coerce||!1,...ce(t)});var Lr=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==B.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:B.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()):B.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:ee.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:ee.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=Lr;Lr.create=t=>new Lr({checks:[],coerce:t?.coerce||!1,typeName:se.ZodDate,...ce(t)});var Hs=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.symbol,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodSymbol=Hs;Hs.create=t=>new Hs({typeName:se.ZodSymbol,...ce(t)});var Ur=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.undefined,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodUndefined=Ur;Ur.create=t=>new Ur({typeName:se.ZodUndefined,...ce(t)});var qr=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.null,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodNull=qr;qr.create=t=>new qr({typeName:se.ZodNull,...ce(t)});var Vn=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodAny=Vn;Vn.create=t=>new Vn({typeName:se.ZodAny,...ce(t)});var xn=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodUnknown=xn;xn.create=t=>new xn({typeName:se.ZodUnknown,...ce(t)});var qt=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.never,received:n.parsedType}),I.INVALID}};R.ZodNever=qt;qt.create=t=>new qt({typeName:se.ZodNever,...ce(t)});var Ks=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.void,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodVoid=Ks;Ks.create=t=>new Ks({typeName:se.ZodVoid,...ce(t)});var Tn=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==B.ZodParsedType.array)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.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 Tt(n,a,n.path,c)))).then(a=>I.ParseStatus.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new Tt(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:ee.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:ee.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:ee.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};R.ZodArray=Tn;Tn.create=(t,e)=>new Tn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...ce(e)});function Bs(t){if(t instanceof at){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=xt.create(Bs(r))}return new at({...t._def,shape:()=>e})}else return t instanceof Tn?new Tn({...t._def,type:Bs(t.element)}):t instanceof xt?xt.create(Bs(t.unwrap())):t instanceof tn?tn.create(Bs(t.unwrap())):t instanceof en?en.create(t.items.map(e=>Bs(e))):t}var at=class t extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=B.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==B.ZodParsedType.object){let d=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(d,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.object,received:d.parsedType}),I.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof qt&&this._def.unknownKeys==="strip"))for(let d in s.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let p=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:p._parse(new Tt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof qt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")c.length>0&&((0,I.addIssueToContext)(s,{code:q.ZodIssueCode.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:d._parse(new Tt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of l){let f=await p.key,g=await p.value;d.push({key:f,value:g,alwaysSet:p.alwaysSet})}return d}).then(d=>I.ParseStatus.mergeObjectSync(r,d)):I.ParseStatus.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return ee.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:ee.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:se.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 B.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 B.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Bs(this)}partial(e){let n={};for(let r of B.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 B.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof xt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Tp(B.util.objectKeys(this.shape))}};R.ZodObject=at;at.create=(t,e)=>new at({shape:()=>t,unknownKeys:"strip",catchall:qt.create(),typeName:se.ZodObject,...ce(e)});at.strictCreate=(t,e)=>new at({shape:()=>t,unknownKeys:"strict",catchall:qt.create(),typeName:se.ZodObject,...ce(e)});at.lazycreate=(t,e)=>new at({shape:t,unknownKeys:"strip",catchall:qt.create(),typeName:se.ZodObject,...ce(e)});var Fr=class extends le{_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 d={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&a.push(d.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=Fr;Fr.create=(t,e)=>new Fr({options:t,typeName:se.ZodUnion,...ce(e)});var _n=t=>t instanceof Hr?_n(t.schema):t instanceof ht?_n(t.innerType()):t instanceof Kr?[t.value]:t instanceof Wr?t.options:t instanceof Gr?B.util.objectValues(t.enum):t instanceof Zr?_n(t._def.innerType):t instanceof Ur?[void 0]:t instanceof qr?[null]:t instanceof xt?[void 0,..._n(t.unwrap())]:t instanceof tn?[null,..._n(t.unwrap())]:t instanceof Bi||t instanceof Yr?_n(t.unwrap()):t instanceof Vr?_n(t._def.innerType):[],ra=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==B.ZodParsedType.object)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.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=_n(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:se.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ce(r)})}};R.ZodDiscriminatedUnion=ra;function $l(t,e){let n=(0,B.getParsedType)(t),r=(0,B.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===B.ZodParsedType.object&&r===B.ZodParsedType.object){let s=B.util.objectKeys(e),i=B.util.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=$l(t[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.ZodParsedType.array&&r===B.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=$l(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===B.ZodParsedType.date&&r===B.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Br=class extends le{_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=$l(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=Br;Br.create=(t,e,n)=>new Br({left:t,right:e,typeName:se.ZodIntersection,...ce(n)});var en=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.array)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.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 Tt(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=en;en.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new en({items:t,typeName:se.ZodTuple,rest:null,...ce(e)})};var sa=class t extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.object)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.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 Tt(r,c,r.path,c)),value:a._parse(new Tt(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 le?new t({keyType:e,valueType:n,typeName:se.ZodRecord,...ce(r)}):new t({keyType:Zn.create(),valueType:e,typeName:se.ZodRecord,...ce(n)})}};R.ZodRecord=sa;var Ws=class extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.map)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.map,received:r.parsedType}),I.INVALID;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Tt(r,c,r.path,[d,"key"])),value:i._parse(new Tt(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,p=await l.value;if(d.status==="aborted"||p.status==="aborted")return I.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(d.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,p=l.value;if(d.status==="aborted"||p.status==="aborted")return I.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(d.value,p.value)}return{status:n.value,value:c}}}};R.ZodMap=Ws;Ws.create=(t,e,n)=>new Ws({valueType:e,keyType:t,typeName:se.ZodMap,...ce(n)});var Gs=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.set)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.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 d=new Set;for(let p of l){if(p.status==="aborted")return I.INVALID;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let c=[...r.data.values()].map((l,d)=>i._parse(new Tt(r,l,r.path,d)));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:ee.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:ee.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};R.ZodSet=Gs;Gs.create=(t,e)=>new Gs({valueType:t,minSize:null,maxSize:null,typeName:se.ZodSet,...ce(e)});var ia=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==B.ZodParsedType.function)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.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,na.getErrorMap)(),na.defaultErrorMap].filter(d=>!!d),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,na.getErrorMap)(),na.defaultErrorMap].filter(d=>!!d),issueData:{code:q.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Yn){let c=this;return(0,I.OK)(async function(...l){let d=new q.ZodError([]),p=await c._def.args.parseAsync(l,i).catch(v=>{throw d.addIssue(r(l,v)),d}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let c=this;return(0,I.OK)(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new q.ZodError([r(l,d.error)]);let p=Reflect.apply(a,this,d.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:en.create(e).rest(xn.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||en.create([]).rest(xn.create()),returns:n||xn.create(),typeName:se.ZodFunction,...ce(r)})}};R.ZodFunction=ia;var Hr=class extends le{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};R.ZodLazy=Hr;Hr.create=(t,e)=>new Hr({getter:t,typeName:se.ZodLazy,...ce(e)});var Kr=class extends le{_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=Kr;Kr.create=(t,e)=>new Kr({value:t,typeName:se.ZodLiteral,...ce(e)});function Tp(t,e){return new Wr({values:t,typeName:se.ZodEnum,...ce(e)})}var Wr=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,I.addIssueToContext)(n,{expected:B.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=Wr;Wr.create=Tp;var Gr=class extends le{_parse(e){let n=B.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==B.ZodParsedType.string&&r.parsedType!==B.ZodParsedType.number){let s=B.util.objectValues(n);return(0,I.addIssueToContext)(r,{expected:B.util.joinValues(s),received:r.parsedType,code:q.ZodIssueCode.invalid_type}),I.INVALID}if(this._cache||(this._cache=new Set(B.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=B.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=Gr;Gr.create=(t,e)=>new Gr({values:t,typeName:se.ZodNativeEnum,...ce(e)});var Yn=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==B.ZodParsedType.promise&&n.common.async===!1)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.promise,received:n.parsedType}),I.INVALID;let r=n.parsedType===B.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=Yn;Yn.create=(t,e)=>new Yn({type:t,typeName:se.ZodPromise,...ce(e)});var ht=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.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);B.util.assertNever(s)}};R.ZodEffects=ht;R.ZodTransformer=ht;ht.create=(t,e,n)=>new ht({schema:t,typeName:se.ZodEffects,effect:e,...ce(n)});ht.createWithPreprocess=(t,e,n)=>new ht({schema:e,effect:{type:"preprocess",transform:t},typeName:se.ZodEffects,...ce(n)});var xt=class extends le{_parse(e){return this._getType(e)===B.ZodParsedType.undefined?(0,I.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodOptional=xt;xt.create=(t,e)=>new xt({innerType:t,typeName:se.ZodOptional,...ce(e)});var tn=class extends le{_parse(e){return this._getType(e)===B.ZodParsedType.null?(0,I.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodNullable=tn;tn.create=(t,e)=>new tn({innerType:t,typeName:se.ZodNullable,...ce(e)});var Zr=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===B.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};R.ZodDefault=Zr;Zr.create=(t,e)=>new Zr({innerType:t,typeName:se.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ce(e)});var Vr=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(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=Vr;Vr.create=(t,e)=>new Vr({innerType:t,typeName:se.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ce(e)});var Zs=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.nan,received:r.parsedType}),I.INVALID}return{status:"valid",value:e.data}}};R.ZodNaN=Zs;Zs.create=t=>new Zs({typeName:se.ZodNaN,...ce(t)});R.BRAND=Symbol("zod_brand");var Bi=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};R.ZodBranded=Bi;var Hi=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?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:se.ZodPipeline})}};R.ZodPipeline=Hi;var Yr=class extends le{_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=Yr;Yr.create=(t,e)=>new Yr({innerType:t,typeName:se.ZodReadonly,...ce(e)});function kp(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Rp(t,e={},n){return t?Vn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=kp(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=kp(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Vn.create()}R.late={object:at.lazycreate};var se;(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"})(se||(R.ZodFirstPartyTypeKind=se={}));var dS=(t,e={message:`Input not instance of ${t.name}`})=>Rp(n=>n instanceof t,e);R.instanceof=dS;var Ip=Zn.create;R.string=Ip;var Ep=Or.create;R.number=Ep;var uS=Zs.create;R.nan=uS;var hS=zr.create;R.bigint=hS;var Ap=Dr.create;R.boolean=Ap;var pS=Lr.create;R.date=pS;var fS=Hs.create;R.symbol=fS;var mS=Ur.create;R.undefined=mS;var gS=qr.create;R.null=gS;var yS=Vn.create;R.any=yS;var bS=xn.create;R.unknown=bS;var wS=qt.create;R.never=wS;var vS=Ks.create;R.void=vS;var kS=Tn.create;R.array=kS;var SS=at.create;R.object=SS;var _S=at.strictCreate;R.strictObject=_S;var xS=Fr.create;R.union=xS;var TS=ra.create;R.discriminatedUnion=TS;var RS=Br.create;R.intersection=RS;var IS=en.create;R.tuple=IS;var ES=sa.create;R.record=ES;var AS=Ws.create;R.map=AS;var $S=Gs.create;R.set=$S;var CS=ia.create;R.function=CS;var PS=Hr.create;R.lazy=PS;var NS=Kr.create;R.literal=NS;var MS=Wr.create;R.enum=MS;var jS=Gr.create;R.nativeEnum=jS;var OS=Yn.create;R.promise=OS;var $p=ht.create;R.effect=$p;R.transformer=$p;var zS=xt.create;R.optional=zS;var DS=tn.create;R.nullable=DS;var LS=ht.createWithPreprocess;R.preprocess=LS;var US=Hi.create;R.pipeline=US;var qS=()=>Ip().optional();R.ostring=qS;var FS=()=>Ep().optional();R.onumber=FS;var BS=()=>Ap().optional();R.oboolean=BS;R.coerce={string:(t=>Zn.create({...t,coerce:!0})),number:(t=>Or.create({...t,coerce:!0})),boolean:(t=>Dr.create({...t,coerce:!0})),bigint:(t=>zr.create({...t,coerce:!0})),date:(t=>Lr.create({...t,coerce:!0}))};R.NEVER=I.INVALID});var Cl=me(Rt=>{"use strict";var HS=Rt&&Rt.__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]})),Vs=Rt&&Rt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&HS(e,t,n)};Object.defineProperty(Rt,"__esModule",{value:!0});Vs(ea(),Rt);Vs(El(),Rt);Vs(yp(),Rt);Vs(qi(),Rt);Vs(Cp(),Rt);Vs(Qo(),Rt)});var Mp=me(ct=>{"use strict";var Pp=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),KS=ct&&ct.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),WS=ct&&ct.__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)&&Pp(e,t,n);return KS(e,t),e},GS=ct&&ct.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Pp(e,t,n)};Object.defineProperty(ct,"__esModule",{value:!0});ct.z=void 0;var Np=WS(Cl());ct.z=Np;GS(Cl(),ct);ct.default=Np});var Ne=me(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.ChatDiagnosticResultMsg=h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.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.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=void 0;h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupAskResultMsg=h.SetupAskMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=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=void 0;h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.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=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.JiraUsersMsg=h.DeploySuggestMsg=void 0;h.missingAgentCapabilities=ZS;h.replyPreferenceAppendix=YS;h.monitorChecksAppendix=JS;h.pendingMigrationsAppendix=XS;h.deployTargetsAppendix=QS;h.savedStepChecksAppendix=e_;h.failureCollector=jp;h.failureLines=s_;h.composeCommandAppendix=i_;h.isSelfMigrationFilename=o_;h.parseRunnerMsg=a_;h.parseServerMsg=c_;var o=Mp();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.119";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 ZS(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 VS=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=VS;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",kind:"compliance",description:"Personal-data duties on both surfaces: implement runs follow GDPR build rules (GDPR-B01\u2026) while writing code, and security audits cite article numbers (GDPR-5\u2026GDPR-44).",roles:["security","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.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 YS(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?`
24
+ `,{mode:384}),kn.default.renameSync(r,n),kn.default.chmodSync(n,384)}function Yo(t,e){return`${t}:${e}`}function Qt(t,e,n){return t.environments[Yo(e,n)]?.secrets??{}}function Li(t,e){return t.repos[e]?.jira??t.jira}function Ui(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function he(){let t=_e();if(!t)throw new Error(`No runner config found at ${Sn()}. Run \`allwright init\` first.`);return t}var kn,Zo,Vo,cp,_l,Ae=X(()=>{"use strict";kn=E(require("node:fs"),1),Zo=E(require("node:os"),1),Vo=E(require("node:path"),1);_t();cp=S.object({baseUrl:S.string().url(),email:S.string().email(),apiToken:S.string().min(1)}),_l=S.object({controlPlaneUrl:S.string().url(),runnerId:S.string().optional(),runnerToken:S.string().optional(),runnerName:S.string().default(Zo.default.hostname()),jira:cp.optional(),repos:S.record(S.object({path:S.string(),jira:cp.optional(),github:S.object({token:S.string().min(1),login:S.string().optional()}).optional()})).default({}),github:S.object({token:S.string().min(1),login:S.string().optional()}).optional(),githubUsers:S.record(S.object({token:S.string().min(1),login:S.string().optional()})).default({}),deploy:S.object({enabled:S.boolean().default(!1)}).default({enabled:!1}),environments:S.record(S.object({secrets:S.record(S.string()).default({})})).default({}),claudeProfiles:S.record(S.object({configDir:S.string()})).default({}),claudeBin:S.string().default("claude"),agents:S.record(S.object({bin:S.string()})).default({}),jiraUsers:S.record(S.object({email:S.string().email(),apiToken:S.string().min(1)})).default({}),auditSchedules:S.array(S.object({repoName:S.string(),role:S.enum(["security","testing"]),intervalHours:S.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:S.number().int().min(10).max(600).default(30),operatorEnabled:S.boolean().default(!1)})});var qi=me(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getParsedType=Te.ZodParsedType=Te.objectUtil=Te.util=void 0;var xl;(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})(xl||(Te.util=xl={}));var up;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(up||(Te.objectUtil=up={}));Te.ZodParsedType=xl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var I0=t=>{switch(typeof t){case"undefined":return Te.ZodParsedType.undefined;case"string":return Te.ZodParsedType.string;case"number":return Number.isNaN(t)?Te.ZodParsedType.nan:Te.ZodParsedType.number;case"boolean":return Te.ZodParsedType.boolean;case"function":return Te.ZodParsedType.function;case"bigint":return Te.ZodParsedType.bigint;case"symbol":return Te.ZodParsedType.symbol;case"object":return Array.isArray(t)?Te.ZodParsedType.array:t===null?Te.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Te.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?Te.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?Te.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?Te.ZodParsedType.date:Te.ZodParsedType.object;default:return Te.ZodParsedType.unknown}};Te.getParsedType=I0});var Qo=me(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.ZodError=Wn.quotelessJson=Wn.ZodIssueCode=void 0;var hp=qi();Wn.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 E0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");Wn.quotelessJson=E0;var Fi=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 d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],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()}};Wn.ZodError=Fi;Fi.create=t=>new Fi(t)});var Rl=me(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var Ye=Qo(),jr=qi(),A0=(t,e)=>{let n;switch(t.code){case Ye.ZodIssueCode.invalid_type:t.received===jr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Ye.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,jr.util.jsonStringifyReplacer)}`;break;case Ye.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${jr.util.joinValues(t.keys,", ")}`;break;case Ye.ZodIssueCode.invalid_union:n="Invalid input";break;case Ye.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${jr.util.joinValues(t.options)}`;break;case Ye.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${jr.util.joinValues(t.options)}, received '${t.received}'`;break;case Ye.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Ye.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Ye.ZodIssueCode.invalid_date:n="Invalid date";break;case Ye.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}"`:jr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Ye.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 Ye.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 Ye.ZodIssueCode.custom:n="Invalid input";break;case Ye.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Ye.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Ye.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,jr.util.assertNever(t)}return{message:n}};Tl.default=A0});var ea=me(Gn=>{"use strict";var $0=Gn&&Gn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Gn,"__esModule",{value:!0});Gn.defaultErrorMap=void 0;Gn.setErrorMap=C0;Gn.getErrorMap=P0;var pp=$0(Rl());Gn.defaultErrorMap=pp.default;var fp=pp.default;function C0(t){fp=t}function P0(){return fp}});var El=me(ye=>{"use strict";var N0=ye&&ye.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ye,"__esModule",{value:!0});ye.isAsync=ye.isValid=ye.isDirty=ye.isAborted=ye.OK=ye.DIRTY=ye.INVALID=ye.ParseStatus=ye.EMPTY_PATH=ye.makeIssue=void 0;ye.addIssueToContext=O0;var M0=ea(),mp=N0(Rl()),j0=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(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:e,defaultError:c}).message;return{...s,path:i,message:c}};ye.makeIssue=j0;ye.EMPTY_PATH=[];function O0(t,e){let n=(0,M0.getErrorMap)(),r=(0,ye.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===mp.default?void 0:mp.default].filter(s=>!!s)});t.common.issues.push(r)}var Il=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 ye.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 ye.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}}};ye.ParseStatus=Il;ye.INVALID=Object.freeze({status:"aborted"});var z0=t=>({status:"dirty",value:t});ye.DIRTY=z0;var D0=t=>({status:"valid",value:t});ye.OK=D0;var L0=t=>t.status==="aborted";ye.isAborted=L0;var U0=t=>t.status==="dirty";ye.isDirty=U0;var q0=t=>t.status==="valid";ye.isValid=q0;var F0=t=>typeof Promise<"u"&&t instanceof Promise;ye.isAsync=F0});var yp=me(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0})});var wp=me(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.errorUtil=void 0;var bp;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(bp||(ta.errorUtil=bp={}))});var Cp=me(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=xp;R.custom=Rp;var q=Qo(),na=ea(),ee=wp(),I=El(),B=qi(),Tt=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}},vp=(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 ce(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 le=class{get description(){return this._def.description}_getType(e){return(0,B.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,B.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,B.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,B.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return vp(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,B.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,B.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,I.isAsync)(s)?s:Promise.resolve(s));return vp(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 ht({schema:this,typeName:se.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 xt.create(this,this._def)}nullable(){return tn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tn.create(this)}promise(){return Yn.create(this,this._def)}or(e){return Fr.create([this,e],this._def)}and(e){return Br.create(this,e,this._def)}transform(e){return new ht({...ce(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Zr({...ce(this._def),innerType:this,defaultValue:n,typeName:se.ZodDefault})}brand(){return new Bi({typeName:se.ZodBranded,type:this,...ce(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Vr({...ce(this._def),innerType:this,catchValue:n,typeName:se.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Hi.create(this,e)}readonly(){return Yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};R.ZodType=le;R.Schema=le;R.ZodSchema=le;var B0=/^c[^\s-]{8,}$/i,H0=/^[0-9a-z]+$/,K0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,W0=/^[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,G0=/^[a-z0-9_-]{21}$/i,Z0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,V0=/^[-+]?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)?)??$/,Y0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Al,X0=/^(?:(?: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])$/,Q0=/^(?:(?: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])$/,eS=/^(([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]))$/,tS=/^(([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])$/,nS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sp="((\\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])))",sS=new RegExp(`^${Sp}$`);function _p(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 iS(t){return new RegExp(`^${_p(t)}$`)}function xp(t){let e=`${Sp}T${_p(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 oS(t,e){return!!((e==="v4"||!e)&&X0.test(t)||(e==="v6"||!e)&&eS.test(t))}function aS(t,e){if(!Z0.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 cS(t,e){return!!((e==="v4"||!e)&&Q0.test(t)||(e==="v6"||!e)&&tS.test(t))}var Zn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==B.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:B.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")Y0.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")Al||(Al=new RegExp(J0,"u")),Al.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")W0.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")G0.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")B0.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")H0.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")K0.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"?xp(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"?sS.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"?iS(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"?V0.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"?oS(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"?aS(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"?cS(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"?nS.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"?rS.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,I.addIssueToContext)(s,{validation:"base64url",code:q.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):B.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,...ee.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ee.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ee.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ee.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ee.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ee.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ee.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ee.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ee.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ee.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ee.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ee.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ee.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ee.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,...ee.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,...ee.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ee.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...ee.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...ee.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...ee.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...ee.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...ee.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...ee.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...ee.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,ee.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=Zn;Zn.create=t=>new Zn({checks:[],typeName:se.ZodString,coerce:t?.coerce??!1,...ce(t)});function lS(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 Or=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==B.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.number,received:i.parsedType}),I.INVALID}let r,s=new I.ParseStatus;for(let i of this._def.checks)i.kind==="int"?B.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"?lS(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()):B.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,ee.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ee.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ee.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ee.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ee.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ee.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ee.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ee.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ee.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ee.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ee.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:ee.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ee.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ee.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"&&B.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=Or;Or.create=t=>new Or({checks:[],typeName:se.ZodNumber,coerce:t?.coerce||!1,...ce(t)});var zr=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==B.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()):B.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:B.ZodParsedType.bigint,received:n.parsedType}),I.INVALID}gte(e,n){return this.setLimit("min",e,!0,ee.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,ee.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,ee.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,ee.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:ee.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:ee.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ee.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ee.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ee.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:ee.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:se.ZodBigInt,coerce:t?.coerce??!1,...ce(t)});var Dr=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==B.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.boolean,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodBoolean=Dr;Dr.create=t=>new Dr({typeName:se.ZodBoolean,coerce:t?.coerce||!1,...ce(t)});var Lr=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==B.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(i,{code:q.ZodIssueCode.invalid_type,expected:B.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()):B.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:ee.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:ee.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=Lr;Lr.create=t=>new Lr({checks:[],coerce:t?.coerce||!1,typeName:se.ZodDate,...ce(t)});var Hs=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.symbol,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodSymbol=Hs;Hs.create=t=>new Hs({typeName:se.ZodSymbol,...ce(t)});var Ur=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.undefined,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodUndefined=Ur;Ur.create=t=>new Ur({typeName:se.ZodUndefined,...ce(t)});var qr=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.null,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodNull=qr;qr.create=t=>new qr({typeName:se.ZodNull,...ce(t)});var Vn=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodAny=Vn;Vn.create=t=>new Vn({typeName:se.ZodAny,...ce(t)});var xn=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,I.OK)(e.data)}};R.ZodUnknown=xn;xn.create=t=>new xn({typeName:se.ZodUnknown,...ce(t)});var qt=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.never,received:n.parsedType}),I.INVALID}};R.ZodNever=qt;qt.create=t=>new qt({typeName:se.ZodNever,...ce(t)});var Ks=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.void,received:r.parsedType}),I.INVALID}return(0,I.OK)(e.data)}};R.ZodVoid=Ks;Ks.create=t=>new Ks({typeName:se.ZodVoid,...ce(t)});var Tn=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==B.ZodParsedType.array)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.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 Tt(n,a,n.path,c)))).then(a=>I.ParseStatus.mergeArray(r,a));let i=[...n.data].map((a,c)=>s.type._parseSync(new Tt(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:ee.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:ee.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:ee.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};R.ZodArray=Tn;Tn.create=(t,e)=>new Tn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...ce(e)});function Bs(t){if(t instanceof at){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=xt.create(Bs(r))}return new at({...t._def,shape:()=>e})}else return t instanceof Tn?new Tn({...t._def,type:Bs(t.element)}):t instanceof xt?xt.create(Bs(t.unwrap())):t instanceof tn?tn.create(Bs(t.unwrap())):t instanceof en?en.create(t.items.map(e=>Bs(e))):t}var at=class t extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=B.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==B.ZodParsedType.object){let d=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(d,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.object,received:d.parsedType}),I.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof qt&&this._def.unknownKeys==="strip"))for(let d in s.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let p=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:p._parse(new Tt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof qt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of c)l.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")c.length>0&&((0,I.addIssueToContext)(s,{code:q.ZodIssueCode.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of c){let f=s.data[p];l.push({key:{status:"valid",value:p},value:d._parse(new Tt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of l){let f=await p.key,g=await p.value;d.push({key:f,value:g,alwaysSet:p.alwaysSet})}return d}).then(d=>I.ParseStatus.mergeObjectSync(r,d)):I.ParseStatus.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return ee.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:ee.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:se.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 B.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 B.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Bs(this)}partial(e){let n={};for(let r of B.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 B.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof xt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Tp(B.util.objectKeys(this.shape))}};R.ZodObject=at;at.create=(t,e)=>new at({shape:()=>t,unknownKeys:"strip",catchall:qt.create(),typeName:se.ZodObject,...ce(e)});at.strictCreate=(t,e)=>new at({shape:()=>t,unknownKeys:"strict",catchall:qt.create(),typeName:se.ZodObject,...ce(e)});at.lazycreate=(t,e)=>new at({shape:t,unknownKeys:"strip",catchall:qt.create(),typeName:se.ZodObject,...ce(e)});var Fr=class extends le{_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 d={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&a.push(d.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=Fr;Fr.create=(t,e)=>new Fr({options:t,typeName:se.ZodUnion,...ce(e)});var _n=t=>t instanceof Hr?_n(t.schema):t instanceof ht?_n(t.innerType()):t instanceof Kr?[t.value]:t instanceof Wr?t.options:t instanceof Gr?B.util.objectValues(t.enum):t instanceof Zr?_n(t._def.innerType):t instanceof Ur?[void 0]:t instanceof qr?[null]:t instanceof xt?[void 0,..._n(t.unwrap())]:t instanceof tn?[null,..._n(t.unwrap())]:t instanceof Bi||t instanceof Yr?_n(t.unwrap()):t instanceof Vr?_n(t._def.innerType):[],ra=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==B.ZodParsedType.object)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.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=_n(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:se.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ce(r)})}};R.ZodDiscriminatedUnion=ra;function $l(t,e){let n=(0,B.getParsedType)(t),r=(0,B.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===B.ZodParsedType.object&&r===B.ZodParsedType.object){let s=B.util.objectKeys(e),i=B.util.objectKeys(t).filter(c=>s.indexOf(c)!==-1),a={...t,...e};for(let c of i){let l=$l(t[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.ZodParsedType.array&&r===B.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=$l(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===B.ZodParsedType.date&&r===B.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Br=class extends le{_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=$l(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=Br;Br.create=(t,e,n)=>new Br({left:t,right:e,typeName:se.ZodIntersection,...ce(n)});var en=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.array)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.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 Tt(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=en;en.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new en({items:t,typeName:se.ZodTuple,rest:null,...ce(e)})};var sa=class t extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.object)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.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 Tt(r,c,r.path,c)),value:a._parse(new Tt(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 le?new t({keyType:e,valueType:n,typeName:se.ZodRecord,...ce(r)}):new t({keyType:Zn.create(),valueType:e,typeName:se.ZodRecord,...ce(n)})}};R.ZodRecord=sa;var Ws=class extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.map)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.map,received:r.parsedType}),I.INVALID;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Tt(r,c,r.path,[d,"key"])),value:i._parse(new Tt(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,p=await l.value;if(d.status==="aborted"||p.status==="aborted")return I.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(d.value,p.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,p=l.value;if(d.status==="aborted"||p.status==="aborted")return I.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),c.set(d.value,p.value)}return{status:n.value,value:c}}}};R.ZodMap=Ws;Ws.create=(t,e,n)=>new Ws({valueType:e,keyType:t,typeName:se.ZodMap,...ce(n)});var Gs=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==B.ZodParsedType.set)return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.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 d=new Set;for(let p of l){if(p.status==="aborted")return I.INVALID;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let c=[...r.data.values()].map((l,d)=>i._parse(new Tt(r,l,r.path,d)));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:ee.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:ee.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};R.ZodSet=Gs;Gs.create=(t,e)=>new Gs({valueType:t,minSize:null,maxSize:null,typeName:se.ZodSet,...ce(e)});var ia=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==B.ZodParsedType.function)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.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,na.getErrorMap)(),na.defaultErrorMap].filter(d=>!!d),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,na.getErrorMap)(),na.defaultErrorMap].filter(d=>!!d),issueData:{code:q.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Yn){let c=this;return(0,I.OK)(async function(...l){let d=new q.ZodError([]),p=await c._def.args.parseAsync(l,i).catch(v=>{throw d.addIssue(r(l,v)),d}),f=await Reflect.apply(a,this,p);return await c._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let c=this;return(0,I.OK)(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new q.ZodError([r(l,d.error)]);let p=Reflect.apply(a,this,d.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:en.create(e).rest(xn.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||en.create([]).rest(xn.create()),returns:n||xn.create(),typeName:se.ZodFunction,...ce(r)})}};R.ZodFunction=ia;var Hr=class extends le{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};R.ZodLazy=Hr;Hr.create=(t,e)=>new Hr({getter:t,typeName:se.ZodLazy,...ce(e)});var Kr=class extends le{_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=Kr;Kr.create=(t,e)=>new Kr({value:t,typeName:se.ZodLiteral,...ce(e)});function Tp(t,e){return new Wr({values:t,typeName:se.ZodEnum,...ce(e)})}var Wr=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,I.addIssueToContext)(n,{expected:B.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=Wr;Wr.create=Tp;var Gr=class extends le{_parse(e){let n=B.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==B.ZodParsedType.string&&r.parsedType!==B.ZodParsedType.number){let s=B.util.objectValues(n);return(0,I.addIssueToContext)(r,{expected:B.util.joinValues(s),received:r.parsedType,code:q.ZodIssueCode.invalid_type}),I.INVALID}if(this._cache||(this._cache=new Set(B.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=B.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=Gr;Gr.create=(t,e)=>new Gr({values:t,typeName:se.ZodNativeEnum,...ce(e)});var Yn=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==B.ZodParsedType.promise&&n.common.async===!1)return(0,I.addIssueToContext)(n,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.promise,received:n.parsedType}),I.INVALID;let r=n.parsedType===B.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=Yn;Yn.create=(t,e)=>new Yn({type:t,typeName:se.ZodPromise,...ce(e)});var ht=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.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);B.util.assertNever(s)}};R.ZodEffects=ht;R.ZodTransformer=ht;ht.create=(t,e,n)=>new ht({schema:t,typeName:se.ZodEffects,effect:e,...ce(n)});ht.createWithPreprocess=(t,e,n)=>new ht({schema:e,effect:{type:"preprocess",transform:t},typeName:se.ZodEffects,...ce(n)});var xt=class extends le{_parse(e){return this._getType(e)===B.ZodParsedType.undefined?(0,I.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodOptional=xt;xt.create=(t,e)=>new xt({innerType:t,typeName:se.ZodOptional,...ce(e)});var tn=class extends le{_parse(e){return this._getType(e)===B.ZodParsedType.null?(0,I.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.ZodNullable=tn;tn.create=(t,e)=>new tn({innerType:t,typeName:se.ZodNullable,...ce(e)});var Zr=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===B.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};R.ZodDefault=Zr;Zr.create=(t,e)=>new Zr({innerType:t,typeName:se.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ce(e)});var Vr=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(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=Vr;Vr.create=(t,e)=>new Vr({innerType:t,typeName:se.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ce(e)});var Zs=class extends le{_parse(e){if(this._getType(e)!==B.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,I.addIssueToContext)(r,{code:q.ZodIssueCode.invalid_type,expected:B.ZodParsedType.nan,received:r.parsedType}),I.INVALID}return{status:"valid",value:e.data}}};R.ZodNaN=Zs;Zs.create=t=>new Zs({typeName:se.ZodNaN,...ce(t)});R.BRAND=Symbol("zod_brand");var Bi=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};R.ZodBranded=Bi;var Hi=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?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:se.ZodPipeline})}};R.ZodPipeline=Hi;var Yr=class extends le{_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=Yr;Yr.create=(t,e)=>new Yr({innerType:t,typeName:se.ZodReadonly,...ce(e)});function kp(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Rp(t,e={},n){return t?Vn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let c=kp(e,r),l=c.fatal??n??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let a=kp(e,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}}):Vn.create()}R.late={object:at.lazycreate};var se;(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"})(se||(R.ZodFirstPartyTypeKind=se={}));var dS=(t,e={message:`Input not instance of ${t.name}`})=>Rp(n=>n instanceof t,e);R.instanceof=dS;var Ip=Zn.create;R.string=Ip;var Ep=Or.create;R.number=Ep;var uS=Zs.create;R.nan=uS;var hS=zr.create;R.bigint=hS;var Ap=Dr.create;R.boolean=Ap;var pS=Lr.create;R.date=pS;var fS=Hs.create;R.symbol=fS;var mS=Ur.create;R.undefined=mS;var gS=qr.create;R.null=gS;var yS=Vn.create;R.any=yS;var bS=xn.create;R.unknown=bS;var wS=qt.create;R.never=wS;var vS=Ks.create;R.void=vS;var kS=Tn.create;R.array=kS;var SS=at.create;R.object=SS;var _S=at.strictCreate;R.strictObject=_S;var xS=Fr.create;R.union=xS;var TS=ra.create;R.discriminatedUnion=TS;var RS=Br.create;R.intersection=RS;var IS=en.create;R.tuple=IS;var ES=sa.create;R.record=ES;var AS=Ws.create;R.map=AS;var $S=Gs.create;R.set=$S;var CS=ia.create;R.function=CS;var PS=Hr.create;R.lazy=PS;var NS=Kr.create;R.literal=NS;var MS=Wr.create;R.enum=MS;var jS=Gr.create;R.nativeEnum=jS;var OS=Yn.create;R.promise=OS;var $p=ht.create;R.effect=$p;R.transformer=$p;var zS=xt.create;R.optional=zS;var DS=tn.create;R.nullable=DS;var LS=ht.createWithPreprocess;R.preprocess=LS;var US=Hi.create;R.pipeline=US;var qS=()=>Ip().optional();R.ostring=qS;var FS=()=>Ep().optional();R.onumber=FS;var BS=()=>Ap().optional();R.oboolean=BS;R.coerce={string:(t=>Zn.create({...t,coerce:!0})),number:(t=>Or.create({...t,coerce:!0})),boolean:(t=>Dr.create({...t,coerce:!0})),bigint:(t=>zr.create({...t,coerce:!0})),date:(t=>Lr.create({...t,coerce:!0}))};R.NEVER=I.INVALID});var Cl=me(Rt=>{"use strict";var HS=Rt&&Rt.__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]})),Vs=Rt&&Rt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&HS(e,t,n)};Object.defineProperty(Rt,"__esModule",{value:!0});Vs(ea(),Rt);Vs(El(),Rt);Vs(yp(),Rt);Vs(qi(),Rt);Vs(Cp(),Rt);Vs(Qo(),Rt)});var Mp=me(ct=>{"use strict";var Pp=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),KS=ct&&ct.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),WS=ct&&ct.__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)&&Pp(e,t,n);return KS(e,t),e},GS=ct&&ct.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Pp(e,t,n)};Object.defineProperty(ct,"__esModule",{value:!0});ct.z=void 0;var Np=WS(Cl());ct.z=Np;GS(Cl(),ct);ct.default=Np});var Ne=me(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.ChatDiagnosticResultMsg=h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.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.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=void 0;h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupAskResultMsg=h.SetupAskMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=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=void 0;h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.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=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.JiraUsersMsg=h.DeploySuggestMsg=void 0;h.missingAgentCapabilities=ZS;h.replyPreferenceAppendix=YS;h.monitorChecksAppendix=JS;h.pendingMigrationsAppendix=XS;h.deployTargetsAppendix=QS;h.savedStepChecksAppendix=e_;h.failureCollector=jp;h.failureLines=s_;h.composeCommandAppendix=i_;h.isSelfMigrationFilename=o_;h.parseRunnerMsg=a_;h.parseServerMsg=c_;var o=Mp();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.119";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 ZS(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 VS=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=VS;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.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 YS(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(`
@@ -471,7 +471,7 @@ Explore the repository first - entry points, routes, storage, tests - then audit
471
471
  Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`+f}function wf(t){let n=t.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??t.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!n)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(n)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,a=new Set;for(let c of r.findings.slice(0,25)){let l=j_(c),d=l?ba.AuditFinding.safeParse(l):null;if(!d?.success){i++;continue}let p=d.data.id;for(;a.has(p);)p=`${p}-2`;a.add(p),s.push({...d.data,id:p})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function j_(t){if(typeof t!="object"||t===null)return null;let e=t,n=typeof e.severity=="string"?e.severity.toLowerCase():"",r=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...yf(i.line)?{line:yf(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:O_(typeof e.id=="string"&&e.id?e.id:String(e.title??"")),ruleId:/^[A-Z]{2,8}-\d{1,4}$/.test(s)?s:"",title:typeof e.title=="string"?e.title.slice(0,200):"",severity:ba.AuditSeverity.options.includes(n)?n:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:r,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function yf(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function O_(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function z_(t){try{let e=cd.default.readFileSync(t,"utf8");return e?e.split(`
472
472
  `).length:0}catch{return null}}function vf(t,e){let n=ya.default.resolve(t),r=[],s=[],i=0;for(let a of e){let c=[];for(let l of a.evidence){let d=l.file.trim().replace(/^\.\//,""),p=ya.default.resolve(n,d);if(p!==n&&!p.startsWith(n+ya.default.sep))continue;let f;try{f=cd.default.statSync(p)}catch{continue}if(f.isFile()){if(l.line!==void 0){let g=z_(p);if(g!==null&&l.line>g){c.push({...l,line:void 0}),i++;continue}}c.push(l)}}if(!c.length){s.push({title:a.title,files:a.evidence.map(l=>l.file)});continue}r.push({...a,evidence:c})}return{findings:r,droppedFindings:s,correctedLines:i}}var cd,ya,ba,M_,kf=X(()=>{"use strict";cd=E(require("node:fs"),1),ya=E(require("node:path"),1),ba=E(Ne(),1),M_={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems - not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below - gaps that would actually bite this product, not generic coverage philosophy.",engineering:"You are writing an ENGINEERING REVIEW of this repository for a manager who will not read the code - the person deciding whether to fund it, rebuild it, or trust it in production. You can READ; you can never run or change anything.\n\nCover ALL NINE dimensions, in this order, as the `area` of your findings: architecture, security, performance, maintainability, testing, deployment, devops, documentation, ai-readiness. Every dimension gets at least one finding - and when a dimension is genuinely healthy, say so as an `info` finding with the evidence that proves it. A silent dimension reads as 'not looked at', which is the one thing a review must never be.\n\nWrite findings a manager can act on: what it costs the business if it stays, not what a linter would call it. Severity is about consequence, not about how unusual the code is. Your summary is the three sentences someone would repeat in a meeting - the shape of this codebase's health, its single biggest risk, and the highest-payoff thing to do next.",seo:"You are an SEO / AI-visibility / marketing-tags auditor reading this repository - the site's CODE side of the audit. You can READ; you can never run or change anything.\n\nCover ALL SEVEN dimensions, in this order, as the `area` of your findings: metadata (titles, descriptions, canonicals - how pages BUILD them, per-page or hardcoded), structured-data (JSON-LD emitted where content deserves it), rendering (is content in the initial HTML - SSR/SSG vs client-only, which answer engines cannot read), aeo-readiness (semantic headings, FAQ/HowTo shaped content, llms.txt, robots access for AI crawlers), sitemap-robots (generated or stale, per-environment correctness), ads-tracking (GA4/Tag Manager/Google Ads/Meta pixel wiring - present, duplicated, or firing on localhost), and performance-signals (image sizing, font loading, render-blocking scripts - the code causes of Core Web Vitals). Every dimension gets at least one finding; a healthy one gets an `info` finding with the evidence that proves it, because silence reads as 'not looked at'.\n\nWhen a SITE PROBE report is included below, treat it as measured fact: your job is the WHY behind each failed check (which template, which config) and the fix, in the code. Severity is about lost visibility and wasted ad spend, not code style.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below - real structural pain for this team, not textbook purity.",incident:`You are diagnosing a SERVER INCIDENT. The monitoring evidence is in the scope section below - treat it as measured fact. You can READ this repository (the code that runs on the affected machine); you can never run or change anything, and you are NOT on the affected machine itself - never claim to have inspected live state you cannot see.
473
473
 
474
- Answer four things, as findings: what most likely HAPPENED (the mechanism, traced to the evidence), what should be CHECKED next on the machine (each as its own finding whose fix is the exact command or file to look at), what should be done to CONTAIN/FIX it, and what would PREVENT a recurrence. Rank findings by consequence. Say plainly when the evidence cannot distinguish two causes - name the one observation that would settle it.`,functional:"You are a functional tester of the RUNNING site. The runner has already crawled it - the transcript is below, and it is your primary evidence; the repository is open READ-ONLY so you can trace a broken page to its code. Report what a real visitor hits: broken links (with the page that links there), errors, missing pages, mixed content, slow responses. The crawl ran without JavaScript - never claim client-side behaviour was checked. Every finding cites a URL from the crawl AND, where you traced it, the file behind it."}});function _f(){return ld.default.join(te(),"audits.json")}function ei(){try{return{byProject:JSON.parse(Zi.default.readFileSync(_f(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function xf(t){let e=_f();Zi.default.mkdirSync(ld.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Zi.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Zi.default.renameSync(n,e)}function Tf(t,e){let n=ei(),r=n.byProject[t]??[];r.unshift(Sf.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,D_),xf(n)}function Rf(t){return(ei().byProject[t]??[]).map(e=>{let n={};for(let r of e.findings)n[r.severity]=(n[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:n,costUsd:e.costUsd??0,inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,detailLevel:e.detailLevel??"technical"}})}function If(t,e){let n=ei(),r=e?Date.parse(e):NaN,s={};for(let i of t){let a=(n.byProject[i]??[]).filter(l=>!Number.isFinite(r)||Date.parse(l.createdAt)>=r);if(!a.length)continue;let c={audits:a.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let l of a){c.findings+=l.findings.length;for(let d of l.findings){let p=l.verdicts[d.id]?.verdict;p==="valid"?c.valid++:p==="false-positive"?c.falsePositive++:p==="wont-fix"?c.wontFix++:c.unreviewed++}}s[i]=c}return s}function dd(t,e,n){let r=ei(),i=(r.byProject[t]??[]).find(c=>c.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let a=new Set(i.findings.map(c=>c.id));n.selected&&(i.review={selected:n.selected.filter(c=>a.has(c)),updatedAt:new Date().toISOString()});for(let c of n.ticketed??[])a.has(c.findingId)&&(i.ticketed={...i.ticketed,[c.findingId]:c.issueKey});for(let c of n.verdicts??[])a.has(c.findingId)&&(i.verdicts={...i.verdicts,[c.findingId]:{verdict:c.verdict,note:c.note,by:n.verdictBy??"",at:new Date().toISOString()}});for(let c of n.markLessonsWritten??[])a.has(c)&&!i.lessonsWritten.includes(c)&&i.lessonsWritten.push(c);return xf(r),i}function Ef(t,e){return(ei().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ud(t,e){return(ei().byProject[t]??[]).find(n=>n.id===e)??null}var Zi,ld,Sf,D_,wa=X(()=>{"use strict";Zi=E(require("node:fs"),1),ld=E(require("node:path"),1),Sf=E(Ne(),1);Ae();D_=20});function Pf(t,e){let n=[];for(let r of e)for(let s of B_[r]??[])s.role===t&&n.push({name:`${r}/${s.name}`,content:s.content});return n}var L_,U_,Af,$f,Cf,q_,F_,B_,Nf=X(()=>{"use strict";L_=`# OWASP Top 10 (2021) \u2014 findings cite these as ruleId
474
+ Answer four things, as findings: what most likely HAPPENED (the mechanism, traced to the evidence), what should be CHECKED next on the machine (each as its own finding whose fix is the exact command or file to look at), what should be done to CONTAIN/FIX it, and what would PREVENT a recurrence. Rank findings by consequence. Say plainly when the evidence cannot distinguish two causes - name the one observation that would settle it.`,functional:"You are a functional tester of the RUNNING site. The runner has already crawled it - the transcript is below, and it is your primary evidence; the repository is open READ-ONLY so you can trace a broken page to its code. Report what a real visitor hits: broken links (with the page that links there), errors, missing pages, mixed content, slow responses. The crawl ran without JavaScript - never claim client-side behaviour was checked. Every finding cites a URL from the crawl AND, where you traced it, the file behind it."}});function _f(){return ld.default.join(te(),"audits.json")}function ei(){try{return{byProject:JSON.parse(Zi.default.readFileSync(_f(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function xf(t){let e=_f();Zi.default.mkdirSync(ld.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Zi.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Zi.default.renameSync(n,e)}function Tf(t,e){let n=ei(),r=n.byProject[t]??[];r.unshift(Sf.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,D_),xf(n)}function Rf(t){return(ei().byProject[t]??[]).map(e=>{let n={};for(let r of e.findings)n[r.severity]=(n[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:n,costUsd:e.costUsd??0,inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,detailLevel:e.detailLevel??"technical"}})}function If(t,e){let n=ei(),r=e?Date.parse(e):NaN,s={};for(let i of t){let a=(n.byProject[i]??[]).filter(l=>!Number.isFinite(r)||Date.parse(l.createdAt)>=r);if(!a.length)continue;let c={audits:a.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let l of a){c.findings+=l.findings.length;for(let d of l.findings){let p=l.verdicts[d.id]?.verdict;p==="valid"?c.valid++:p==="false-positive"?c.falsePositive++:p==="wont-fix"?c.wontFix++:c.unreviewed++}}s[i]=c}return s}function dd(t,e,n){let r=ei(),i=(r.byProject[t]??[]).find(c=>c.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let a=new Set(i.findings.map(c=>c.id));n.selected&&(i.review={selected:n.selected.filter(c=>a.has(c)),updatedAt:new Date().toISOString()});for(let c of n.ticketed??[])a.has(c.findingId)&&(i.ticketed={...i.ticketed,[c.findingId]:c.issueKey});for(let c of n.verdicts??[])a.has(c.findingId)&&(i.verdicts={...i.verdicts,[c.findingId]:{verdict:c.verdict,note:c.note,by:n.verdictBy??"",at:new Date().toISOString()}});for(let c of n.markLessonsWritten??[])a.has(c)&&!i.lessonsWritten.includes(c)&&i.lessonsWritten.push(c);return xf(r),i}function Ef(t,e){return(ei().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ud(t,e){return(ei().byProject[t]??[]).find(n=>n.id===e)??null}var Zi,ld,Sf,D_,wa=X(()=>{"use strict";Zi=E(require("node:fs"),1),ld=E(require("node:path"),1),Sf=E(Ne(),1);Ae();D_=20});function Pf(t,e){let n=[];for(let r of e)for(let s of F_[r]??[])s.role===t&&n.push({name:`${r}/${s.name}`,content:s.content});return n}var L_,U_,Af,$f,Cf,q_,F_,Nf=X(()=>{"use strict";L_=`# OWASP Top 10 (2021) \u2014 findings cite these as ruleId
475
475
 
476
476
  Audit against each category. A finding that matches one MUST use the
477
477
  category id (OWASP-A01 \u2026 OWASP-A10) as its ruleId, so the report maps
@@ -592,50 +592,7 @@ choice drags in.
592
592
  - **NODE-007**: long-running work leaves the request path (queue, worker,
593
593
  detached job with progress) - a 10-minute await in a handler is a
594
594
  gateway timeout with extra steps.
595
- `,q_=`# GDPR \u2014 findings cite article numbers as ruleId
596
-
597
- Audit how this codebase handles PERSONAL DATA (anything identifying a
598
- person: names, emails, phones, addresses, ids, IPs, photos, device
599
- identifiers). A finding that maps onto an article MUST use the article id
600
- (GDPR-5 \u2026 GDPR-44) as its ruleId, so the report reads as a compliance
601
- assessment.
602
-
603
- - **GDPR-5 Minimisation & storage limitation**: personal-data fields
604
- collected or kept with no use; tables/collections that grow forever with
605
- no retention rule; "just in case" copies of people's data.
606
- - **GDPR-6 Lawful basis**: features that email, message, track or profile
607
- people with no consent or basis recorded anywhere.
608
- - **GDPR-7 Consent**: consent captured but not stored verifiably, or
609
- harder to withdraw than it was to give.
610
- - **GDPR-15 Right of access**: no way to produce everything held about ONE
611
- person (a subject access request) without hand-written queries.
612
- - **GDPR-17 Erasure**: no deletion path for a person's data; deletes that
613
- orphan personal data in related tables, files or exports.
614
- - **GDPR-20 Portability**: no machine-readable export of a person's own
615
- data where the product clearly holds user-provided data.
616
- - **GDPR-25 Protection by design**: defaults that expose more than needed
617
- - public-by-default, list endpoints returning emails/phones the UI never
618
- shows.
619
- - **GDPR-28 Processors**: personal data sent to third parties (mail,
620
- analytics, error trackers, AI APIs) that are named nowhere; payloads
621
- carrying more personal data than the integration needs.
622
- - **GDPR-30 Records of processing**: no way to answer "where does personal
623
- data live in this system" - undocumented stores, shadow copies.
624
- - **GDPR-32 Security of processing**: personal data cleartext at rest
625
- where the stack offers better, or in LOGS, error messages or URLs;
626
- credentials committed to the repo; personal-data endpoints missing
627
- access control (overlaps OWASP - cite both ids).
628
- - **GDPR-33 Breach readiness**: no audit trail of who read or changed
629
- personal data - an incident that could not be reconstructed afterwards.
630
- - **GDPR-44 Transfers & residency**: personal data stored, processed or
631
- backed up outside the declared region (hosting, mail, analytics), or no
632
- region pinned anywhere at all.
633
-
634
- Report each area even when HEALTHY - an info finding with evidence -
635
- because a compliance reader treats silence as "not assessed". Close with
636
- what code cannot answer: policies, DPAs and the processing register are
637
- HUMAN work; name them as gaps for the humans, never as code findings.
638
- `,F_=`# GDPR \u2014 rules for code that touches personal data
595
+ `,q_=`# GDPR \u2014 rules for code that touches personal data
639
596
 
640
597
  Personal data = anything identifying a person (names, emails, phones,
641
598
  addresses, ids, IPs, photos, device identifiers). While implementing:
@@ -666,7 +623,7 @@ addresses, ids, IPs, photos, device identifiers). While implementing:
666
623
 
667
624
  When a ticket forces a violation, say so in the PR description instead of
668
625
  silently complying.
669
- `,B_={owasp:[{role:"security",name:"owasp-top-10.md",content:L_}],"pci-dss":[{role:"security",name:"pci-dss.md",content:U_}],gdpr:[{role:"security",name:"gdpr.md",content:q_},{role:"implement",name:"gdpr-build.md",content:F_}],laravel:[{role:"implement",name:"laravel.md",content:Af},{role:"architecture",name:"laravel.md",content:Af}],react:[{role:"implement",name:"react.md",content:$f},{role:"architecture",name:"react.md",content:$f}],node:[{role:"implement",name:"node.md",content:Cf},{role:"architecture",name:"node.md",content:Cf}]}});function hd(t){return on.default.join(te(),"knowledge",t)}function Of(t,e){return on.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function pd(t,e){return on.default.join(t,".ticketpilot","lessons",`${e}.md`)}function va(t,e,n=[]){let r=[],s=hd(t),i=[];if(nt.default.existsSync(s)){for(let d of nt.default.readdirSync(s)){if(!d.endsWith(".md"))continue;let p=on.default.join(s,d),f=nt.default.readFileSync(p,"utf8");if(Z_.some(g=>f.includes(g))&&Mf[t].map(v=>v.name).includes(d)&&!f.includes("SEC-0")&&!f.includes("TEST-0")&&!f.includes("GDPR-0")){nt.default.rmSync(p);continue}i.push(d)}i.sort()}let a=new Set(i);for(let d of Mf[t])a.has(d.name)||r.push({level:"global",source:"pack",name:d.name,content:d.content,editable:!1});for(let d of Pf(t,n))a.has(d.name)||r.push({level:"global",source:"pack",name:d.name,content:d.content,editable:!1});for(let d of i)r.push({level:"org",source:"pack",name:d,content:nt.default.readFileSync(on.default.join(s,d),"utf8").slice(0,3e4),editable:!0});let c=Of(e,t);nt.default.existsSync(c)&&r.push({level:"project",source:"pack",name:`${t}.md`,content:nt.default.readFileSync(c,"utf8").slice(0,3e4),editable:!0});let l=pd(e,t);return nt.default.existsSync(l)&&r.push({level:"project",source:"lessons",name:`${t}.md`,content:nt.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),r}function ti(t,e,n=[]){let r=va(t,e,n);return{packs:r.filter(s=>s.source==="pack").map(s=>({name:`${s.level}/${s.name}`,content:s.content})),lessons:r.find(s=>s.source==="lessons")?.content??"",layers:r}}function fd(t,e,n,r="project"){let s=r==="org"?on.default.join(hd(e),"org-lessons.md"):pd(t,e);nt.default.mkdirSync(on.default.dirname(s),{recursive:!0});let i=nt.default.existsSync(s)?"":`# ${e} lessons (${r} level)
626
+ `,F_={owasp:[{role:"security",name:"owasp-top-10.md",content:L_}],"pci-dss":[{role:"security",name:"pci-dss.md",content:U_}],gdpr:[{role:"implement",name:"gdpr-build.md",content:q_}],laravel:[{role:"implement",name:"laravel.md",content:Af},{role:"architecture",name:"laravel.md",content:Af}],react:[{role:"implement",name:"react.md",content:$f},{role:"architecture",name:"react.md",content:$f}],node:[{role:"implement",name:"node.md",content:Cf},{role:"architecture",name:"node.md",content:Cf}]}});function hd(t){return on.default.join(te(),"knowledge",t)}function Of(t,e){return on.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function pd(t,e){return on.default.join(t,".ticketpilot","lessons",`${e}.md`)}function va(t,e,n=[]){let r=[],s=hd(t),i=[];if(nt.default.existsSync(s)){for(let d of nt.default.readdirSync(s)){if(!d.endsWith(".md"))continue;let p=on.default.join(s,d),f=nt.default.readFileSync(p,"utf8");if(G_.some(g=>f.includes(g))&&Mf[t].map(v=>v.name).includes(d)&&!f.includes("SEC-0")&&!f.includes("TEST-0")&&!f.includes("GDPR-0")){nt.default.rmSync(p);continue}i.push(d)}i.sort()}let a=new Set(i);for(let d of Mf[t])a.has(d.name)||r.push({level:"global",source:"pack",name:d.name,content:d.content,editable:!1});for(let d of Pf(t,n))a.has(d.name)||r.push({level:"global",source:"pack",name:d.name,content:d.content,editable:!1});for(let d of i)r.push({level:"org",source:"pack",name:d,content:nt.default.readFileSync(on.default.join(s,d),"utf8").slice(0,3e4),editable:!0});let c=Of(e,t);nt.default.existsSync(c)&&r.push({level:"project",source:"pack",name:`${t}.md`,content:nt.default.readFileSync(c,"utf8").slice(0,3e4),editable:!0});let l=pd(e,t);return nt.default.existsSync(l)&&r.push({level:"project",source:"lessons",name:`${t}.md`,content:nt.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),r}function ti(t,e,n=[]){let r=va(t,e,n);return{packs:r.filter(s=>s.source==="pack").map(s=>({name:`${s.level}/${s.name}`,content:s.content})),lessons:r.find(s=>s.source==="lessons")?.content??"",layers:r}}function fd(t,e,n,r="project"){let s=r==="org"?on.default.join(hd(e),"org-lessons.md"):pd(t,e);nt.default.mkdirSync(on.default.dirname(s),{recursive:!0});let i=nt.default.existsSync(s)?"":`# ${e} lessons (${r} level)
670
627
 
671
628
  Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
672
629
 
@@ -677,7 +634,7 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
677
634
  `)}function zf(t,e,n,r){let s=new Date().toISOString().slice(0,10),i=t.evidence[0]?` (${t.evidence[0].file}${t.evidence[0].line?`:${t.evidence[0].line}`:""})`:"",a=t.ruleId?` \xB7 rule ${t.ruleId}`:"";return`## ${s} \xB7 ${e}${a} \xB7 ${t.title}${i}
678
635
  Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
679
636
  `+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function Df(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
680
- ${t.trim()}`}function Lf(t){let e=[];for(let r of jf.KnowledgeRole.options)for(let s of va(r,t))e.push({role:r,...s});let n=oa(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Uf(t,e,n,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let a=n==="org"?on.default.join(hd(e),s):r==="lessons"?pd(t,e):Of(t,e);nt.default.mkdirSync(on.default.dirname(a),{recursive:!0}),nt.default.writeFileSync(a,i,{mode:n==="org"?384:420})}var nt,on,jf,H_,K_,W_,G_,Mf,Z_,Vi=X(()=>{"use strict";nt=E(require("node:fs"),1),on=E(require("node:path"),1),jf=E(Ne(),1);Nf();Ys();Ae();H_=`# Security baseline - what to check in any repo
637
+ ${t.trim()}`}function Lf(t){let e=[];for(let r of jf.KnowledgeRole.options)for(let s of va(r,t))e.push({role:r,...s});let n=oa(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Uf(t,e,n,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let a=n==="org"?on.default.join(hd(e),s):r==="lessons"?pd(t,e):Of(t,e);nt.default.mkdirSync(on.default.dirname(a),{recursive:!0}),nt.default.writeFileSync(a,i,{mode:n==="org"?384:420})}var nt,on,jf,B_,H_,K_,W_,Mf,G_,Vi=X(()=>{"use strict";nt=E(require("node:fs"),1),on=E(require("node:path"),1),jf=E(Ne(),1);Nf();Ys();Ae();B_=`# Security baseline - what to check in any repo
681
638
 
682
639
  Every rule has a stable id. Findings must cite the id they violate.
683
640
 
@@ -720,7 +677,7 @@ Every rule has a stable id. Findings must cite the id they violate.
720
677
  - **SEC-042** TLS/redirect handling that downgrades to http.
721
678
 
722
679
  Prioritize by real exploitability in THIS codebase, not by rule order.
723
- `,K_=`# Test gaps - what to check in any repo
680
+ `,H_=`# Test gaps - what to check in any repo
724
681
 
725
682
  Every rule has a stable id. Findings must cite the id they violate.
726
683
 
@@ -750,7 +707,7 @@ Every rule has a stable id. Findings must cite the id they violate.
750
707
  flaky suspects.
751
708
 
752
709
  Report the GAP and why it is risky here, not generic coverage philosophy.
753
- `,W_=`# GDPR readiness - data-protection audit for repos with EU exposure
710
+ `,K_=`# GDPR readiness - data-protection audit for repos with EU exposure
754
711
 
755
712
  FIRST decide exposure: if this product clearly has no EU users, no personal
756
713
  data, or is a purely static/internal tool, say so in ONE summary sentence and
@@ -794,7 +751,13 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
794
751
 
795
752
  Severity: many users' data exposed or a missing legal-basis mechanism is
796
753
  high/critical; hygiene and documentation gaps are medium/low.
797
- `,G_=`# Architecture health - is this repository structurally sound?
754
+
755
+ When exposure is real, answer EVERY area above even when healthy - an
756
+ info finding with evidence - because a compliance reader treats silence
757
+ as "not assessed". And close with what code cannot answer: policies,
758
+ DPAs and the processing register are HUMAN work; name them as gaps for
759
+ the humans, never as code findings.
760
+ `,W_=`# Architecture health - is this repository structurally sound?
798
761
 
799
762
  Every rule has a stable id. Findings must cite the id they violate. Judge
800
763
  against what THIS codebase is trying to be (a static site does not need
@@ -833,24 +796,24 @@ deviations.
833
796
 
834
797
  Summarize with an overall verdict: is this repository HEALTHY for its
835
798
  purpose, and what are the 2-3 structural moves with the best payoff?
836
- `,Mf={security:[{name:"baseline.md",content:H_},{name:"gdpr.md",content:W_}],testing:[{name:"test-gaps.md",content:K_}],architecture:[{name:"architecture-health.md",content:G_}],functional:[],engineering:[],seo:[],incident:[],implement:[],compose:[]},Z_=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"]});function qf(t){return new Set((t.toLowerCase().match(/[a-z][a-z0-9_.-]{3,}/g)??[]).filter(e=>!X_.has(e)))}function Ff(t){let e=t.match(/[\w.-]+\/[\w./-]+|[\w-]+\.(ts|tsx|mjs|js|sql|md|json|prisma)/g)??[],n=new Set;for(let r of e){n.add(r.toLowerCase());let s=r.toLowerCase().split("/");for(let i=2;i<=s.length;i++)n.add(s.slice(0,i).join("/"))}return n}function Bf(t,e){let n=0;for(let r of t)e.has(r)&&n++;return n}function Hf(t,e){let n=[],r=t.split(/\n(?=## )/);for(let s of r){let i=s.trim();if(!i||!i.startsWith("## "))continue;let[a,...c]=i.split(`
799
+ `,Mf={security:[{name:"baseline.md",content:B_},{name:"gdpr.md",content:K_}],testing:[{name:"test-gaps.md",content:H_}],architecture:[{name:"architecture-health.md",content:W_}],functional:[],engineering:[],seo:[],incident:[],implement:[],compose:[]},G_=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"]});function qf(t){return new Set((t.toLowerCase().match(/[a-z][a-z0-9_.-]{3,}/g)??[]).filter(e=>!J_.has(e)))}function Ff(t){let e=t.match(/[\w.-]+\/[\w./-]+|[\w-]+\.(ts|tsx|mjs|js|sql|md|json|prisma)/g)??[],n=new Set;for(let r of e){n.add(r.toLowerCase());let s=r.toLowerCase().split("/");for(let i=2;i<=s.length;i++)n.add(s.slice(0,i).join("/"))}return n}function Bf(t,e){let n=0;for(let r of t)e.has(r)&&n++;return n}function Hf(t,e){let n=[],r=t.split(/\n(?=## )/);for(let s of r){let i=s.trim();if(!i||!i.startsWith("## "))continue;let[a,...c]=i.split(`
837
800
  `),l=a.replace(/^##\s*/,""),d=l.split("\xB7").map(f=>f.trim()),p=/^\d{4}-\d{2}-\d{2}/.exec(d[0]??"")?.[0]??"";n.push({date:p,issueKey:d.length>=3?d[1]:"",title:d.length>=3?d.slice(2).join(" \xB7 "):l,body:c.join(`
838
- `).trim(),raw:i,source:e})}return!n.length&&t.trim()&&n.push({date:"",issueKey:"",title:"",body:t.trim(),raw:t.trim(),source:e}),n}function Q_(t,e){let n=`${e.summary??""} ${e.description??""}`,r=`${t.title} ${t.body}`,s=0;e.issueKey&&t.issueKey&&t.issueKey===e.issueKey&&(s+=10),e.ruleName&&t.title.toLowerCase().includes(e.ruleName.toLowerCase())&&(s+=3);let i=Ff(`${n} ${(e.paths??[]).join(" ")}`);return s+=Math.min(6,Bf(i,Ff(r))*2),s+=Math.min(4,Bf(qf(n),qf(r))),s}function ex(t,e,n={}){let r=n.maxEntries??V_,s=n.maxChars??Y_,i=t.map((l,d)=>({entry:l,index:d,score:Q_(l,e)})).filter(l=>l.score>=J_).sort((l,d)=>d.score-l.score||d.index-l.index),a=[],c=0;for(let{entry:l}of i){if(a.length>=r)break;c+l.raw.length>s||(a.push(l),c+=l.raw.length)}return a}function rr(t,e,n,r={}){let s=[];try{let a=oa(e);a&&(s=s.concat(Hf(a,"incidents")))}catch{}try{for(let a of va(t,e))a.source==="lessons"&&(s=s.concat(Hf(a.content,"lessons")))}catch{}let i=ex(s,n,r);return i.length?`
801
+ `).trim(),raw:i,source:e})}return!n.length&&t.trim()&&n.push({date:"",issueKey:"",title:"",body:t.trim(),raw:t.trim(),source:e}),n}function X_(t,e){let n=`${e.summary??""} ${e.description??""}`,r=`${t.title} ${t.body}`,s=0;e.issueKey&&t.issueKey&&t.issueKey===e.issueKey&&(s+=10),e.ruleName&&t.title.toLowerCase().includes(e.ruleName.toLowerCase())&&(s+=3);let i=Ff(`${n} ${(e.paths??[]).join(" ")}`);return s+=Math.min(6,Bf(i,Ff(r))*2),s+=Math.min(4,Bf(qf(n),qf(r))),s}function Q_(t,e,n={}){let r=n.maxEntries??Z_,s=n.maxChars??V_,i=t.map((l,d)=>({entry:l,index:d,score:X_(l,e)})).filter(l=>l.score>=Y_).sort((l,d)=>d.score-l.score||d.index-l.index),a=[],c=0;for(let{entry:l}of i){if(a.length>=r)break;c+l.raw.length>s||(a.push(l),c+=l.raw.length)}return a}function rr(t,e,n,r={}){let s=[];try{let a=oa(e);a&&(s=s.concat(Hf(a,"incidents")))}catch{}try{for(let a of va(t,e))a.source==="lessons"&&(s=s.concat(Hf(a.content,"lessons")))}catch{}let i=Q_(s,n,r);return i.length?`
839
802
 
840
803
  RELEVANT HISTORY from this repository (selected for this ticket, not the whole ledger - facts recorded by earlier runs and by people teaching this project; verify anything that looks stale):
841
804
  `+i.map(a=>a.raw).join(`
842
805
 
843
- `):""}var V_,Y_,J_,X_,ka=X(()=>{"use strict";Ys();Vi();V_=5,Y_=2500,J_=2,X_=new Set(["the","and","for","with","that","this","from","into","when","then","than","have","has","was","were","will","would","should","could","run","runs","ran","step","steps","error","failed","fail","fails","after","before","does","not","but","its","it's","allwright","ticketpilot","jira","claude","agent","ticket","commit","branch","deploy"])});function ni(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Gf.default.join(t,e);if(Wf.default.existsSync(n))return n}return null}function sr(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
844
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(tx.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function An(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let a=Date.now(),c=await new Promise(l=>{let d=(0,Kf.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};d.stdout.on("data",f),d.stderr.on("data",f);let g=setTimeout(()=>{d.kill("SIGKILL"),p+=`
845
- [killed: timed out]`},s);d.on("close",v=>{clearTimeout(g),l({command:i,exitCode:v??-1,durationMs:Date.now()-a,tail:p.slice(-4e3)})}),d.on("error",v=>{clearTimeout(g),l({command:i,exitCode:-1,durationMs:Date.now()-a,tail:String(v)})})});n.onProgress?.(`exit ${c.exitCode} in ${Math.round(c.durationMs/1e3)}s: ${i}`),r.push(c)}return r}var Kf,Wf,Gf,tx,Yi=X(()=>{"use strict";Kf=require("node:child_process"),Wf=E(require("node:fs"),1),Gf=E(require("node:path"),1);tx=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/});var Yf={};De(Yf,{crawlSite:()=>nx,extractLinks:()=>Zf,formatCrawlReport:()=>rx,pageIssues:()=>Vf});function Zf(t,e,n){let r=new Set;for(let s of t.matchAll(/href\s*=\s*["']([^"']+)["']/gi)){let i=s[1].trim();if(!(!i||i.startsWith("#")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("javascript:")))try{let a=new URL(i,e);if(a.hash="",a.origin!==n||/\.(png|jpe?g|gif|svg|webp|ico|css|js|mjs|woff2?|ttf|pdf|zip|mp4|webm)$/i.test(a.pathname))continue;r.add(a.toString())}catch{}}return[...r]}function Vf(t){let e=[],{html:n}=t;return t.status>=400&&e.push(`returns HTTP ${t.status}`),t.status===200&&((/<title[^>]*>([\s\S]*?)<\/title>/i.exec(n)?.[1]?.trim()??"")||e.push("no <title>"),/<h1[\s>]/i.test(n)||e.push("no <h1>"),t.url.startsWith("https:")&&/(?:src|href)\s*=\s*["']http:\/\//i.test(n)&&e.push("loads http:// resources from an https page (mixed content - browsers block these)"),/<a\s[^>]*href\s*=\s*["']\s*["']/i.test(n)&&e.push("has links with an empty href")),t.ms>5e3&&e.push(`took ${(t.ms/1e3).toFixed(1)}s to respond`),e}async function nx(t){let e=new URL(t),n=e.origin,r=Date.now(),s={baseUrl:e.toString(),pages:[],notes:[]},i=new Map,a=[e.toString()],c=new Set(a),l=new Map,d=async g=>{let v=Date.now();try{let k=await fetch(g,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),T=await k.arrayBuffer(),_=T.byteLength,$=new TextDecoder().decode(T.slice(0,3e6));return{status:k.status,html:$,ms:Date.now()-v,bytes:_}}catch{return{status:0,html:"",ms:Date.now()-v,bytes:0}}};for(;a.length&&s.pages.length<30&&Date.now()-r<12e4;){let g=a.shift(),{status:v,html:k,ms:T,bytes:_}=await d(g),$=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",D=Vf({status:v,html:k,url:g,ms:T});if(v===0&&D.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:g,status:v,ms:T,bytes:_,title:$,linkedFrom:[...i.get(g)??[]].slice(0,3),issues:D}),$&&l.set($,[...l.get($)??[],g]),v===200&&k)for(let z of Zf(k,g,n))i.has(z)||i.set(z,new Set),i.get(z).add(g),c.has(z)||(c.add(z),a.push(z))}let p=[...l.entries()].filter(([,g])=>g.length>1);for(let[g,v]of p.slice(0,5))s.notes.push(`${v.length} pages share the title "${g.slice(0,60)}" (${v.slice(0,3).join(", ")})`);return(await d(new URL("/allwright-crawl-probe-404",n).toString())).status===200&&s.notes.push("an unknown path returns HTTP 200 - a catch-all is answering everything, so broken links on this site LOOK fine to a crawler and to search engines"),a.length&&s.notes.push(`stopped at ${s.pages.length} pages (cap) - ${a.length} discovered links not visited`),s.notes.push("crawled without JavaScript: what curl sees. Client-side rendering, broken interactivity and console errors are NOT covered by this evidence - do not claim they were checked."),s}function rx(t){let e=t.pages.map(n=>{let r=n.issues.length?` !! ${n.issues.join("; ")}`:"",s=n.linkedFrom.length?` (linked from ${n.linkedFrom.join(", ")})`:"";return`${n.status} ${n.ms}ms ${Math.round(n.bytes/1024)}KB ${n.url}${s}${r}`}).join(`
806
+ `):""}var Z_,V_,Y_,J_,ka=X(()=>{"use strict";Ys();Vi();Z_=5,V_=2500,Y_=2,J_=new Set(["the","and","for","with","that","this","from","into","when","then","than","have","has","was","were","will","would","should","could","run","runs","ran","step","steps","error","failed","fail","fails","after","before","does","not","but","its","it's","allwright","ticketpilot","jira","claude","agent","ticket","commit","branch","deploy"])});function ni(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Gf.default.join(t,e);if(Wf.default.existsSync(n))return n}return null}function sr(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
807
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(ex.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function An(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let a=Date.now(),c=await new Promise(l=>{let d=(0,Kf.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};d.stdout.on("data",f),d.stderr.on("data",f);let g=setTimeout(()=>{d.kill("SIGKILL"),p+=`
808
+ [killed: timed out]`},s);d.on("close",v=>{clearTimeout(g),l({command:i,exitCode:v??-1,durationMs:Date.now()-a,tail:p.slice(-4e3)})}),d.on("error",v=>{clearTimeout(g),l({command:i,exitCode:-1,durationMs:Date.now()-a,tail:String(v)})})});n.onProgress?.(`exit ${c.exitCode} in ${Math.round(c.durationMs/1e3)}s: ${i}`),r.push(c)}return r}var Kf,Wf,Gf,ex,Yi=X(()=>{"use strict";Kf=require("node:child_process"),Wf=E(require("node:fs"),1),Gf=E(require("node:path"),1);ex=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/});var Yf={};De(Yf,{crawlSite:()=>tx,extractLinks:()=>Zf,formatCrawlReport:()=>nx,pageIssues:()=>Vf});function Zf(t,e,n){let r=new Set;for(let s of t.matchAll(/href\s*=\s*["']([^"']+)["']/gi)){let i=s[1].trim();if(!(!i||i.startsWith("#")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("javascript:")))try{let a=new URL(i,e);if(a.hash="",a.origin!==n||/\.(png|jpe?g|gif|svg|webp|ico|css|js|mjs|woff2?|ttf|pdf|zip|mp4|webm)$/i.test(a.pathname))continue;r.add(a.toString())}catch{}}return[...r]}function Vf(t){let e=[],{html:n}=t;return t.status>=400&&e.push(`returns HTTP ${t.status}`),t.status===200&&((/<title[^>]*>([\s\S]*?)<\/title>/i.exec(n)?.[1]?.trim()??"")||e.push("no <title>"),/<h1[\s>]/i.test(n)||e.push("no <h1>"),t.url.startsWith("https:")&&/(?:src|href)\s*=\s*["']http:\/\//i.test(n)&&e.push("loads http:// resources from an https page (mixed content - browsers block these)"),/<a\s[^>]*href\s*=\s*["']\s*["']/i.test(n)&&e.push("has links with an empty href")),t.ms>5e3&&e.push(`took ${(t.ms/1e3).toFixed(1)}s to respond`),e}async function tx(t){let e=new URL(t),n=e.origin,r=Date.now(),s={baseUrl:e.toString(),pages:[],notes:[]},i=new Map,a=[e.toString()],c=new Set(a),l=new Map,d=async g=>{let v=Date.now();try{let k=await fetch(g,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),T=await k.arrayBuffer(),_=T.byteLength,$=new TextDecoder().decode(T.slice(0,3e6));return{status:k.status,html:$,ms:Date.now()-v,bytes:_}}catch{return{status:0,html:"",ms:Date.now()-v,bytes:0}}};for(;a.length&&s.pages.length<30&&Date.now()-r<12e4;){let g=a.shift(),{status:v,html:k,ms:T,bytes:_}=await d(g),$=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",D=Vf({status:v,html:k,url:g,ms:T});if(v===0&&D.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:g,status:v,ms:T,bytes:_,title:$,linkedFrom:[...i.get(g)??[]].slice(0,3),issues:D}),$&&l.set($,[...l.get($)??[],g]),v===200&&k)for(let z of Zf(k,g,n))i.has(z)||i.set(z,new Set),i.get(z).add(g),c.has(z)||(c.add(z),a.push(z))}let p=[...l.entries()].filter(([,g])=>g.length>1);for(let[g,v]of p.slice(0,5))s.notes.push(`${v.length} pages share the title "${g.slice(0,60)}" (${v.slice(0,3).join(", ")})`);return(await d(new URL("/allwright-crawl-probe-404",n).toString())).status===200&&s.notes.push("an unknown path returns HTTP 200 - a catch-all is answering everything, so broken links on this site LOOK fine to a crawler and to search engines"),a.length&&s.notes.push(`stopped at ${s.pages.length} pages (cap) - ${a.length} discovered links not visited`),s.notes.push("crawled without JavaScript: what curl sees. Client-side rendering, broken interactivity and console errors are NOT covered by this evidence - do not claim they were checked."),s}function nx(t){let e=t.pages.map(n=>{let r=n.issues.length?` !! ${n.issues.join("; ")}`:"",s=n.linkedFrom.length?` (linked from ${n.linkedFrom.join(", ")})`:"";return`${n.status} ${n.ms}ms ${Math.round(n.bytes/1024)}KB ${n.url}${s}${r}`}).join(`
846
809
  `);return`CRAWL OF THE RUNNING SITE (${t.baseUrl}) - gathered by the runner just now, GET only, same-origin only:
847
810
  ${e}
848
811
 
849
812
  SITE-WIDE:
850
813
  ${t.notes.map(n=>`- ${n}`).join(`
851
- `)}`}var Jf=X(()=>{"use strict"});var yd={};De(yd,{AI_CRAWLERS:()=>rm,CATEGORIES:()=>tm,assertPublicHttpUrl:()=>nm,blockedAgents:()=>gd,formatSiteAuditReport:()=>lx,probeSite:()=>cx});async function nm(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(Qf.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 em.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 gd(t,e){let n=[],r=null,s=!1;for(let a of t.split(`
852
- `)){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(d=>d.agents.some(p=>p.toLowerCase()===a.toLowerCase()));return(c.length?c:n.filter(d=>d.agents.includes("*"))).some(d=>d.disallowAll)};return e.filter(i)}async function cx(t,e=Xf){let n=[],r=(N,Z,U,ie,fe,ge=2)=>n.push({id:N,category:Z,label:U,status:ie,detail:fe,weight:ie==="info"?0:ge}),s;try{s=await nm(t,{resolveDns:e===Xf})}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 d=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(a)?.[1]?.trim()??"";r("title","seo","Title tag present and sized for results (10-60 chars)",d?d.length>=10&&d.length<=60?"pass":"warn":"fail",d?`"${d.slice(0,80)}" (${d.length} chars)`:"no <title>",3);let p=$n(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 g=/<link[^>]+rel\s*=\s*["']canonical["'][^>]*>/i.exec(a)?.[0]??"";r("canonical","seo","Canonical URL declared",g?"pass":"warn",g?md(g,"href"):"none",2),r("viewport","seo","Mobile viewport meta",$n(a,"viewport")?"pass":"fail",$n(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 v=$n(a,"robots").toLowerCase();r("noindex","seo","Page is indexable (no noindex)",v.includes("noindex")?"fail":"pass",v||"no robots meta (indexable)",3);let k=a.match(/<img[^>]*>/gi)??[],T=k.filter(N=>md(N,"alt")!=="").length;r("img-alt","seo","Images carry alt text",k.length===0?"info":T/k.length>=.8?"pass":"warn",k.length?`${T}/${k.length} images`:"no images on this page",1);let _="";try{let N=await e(`${l}/robots.txt`);_=N.status===200?N.body.slice(0,1e5):""}catch{_=""}r("robots","seo","robots.txt present",_?"pass":"warn",_?`${l}/robots.txt`:"missing",1),_&&gd(_,["*"]).length&&r("robots-all","seo","robots.txt does not block the whole site","fail","Disallow: / for all agents",3);let $=/sitemap:\s*(\S+)/i.exec(_)?.[1]??"",D=!1;try{let N=await e($||`${l}/sitemap.xml`);D=N.status===200&&N.body.includes("<")}catch{D=!1}r("sitemap","seo","XML sitemap reachable",D?"pass":"warn",$||`${l}/sitemap.xml`,2);let z=a.match(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)??[],A=new Set;for(let N of z)for(let Z of N.matchAll(/"@type"\s*:\s*"([^"]+)"/g))A.add(Z[1]);r("json-ld","aeo","Structured data (JSON-LD) present",z.length?"pass":"warn",z.length?[...A].slice(0,8).join(", "):"none found",3),r("faq-schema","aeo","Q&A-shaped schema (FAQPage/HowTo) - answer engines lift these",A.has("FAQPage")||A.has("HowTo")?"pass":"info",A.has("FAQPage")?"FAQPage found":A.has("HowTo")?"HowTo found":"none - worth adding where it fits the content",1);let P=ax(a);r("ssr-content","aeo","Content present in the initial HTML (answer engines read this, not the hydrated app)",P.length>400?"pass":P.length>100?"warn":"fail",`${P.length} chars of visible text before JavaScript`,3);let w=_?gd(_,rm):[];r("ai-crawlers","aeo","AI crawlers allowed (GPTBot, ClaudeBot, PerplexityBot\u2026)",w.length===0?"pass":"warn",w.length?`blocked: ${w.join(", ")}`:"none blocked in robots.txt",2);let j=!1;try{let N=await e(`${l}/llms.txt`);j=N.status===200&&N.body.trim().length>0&&!N.body.trim().startsWith("<")}catch{j=!1}r("llms-txt","aeo","llms.txt (optional AI index - Google says unnecessary, early adopters ship it anyway)",j?"pass":"info",j?`${l}/llms.txt`:"not present - a bonus, not a defect",1);let W=[...a.matchAll(/<h([1-3])[\s>]/gi)].map(N=>Number(N[1]));r("headings","aeo","Heading structure starts at H1",W.length===0?"warn":W[0]===1?"pass":"warn",W.slice(0,10).map(N=>`h${N}`).join(" \u2192 ")||"no h1-h3 at all",1);let L={title:$n(a,"og:title"),description:$n(a,"og:description"),image:$n(a,"og:image")};r("og","social","Open Graph card (og:title / og:description / og:image)",L.title&&L.image?"pass":L.title||L.description?"warn":"fail",Object.entries(L).map(([N,Z])=>`${N}: ${Z?"\u2713":"\u2717"}`).join(" \xB7 "),2),r("twitter","social","Twitter/X card",$n(a,"twitter:card")?"pass":"warn",$n(a,"twitter:card")||"no twitter:card meta",1);let V=N=>N.test(a),u=/G-[A-Z0-9]{6,}/.exec(a)?.[0]??"",m=/GTM-[A-Z0-9]{4,}/.exec(a)?.[0]??"",y=/AW-\d{6,}/.exec(a)?.[0]??"",x=V(/googletagmanager\.com|gtag\(/);r("google-tag","ads","Google tag installed (GA4 / Tag Manager)",x?"pass":"warn",[u&&`GA4 ${u}`,m&&`GTM ${m}`].filter(Boolean).join(" \xB7 ")||(x?"gtag present":"not found"),2),r("google-ads","ads","Google Ads conversion tag (AW-\u2026)",y?"pass":"info",y||"none - only needed when running Google Ads",1);let C=V(/connect\.facebook\.net|fbq\s*\(/);r("meta-pixel","ads","Meta (Facebook) pixel",C?"pass":"info",C?/fbq\s*\(\s*['"]init['"]\s*,\s*['"](\d+)/.exec(a)?.[1]??"pixel present":"none - only needed when running Meta ads",1);let M=[V(/snap\.licdn\.com|_linkedin_partner_id/)&&"LinkedIn",V(/analytics\.tiktok\.com/)&&"TikTok",V(/static\.hotjar\.com|clarity\.ms/)&&"Heatmaps",V(/plausible\.io|umami|posthog/)&&"Privacy analytics"].filter(Boolean);M.length&&r("other-tags","ads","Other marketing tags detected","info",M.join(", "),0);let Y=tm.map(({key:N,label:Z})=>{let U=n.filter(ge=>ge.category===N&&ge.weight>0),ie=U.reduce((ge,ke)=>ge+ke.weight,0),fe=U.reduce((ge,ke)=>ge+(ke.status==="pass"?ke.weight:ke.status==="warn"?ke.weight/2:0),0);return{key:N,label:Z,score:ie?Math.round(100*fe/ie):null}}),H=n.filter(N=>N.weight>0),F=H.length?Math.round(100*H.reduce((N,Z)=>N+(Z.status==="pass"?Z.weight:Z.status==="warn"?Z.weight/2:0),0)/H.reduce((N,Z)=>N+Z.weight,0)):0;return{ok:!0,url:i.finalUrl,overall:F,categories:Y,checks:n}}function lx(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(`
853
- `):`Site probe of ${t.url} FAILED: ${t.error}`}var Qf,em,sx,ix,ox,tm,Xf,ax,md,$n,rm,bd=X(()=>{"use strict";Qf=E(require("node:net"),1),em=E(require("node:dns/promises"),1),sx=2e4,ix=2e6,ox="AllwrightSiteAuditor/1.0 (+https://getallwright.com)",tm=[{key:"seo",label:"Technical SEO"},{key:"aeo",label:"AI visibility (AEO/GEO)"},{key:"social",label:"Social sharing"},{key:"ads",label:"Analytics & ads tags"}];Xf=async t=>{let e=await fetch(t,{headers:{"user-agent":ox,accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow",signal:AbortSignal.timeout(sx)}),n=Buffer.from(await e.arrayBuffer());return{status:e.status,finalUrl:e.url||t,body:n.subarray(0,ix).toString("utf8"),contentType:e.headers.get("content-type")??""}},ax=t=>t.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),md=(t,e)=>{let n=new RegExp(`${e}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i").exec(t);return(n?.[2]??n?.[3]??"").trim()},$n=(t,e)=>{let r=new RegExp(`<meta[^>]+(?:name|property)\\s*=\\s*["']${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["'][^>]*>`,"i").exec(t)?.[0];return r?md(r,"content"):""},rm=["GPTBot","ClaudeBot","Claude-Web","PerplexityBot","Google-Extended","Bingbot"]});async function ri(t){let{packs:e,lessons:n}=ti(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:k,formatCrawlReport:T}=await Promise.resolve().then(()=>(Jf(),Yf));try{r=T(await k(t.baseUrl.trim()))}catch(_){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${_ instanceof Error?_.message:"unreachable"}`}}}let s;if(t.role==="seo"&&t.baseUrl?.trim()){let{probeSite:k,formatSiteAuditReport:T}=await Promise.resolve().then(()=>(bd(),yd));try{s=T(await k(t.baseUrl.trim()))}catch(_){s=`Site probe of ${t.baseUrl} failed: ${_ instanceof Error?_.message:"unreachable"}`}}let i="";if(t.brief?.trim()&&(i=t.brief.trim().slice(0,16e3)),t.scope.kind==="ticket"&&t.scope.ref){let k=t.scope.ref,T="";try{let $=await t.jira.getIssue(k);T=`Ticket ${k}: ${$.summary}
814
+ `)}`}var Jf=X(()=>{"use strict"});var yd={};De(yd,{AI_CRAWLERS:()=>rm,CATEGORIES:()=>tm,assertPublicHttpUrl:()=>nm,blockedAgents:()=>gd,formatSiteAuditReport:()=>cx,probeSite:()=>ax});async function nm(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(Qf.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 em.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 gd(t,e){let n=[],r=null,s=!1;for(let a of t.split(`
815
+ `)){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(d=>d.agents.some(p=>p.toLowerCase()===a.toLowerCase()));return(c.length?c:n.filter(d=>d.agents.includes("*"))).some(d=>d.disallowAll)};return e.filter(i)}async function ax(t,e=Xf){let n=[],r=(N,Z,U,ie,fe,ge=2)=>n.push({id:N,category:Z,label:U,status:ie,detail:fe,weight:ie==="info"?0:ge}),s;try{s=await nm(t,{resolveDns:e===Xf})}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 d=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(a)?.[1]?.trim()??"";r("title","seo","Title tag present and sized for results (10-60 chars)",d?d.length>=10&&d.length<=60?"pass":"warn":"fail",d?`"${d.slice(0,80)}" (${d.length} chars)`:"no <title>",3);let p=$n(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 g=/<link[^>]+rel\s*=\s*["']canonical["'][^>]*>/i.exec(a)?.[0]??"";r("canonical","seo","Canonical URL declared",g?"pass":"warn",g?md(g,"href"):"none",2),r("viewport","seo","Mobile viewport meta",$n(a,"viewport")?"pass":"fail",$n(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 v=$n(a,"robots").toLowerCase();r("noindex","seo","Page is indexable (no noindex)",v.includes("noindex")?"fail":"pass",v||"no robots meta (indexable)",3);let k=a.match(/<img[^>]*>/gi)??[],T=k.filter(N=>md(N,"alt")!=="").length;r("img-alt","seo","Images carry alt text",k.length===0?"info":T/k.length>=.8?"pass":"warn",k.length?`${T}/${k.length} images`:"no images on this page",1);let _="";try{let N=await e(`${l}/robots.txt`);_=N.status===200?N.body.slice(0,1e5):""}catch{_=""}r("robots","seo","robots.txt present",_?"pass":"warn",_?`${l}/robots.txt`:"missing",1),_&&gd(_,["*"]).length&&r("robots-all","seo","robots.txt does not block the whole site","fail","Disallow: / for all agents",3);let $=/sitemap:\s*(\S+)/i.exec(_)?.[1]??"",D=!1;try{let N=await e($||`${l}/sitemap.xml`);D=N.status===200&&N.body.includes("<")}catch{D=!1}r("sitemap","seo","XML sitemap reachable",D?"pass":"warn",$||`${l}/sitemap.xml`,2);let z=a.match(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)??[],A=new Set;for(let N of z)for(let Z of N.matchAll(/"@type"\s*:\s*"([^"]+)"/g))A.add(Z[1]);r("json-ld","aeo","Structured data (JSON-LD) present",z.length?"pass":"warn",z.length?[...A].slice(0,8).join(", "):"none found",3),r("faq-schema","aeo","Q&A-shaped schema (FAQPage/HowTo) - answer engines lift these",A.has("FAQPage")||A.has("HowTo")?"pass":"info",A.has("FAQPage")?"FAQPage found":A.has("HowTo")?"HowTo found":"none - worth adding where it fits the content",1);let P=ox(a);r("ssr-content","aeo","Content present in the initial HTML (answer engines read this, not the hydrated app)",P.length>400?"pass":P.length>100?"warn":"fail",`${P.length} chars of visible text before JavaScript`,3);let w=_?gd(_,rm):[];r("ai-crawlers","aeo","AI crawlers allowed (GPTBot, ClaudeBot, PerplexityBot\u2026)",w.length===0?"pass":"warn",w.length?`blocked: ${w.join(", ")}`:"none blocked in robots.txt",2);let j=!1;try{let N=await e(`${l}/llms.txt`);j=N.status===200&&N.body.trim().length>0&&!N.body.trim().startsWith("<")}catch{j=!1}r("llms-txt","aeo","llms.txt (optional AI index - Google says unnecessary, early adopters ship it anyway)",j?"pass":"info",j?`${l}/llms.txt`:"not present - a bonus, not a defect",1);let W=[...a.matchAll(/<h([1-3])[\s>]/gi)].map(N=>Number(N[1]));r("headings","aeo","Heading structure starts at H1",W.length===0?"warn":W[0]===1?"pass":"warn",W.slice(0,10).map(N=>`h${N}`).join(" \u2192 ")||"no h1-h3 at all",1);let L={title:$n(a,"og:title"),description:$n(a,"og:description"),image:$n(a,"og:image")};r("og","social","Open Graph card (og:title / og:description / og:image)",L.title&&L.image?"pass":L.title||L.description?"warn":"fail",Object.entries(L).map(([N,Z])=>`${N}: ${Z?"\u2713":"\u2717"}`).join(" \xB7 "),2),r("twitter","social","Twitter/X card",$n(a,"twitter:card")?"pass":"warn",$n(a,"twitter:card")||"no twitter:card meta",1);let V=N=>N.test(a),u=/G-[A-Z0-9]{6,}/.exec(a)?.[0]??"",m=/GTM-[A-Z0-9]{4,}/.exec(a)?.[0]??"",y=/AW-\d{6,}/.exec(a)?.[0]??"",x=V(/googletagmanager\.com|gtag\(/);r("google-tag","ads","Google tag installed (GA4 / Tag Manager)",x?"pass":"warn",[u&&`GA4 ${u}`,m&&`GTM ${m}`].filter(Boolean).join(" \xB7 ")||(x?"gtag present":"not found"),2),r("google-ads","ads","Google Ads conversion tag (AW-\u2026)",y?"pass":"info",y||"none - only needed when running Google Ads",1);let C=V(/connect\.facebook\.net|fbq\s*\(/);r("meta-pixel","ads","Meta (Facebook) pixel",C?"pass":"info",C?/fbq\s*\(\s*['"]init['"]\s*,\s*['"](\d+)/.exec(a)?.[1]??"pixel present":"none - only needed when running Meta ads",1);let M=[V(/snap\.licdn\.com|_linkedin_partner_id/)&&"LinkedIn",V(/analytics\.tiktok\.com/)&&"TikTok",V(/static\.hotjar\.com|clarity\.ms/)&&"Heatmaps",V(/plausible\.io|umami|posthog/)&&"Privacy analytics"].filter(Boolean);M.length&&r("other-tags","ads","Other marketing tags detected","info",M.join(", "),0);let Y=tm.map(({key:N,label:Z})=>{let U=n.filter(ge=>ge.category===N&&ge.weight>0),ie=U.reduce((ge,ke)=>ge+ke.weight,0),fe=U.reduce((ge,ke)=>ge+(ke.status==="pass"?ke.weight:ke.status==="warn"?ke.weight/2:0),0);return{key:N,label:Z,score:ie?Math.round(100*fe/ie):null}}),H=n.filter(N=>N.weight>0),F=H.length?Math.round(100*H.reduce((N,Z)=>N+(Z.status==="pass"?Z.weight:Z.status==="warn"?Z.weight/2:0),0)/H.reduce((N,Z)=>N+Z.weight,0)):0;return{ok:!0,url:i.finalUrl,overall:F,categories:Y,checks:n}}function cx(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(`
816
+ `):`Site probe of ${t.url} FAILED: ${t.error}`}var Qf,em,rx,sx,ix,tm,Xf,ox,md,$n,rm,bd=X(()=>{"use strict";Qf=E(require("node:net"),1),em=E(require("node:dns/promises"),1),rx=2e4,sx=2e6,ix="AllwrightSiteAuditor/1.0 (+https://getallwright.com)",tm=[{key:"seo",label:"Technical SEO"},{key:"aeo",label:"AI visibility (AEO/GEO)"},{key:"social",label:"Social sharing"},{key:"ads",label:"Analytics & ads tags"}];Xf=async t=>{let e=await fetch(t,{headers:{"user-agent":ix,accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow",signal:AbortSignal.timeout(rx)}),n=Buffer.from(await e.arrayBuffer());return{status:e.status,finalUrl:e.url||t,body:n.subarray(0,sx).toString("utf8"),contentType:e.headers.get("content-type")??""}},ox=t=>t.replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),md=(t,e)=>{let n=new RegExp(`${e}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i").exec(t);return(n?.[2]??n?.[3]??"").trim()},$n=(t,e)=>{let r=new RegExp(`<meta[^>]+(?:name|property)\\s*=\\s*["']${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["'][^>]*>`,"i").exec(t)?.[0];return r?md(r,"content"):""},rm=["GPTBot","ClaudeBot","Claude-Web","PerplexityBot","Google-Extended","Bingbot"]});async function ri(t){let{packs:e,lessons:n}=ti(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:k,formatCrawlReport:T}=await Promise.resolve().then(()=>(Jf(),Yf));try{r=T(await k(t.baseUrl.trim()))}catch(_){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${_ instanceof Error?_.message:"unreachable"}`}}}let s;if(t.role==="seo"&&t.baseUrl?.trim()){let{probeSite:k,formatSiteAuditReport:T}=await Promise.resolve().then(()=>(bd(),yd));try{s=T(await k(t.baseUrl.trim()))}catch(_){s=`Site probe of ${t.baseUrl} failed: ${_ instanceof Error?_.message:"unreachable"}`}}let i="";if(t.brief?.trim()&&(i=t.brief.trim().slice(0,16e3)),t.scope.kind==="ticket"&&t.scope.ref){let k=t.scope.ref,T="";try{let $=await t.jira.getIssue(k);T=`Ticket ${k}: ${$.summary}
854
817
 
855
818
  ${$.description}`.slice(0,4e3)}catch{T=`Ticket ${k} (could not fetch its text from Jira).`}let _=await Ql(t.repoPath,k).catch(()=>null);if(_){let{base:$,stat:D,diff:z}=await fa(t.repoPath,_).catch(()=>({base:"",stat:"",diff:""}));i=`${T}
856
819
 
@@ -872,27 +835,27 @@ ${_.tail.slice(-2e3)}`).join(`
872
835
 
873
836
  ---
874
837
 
875
- `))}let l=t.model||t.agent.adapter.deepModel,d=t.detailLevel??"technical",p=await t.agent.adapter.run({repoPath:t.repoPath,prompt:bf(t.role,e,n,{scopeNote:i,testResults:a,crawlResults:r,siteProbe:s,detailLevel:d,memory:rr(t.role,t.repoPath,{summary:i||`${t.role} audit`,description:i??""})}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,wd.randomUUID)(),model:l,onLog:(k,T)=>{k==="agent"&&b.info(`[audit:${t.role}] ${T.slice(0,160)}`)}});be({surface:t.role==="incident"?"incident_diagnosis":"audit",projectId:t.projectId,agentId:t.agent.adapter.id,refKind:"audit",refLabel:t.role,...we(p)});let f=wf(p.resultText);if("error"in f)return{ok:!1,error:f.error};let g=vf(t.repoPath,f.findings);for(let k of g.droppedFindings)b.warn(`[audit:${t.role}] dropped "${k.title}" - cited files do not exist: `+k.files.join(", "));let v={id:(0,wd.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:p.model||l,summary:f.summary,packNames:e.map(k=>k.name),findings:g.findings,costUsd:p.costUsd??0,inputTokens:p.inputTokens??0,outputTokens:p.outputTokens??0,cacheReadTokens:p.cacheReadTokens??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:d,...c?{testRun:c}:{}};return Tf(t.projectId,v),b.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${g.findings.length} finding(s)`+(f.dropped?`, ${f.dropped} malformed`:"")+(g.droppedFindings.length?`, ${g.droppedFindings.length} dropped for citing files that do not exist`:"")+(g.correctedLines?`, ${g.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:v}}var wd,sm,Sa=X(()=>{"use strict";wd=require("node:crypto"),sm=E(require("node:fs"),1);kf();wa();sn();Vi();ka();nn();lt();Yi()});function im(){return si.default.join(te(),"pending-runs.json")}function vd(){return si.default.join(te(),"pending-deploys.json")}function kd(){return si.default.join(te(),"pending-inputs.json")}function Sd(){return si.default.join(te(),"merge-watch.json")}function _d(){return si.default.join(te(),"pending-pushes.json")}function xd(){let t=_d();if(!rt.default.existsSync(t))return{};try{return gx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function _a(t){let e=xd();e[t.runId]=t,Cn(_d(),e)}function xa(t){return xd()[t]??null}function Td(t){let e=xd();t in e&&(delete e[t],Cn(_d(),e))}function Ta(){let t=Sd();if(!rt.default.existsSync(t))return{};try{return bx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function om(t){let e=Ta();e[t.runId]=t,Cn(Sd(),e)}function Ji(t){let e=Ta();t in e&&(delete e[t],Cn(Sd(),e))}function Xi(){let t=im();if(!rt.default.existsSync(t))return{};try{return ux.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function Cn(t,e){rt.default.mkdirSync(te(),{recursive:!0,mode:448});let n=t+".tmp";rt.default.writeFileSync(n,JSON.stringify(e,null,2)+`
876
- `,{mode:384}),rt.default.renameSync(n,t),rt.default.chmodSync(t,384)}function am(t){Cn(im(),t)}function At(t){let e=Xi();e[t.runId]=t,am(e)}function ii(t){return Xi()[t]??null}function ir(t){let e=Xi();t in e&&(delete e[t],am(e))}function Rd(){let t=vd();if(!rt.default.existsSync(t))return{};try{return px.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function cm(t){let e=Rd();e[t.runId]=t,Cn(vd(),e)}function Ra(t){return Rd()[t]??null}function Ia(t){let e=Rd();t in e&&(delete e[t],Cn(vd(),e))}function os(){let t=kd();if(!rt.default.existsSync(t))return{};try{return wx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function lm(t){let e=os();e[t.runId]=t,Cn(kd(),e)}function dm(t){return os()[t]??null}function an(t){let e=os();t in e&&(delete e[t],Cn(kd(),e))}var rt,si,dx,ux,hx,px,fx,mx,gx,yx,bx,wx,Qi=X(()=>{"use strict";rt=E(require("node:fs"),1),si=E(require("node:path"),1);_t();Ae();dx=S.object({runId:S.string(),issueKey:S.string(),repoName:S.string(),owner:S.string(),repo:S.string(),prNumber:S.number().int(),prUrl:S.string(),branch:S.string(),headSha:S.string(),doneLabel:S.string(),failedLabel:S.string(),jiraTransition:S.string().optional(),mergeOnApprove:S.boolean().default(!1),mergeMethod:S.enum(["squash","merge","rebase"]).default("squash"),autoMerge:S.boolean().default(!1),nextDecisionSeq:S.number().int().default(1e5),changesRequestedNotified:S.boolean().optional(),conflictNotified:S.boolean().optional(),agentConfigDir:S.string().optional()}),ux=S.record(dx),hx=S.object({runId:S.string(),issueKey:S.string(),issueSummary:S.string().default(""),projectId:S.string(),repoName:S.string(),environmentName:S.string(),requestedBy:S.string().default(""),createdAt:S.string()}),px=S.record(hx),fx=S.object({runId:S.string(),issueKey:S.string(),kind:S.enum(["plan","implement"]),repoPath:S.string(),sessionId:S.string(),doneLabel:S.string(),failedLabel:S.string(),timeoutSeconds:S.number(),createdAt:S.string(),questionsPostedAt:S.string(),rounds:S.number().int().default(1),nextLogSeq:S.number().int().nonnegative().default(0),baseRepoPath:S.string().optional(),repoName:S.string().optional(),branch:S.string().optional(),baseBranch:S.string().optional(),jiraTransition:S.string().optional(),jiraTransitionOnMerge:S.string().optional(),requireApproval:S.boolean().optional(),maxTurns:S.number().int().optional(),runTests:S.boolean().default(!0),allowWeb:S.boolean().default(!1),mergeOnApprove:S.boolean().default(!1),mergeMethod:S.enum(["squash","merge","rebase"]).default("squash"),autoMerge:S.boolean().default(!1),issueSummary:S.string().default(""),claudeConfigDir:S.string().optional(),agent:S.string().optional(),model:S.string().optional(),actorEmail:S.string().optional(),preflight:S.enum(["epic-confirm"]).optional(),ruleId:S.string().optional()}),mx=S.object({runId:S.string(),issueKey:S.string(),issueSummary:S.string().default(""),repoName:S.string(),baseRepoPath:S.string(),branch:S.string(),baseBranch:S.string(),headSha:S.string(),requireApproval:S.boolean(),mergeOnApprove:S.boolean().default(!1),mergeMethod:S.enum(["squash","merge","rebase"]).default("squash"),autoMerge:S.boolean().default(!1),doneLabel:S.string(),failedLabel:S.string(),jiraTransition:S.string().optional(),jiraTransitionOnMerge:S.string().optional(),actorEmail:S.string().optional(),resultSummary:S.string().default(""),prSummary:S.string().default(""),costUsd:S.number().default(0),nextLogSeq:S.number().int().default(1e5),createdAt:S.string()}),gx=S.record(mx),yx=S.object({runId:S.string(),issueKey:S.string(),repoName:S.string(),owner:S.string(),repo:S.string(),prNumber:S.number().int(),prUrl:S.string(),jiraTransitionOnMerge:S.string().default(""),createdAt:S.string()}),bx=S.record(yx),wx=S.record(fx)});function pm(t,e=512e3){try{let n=pt.default.statSync(t);return!n.isFile()||n.size>e?null:pt.default.readFileSync(t,"utf8")}catch{return null}}function fm(t,e=60){try{return pt.default.readdirSync(t).slice(0,e).map(n=>eo.default.join(t,n)).filter(n=>{try{return pt.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function Ea(t,e=vx){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of fm(s)){if(!i.endsWith(".service"))continue;let a=pm(i);if(!a||!a.includes(n))continue;let c=/^\s*ExecStart\s*=\s*(.+)$/m.exec(a)?.[1]?.trim()??"",l=/^\s*User\s*=\s*(.+)$/m.exec(a)?.[1]?.trim()??"root (no User= line)";r.push(`${eo.default.basename(i,".service")} (User=${l})`+(c?` runs: ${c}`:""))}return r}function mm(t,e=um,n=hm){let r=t.map(a=>a.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(a=>fm(a))],i=[];for(let a of s){let c=pm(a);if(!c)continue;let l=c.toLowerCase(),d=r.find(f=>l.includes(f));if(!d)continue;let p=c.split(`
877
- `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push({file:a,host:d,lines:p})}return i}function gm(t){return`${t.file} mentions ${t.host}`+(t.lines.length?` - routing lines: ${t.lines.join(" | ")}`:" - no routing line found")}function kx(t,e=um,n=hm){return mm(t,e,n).map(gm)}function ym(t){return t.trim().replace(/\/+$/,"")}function Sx(t){let e=t.trim().replace(/;\s*$/,"").replace(/\{\s*$/,"").trim(),n=/^root\s+(?:\*\s+)?(\S+)$/i.exec(e);return n?.[1]?ym(n[1].replace(/^["']|["']$/g,"")):null}function _x(t,e){let n=ym(e);if(!n)return!1;let r=!1;for(let s of t){if(/(?:^|\s)(?:reverse_proxy|proxy_pass)(?:\s|$|;)/i.test(s))return!1;let i=Sx(s);i&&(i===n||i.startsWith(`${n}/`))&&(r=!0)}return r}function xx(t){return t.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi,"$1***@").replace(/\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/g,"$1_***").replace(/\bgithub_pat_[A-Za-z0-9_]{10,}/g,"github_pat_***")}function Tx(t){try{let e=pt.default.statSync(t).uid;return(0,cn.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function Aa(t){let e=(0,cn.spawnSync)("git",["-C",t,"ls-remote","--heads","origin"],{encoding:"utf8",timeout:25e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true",GIT_SSH_COMMAND:"ssh -oBatchMode=yes"}});return e.status===0?{ok:!0,branches:(e.stdout??"").split(`
878
- `).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:Rx(`${e.stderr??""}`,t,Tx(t),e.error?.message)}function Rx(t,e,n,r){let s=xx(t.trim()),i=s.split(`
838
+ `))}let l=t.model||t.agent.adapter.deepModel,d=t.detailLevel??"technical",p=await t.agent.adapter.run({repoPath:t.repoPath,prompt:bf(t.role,e,n,{scopeNote:i,testResults:a,crawlResults:r,siteProbe:s,detailLevel:d,memory:rr(t.role,t.repoPath,{summary:i||`${t.role} audit`,description:i??""})}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,wd.randomUUID)(),model:l,onLog:(k,T)=>{k==="agent"&&b.info(`[audit:${t.role}] ${T.slice(0,160)}`)}});be({surface:t.role==="incident"?"incident_diagnosis":"audit",projectId:t.projectId,agentId:t.agent.adapter.id,refKind:"audit",refLabel:t.role,...we(p)});let f=wf(p.resultText);if("error"in f)return{ok:!1,error:f.error};let g=vf(t.repoPath,f.findings);for(let k of g.droppedFindings)b.warn(`[audit:${t.role}] dropped "${k.title}" - cited files do not exist: `+k.files.join(", "));let v={id:(0,wd.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:p.model||l,summary:f.summary,packNames:e.map(k=>k.name),findings:g.findings,costUsd:p.costUsd??0,inputTokens:p.inputTokens??0,outputTokens:p.outputTokens??0,cacheReadTokens:p.cacheReadTokens??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:d,...c?{testRun:c}:{}};return Tf(t.projectId,v),b.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${g.findings.length} finding(s)`+(f.dropped?`, ${f.dropped} malformed`:"")+(g.droppedFindings.length?`, ${g.droppedFindings.length} dropped for citing files that do not exist`:"")+(g.correctedLines?`, ${g.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:v}}var wd,sm,Sa=X(()=>{"use strict";wd=require("node:crypto"),sm=E(require("node:fs"),1);kf();wa();sn();Vi();ka();nn();lt();Yi()});function im(){return si.default.join(te(),"pending-runs.json")}function vd(){return si.default.join(te(),"pending-deploys.json")}function kd(){return si.default.join(te(),"pending-inputs.json")}function Sd(){return si.default.join(te(),"merge-watch.json")}function _d(){return si.default.join(te(),"pending-pushes.json")}function xd(){let t=_d();if(!rt.default.existsSync(t))return{};try{return mx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function _a(t){let e=xd();e[t.runId]=t,Cn(_d(),e)}function xa(t){return xd()[t]??null}function Td(t){let e=xd();t in e&&(delete e[t],Cn(_d(),e))}function Ta(){let t=Sd();if(!rt.default.existsSync(t))return{};try{return yx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function om(t){let e=Ta();e[t.runId]=t,Cn(Sd(),e)}function Ji(t){let e=Ta();t in e&&(delete e[t],Cn(Sd(),e))}function Xi(){let t=im();if(!rt.default.existsSync(t))return{};try{return dx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function Cn(t,e){rt.default.mkdirSync(te(),{recursive:!0,mode:448});let n=t+".tmp";rt.default.writeFileSync(n,JSON.stringify(e,null,2)+`
839
+ `,{mode:384}),rt.default.renameSync(n,t),rt.default.chmodSync(t,384)}function am(t){Cn(im(),t)}function At(t){let e=Xi();e[t.runId]=t,am(e)}function ii(t){return Xi()[t]??null}function ir(t){let e=Xi();t in e&&(delete e[t],am(e))}function Rd(){let t=vd();if(!rt.default.existsSync(t))return{};try{return hx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function cm(t){let e=Rd();e[t.runId]=t,Cn(vd(),e)}function Ra(t){return Rd()[t]??null}function Ia(t){let e=Rd();t in e&&(delete e[t],Cn(vd(),e))}function os(){let t=kd();if(!rt.default.existsSync(t))return{};try{return bx.parse(JSON.parse(rt.default.readFileSync(t,"utf8")))}catch{return{}}}function lm(t){let e=os();e[t.runId]=t,Cn(kd(),e)}function dm(t){return os()[t]??null}function an(t){let e=os();t in e&&(delete e[t],Cn(kd(),e))}var rt,si,lx,dx,ux,hx,px,fx,mx,gx,yx,bx,Qi=X(()=>{"use strict";rt=E(require("node:fs"),1),si=E(require("node:path"),1);_t();Ae();lx=S.object({runId:S.string(),issueKey:S.string(),repoName:S.string(),owner:S.string(),repo:S.string(),prNumber:S.number().int(),prUrl:S.string(),branch:S.string(),headSha:S.string(),doneLabel:S.string(),failedLabel:S.string(),jiraTransition:S.string().optional(),mergeOnApprove:S.boolean().default(!1),mergeMethod:S.enum(["squash","merge","rebase"]).default("squash"),autoMerge:S.boolean().default(!1),nextDecisionSeq:S.number().int().default(1e5),changesRequestedNotified:S.boolean().optional(),conflictNotified:S.boolean().optional(),agentConfigDir:S.string().optional()}),dx=S.record(lx),ux=S.object({runId:S.string(),issueKey:S.string(),issueSummary:S.string().default(""),projectId:S.string(),repoName:S.string(),environmentName:S.string(),requestedBy:S.string().default(""),createdAt:S.string()}),hx=S.record(ux),px=S.object({runId:S.string(),issueKey:S.string(),kind:S.enum(["plan","implement"]),repoPath:S.string(),sessionId:S.string(),doneLabel:S.string(),failedLabel:S.string(),timeoutSeconds:S.number(),createdAt:S.string(),questionsPostedAt:S.string(),rounds:S.number().int().default(1),nextLogSeq:S.number().int().nonnegative().default(0),baseRepoPath:S.string().optional(),repoName:S.string().optional(),branch:S.string().optional(),baseBranch:S.string().optional(),jiraTransition:S.string().optional(),jiraTransitionOnMerge:S.string().optional(),requireApproval:S.boolean().optional(),maxTurns:S.number().int().optional(),runTests:S.boolean().default(!0),allowWeb:S.boolean().default(!1),mergeOnApprove:S.boolean().default(!1),mergeMethod:S.enum(["squash","merge","rebase"]).default("squash"),autoMerge:S.boolean().default(!1),issueSummary:S.string().default(""),claudeConfigDir:S.string().optional(),agent:S.string().optional(),model:S.string().optional(),actorEmail:S.string().optional(),preflight:S.enum(["epic-confirm"]).optional(),ruleId:S.string().optional()}),fx=S.object({runId:S.string(),issueKey:S.string(),issueSummary:S.string().default(""),repoName:S.string(),baseRepoPath:S.string(),branch:S.string(),baseBranch:S.string(),headSha:S.string(),requireApproval:S.boolean(),mergeOnApprove:S.boolean().default(!1),mergeMethod:S.enum(["squash","merge","rebase"]).default("squash"),autoMerge:S.boolean().default(!1),doneLabel:S.string(),failedLabel:S.string(),jiraTransition:S.string().optional(),jiraTransitionOnMerge:S.string().optional(),actorEmail:S.string().optional(),resultSummary:S.string().default(""),prSummary:S.string().default(""),costUsd:S.number().default(0),nextLogSeq:S.number().int().default(1e5),createdAt:S.string()}),mx=S.record(fx),gx=S.object({runId:S.string(),issueKey:S.string(),repoName:S.string(),owner:S.string(),repo:S.string(),prNumber:S.number().int(),prUrl:S.string(),jiraTransitionOnMerge:S.string().default(""),createdAt:S.string()}),yx=S.record(gx),bx=S.record(px)});function pm(t,e=512e3){try{let n=pt.default.statSync(t);return!n.isFile()||n.size>e?null:pt.default.readFileSync(t,"utf8")}catch{return null}}function fm(t,e=60){try{return pt.default.readdirSync(t).slice(0,e).map(n=>eo.default.join(t,n)).filter(n=>{try{return pt.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function Ea(t,e=wx){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of fm(s)){if(!i.endsWith(".service"))continue;let a=pm(i);if(!a||!a.includes(n))continue;let c=/^\s*ExecStart\s*=\s*(.+)$/m.exec(a)?.[1]?.trim()??"",l=/^\s*User\s*=\s*(.+)$/m.exec(a)?.[1]?.trim()??"root (no User= line)";r.push(`${eo.default.basename(i,".service")} (User=${l})`+(c?` runs: ${c}`:""))}return r}function mm(t,e=um,n=hm){let r=t.map(a=>a.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(a=>fm(a))],i=[];for(let a of s){let c=pm(a);if(!c)continue;let l=c.toLowerCase(),d=r.find(f=>l.includes(f));if(!d)continue;let p=c.split(`
840
+ `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push({file:a,host:d,lines:p})}return i}function gm(t){return`${t.file} mentions ${t.host}`+(t.lines.length?` - routing lines: ${t.lines.join(" | ")}`:" - no routing line found")}function vx(t,e=um,n=hm){return mm(t,e,n).map(gm)}function ym(t){return t.trim().replace(/\/+$/,"")}function kx(t){let e=t.trim().replace(/;\s*$/,"").replace(/\{\s*$/,"").trim(),n=/^root\s+(?:\*\s+)?(\S+)$/i.exec(e);return n?.[1]?ym(n[1].replace(/^["']|["']$/g,"")):null}function Sx(t,e){let n=ym(e);if(!n)return!1;let r=!1;for(let s of t){if(/(?:^|\s)(?:reverse_proxy|proxy_pass)(?:\s|$|;)/i.test(s))return!1;let i=kx(s);i&&(i===n||i.startsWith(`${n}/`))&&(r=!0)}return r}function _x(t){return t.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi,"$1***@").replace(/\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/g,"$1_***").replace(/\bgithub_pat_[A-Za-z0-9_]{10,}/g,"github_pat_***")}function xx(t){try{let e=pt.default.statSync(t).uid;return(0,cn.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function Aa(t){let e=(0,cn.spawnSync)("git",["-C",t,"ls-remote","--heads","origin"],{encoding:"utf8",timeout:25e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true",GIT_SSH_COMMAND:"ssh -oBatchMode=yes"}});return e.status===0?{ok:!0,branches:(e.stdout??"").split(`
841
+ `).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:Tx(`${e.stderr??""}`,t,xx(t),e.error?.message)}function Tx(t,e,n,r){let s=_x(t.trim()),i=s.split(`
879
842
  `).find(l=>l.trim())??r??"git failed with no output",a=n?`sudo -u ${n} `:"",c=`Verify it non-interactively (a plain ls-remote would just prompt you and pass): GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=true git -C ${e} ls-remote --heads origin`;return/not a git repository/i.test(s)?{ok:!1,reason:"not-a-checkout",detail:`${e} is not a git checkout`,fix:`Clone the repository into ${e} first.`}:/No such remote|does not appear to be a git repository|'origin' does not appear/i.test(s)&&!/authenticat/i.test(s)?{ok:!1,reason:"no-remote",detail:`this checkout has no usable "origin" remote - ${i}`,fix:`Add it: ${a}git -C ${e} remote add origin <url>`}:/could not read (Username|Password)|terminal prompts disabled|Authentication failed|Invalid username or password|Permission denied \(publickey\)|Support for password authentication was removed|Repository not found|access rights|Host key verification failed/i.test(s)?{ok:!1,reason:"auth",detail:`cannot read origin: git has no usable credential${n?` for ${n}`:""} on this machine - ${i}. The branch may well exist; this machine simply cannot ask.`,fix:`Give ${n??"the user the deploy runs as"} a saved credential: ${a}git config --global credential.helper store, then ${a}git -C ${e} fetch origin once and paste a GitHub PAT as the password (an account password is refused). ${c}`}:/Could not resolve host|Connection (timed out|refused)|Network is unreachable|unable to access|Operation timed out/i.test(s)||r?{ok:!1,reason:"network",detail:`origin could not be reached from this machine - ${i}. This is DNS or a firewall, not a missing branch.`,fix:`Check outbound network from this machine, then re-run. ${c}`}:{ok:!1,reason:"unknown",detail:`origin could not be read - ${i}`,fix:`Run it by hand on this machine to see the whole error: ${a}git -C ${e} ls-remote --heads origin`}}function to(t){let e=c=>{try{return(0,cn.execFileSync)("git",c,{cwd:t,encoding:"utf8",timeout:2e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},n=Aa(t),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n.ok?n.branches:null,a=[`
880
843
 
881
844
  BRANCHES - asked of git just now by the runner, which has a shell. Do NOT conclude a branch is missing from what is under .git/refs: that only says what this checkout has fetched, and a branch pushed from somewhere else is invisible there until someone runs git fetch.`];if(a.push(n.ok?`- on origin: ${n.branches.join(", ")||"(none)"}`:`- origin could NOT be read (${n.reason}): ${n.detail} Report this as "the branch could not be verified from this machine", never as "the branch does not exist", and give this as the fix: ${n.fix}`),r&&a.push(`- local branches in this checkout: ${r.split(`
882
845
  `).join(", ")}`),s&&a.push(`- remote-tracking refs already fetched here: ${s.split(`
883
846
  `).join(", ")}`),i&&s){let c=new Set(s.split(`
884
847
  `).map(d=>d.replace(/^origin\//,""))),l=i.filter(d=>!c.has(d));l.length&&a.push(`- exists on origin but NOT fetched here yet: ${l.join(", ")}. This is a \`git fetch\`, not a missing branch - never report it as a blocker.`)}return a.join(`
885
- `)}function Ix(t){try{let e=pt.default.realpathSync(t),n=pt.default.openSync(e,"r"),r=Buffer.alloc(128),s=pt.default.readSync(n,r,0,128,0);pt.default.closeSync(n);let i=r.subarray(0,s).toString("utf8").split(`
886
- `)[0]??"";if(!i.startsWith("#!"))return null;let a=i.trim(),c=/^#!\s*\/usr\/bin\/env\s+(?:-S\s+)?(\S+)/.exec(a);return{target:e,shebang:a,viaEnv:c?.[1]??null}}catch{return null}}function Id(){let t=s=>{try{return(0,cn.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,cn.execFileSync)("which",[s],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],...i?{env:{...process.env,PATH:i}}:{}}).trim()}catch{return""}},n=[],r=!1;for(let s of["node","npm","python3","pip3","yarn","pnpm"]){let i=e(s);if(!i)continue;let a=[i,`/usr/bin/${s}`,`/usr/local/bin/${s}`].filter((c,l,d)=>d.indexOf(c)===l&&pt.default.existsSync(c));for(let c of a){let l=t(c);if(!l)continue;let d=c===i?`${s} in the RUNNER's PATH (${c}) - deploy steps run with THIS`:`${s} at ${c}`;n.push(`- ${d}: ${l}`);let p=Ix(c);if(p)if(p.viaEnv){let f=p.viaEnv,g=e(f),v=g?t(g):null;if(n.push(` ${c}${p.target===c?"":` -> ${p.target}`} is a SCRIPT, not a binary. Its shebang is "${p.shebang}", so it runs under the FIRST ${f} in PATH`+(g?` - right now ${g}${v?` (${v})`:""}`:"")+`. Writing the absolute path to ${eo.default.basename(c)} therefore pins NOTHING.`),g&&pt.default.existsSync(`/usr/bin/${f}`)){let k=t(`/usr/bin/${f}`),T=v;k&&T&&k!==T&&(r=!0)}}else n.push(` ${c} runs under ${p.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
848
+ `)}function Rx(t){try{let e=pt.default.realpathSync(t),n=pt.default.openSync(e,"r"),r=Buffer.alloc(128),s=pt.default.readSync(n,r,0,128,0);pt.default.closeSync(n);let i=r.subarray(0,s).toString("utf8").split(`
849
+ `)[0]??"";if(!i.startsWith("#!"))return null;let a=i.trim(),c=/^#!\s*\/usr\/bin\/env\s+(?:-S\s+)?(\S+)/.exec(a);return{target:e,shebang:a,viaEnv:c?.[1]??null}}catch{return null}}function Id(){let t=s=>{try{return(0,cn.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,cn.execFileSync)("which",[s],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],...i?{env:{...process.env,PATH:i}}:{}}).trim()}catch{return""}},n=[],r=!1;for(let s of["node","npm","python3","pip3","yarn","pnpm"]){let i=e(s);if(!i)continue;let a=[i,`/usr/bin/${s}`,`/usr/local/bin/${s}`].filter((c,l,d)=>d.indexOf(c)===l&&pt.default.existsSync(c));for(let c of a){let l=t(c);if(!l)continue;let d=c===i?`${s} in the RUNNER's PATH (${c}) - deploy steps run with THIS`:`${s} at ${c}`;n.push(`- ${d}: ${l}`);let p=Rx(c);if(p)if(p.viaEnv){let f=p.viaEnv,g=e(f),v=g?t(g):null;if(n.push(` ${c}${p.target===c?"":` -> ${p.target}`} is a SCRIPT, not a binary. Its shebang is "${p.shebang}", so it runs under the FIRST ${f} in PATH`+(g?` - right now ${g}${v?` (${v})`:""}`:"")+`. Writing the absolute path to ${eo.default.basename(c)} therefore pins NOTHING.`),g&&pt.default.existsSync(`/usr/bin/${f}`)){let k=t(`/usr/bin/${f}`),T=v;k&&T&&k!==T&&(r=!0)}}else n.push(` ${c} runs under ${p.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
887
850
  - runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
888
851
  ${n.map(s=>` ${s}`).join(`
889
- `)}`+(r?"\n- PINNING A RUNTIME - this machine needs it, and it is the step most contracts get wrong: a wrapper script above resolves its interpreter through PATH, and the PATH the deploy steps inherit selects a DIFFERENT version from the system one. An absolute path to the wrapper does not fix that. Pin PATH itself in any step that builds, installs or compiles, e.g. `env PATH=/usr/bin:/bin /usr/bin/npm ci`, and say in the document WHY the bare form is wrong. This matters most for native modules: they are compiled against whichever interpreter ran the install, and the service then fails to load them at runtime.":""):""}function Ex(){let t=a=>{try{return(0,cn.execFileSync)("bash",["-lc",`command -v ${JSON.stringify(a)}`],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}},e=a=>{try{return(0,cn.execFileSync)("systemctl",["is-active",a],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()==="active"}catch{return!1}},n=["caddy","nginx","apache2","haproxy","docker","pm2","systemctl","certbot"],r=n.filter(t),s=n.filter(a=>!r.includes(a)),i=["caddy","nginx","apache2","haproxy"].filter(a=>e(a));return`
852
+ `)}`+(r?"\n- PINNING A RUNTIME - this machine needs it, and it is the step most contracts get wrong: a wrapper script above resolves its interpreter through PATH, and the PATH the deploy steps inherit selects a DIFFERENT version from the system one. An absolute path to the wrapper does not fix that. Pin PATH itself in any step that builds, installs or compiles, e.g. `env PATH=/usr/bin:/bin /usr/bin/npm ci`, and say in the document WHY the bare form is wrong. This matters most for native modules: they are compiled against whichever interpreter ran the install, and the service then fails to load them at runtime.":""):""}function Ix(){let t=a=>{try{return(0,cn.execFileSync)("bash",["-lc",`command -v ${JSON.stringify(a)}`],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}},e=a=>{try{return(0,cn.execFileSync)("systemctl",["is-active",a],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()==="active"}catch{return!1}},n=["caddy","nginx","apache2","haproxy","docker","pm2","systemctl","certbot"],r=n.filter(t),s=n.filter(a=>!r.includes(a)),i=["caddy","nginx","apache2","haproxy"].filter(a=>e(a));return`
890
853
 
891
854
  WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that is not here:
892
855
  - installed: ${r.join(", ")||"(none of the usual ones)"}
893
856
  - NOT installed: ${s.join(", ")||"(none missing)"}
894
857
  - reverse proxy currently running: ${i.join(", ")||"(none)"}
895
- A proxy that is already running is almost certainly serving something else on this box. EXTEND its configuration; never introduce a second one. Two cannot hold port 80, so the best case is that yours refuses to start and the worst is that someone stops the running one to make room and takes an unrelated site down. Same for supervisors: if units already exist here, write one in that style rather than proposing docker or pm2 because they are more familiar.`}function Ax(t){try{return new URL(t).hostname}catch{return""}}function Ed(t){let e=t.urls.map(Ax).filter(Boolean),n=Ea(t.repoPath),r=kx(e),s=[`
858
+ A proxy that is already running is almost certainly serving something else on this box. EXTEND its configuration; never introduce a second one. Two cannot hold port 80, so the best case is that yours refuses to start and the worst is that someone stops the running one to make room and takes an unrelated site down. Same for supervisors: if units already exist here, write one in that style rather than proposing docker or pm2 because they are more familiar.`}function Ex(t){try{return new URL(t).hostname}catch{return""}}function Ed(t){let e=t.urls.map(Ex).filter(Boolean),n=Ea(t.repoPath),r=vx(e),s=[`
896
859
 
897
860
  ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Trust these over anything you infer from the repository: the repo is exactly where supervision and proxying are NOT configured, so "the repo has no systemd unit" says nothing about whether a unit exists.`];return s.push(n.length?`- systemd units pointing at this checkout (${t.repoPath}):
898
861
  `+n.map(i=>` - ${i}`).join(`
@@ -901,7 +864,7 @@ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Tru
901
864
  `+r.map(i=>` - ${i}`).join(`
902
865
  `)+`
903
866
  Public checks must go through the public URL; a check against localhost only proves the app started, not that visitors can reach it.`:e.length?`- NO reverse-proxy file on this machine mentions ${e.join(", ")}. Either the site is served another way, or the public URL does not reach this machine at all - flag it, do not assume it works.`:"- no public URL was declared for these environments, so nothing could be checked against a proxy configuration."),s.join(`
904
- `)+Ex()+Id()}function bm(t){let e=[],n=a=>a.workdir.trim()||t.repoPath,r=Aa(t.repoPath),s=t.environments.map(a=>({name:a.name,dir:n(a)})),i=s.filter((a,c)=>s.findIndex(l=>l.dir===a.dir)!==c);t.environments.length>1&&e.push({environment:"",question:"Each environment has a working directory of its own",ok:i.length===0,blocking:!0,detail:i.length===0?s.map(a=>`${a.name}: ${a.dir}`).join(" \xB7 "):`${s.map(a=>`${a.name}: ${a.dir}`).join(" \xB7 ")} - a deploy of one replaces the other's checkout and build. Set the Working directory on the environment; creating the directory on the machine is not enough on its own.`});for(let a of t.environments){let c=n(a),l=Ea(c),d="";try{d=a.publicUrl?new URL(a.publicUrl).hostname:""}catch{d=""}let p=d?mm([d]):[],f=l.length?void 0:p.find(g=>_x(g.lines,c));if(e.push({environment:a.name,question:`Something supervises the app in ${c}`,ok:l.length>0||!!f,blocking:!f,detail:l.length?l.join(" \xB7 "):f?`static site - ${f.file} serves files from ${c} directly, so there is no process to supervise`:`no systemd unit on this machine references ${c}. This goes green with either a unit whose WorkingDirectory or ExecStart names ${c}, or a reverse-proxy root serving this environment's hostname from it.`}),a.servePath?.trim()){let g=a.servePath.trim(),v=($,D)=>{try{return(0,cn.execFileSync)("git",D,{cwd:$,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},k=v(g,["rev-parse","HEAD"]),T=a.branch.trim()?v(t.repoPath,["rev-parse",`origin/${a.branch.trim()}`]):null,_=k&&T&&k!==T?v(t.repoPath,["rev-list","--count",`${k}..${T}`]):null;e.push({environment:a.name,question:`The live checkout at ${g} serves the latest ${a.branch.trim()||"commit"}`,ok:k!==null&&(T===null||k===T),blocking:!1,detail:k?T===null?`serving ${k.slice(0,10)}${a.branch.trim()?` (could not resolve origin/${a.branch.trim()} to compare)`:""}`:k===T?`serving ${k.slice(0,10)} = origin/${a.branch.trim()}`:`serving ${k.slice(0,10)}, but origin/${a.branch.trim()} is at ${T.slice(0,10)}`+(_?` - ${_} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${g} - wrong path, or not a git checkout`})}if(a.publicUrl){let g=d,v=p.map(gm);e.push({environment:a.name,question:`A reverse proxy here serves ${g||a.publicUrl}`,ok:v.length>0,blocking:!1,detail:v.length?v.join(" \xB7 "):`no proxy configuration on this machine mentions ${g||a.publicUrl}`})}if(a.publicUrl){let g=d;if(g){let v="";for(let k of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=pt.default.readFileSync(eo.default.join(c,k),"utf8");break}catch{}if(v){let k=v.includes(g);e.push({environment:a.name,question:`DEPLOY.md mentions ${g}`,ok:k,blocking:!1,detail:k?"":"the deploy contract never names this URL - it likely describes an older address. Re-draft DEPLOY.md from Setup (the draft reads the declared environments), then regenerate the steps."})}}}if(a.branch)if(!r.ok)e.push({environment:a.name,question:`Branch "${a.branch}" could be checked on origin`,ok:!1,blocking:!0,detail:`${r.detail} Fix: ${r.fix}`});else{let g=r.branches.includes(a.branch);e.push({environment:a.name,question:`Branch "${a.branch}" exists on origin`,ok:g,blocking:!0,detail:g?"":`origin was reached and does not have "${a.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var cn,pt,eo,vx,um,hm,$a=X(()=>{"use strict";cn=require("node:child_process"),pt=E(require("node:fs"),1),eo=E(require("node:path"),1),vx=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],um=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],hm=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function vm(t){wm=(t??"").trim()}function km(){return wm}var wm,Ad=X(()=>{"use strict";wm=""});function Cd(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>$x.test(n)?`${n}=<redacted>`:e)}function Pn(t,e){try{let r=(0,_m.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,Sm):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,Sm):null}}function Cx(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=$d.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let a=$d.default.readFileSync(xm.default.join(r,i),"utf8");t&&a.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Tm(t){let e=t.errorText.slice(-6e3),n=[],r=(a,c)=>{c&&n.push({command:a,output:Cd(c)})},s=Cx(t.repoPath);for(let a of s)r(`systemctl status ${a}`,Pn("systemctl",["status",a,"--no-pager","-l"])),r(`journalctl -u ${a} -n 40`,Pn("journalctl",["-u",a,"-n","40","--no-pager"])),r(`systemctl show ${a} -p ExecStart -p Environment -p WorkingDirectory -p User`,Pn("systemctl",["show",a,"-p","ExecStart","-p","Environment","-p","WorkingDirectory","-p","User"]));/refused|Failed to connect|Couldn't connect|ECONNREFUSED/i.test(e)&&r("ss -ltnp",Pn("bash",["-lc","ss -ltnp 2>/dev/null | head -40"]));let i=/(?:^|\s)(?:bash: )?['"\u2018]?([\w.-]+)['"\u2019]?: (?:command not found|No such file or directory)/i.exec(e);if(i){let a=i[1];r(`which ${a} (in the runner's PATH)`,Pn("bash",["-lc",`command -v ${JSON.stringify(a)} || echo "not on this PATH"`])),r("ls of the usual system locations",Pn("bash",["-lc",`ls -l /usr/bin/${a} /usr/local/bin/${a} 2>&1 | head -5`]))}return/ENOSPC|No space left|write error/i.test(e)&&r("df -h",Pn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",Pn("id",[])),r(`ls -ld ${t.repoPath}`,Pn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Rm(t){return t.length?`
867
+ `)+Ix()+Id()}function bm(t){let e=[],n=a=>a.workdir.trim()||t.repoPath,r=Aa(t.repoPath),s=t.environments.map(a=>({name:a.name,dir:n(a)})),i=s.filter((a,c)=>s.findIndex(l=>l.dir===a.dir)!==c);t.environments.length>1&&e.push({environment:"",question:"Each environment has a working directory of its own",ok:i.length===0,blocking:!0,detail:i.length===0?s.map(a=>`${a.name}: ${a.dir}`).join(" \xB7 "):`${s.map(a=>`${a.name}: ${a.dir}`).join(" \xB7 ")} - a deploy of one replaces the other's checkout and build. Set the Working directory on the environment; creating the directory on the machine is not enough on its own.`});for(let a of t.environments){let c=n(a),l=Ea(c),d="";try{d=a.publicUrl?new URL(a.publicUrl).hostname:""}catch{d=""}let p=d?mm([d]):[],f=l.length?void 0:p.find(g=>Sx(g.lines,c));if(e.push({environment:a.name,question:`Something supervises the app in ${c}`,ok:l.length>0||!!f,blocking:!f,detail:l.length?l.join(" \xB7 "):f?`static site - ${f.file} serves files from ${c} directly, so there is no process to supervise`:`no systemd unit on this machine references ${c}. This goes green with either a unit whose WorkingDirectory or ExecStart names ${c}, or a reverse-proxy root serving this environment's hostname from it.`}),a.servePath?.trim()){let g=a.servePath.trim(),v=($,D)=>{try{return(0,cn.execFileSync)("git",D,{cwd:$,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},k=v(g,["rev-parse","HEAD"]),T=a.branch.trim()?v(t.repoPath,["rev-parse",`origin/${a.branch.trim()}`]):null,_=k&&T&&k!==T?v(t.repoPath,["rev-list","--count",`${k}..${T}`]):null;e.push({environment:a.name,question:`The live checkout at ${g} serves the latest ${a.branch.trim()||"commit"}`,ok:k!==null&&(T===null||k===T),blocking:!1,detail:k?T===null?`serving ${k.slice(0,10)}${a.branch.trim()?` (could not resolve origin/${a.branch.trim()} to compare)`:""}`:k===T?`serving ${k.slice(0,10)} = origin/${a.branch.trim()}`:`serving ${k.slice(0,10)}, but origin/${a.branch.trim()} is at ${T.slice(0,10)}`+(_?` - ${_} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${g} - wrong path, or not a git checkout`})}if(a.publicUrl){let g=d,v=p.map(gm);e.push({environment:a.name,question:`A reverse proxy here serves ${g||a.publicUrl}`,ok:v.length>0,blocking:!1,detail:v.length?v.join(" \xB7 "):`no proxy configuration on this machine mentions ${g||a.publicUrl}`})}if(a.publicUrl){let g=d;if(g){let v="";for(let k of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=pt.default.readFileSync(eo.default.join(c,k),"utf8");break}catch{}if(v){let k=v.includes(g);e.push({environment:a.name,question:`DEPLOY.md mentions ${g}`,ok:k,blocking:!1,detail:k?"":"the deploy contract never names this URL - it likely describes an older address. Re-draft DEPLOY.md from Setup (the draft reads the declared environments), then regenerate the steps."})}}}if(a.branch)if(!r.ok)e.push({environment:a.name,question:`Branch "${a.branch}" could be checked on origin`,ok:!1,blocking:!0,detail:`${r.detail} Fix: ${r.fix}`});else{let g=r.branches.includes(a.branch);e.push({environment:a.name,question:`Branch "${a.branch}" exists on origin`,ok:g,blocking:!0,detail:g?"":`origin was reached and does not have "${a.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var cn,pt,eo,wx,um,hm,$a=X(()=>{"use strict";cn=require("node:child_process"),pt=E(require("node:fs"),1),eo=E(require("node:path"),1),wx=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],um=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],hm=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function vm(t){wm=(t??"").trim()}function km(){return wm}var wm,Ad=X(()=>{"use strict";wm=""});function Cd(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>Ax.test(n)?`${n}=<redacted>`:e)}function Pn(t,e){try{let r=(0,_m.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,Sm):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,Sm):null}}function $x(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=$d.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let a=$d.default.readFileSync(xm.default.join(r,i),"utf8");t&&a.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Tm(t){let e=t.errorText.slice(-6e3),n=[],r=(a,c)=>{c&&n.push({command:a,output:Cd(c)})},s=$x(t.repoPath);for(let a of s)r(`systemctl status ${a}`,Pn("systemctl",["status",a,"--no-pager","-l"])),r(`journalctl -u ${a} -n 40`,Pn("journalctl",["-u",a,"-n","40","--no-pager"])),r(`systemctl show ${a} -p ExecStart -p Environment -p WorkingDirectory -p User`,Pn("systemctl",["show",a,"-p","ExecStart","-p","Environment","-p","WorkingDirectory","-p","User"]));/refused|Failed to connect|Couldn't connect|ECONNREFUSED/i.test(e)&&r("ss -ltnp",Pn("bash",["-lc","ss -ltnp 2>/dev/null | head -40"]));let i=/(?:^|\s)(?:bash: )?['"\u2018]?([\w.-]+)['"\u2019]?: (?:command not found|No such file or directory)/i.exec(e);if(i){let a=i[1];r(`which ${a} (in the runner's PATH)`,Pn("bash",["-lc",`command -v ${JSON.stringify(a)} || echo "not on this PATH"`])),r("ls of the usual system locations",Pn("bash",["-lc",`ls -l /usr/bin/${a} /usr/local/bin/${a} 2>&1 | head -5`]))}return/ENOSPC|No space left|write error/i.test(e)&&r("df -h",Pn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",Pn("id",[])),r(`ls -ld ${t.repoPath}`,Pn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Rm(t){return t.length?`
905
868
 
906
869
  EVIDENCE FROM THE MACHINE - gathered by the runner just now, read-only, because you cannot run commands yourself. This is the part of the system the repository cannot tell you about, and it is usually where the answer is. Values that looked like credentials were redacted before you saw them.
907
870
 
@@ -910,17 +873,17 @@ ${e.output}`).join(`
910
873
 
911
874
  `)+`
912
875
 
913
- Reason from THIS. If it does not contain the answer, say what you would need to look at and why - naming a command someone can run beats inventing a cause that fits the little you were shown.`:""}var _m,$d,xm,Sm,$x,Pd=X(()=>{"use strict";_m=require("node:child_process"),$d=E(require("node:fs"),1),xm=E(require("node:path"),1),Sm=4e3,$x=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});function Em(t,e){let n=or.default.basename(t).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=n,s=1;for(;e.has(r);)r=`${s++}-${n}`;return e.add(r),r}async function ai(t,e,n,r){if(!e.length)return"";let s=or.default.join(n,Ca);oi.default.mkdirSync(s,{recursive:!0});let i=new Set,a=[],c=0;for(let l of e){if(a.length>=Im){r("warn",`attachment cap reached (${Im} files) - skipping the rest`);break}if(l.size>Px){r("warn",`skipping attachment "${l.filename}" - ${Ox(l.size)} MB exceeds the 15 MB limit`);continue}if(c+l.size>Nx){r("warn",`attachment size budget reached - skipping "${l.filename}" and the rest`);break}try{let d=await t.downloadAttachment(l.contentUrl),p=Em(l.filename,i);oi.default.writeFileSync(or.default.join(s,p),d),c+=d.length,a.push(`- ${Ca}/${p} (${l.mimeType||"unknown type"}, ${Nd(d.length)} KB)`),r("info",`Downloaded attachment "${l.filename}" (${Nd(d.length)} KB)`)}catch(d){r("warn",`could not download attachment "${l.filename}": ${d instanceof Error?d.message:d}`)}}return a.length?`
876
+ Reason from THIS. If it does not contain the answer, say what you would need to look at and why - naming a command someone can run beats inventing a cause that fits the little you were shown.`:""}var _m,$d,xm,Sm,Ax,Pd=X(()=>{"use strict";_m=require("node:child_process"),$d=E(require("node:fs"),1),xm=E(require("node:path"),1),Sm=4e3,Ax=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});function Em(t,e){let n=or.default.basename(t).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=n,s=1;for(;e.has(r);)r=`${s++}-${n}`;return e.add(r),r}async function ai(t,e,n,r){if(!e.length)return"";let s=or.default.join(n,Ca);oi.default.mkdirSync(s,{recursive:!0});let i=new Set,a=[],c=0;for(let l of e){if(a.length>=Im){r("warn",`attachment cap reached (${Im} files) - skipping the rest`);break}if(l.size>Cx){r("warn",`skipping attachment "${l.filename}" - ${jx(l.size)} MB exceeds the 15 MB limit`);continue}if(c+l.size>Px){r("warn",`attachment size budget reached - skipping "${l.filename}" and the rest`);break}try{let d=await t.downloadAttachment(l.contentUrl),p=Em(l.filename,i);oi.default.writeFileSync(or.default.join(s,p),d),c+=d.length,a.push(`- ${Ca}/${p} (${l.mimeType||"unknown type"}, ${Nd(d.length)} KB)`),r("info",`Downloaded attachment "${l.filename}" (${Nd(d.length)} KB)`)}catch(d){r("warn",`could not download attachment "${l.filename}": ${d instanceof Error?d.message:d}`)}}return a.length?`
914
877
 
915
878
  Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository - never commit, copy, or edit them:
916
879
  ${a.join(`
917
880
  `)}
918
- Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(ar(n),"")}function ar(t){oi.default.rmSync(or.default.join(t,Ca),{recursive:!0,force:!0})}function Am(t,e,n){let r=or.default.join(t,Ca,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};oi.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],a=0,c=or.default.relative(t,r);for(let d of n){let p=Buffer.from(d.contentBase64,"base64");if(p.length>Mx||a+p.length>jx){i.push(`- (skipped "${d.name}" - over the upload size budget)`);continue}let f=Em(d.name,s);oi.default.writeFileSync(or.default.join(r,f),p),a+=p.length,i.push(`- ${c}/${f} (${Nd(p.length)} KB)`)}return{section:`
881
+ Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(ar(n),"")}function ar(t){oi.default.rmSync(or.default.join(t,Ca),{recursive:!0,force:!0})}function Am(t,e,n){let r=or.default.join(t,Ca,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};oi.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],a=0,c=or.default.relative(t,r);for(let d of n){let p=Buffer.from(d.contentBase64,"base64");if(p.length>Nx||a+p.length>Mx){i.push(`- (skipped "${d.name}" - over the upload size budget)`);continue}let f=Em(d.name,s);oi.default.writeFileSync(or.default.join(r,f),p),a+=p.length,i.push(`- ${c}/${f} (${Nd(p.length)} KB)`)}return{section:`
919
882
 
920
883
  The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository - never commit, copy, or edit them. If a ticket is created from this chat, these files are attached to it automatically, so reference them by filename instead of pasting their content:
921
884
  ${i.join(`
922
885
  `)}
923
- Read them with the Read tool; images can be viewed directly.`,dir:r}}var oi,or,Ca,Px,Nx,Im,Mx,jx,Nd,Ox,Md=X(()=>{"use strict";oi=E(require("node:fs"),1),or=E(require("node:path"),1),Ca=".ticketpilot-attachments",Px=15*1024*1024,Nx=50*1024*1024,Im=20;Mx=16*1024*1024,jx=32*1024*1024;Nd=t=>Math.max(1,Math.round(t/1024)),Ox=t=>Math.round(t/(1024*1024)*10)/10});function Dx(t){return t.length<=3e4?t:`${t.slice(0,3e4)}
886
+ Read them with the Read tool; images can be viewed directly.`,dir:r}}var oi,or,Ca,Cx,Px,Im,Nx,Mx,Nd,jx,Md=X(()=>{"use strict";oi=E(require("node:fs"),1),or=E(require("node:path"),1),Ca=".ticketpilot-attachments",Cx=15*1024*1024,Px=50*1024*1024,Im=20;Nx=16*1024*1024,Mx=32*1024*1024;Nd=t=>Math.max(1,Math.round(t/1024)),jx=t=>Math.round(t/(1024*1024)*10)/10});function zx(t){return t.length<=3e4?t:`${t.slice(0,3e4)}
924
887
 
925
888
  [description truncated by Allwright at 30,000 characters - read the rest on the ticket]`}function Od(){return new We({baseUrl:"",email:"",apiToken:""},!1)}function $m(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
926
889
  `);for(let s of r.content??[])n(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
@@ -929,22 +892,22 @@ Read them with the Read tool; images can be viewed directly.`,dir:r}}var oi,or,C
929
892
  `).trim()}function Pa(t){let e=t.replace(/\r\n/g,`
930
893
  `).split(`
931
894
  `),n=[],r=0,s=i=>{let a=[],c=/(\*\*[^*]+\*\*|`[^`]+`)/g,l=0,d;for(;(d=c.exec(i))!==null;){d.index>l&&a.push({type:"text",text:i.slice(l,d.index)});let p=d[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=d.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(`
932
- `)||" "}]});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 g=e[r].match(/^\s*[-*]\s+(.*)$/);if(!g)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(g[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let g=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!g)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(g[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 Cm,zx,$t,jd,Lx,We,no=X(()=>{"use strict";Cm="Posted automatically by Allwright",zx=["Posted automatically by TicketPilot"],$t=t=>t.includes(Cm)||zx.some(e=>t.includes(e));jd=200,Lx="no Jira credentials on this runner - add them with `allwright jira set-default`";We=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(Lx)}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"],...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)});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`),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:$m(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=Dx($m(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}}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-jd),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,jd);){let a=await this.fetchCommentPage(e,s+i.length);if(!a.comments.length)break;i.push(...a.comments)}return i.slice(-jd)}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=[]){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:Pa(r),...i?{parent:{key:i}}:{},...a.length?{components:a.map(l=>({name:l}))}:{}}})).key}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:Pa(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:Pa(n)})}async addComment(e,n){let r=`${n}
895
+ `)||" "}]});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 g=e[r].match(/^\s*[-*]\s+(.*)$/);if(!g)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(g[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let g=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!g)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(g[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 Cm,Ox,$t,jd,Dx,We,no=X(()=>{"use strict";Cm="Posted automatically by Allwright",Ox=["Posted automatically by TicketPilot"],$t=t=>t.includes(Cm)||Ox.some(e=>t.includes(e));jd=200,Dx="no Jira credentials on this runner - add them with `allwright jira set-default`";We=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(Dx)}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"],...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)});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`),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:$m(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=zx($m(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}}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-jd),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,jd);){let a=await this.fetchCommentPage(e,s+i.length);if(!a.comments.length)break;i.push(...a.comments)}return i.slice(-jd)}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=[]){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:Pa(r),...i?{parent:{key:i}}:{},...a.length?{components:a.map(l=>({name:l}))}:{}}})).key}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:Pa(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:Pa(n)})}async addComment(e,n){let r=`${n}
933
896
 
934
897
  ---
935
- _${Cm} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Pa(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 Kx(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=zd.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let a of i){if(a.name.startsWith(".")||Hx.has(a.name))continue;let c=Na.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 Ma(t){let e=[],n=0;for(let r of Kx(t)){if(n>=Ux||e.join(`
936
- `).length>Bx)break;let s=Na.default.relative(t,r);if(Na.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=zd.default.readFileSync(r,"utf8")}catch{continue}let a=i.split(`
937
- `);if(a.length<qx)continue;let c=[],l=!1;for(let d=0;d<a.length;d++){let p=a[d];if(/^\s*(```|~~~)/.test(p)){l=!l;continue}if(!l&&/^#{1,3}\s+\S/.test(p)&&(c.push(` L${d+1} ${p.trim().slice(0,110)}`),c.length>=Fx)){c.push(" \u2026 more headings follow in the file");break}}c.length<2||(e.push(`${s} (${a.length} lines)`),e.push(...c),n++)}return e.length?`
898
+ _${Cm} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Pa(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 Hx(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=zd.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let a of i){if(a.name.startsWith(".")||Bx.has(a.name))continue;let c=Na.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 Ma(t){let e=[],n=0;for(let r of Hx(t)){if(n>=Lx||e.join(`
899
+ `).length>Fx)break;let s=Na.default.relative(t,r);if(Na.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=zd.default.readFileSync(r,"utf8")}catch{continue}let a=i.split(`
900
+ `);if(a.length<Ux)continue;let c=[],l=!1;for(let d=0;d<a.length;d++){let p=a[d];if(/^\s*(```|~~~)/.test(p)){l=!l;continue}if(!l&&/^#{1,3}\s+\S/.test(p)&&(c.push(` L${d+1} ${p.trim().slice(0,110)}`),c.length>=qx)){c.push(" \u2026 more headings follow in the file");break}}c.length<2||(e.push(`${s} (${a.length} lines)`),e.push(...c),n++)}return e.length?`
938
901
 
939
902
  DOCUMENT INDEX - the repo's larger Markdown documents, with 1-based line numbers (generated; the files themselves are the truth):
940
903
  ${e.join(`
941
904
  `)}
942
- Read a document's relevant SECTION with Read offset/limit using these line numbers - read one end-to-end only when the task genuinely needs all of it.`:""}var zd,Na,Ux,qx,Fx,Bx,Hx,Pm=X(()=>{"use strict";zd=E(require("node:fs"),1),Na=E(require("node:path"),1),Ux=24,qx=120,Fx=30,Bx=6e3,Hx=new Set(["node_modules","dist","build","out","coverage","vendor","target"])});function Om(){return Nm.default.join(te(),"repo-briefs.json")}function Ld(){try{return Gx.parse(JSON.parse(ro.default.readFileSync(Om(),"utf8")))}catch{return{}}}function Vx(t){ro.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Om();ro.default.writeFileSync(e+".tmp",JSON.stringify(t,null,2)+`
943
- `,{mode:384}),ro.default.renameSync(e+".tmp",e)}function Yx(t){return new Promise(e=>{(0,Mm.execFile)("git",["-C",t,"rev-parse","HEAD"],{timeout:1e4},(n,r)=>e(n?"":r.trim()))})}function so(t){let e=Ld()[t];return e?.brief?`
905
+ Read a document's relevant SECTION with Read offset/limit using these line numbers - read one end-to-end only when the task genuinely needs all of it.`:""}var zd,Na,Lx,Ux,qx,Fx,Bx,Pm=X(()=>{"use strict";zd=E(require("node:fs"),1),Na=E(require("node:path"),1),Lx=24,Ux=120,qx=30,Fx=6e3,Bx=new Set(["node_modules","dist","build","out","coverage","vendor","target"])});function Om(){return Nm.default.join(te(),"repo-briefs.json")}function Ld(){try{return Wx.parse(JSON.parse(ro.default.readFileSync(Om(),"utf8")))}catch{return{}}}function Zx(t){ro.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Om();ro.default.writeFileSync(e+".tmp",JSON.stringify(t,null,2)+`
906
+ `,{mode:384}),ro.default.renameSync(e+".tmp",e)}function Vx(t){return new Promise(e=>{(0,Mm.execFile)("git",["-C",t,"rev-parse","HEAD"],{timeout:1e4},(n,r)=>e(n?"":r.trim()))})}function so(t){let e=Ld()[t];return e?.brief?`
944
907
 
945
908
  REPO ORIENTATION (machine-generated from commit ${e.headCommit.slice(0,10)} - treat as hints and verify in code; where this disagrees with the repo or its CLAUDE.md, they win):
946
909
  ${e.brief}
947
- `:""}function ja(t,e){let n=t.project.repoName;Dd.has(n)||(Dd.add(n),(async()=>{try{let r=await Yx(t.repoPath);if(!r||Ld()[n]?.headCommit===r)return;let s=$e(e,t.project,"chat");if("error"in s)return;let i=await s.adapter.run({repoPath:t.repoPath,prompt:Jx,timeoutSeconds:240,bin:s.bin,mode:"read_only",maxTurns:20,model:s.adapter.fastModel,sessionId:(0,jm.randomUUID)(),onLog:()=>{}});be({surface:"repo_brief",projectId:t.project.id,agentId:s.adapter.id,refKind:"none",refLabel:n,...we(i)});let a=i.ok?i.resultText.trim().slice(0,Zx):"";if(!a)return;let c=Ld();c[n]={brief:a,headCommit:r,generatedAt:new Date().toISOString()},Vx(c),b.info(`repo brief refreshed for ${n} (${a.length} chars, HEAD ${r.slice(0,10)})`)}catch(r){b.warn(`repo brief refresh failed for ${n}: ${r instanceof Error?r.message:r}`)}finally{Dd.delete(n)}})())}var ro,Nm,Mm,jm,Wx,Gx,Zx,Jx,Dd,Ud=X(()=>{"use strict";ro=E(require("node:fs"),1),Nm=E(require("node:path"),1),Mm=require("node:child_process"),jm=require("node:crypto");_t();Ae();Et();nn();lt();Wx=S.object({brief:S.string(),headCommit:S.string(),generatedAt:S.string()}),Gx=S.record(Wx),Zx=4e3;Jx=`Write an orientation brief for an AI agent that will work in this repository cold. Under 450 words, plain statements, these headings:
910
+ `:""}function ja(t,e){let n=t.project.repoName;Dd.has(n)||(Dd.add(n),(async()=>{try{let r=await Vx(t.repoPath);if(!r||Ld()[n]?.headCommit===r)return;let s=$e(e,t.project,"chat");if("error"in s)return;let i=await s.adapter.run({repoPath:t.repoPath,prompt:Yx,timeoutSeconds:240,bin:s.bin,mode:"read_only",maxTurns:20,model:s.adapter.fastModel,sessionId:(0,jm.randomUUID)(),onLog:()=>{}});be({surface:"repo_brief",projectId:t.project.id,agentId:s.adapter.id,refKind:"none",refLabel:n,...we(i)});let a=i.ok?i.resultText.trim().slice(0,Gx):"";if(!a)return;let c=Ld();c[n]={brief:a,headCommit:r,generatedAt:new Date().toISOString()},Zx(c),b.info(`repo brief refreshed for ${n} (${a.length} chars, HEAD ${r.slice(0,10)})`)}catch(r){b.warn(`repo brief refresh failed for ${n}: ${r instanceof Error?r.message:r}`)}finally{Dd.delete(n)}})())}var ro,Nm,Mm,jm,Kx,Wx,Gx,Yx,Dd,Ud=X(()=>{"use strict";ro=E(require("node:fs"),1),Nm=E(require("node:path"),1),Mm=require("node:child_process"),jm=require("node:crypto");_t();Ae();Et();nn();lt();Kx=S.object({brief:S.string(),headCommit:S.string(),generatedAt:S.string()}),Wx=S.record(Kx),Gx=4e3;Yx=`Write an orientation brief for an AI agent that will work in this repository cold. Under 450 words, plain statements, these headings:
948
911
  What this is: one or two lines.
949
912
  Layout: the directories that matter and what lives in each.
950
913
  Key files: the files most tasks touch or must not miss.
@@ -953,7 +916,7 @@ Gotchas: non-obvious facts that would waste an agent's time to rediscover.
953
916
  Do NOT repeat what CLAUDE.md already says - the agent reads that file itself; add what it lacks. Never include secrets, tokens or credential values. No preamble, no closing offer.`,Dd=new Set});function Lm(){try{return JSON.parse(io.default.readFileSync(Dm(),"utf8"))}catch{return{}}}function Um(t){io.default.mkdirSync(te(),{recursive:!0,mode:448}),io.default.writeFileSync(Dm(),JSON.stringify(t,null,2),{mode:384})}function Fm(t,e,n){let r=Lm();r[qm(t,e)]={...n,at:new Date().toISOString()},Um(r)}function Bm(t,e,n){let r=Lm(),s=qm(t,e),i=r[s];return!i||(delete r[s],Um(r),i.branch!==n)||!io.default.existsSync(i.worktreePath)?null:i}var io,zm,qd,Dm,qm,Hm=X(()=>{"use strict";io=E(require("node:fs"),1),zm=E(require("node:path"),1);Ae();qd=2,Dm=()=>zm.default.join(te(),"timeout-sessions.json");qm=(t,e)=>`${t}:${e}`});function Km(t){let e=/##\s*Go-live draft\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,3500):null}function Wm(t){let e=`${t.exitCode===0?"PASS":"FAIL"} ${t.command} (exit ${t.exitCode})`;if(t.exitCode!==0)return`${e}
954
917
  ${t.tail.slice(-1500)}`;let n=t.tail.split(`
955
918
  `).map(r=>r.trim()).filter(Boolean).pop();return n?`${e}
956
- ${n.slice(0,200)}`:e}function tT(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
919
+ ${n.slice(0,200)}`:e}function eT(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
957
920
  ${n.tail.slice(-2e3)}`).join(`
958
921
 
959
922
  `);return`After you finished, the runner executed this repository's documented TEST.md commands (you cannot run them yourself - you have no shell). ${t.length} failed:
@@ -965,7 +928,7 @@ Fix what these failures point at, with the smallest change that makes them pass.
965
928
  - If a failure is clearly pre-existing on the base branch and unrelated to your change, leave the code alone and say so in one sentence.
966
929
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
967
930
  - The runner re-runs every documented command after you finish, so a fix that breaks a previously passing command will be caught.
968
- End with one short paragraph stating exactly what you changed, or why you changed nothing. Then repeat your "## PR summary" section, updated if your fix changed what a reviewer sees.`}function nT(t,e=[]){try{let{packs:n}=ti("implement",t,e),r="",s=n.map(i=>`### ${i.name}
931
+ End with one short paragraph stating exactly what you changed, or why you changed nothing. Then repeat your "## PR summary" section, updated if your fix changed what a reviewer sees.`}function tT(t,e=[]){try{let{packs:n}=ti("implement",t,e),r="",s=n.map(i=>`### ${i.name}
969
932
  ${i.content}`).join(`
970
933
 
971
934
  `).trim();return s&&(r+=`
@@ -973,10 +936,10 @@ ${i.content}`).join(`
973
936
  This repository has working rules taught to Allwright - follow them:
974
937
  `+s.slice(0,4e3)),r}catch{return""}}function Hd(t){return Oa.default.existsSync(za.default.join(t,"DESIGN.md"))?`
975
938
 
976
- This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}function Jm(t,e,n){let r=tt(t),s=r?.capabilities.readOnlyJail&&r.id!=="kimi"?"read-only tools, path-jailed to the repo":"read-only by instruction - this agent enforces nothing itself";return`Starting ${r?.displayName??t} in ${e} - ${s}, timeout ${n}s`}async function co(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let a=await t.run(e),c=0,l="",d=r?rT:Gm,p=!1;for(;!a.ok&&a.turnLimitHit&&!a.cancelled&&t.capabilities.sessionResume;){if(e.maxCostUsd&&a.costUsd>=e.maxCostUsd){l=`the run's cost cap ($${e.maxCostUsd.toFixed(2)}) is spent ($${a.costUsd.toFixed(2)} so far)`,p=!0;break}if(c>=d){l=`resume cap (${d}) reached`;break}if(r&&c>=Gm){let g=await r().catch(()=>""),v=g!==""&&g!==i;if(i=g,!v){l="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Zm*1e3){l=`wall-clock budget (${Zm}x the rule's timeout) exhausted`;break}}c++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${c}, cap ${d})`);let f=await t.run({...e,prompt:oT,resume:!0});f.costUsd+=a.costUsd,f.inputTokens+=a.inputTokens,f.outputTokens+=a.outputTokens,f.cacheReadTokens=(f.cacheReadTokens??0)+(a.cacheReadTokens??0),a=f}return!a.ok&&a.turnLimitHit&&t.capabilities.sessionResume&&(p&&(a.costCapped=!0),a.error=p?`stopped by the rule's cost cap: $${a.costUsd.toFixed(2)} spent of the $${(e.maxCostUsd??0).toFixed(2)} allowed, with the work unfinished after ${c} resume(s). This is the circuit breaker doing its job - split the ticket into smaller ones, or raise the rule's max cost if the scope really warrants it.`:`${a.error??"hit the turn limit"} - even after ${c} automatic same-session resume(s)${l?` (stopped: ${l})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),a}function Xm(t){let e=oo.get(t);return e?(e.abort(),!0):!1}function Qm(t){let e=new AbortController;return oo.set(t,e),e}function eg(t){oo.delete(t)}async function li(t,e,n,r,s){let i=new AbortController;oo.set(t,i);try{return await co(e,{...n,signal:i.signal},r,s)}finally{oo.delete(t)}}function as(t,e,n=0){let r=n;return{emit:(c,l)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:c,message:l}),c!=="agent"&&b.info(`[run ${t}] ${l}`)},setStatus:(c,l={})=>{e.send({type:"run.status",runId:t,status:c,...l})},sendUsage:c=>{e.send({type:"run.usage",runId:t,inputTokens:Math.round(c.inputTokens),outputTokens:Math.round(c.outputTokens),cacheReadTokens:c.cacheReadTokens===void 0?void 0:Math.round(c.cacheReadTokens),costUsd:c.costUsd,turns:c.turns})},nextSeq:()=>r}}async function lo(t){return ja({project:t.project,repoPath:t.repoPath},t.cfg),t.rule.action.type==="implement"?lT(t):t.rule.action.type==="respond"?cT(t):aT(t)}async function aT(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=as(t.runId,t.transport),{trigger:i}=t.rule,a=t.rule.action;if(a.type!=="plan_only")return;let c=Jn(a.agent,a.type);if(c){e("error",c),await ci(t,c),n("failed",{error:c});return}let l=(0,Da.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let d=await t.jira.getIssue(t.issueKey),p=Rn(a.promptTemplate,{issueKey:d.key,summary:d.summary,description:d.description||"(no description)",comments:cs(d.comments)})+await ai(t.jira,d.attachments,t.repoPath,e)+Hd(t.repoPath)+Ma(t.repoPath)+so(t.project.repoName)+rr("implement",t.repoPath,{issueKey:d.key,summary:d.summary,description:d.description,ruleName:t.rule.name})+cr.FOCUSED_READING_PROMPT+Le.NEEDS_INPUT_OPTIONS_PROMPT;e("info",Jm(a.agent,t.repoPath,a.timeoutSeconds));let f=await li(t.runId,tt(a.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:a.timeoutSeconds,bin:Be(t.cfg,a.agent),configDir:t.claudeConfigDir,mode:a.allowWeb?"read_only_web":"read_only",model:a.model||void 0,sessionId:l,onLog:(k,T)=>e(k,T),onUsage:r},e),g={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens??0,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await ci(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...g});return}let v=ho(f.resultText);if(v){await ao({kind:"plan",allowWeb:a.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:l,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},v,e,n,g);return}await tg({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:g,emit:e,setStatus:n})}catch(d){let p=d instanceof Error?d.message:String(d);e("error",`Run failed: ${p}`),await ci(t,p),n("failed",{error:p})}finally{ar(t.repoPath)}}async function Kd(t,e,n,r){let{emit:s,setStatus:i,sendUsage:a,nextSeq:c}=as(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let l=ug(e)+await ai(r.jiraFor(t.repoName??""),n,t.repoPath,s),d=await li(t.runId,tt(t.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:t.timeoutSeconds,bin:Be(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:t.allowWeb?"read_only_web":"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(g,v)=>s(g,v),onUsage:a},s),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,cacheReadTokens:d.cacheReadTokens??0,billingMode:d.billingMode,model:d.model};if(!d.ok||!d.resultText.trim()){let g=d.error??"Claude Code produced no output";s("error",`Run failed: ${g}`),await ln(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,g),an(t.runId),i(d.timedOut?"timed_out":"failed",{error:g,...d.cancelled?{errorKind:"guard"}:{},...p});return}let f=ho(d.resultText);if(f){if(t.rounds>=Ym){await hg(r.jiraFor(t.repoName??""),t,s,i,p);return}await ao({kind:"plan",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:c(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model},f,s,i,p);return}await tg({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:d.resultText,costFields:p,emit:s,setStatus:i}),an(t.runId)}catch(l){let d=l instanceof Error?l.message:String(l);s("error",`Run failed: ${d}`),await ln(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,d),an(t.runId),i("failed",{error:d})}finally{ar(t.repoPath)}}async function tg(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:a,emit:c,setStatus:l}=t;l("posting",a),c("info",`Posting plan to ${n} (${i.length} chars)`);let d=`
939
+ This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}function Jm(t,e,n){let r=tt(t),s=r?.capabilities.readOnlyJail&&r.id!=="kimi"?"read-only tools, path-jailed to the repo":"read-only by instruction - this agent enforces nothing itself";return`Starting ${r?.displayName??t} in ${e} - ${s}, timeout ${n}s`}async function co(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let a=await t.run(e),c=0,l="",d=r?nT:Gm,p=!1;for(;!a.ok&&a.turnLimitHit&&!a.cancelled&&t.capabilities.sessionResume;){if(e.maxCostUsd&&a.costUsd>=e.maxCostUsd){l=`the run's cost cap ($${e.maxCostUsd.toFixed(2)}) is spent ($${a.costUsd.toFixed(2)} so far)`,p=!0;break}if(c>=d){l=`resume cap (${d}) reached`;break}if(r&&c>=Gm){let g=await r().catch(()=>""),v=g!==""&&g!==i;if(i=g,!v){l="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Zm*1e3){l=`wall-clock budget (${Zm}x the rule's timeout) exhausted`;break}}c++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${c}, cap ${d})`);let f=await t.run({...e,prompt:iT,resume:!0});f.costUsd+=a.costUsd,f.inputTokens+=a.inputTokens,f.outputTokens+=a.outputTokens,f.cacheReadTokens=(f.cacheReadTokens??0)+(a.cacheReadTokens??0),a=f}return!a.ok&&a.turnLimitHit&&t.capabilities.sessionResume&&(p&&(a.costCapped=!0),a.error=p?`stopped by the rule's cost cap: $${a.costUsd.toFixed(2)} spent of the $${(e.maxCostUsd??0).toFixed(2)} allowed, with the work unfinished after ${c} resume(s). This is the circuit breaker doing its job - split the ticket into smaller ones, or raise the rule's max cost if the scope really warrants it.`:`${a.error??"hit the turn limit"} - even after ${c} automatic same-session resume(s)${l?` (stopped: ${l})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),a}function Xm(t){let e=oo.get(t);return e?(e.abort(),!0):!1}function Qm(t){let e=new AbortController;return oo.set(t,e),e}function eg(t){oo.delete(t)}async function li(t,e,n,r,s){let i=new AbortController;oo.set(t,i);try{return await co(e,{...n,signal:i.signal},r,s)}finally{oo.delete(t)}}function as(t,e,n=0){let r=n;return{emit:(c,l)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:c,message:l}),c!=="agent"&&b.info(`[run ${t}] ${l}`)},setStatus:(c,l={})=>{e.send({type:"run.status",runId:t,status:c,...l})},sendUsage:c=>{e.send({type:"run.usage",runId:t,inputTokens:Math.round(c.inputTokens),outputTokens:Math.round(c.outputTokens),cacheReadTokens:c.cacheReadTokens===void 0?void 0:Math.round(c.cacheReadTokens),costUsd:c.costUsd,turns:c.turns})},nextSeq:()=>r}}async function lo(t){return ja({project:t.project,repoPath:t.repoPath},t.cfg),t.rule.action.type==="implement"?cT(t):t.rule.action.type==="respond"?aT(t):oT(t)}async function oT(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=as(t.runId,t.transport),{trigger:i}=t.rule,a=t.rule.action;if(a.type!=="plan_only")return;let c=Jn(a.agent,a.type);if(c){e("error",c),await ci(t,c),n("failed",{error:c});return}let l=(0,Da.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let d=await t.jira.getIssue(t.issueKey),p=Rn(a.promptTemplate,{issueKey:d.key,summary:d.summary,description:d.description||"(no description)",comments:cs(d.comments)})+await ai(t.jira,d.attachments,t.repoPath,e)+Hd(t.repoPath)+Ma(t.repoPath)+so(t.project.repoName)+rr("implement",t.repoPath,{issueKey:d.key,summary:d.summary,description:d.description,ruleName:t.rule.name})+cr.FOCUSED_READING_PROMPT+Le.NEEDS_INPUT_OPTIONS_PROMPT;e("info",Jm(a.agent,t.repoPath,a.timeoutSeconds));let f=await li(t.runId,tt(a.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:a.timeoutSeconds,bin:Be(t.cfg,a.agent),configDir:t.claudeConfigDir,mode:a.allowWeb?"read_only_web":"read_only",model:a.model||void 0,sessionId:l,onLog:(k,T)=>e(k,T),onUsage:r},e),g={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens??0,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await ci(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...g});return}let v=ho(f.resultText);if(v){await ao({kind:"plan",allowWeb:a.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:l,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},v,e,n,g);return}await tg({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:g,emit:e,setStatus:n})}catch(d){let p=d instanceof Error?d.message:String(d);e("error",`Run failed: ${p}`),await ci(t,p),n("failed",{error:p})}finally{ar(t.repoPath)}}async function Kd(t,e,n,r){let{emit:s,setStatus:i,sendUsage:a,nextSeq:c}=as(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let l=ug(e)+await ai(r.jiraFor(t.repoName??""),n,t.repoPath,s),d=await li(t.runId,tt(t.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:t.timeoutSeconds,bin:Be(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:t.allowWeb?"read_only_web":"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(g,v)=>s(g,v),onUsage:a},s),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,cacheReadTokens:d.cacheReadTokens??0,billingMode:d.billingMode,model:d.model};if(!d.ok||!d.resultText.trim()){let g=d.error??"Claude Code produced no output";s("error",`Run failed: ${g}`),await ln(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,g),an(t.runId),i(d.timedOut?"timed_out":"failed",{error:g,...d.cancelled?{errorKind:"guard"}:{},...p});return}let f=ho(d.resultText);if(f){if(t.rounds>=Ym){await hg(r.jiraFor(t.repoName??""),t,s,i,p);return}await ao({kind:"plan",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:c(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model},f,s,i,p);return}await tg({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:d.resultText,costFields:p,emit:s,setStatus:i}),an(t.runId)}catch(l){let d=l instanceof Error?l.message:String(l);s("error",`Run failed: ${d}`),await ln(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,d),an(t.runId),i("failed",{error:d})}finally{ar(t.repoPath)}}async function tg(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:a,emit:c,setStatus:l}=t;l("posting",a),c("info",`Posting plan to ${n} (${i.length} chars)`);let d=`
977
940
 
978
941
  ---
979
- _Allwright plan-only run \`${e}\` \xB7 cost $${a.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+d),await s.editLabels(n,{add:[r],remove:[Le.NEEDS_INPUT_LABEL]}),c("info",`Labeled ${n} with "${r}"`),l("succeeded",{...a,resultSummary:ls(i)}),c("info",`Run succeeded \xB7 $${a.costUsd.toFixed(4)}`)}async function cT(t){let{emit:e,setStatus:n,sendUsage:r}=as(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Jn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
942
+ _Allwright plan-only run \`${e}\` \xB7 cost $${a.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+d),await s.editLabels(n,{add:[r],remove:[Le.NEEDS_INPUT_LABEL]}),c("info",`Labeled ${n} with "${r}"`),l("succeeded",{...a,resultSummary:ls(i)}),c("info",`Run succeeded \xB7 $${a.costUsd.toFixed(4)}`)}async function aT(t){let{emit:e,setStatus:n,sendUsage:r}=as(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Jn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
980
943
 
981
944
  ${i}`).catch(()=>{}),n("failed",{error:i});return}try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", respond`+(t.question?`, question from ${t.question.author}`:"")+")"),e("info",`Fetching ${t.issueKey} from Jira`);let a=await t.jira.getIssue(t.issueKey),c=Rn(s.promptTemplate,{issueKey:a.key,summary:a.summary,description:a.description||"(no description)",comments:cs(a.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await ai(t.jira,a.attachments,t.repoPath,e)+Hd(t.repoPath)+Ma(t.repoPath)+cr.FOCUSED_READING_PROMPT;e("info",Jm(s.agent,t.repoPath,s.timeoutSeconds));let l=await li(t.runId,tt(s.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:s.timeoutSeconds,bin:Be(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Da.randomUUID)(),onLog:(p,f)=>e(p,f),onUsage:r},e),d={costUsd:l.costUsd,inputTokens:l.inputTokens,outputTokens:l.outputTokens,cacheReadTokens:l.cacheReadTokens??0,billingMode:l.billingMode,model:l.model};if(!l.ok||!l.resultText.trim()){let p=l.error??"Claude Code produced no answer";e("error",`Run failed: ${p}`),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
982
945
 
@@ -984,19 +947,19 @@ Error: ${p.slice(0,800)}
984
947
 
985
948
  Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>b.error(`could not post answer failure to ${t.issueKey}: ${f}`)),n(l.timedOut?"timed_out":"failed",{error:p,...l.cancelled?{errorKind:"guard"}:{},...d});return}n("posting",d),e("info",`Posting answer to ${t.issueKey} (${l.resultText.length} chars)`),await t.jira.addComment(t.issueKey,l.resultText),n("succeeded",{...d,resultSummary:ls(l.resultText)}),e("info",`Run succeeded \xB7 $${l.costUsd.toFixed(4)}`)}catch(a){let c=a instanceof Error?a.message:String(a);e("error",`Run failed: ${c}`),n("failed",{error:c})}finally{ar(t.repoPath)}}async function ng(t,e,n,r){let s=`${e}-wip`;try{return ar(t),await ts(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Hl(t,s),r("info",`Partial work preserved on branch "${s}"`),s}catch(i){return r("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function rg(t){return`
986
949
 
987
- Partial work from this run is saved on branch \`${t}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function lT(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=as(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,a=t.rule.action;if(a.type!=="implement")return;let c=Jn(a.agent,a.type);if(c){e("error",c),await ci(t,c),n("failed",{error:c});return}let l=Rn(a.branchTemplate,{issueKey:t.issueKey}),d=t.chain?null:Bm(t.project.id,t.issueKey,l),p=t.chain?.worktreePath??d?.worktreePath??za.default.join(En(),t.runId),f=t.chain?.sessionId??d?.sessionId??(0,Da.randomUUID)(),g=!1,v=!1,k=!1;try{if(!ga(_e()??t.cfg,t.project.repoName,t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(l===a.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${l}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),a.jiraTransitionOnStart)try{await t.jira.transitionByName(t.issueKey,a.jiraTransitionOnStart)?e("info",`Jira transition "${a.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${a.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(m){e("warn",`Jira start transition failed: ${m instanceof Error?m.message:m} - continuing anyway`)}let T=await rs(t.repoPath);if(e("info",`Repo origin: ${T}`),!Bt(T))throw new Error(`origin "${T}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let _=await t.jira.getIssue(t.issueKey);if(/^epic$/i.test(_.issueType)&&!t.preflightAnswer&&!d&&!t.chain){k=!0;let m="```";await ao({kind:"implement",allowWeb:a.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,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:_.summary,preflight:"epic-confirm",ruleId:t.rule.id},`This ticket is an **Epic** - usually a container whose child tickets hold the actual work. Implementing the container itself burns a full agent run on a description that was rarely written as a spec, and can contradict the children.
950
+ Partial work from this run is saved on branch \`${t}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function cT(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=as(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,a=t.rule.action;if(a.type!=="implement")return;let c=Jn(a.agent,a.type);if(c){e("error",c),await ci(t,c),n("failed",{error:c});return}let l=Rn(a.branchTemplate,{issueKey:t.issueKey}),d=t.chain?null:Bm(t.project.id,t.issueKey,l),p=t.chain?.worktreePath??d?.worktreePath??za.default.join(En(),t.runId),f=t.chain?.sessionId??d?.sessionId??(0,Da.randomUUID)(),g=!1,v=!1,k=!1;try{if(!ga(_e()??t.cfg,t.project.repoName,t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(l===a.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${l}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),a.jiraTransitionOnStart)try{await t.jira.transitionByName(t.issueKey,a.jiraTransitionOnStart)?e("info",`Jira transition "${a.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${a.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(m){e("warn",`Jira start transition failed: ${m instanceof Error?m.message:m} - continuing anyway`)}let T=await rs(t.repoPath);if(e("info",`Repo origin: ${T}`),!Bt(T))throw new Error(`origin "${T}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let _=await t.jira.getIssue(t.issueKey);if(/^epic$/i.test(_.issueType)&&!t.preflightAnswer&&!d&&!t.chain){k=!0;let m="```";await ao({kind:"implement",allowWeb:a.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,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:_.summary,preflight:"epic-confirm",ruleId:t.rule.id},`This ticket is an **Epic** - usually a container whose child tickets hold the actual work. Implementing the container itself burns a full agent run on a description that was rarely written as a spec, and can contradict the children.
988
951
 
989
952
  Should this run implement the epic ticket itself?
990
953
 
991
954
  ${m}${Le.NEEDS_INPUT_ASK_FENCE}
992
- {"options": ["${sT}", "${iT}"]}
993
- ${m}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let $=t.continueBranch;$&&!d&&await Gl(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}.`),$=!1);let D=$?l:a.baseBranch;d?e("info",`Resuming the session that timed out on this ticket (timeout resume ${d.resumes}/${qd}) - same worktree, uncommitted work intact, repo context cached`):(e("info",$?`Continuing branch "${l}" from origin/${l} (autopilot batch)`:`Preparing worktree on branch "${l}" from origin/${a.baseBranch}`),await er(t.repoPath,D),t.chain&&$||await Zl(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 ed(p,l,$?`origin/${l}`:`origin/${a.baseBranch}`)):await Vl(t.repoPath,p,l,D)),g=!0;let z=Rn(a.promptTemplate,{issueKey:_.key,summary:_.summary,description:_.description||"(no description)",comments:cs(_.comments)});!d&&!pT(`${_.summary}
994
- ${_.description??""}`)&&e("info","This ticket names no files or symbols - the agent has to discover them, which costs extra reads. Tickets that name paths run cheaper.");let A=d?null:await Wl(p,a.baseBranch,_.key).catch(()=>null),P=[],w=(m,y)=>(y&&P.push({part:m,chars:y.length}),y),j=w("ticket: rule template + summary (rendered)",z)+w("attachments listing",await ai(t.jira,_.attachments,p,e))+w("design guideline pointer",Hd(p))+w("knowledge: rules",nT(t.repoPath,t.project.packs??[]))+w("memory: retrieved history",rr("implement",t.repoPath,{issueKey:_.key,summary:_.summary,description:_.description,ruleName:t.rule.name}))+w("doc index",Ma(p))+w("repo brief (machine-generated)",t.chain?"":so(t.project.repoName))+w("revision: previous delivery + what is new",A?hT(A,_.comments,$t):"")+w("appendix: focused reading",cr.FOCUSED_READING_PROMPT)+w("appendix: protected paths",Xx)+w("appendix: needs-input options",Le.NEEDS_INPUT_OPTIONS_PROMPT)+w("appendix: PR summary",Qx)+w("appendix: go-live",t.project.goLiveIssueKey?eT:"")+w("appendix: write tests",a.writeTests?cr.WRITE_TESTS_PROMPT:"")+w("appendix: update memory",a.updateMemory?Le.MEMORY_UPDATE_PROMPT:"")+w("epic confirmation answer",t.preflightAnswer?`
955
+ {"options": ["${rT}", "${sT}"]}
956
+ ${m}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let $=t.continueBranch;$&&!d&&await Gl(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}.`),$=!1);let D=$?l:a.baseBranch;d?e("info",`Resuming the session that timed out on this ticket (timeout resume ${d.resumes}/${qd}) - same worktree, uncommitted work intact, repo context cached`):(e("info",$?`Continuing branch "${l}" from origin/${l} (autopilot batch)`:`Preparing worktree on branch "${l}" from origin/${a.baseBranch}`),await er(t.repoPath,D),t.chain&&$||await Zl(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 ed(p,l,$?`origin/${l}`:`origin/${a.baseBranch}`)):await Vl(t.repoPath,p,l,D)),g=!0;let z=Rn(a.promptTemplate,{issueKey:_.key,summary:_.summary,description:_.description||"(no description)",comments:cs(_.comments)});!d&&!hT(`${_.summary}
957
+ ${_.description??""}`)&&e("info","This ticket names no files or symbols - the agent has to discover them, which costs extra reads. Tickets that name paths run cheaper.");let A=d?null:await Wl(p,a.baseBranch,_.key).catch(()=>null),P=[],w=(m,y)=>(y&&P.push({part:m,chars:y.length}),y),j=w("ticket: rule template + summary (rendered)",z)+w("attachments listing",await ai(t.jira,_.attachments,p,e))+w("design guideline pointer",Hd(p))+w("knowledge: rules",tT(t.repoPath,t.project.packs??[]))+w("memory: retrieved history",rr("implement",t.repoPath,{issueKey:_.key,summary:_.summary,description:_.description,ruleName:t.rule.name}))+w("doc index",Ma(p))+w("repo brief (machine-generated)",t.chain?"":so(t.project.repoName))+w("revision: previous delivery + what is new",A?uT(A,_.comments,$t):"")+w("appendix: focused reading",cr.FOCUSED_READING_PROMPT)+w("appendix: protected paths",Jx)+w("appendix: needs-input options",Le.NEEDS_INPUT_OPTIONS_PROMPT)+w("appendix: PR summary",Xx)+w("appendix: go-live",t.project.goLiveIssueKey?Qx:"")+w("appendix: write tests",a.writeTests?cr.WRITE_TESTS_PROMPT:"")+w("appendix: update memory",a.updateMemory?Le.MEMORY_UPDATE_PROMPT:"")+w("epic confirmation answer",t.preflightAnswer?`
995
958
 
996
959
  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:
997
960
  ${t.preflightAnswer.slice(0,4e3)}`:"");_.description&&P.push({part:"\u21B3 of which ticket description",chars:_.description.length});let W=cs(_.comments).length;W&&P.push({part:"\u21B3 of which comment history",chars:W}),t.transport.sendRunContext({runId:t.runId,pieces:d?[{part:"continuation prompt (session resumed - original context already cached)",chars:Fd.length}]:P,totalChars:d?Fd.length:j.length,sessionMode:d?"timeout-resume":t.chain?"chained":t.preflightAnswer?"preflight-resume":"fresh"}),e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${a.timeoutSeconds}s`);let L=await li(t.runId,tt(a.agent),{repoPath:p,prompt:d?Fd:j,timeoutSeconds:a.timeoutSeconds,bin:Be(t.cfg,a.agent),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||!!d,onLog:(m,y)=>e(m,y),onUsage:r},e,()=>ha(p)),V={costUsd:L.costUsd,inputTokens:L.inputTokens,outputTokens:L.outputTokens,cacheReadTokens:L.cacheReadTokens??0,billingMode:L.billingMode,model:L.model};if(!L.ok){let m=L.error??"Claude Code failed";e("error",`Run failed: ${m}`);let y=m,x=(L.timedOut||L.costCapped)&&!L.cancelled&&tt(a.agent)?.capabilities.sessionResume&&(d?.resumes??0)<qd;if(L.turnLimitHit&&!x){let C=await ng(p,l,t.runId,e);C&&(y+=rg(C))}x&&(Fm(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:l,resumes:(d?.resumes??0)+1}),v=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),y+=" - the work done so far is preserved: trigger this ticket again and the run RESUMES the same session where it stopped instead of starting over"),It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:m.slice(0,500)}),await ci(t,y),n(L.timedOut?"timed_out":"failed",{error:y,...L.cancelled||L.costCapped?{errorKind:"guard"}:{},...V});return}let u=ho(L.resultText);if(u){k=!0,await ao({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:_.summary},u,e,n,V);return}ar(p),await sg({runId:t.runId,issueKey:t.issueKey,issueSummary:_.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:L.resultText,costFields:V,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 _=T instanceof Error?T.message:String(T);e("error",`Run failed: ${_}`),It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:_.slice(0,500)}),await ci(t,_),n("failed",{error:_})}finally{g&&!k&&!t.keepWorktree&&!v&&await rn(t.repoPath,p).catch(()=>{})}}async function Wd(t,e,n,r){let{emit:s,setStatus:i,sendUsage:a,nextSeq:c}=as(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 lo({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,d=!1;if(!Oa.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(!ga(_e()??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=ug(e)+await ai(r.jiraFor(t.repoName??""),n,l,s),f=await li(t.runId,tt(t.agent),{repoPath:l,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Be(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:(k,T)=>s(k,T),onUsage:a},s,()=>ha(l)),g={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens??0,billingMode:f.billingMode,model:f.model};if(!f.ok){let k=f.error??"Claude Code failed";s("error",`Run failed: ${k}`);let T=k;if(f.turnLimitHit&&t.branch){let _=await ng(l,t.branch,t.runId,s);_&&(T+=rg(_))}await ln(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,T),an(t.runId),i(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...g});return}let v=ho(f.resultText);if(v){if(t.rounds>=Ym){await hg(r.jiraFor(t.repoName??""),t,s,i,g);return}d=!0,await ao({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},v,s,i,g);return}ar(l),await sg({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:g,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}),an(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await ln(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),an(t.runId),i("failed",{error:f})}finally{d||await rn(t.baseRepoPath??l,l).catch(()=>{})}}async function sg(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:a,baseBranch:c,jiraTransition:l,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:g,repoName:v,jira:k,cfg:T,actorEmail:_,runTests:$,mergeOnApprove:D,mergeMethod:z,autoMerge:A,resultText:P,costFields:w,emit:j,setStatus:W}=t,L=await Xs(s);L.deleted.length&&j("info",`Deleted ${L.deleted.length} file(s) listed in ${In}: `+L.deleted.slice(0,10).join(", ")+(L.deleted.length>10?", \u2026":""));for(let U of L.refused)j("warn",`${In} entry refused: ${U}`);j("info","Committing changes"),await ts(s,`${n}: ${r}
998
961
 
999
- Allwright run ${e}`);let V=await tr(s,c);if(!V.ok){let U=V.forbidden.length?`refusing to push: changes touch protected paths (${V.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 (${V.files} files, ${V.insertions+V.deletions} lines; limits ${Xn}/${Qn})`;j("error",U),await ln(k,n,e,g,U),W("failed",{error:U,errorKind:"guard",...w});return}j("info",`Diff: ${V.files} file(s), +${V.insertions}/-${V.deletions}`);let u={...w},m="",y="",x,C,M;if($){let U=ni(s);if(!U)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ie=sr(Oa.default.readFileSync(U,"utf8"));if(!ie.length)j("info",`${za.default.basename(U)} lists no commands - nothing to run`);else{j("info",`Running ${ie.length} documented test command(s) - no tokens, plain shell`);let fe=await An(s,ie,{perCommandTimeoutMs:15*6e4}),ge=fe.filter(Se=>Se.exitCode!==0),ke=ge.length;for(let Se of fe)j(Se.exitCode===0?"info":"warn",Wm(Se));let st="";if(ge.length&&t.fixSession){let Se=await uT({runId:e,issueKey:n,worktreePath:s,baseBranch:c,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:T,failed:ge,emit:j,sendUsage:t.sendUsage,baseCost:u});if(u.costUsd+=Se.cost.costUsd,u.inputTokens+=Se.cost.inputTokens,u.outputTokens+=Se.cost.outputTokens,Se.outcome==="cancelled"){let yt="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",yt),_a({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:z,autoMerge:A,repoName:v,baseRepoPath:i,branch:a,baseBranch:c,headSha:await dt(s),requireApproval:p,doneLabel:f,failedLabel:g,jiraTransition:l,jiraTransitionOnMerge:d,actorEmail:_,resultSummary:Vm(P),prSummary:Bd(P)??"",costUsd:u.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await ln(k,n,e,g,`${yt}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),W("failed",{error:yt,errorKind:"guard",retryAvailable:!0,...u});return}if(Se.outcome==="committed"){y=Se.resultText,j("info",`Re-running ${ie.length} documented test command(s) after the fix`),fe=await An(s,ie,{perCommandTimeoutMs:15*6e4}),ge=fe.filter(yt=>yt.exitCode!==0);for(let yt of fe)j(yt.exitCode===0?"info":"warn",Wm(yt));st=ge.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${ke} failure(s). ${Se.note}`:`The first pass had ${ke} failure(s); one automatic same-session fix attempt resolved them. ${Se.note}`}else st=Se.note}x=ge.slice(0,20).map(Se=>({command:Se.command.slice(0,500),exitCode:Se.exitCode,tail:Se.tail.slice(-4e3)})),C=fe.length-ge.length,M=fe.length,m=`
962
+ Allwright run ${e}`);let V=await tr(s,c);if(!V.ok){let U=V.forbidden.length?`refusing to push: changes touch protected paths (${V.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 (${V.files} files, ${V.insertions+V.deletions} lines; limits ${Xn}/${Qn})`;j("error",U),await ln(k,n,e,g,U),W("failed",{error:U,errorKind:"guard",...w});return}j("info",`Diff: ${V.files} file(s), +${V.insertions}/-${V.deletions}`);let u={...w},m="",y="",x,C,M;if($){let U=ni(s);if(!U)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ie=sr(Oa.default.readFileSync(U,"utf8"));if(!ie.length)j("info",`${za.default.basename(U)} lists no commands - nothing to run`);else{j("info",`Running ${ie.length} documented test command(s) - no tokens, plain shell`);let fe=await An(s,ie,{perCommandTimeoutMs:15*6e4}),ge=fe.filter(Se=>Se.exitCode!==0),ke=ge.length;for(let Se of fe)j(Se.exitCode===0?"info":"warn",Wm(Se));let st="";if(ge.length&&t.fixSession){let Se=await dT({runId:e,issueKey:n,worktreePath:s,baseBranch:c,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:T,failed:ge,emit:j,sendUsage:t.sendUsage,baseCost:u});if(u.costUsd+=Se.cost.costUsd,u.inputTokens+=Se.cost.inputTokens,u.outputTokens+=Se.cost.outputTokens,Se.outcome==="cancelled"){let yt="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",yt),_a({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:z,autoMerge:A,repoName:v,baseRepoPath:i,branch:a,baseBranch:c,headSha:await dt(s),requireApproval:p,doneLabel:f,failedLabel:g,jiraTransition:l,jiraTransitionOnMerge:d,actorEmail:_,resultSummary:Vm(P),prSummary:Bd(P)??"",costUsd:u.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await ln(k,n,e,g,`${yt}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),W("failed",{error:yt,errorKind:"guard",retryAvailable:!0,...u});return}if(Se.outcome==="committed"){y=Se.resultText,j("info",`Re-running ${ie.length} documented test command(s) after the fix`),fe=await An(s,ie,{perCommandTimeoutMs:15*6e4}),ge=fe.filter(yt=>yt.exitCode!==0);for(let yt of fe)j(yt.exitCode===0?"info":"warn",Wm(yt));st=ge.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${ke} failure(s). ${Se.note}`:`The first pass had ${ke} failure(s); one automatic same-session fix attempt resolved them. ${Se.note}`}else st=Se.note}x=ge.slice(0,20).map(Se=>({command:Se.command.slice(0,500),exitCode:Se.exitCode,tail:Se.tail.slice(-4e3)})),C=fe.length-ge.length,M=fe.length,m=`
1000
963
 
1001
964
  ### Tests
1002
965
  `+fe.map(Se=>`- ${Se.exitCode===0?"PASS":"FAIL"} \`${Se.command}\``).join(`
@@ -1010,7 +973,7 @@ ${st}`:""),ge.length&&j("warn",`${ge.length} test command(s) failed - the PR wil
1010
973
  `)+(st?`
1011
974
  ${st}`:"")})}}}let Y=await rs(s),H=Bt(Y);if(!H){let U=`origin "${Y}" is not a GitHub remote - implement mode supports GitHub only`;j("error",U),await ln(k,n,e,g,U),W("failed",{error:U,...w});return}let F=await dt(s),N=Vm(P),Z=(y?Bd(y):null)??Bd(P);try{await ig({gitDir:s,ownerRepo:H,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:a,baseBranch:c,jiraTransition:l,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:g,repoName:v,jira:k,cfg:T,actorEmail:_,mergeOnApprove:D,mergeMethod:z,autoMerge:A,summary:N,prSummary:Z??void 0,cost:u,testReport:m,failedTests:x,testsPassed:C,testsTotal:M,goLiveDraft:(y?Km(y):null)??Km(P)??void 0,emit:j,setStatus:W})}catch(U){let ie=U instanceof Error?U.message:String(U);_a({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:D,mergeMethod:z,autoMerge:A,repoName:v,baseRepoPath:i,branch:a,baseBranch:c,headSha:F,requireApproval:p,doneLabel:f,failedLabel:g,jiraTransition:l,jiraTransitionOnMerge:d,actorEmail:_,resultSummary:N,prSummary:Z??"",costUsd:u.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),j("error",`Run failed: ${ie}`),j("info",`The commit itself survived on the runner (branch ${a}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await ln(k,n,e,g,`${ie}
1012
975
 
1013
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),W("failed",{error:ie,retryAvailable:!0,...u})}}async function uT(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:a,failed:c,emit:l,sendUsage:d,baseCost:p}=t,f=tt(i.agent);if(!f?.capabilities.sessionResume){let $=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return l("info",$),{outcome:"skipped",note:$,cost:dT}}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 g=await dt(r),v=await li(e,f,{repoPath:r,prompt:tT(c),timeoutSeconds:i.timeoutSeconds,bin:Be(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:($,D)=>l($,D),onUsage:d?$=>d({...$,inputTokens:p.inputTokens+$.inputTokens,outputTokens:p.outputTokens+$.outputTokens,costUsd:$.costUsd===void 0?void 0:p.costUsd+$.costUsd}):void 0},l),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:k};if(!v.ok){let $=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return l("warn",$),{outcome:"agent_failed",note:$,cost:k}}if(ho(v.resultText)){let $="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return l("warn",$),{outcome:"agent_failed",note:$,cost:k}}let T=await Xs(r);for(let $ of T.refused)l("warn",`${In} entry refused: ${$}`);try{await ts(r,`${n}: fix failing TEST.md commands
976
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),W("failed",{error:ie,retryAvailable:!0,...u})}}async function dT(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:a,failed:c,emit:l,sendUsage:d,baseCost:p}=t,f=tt(i.agent);if(!f?.capabilities.sessionResume){let $=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return l("info",$),{outcome:"skipped",note:$,cost:lT}}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 g=await dt(r),v=await li(e,f,{repoPath:r,prompt:eT(c),timeoutSeconds:i.timeoutSeconds,bin:Be(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:($,D)=>l($,D),onUsage:d?$=>d({...$,inputTokens:p.inputTokens+$.inputTokens,outputTokens:p.outputTokens+$.outputTokens,costUsd:$.costUsd===void 0?void 0:p.costUsd+$.costUsd}):void 0},l),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:k};if(!v.ok){let $=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return l("warn",$),{outcome:"agent_failed",note:$,cost:k}}if(ho(v.resultText)){let $="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return l("warn",$),{outcome:"agent_failed",note:$,cost:k}}let T=await Xs(r);for(let $ of T.refused)l("warn",`${In} entry refused: ${$}`);try{await ts(r,`${n}: fix failing TEST.md commands
1014
977
 
1015
978
  Allwright run ${e} (automatic test-fix attempt)`)}catch{let $=`An automatic fix attempt concluded no code change was warranted: ${ls(v.resultText)}`;return l("info",$),{outcome:"no_changes",note:$,cost:k}}let _=await tr(r,s);if(!_.ok){await Qs(r,g);let $=_.forbidden.length?`An automatic fix attempt touched protected paths (${_.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",$),{outcome:"reverted",note:$,cost:k}}return{outcome:"committed",note:`Fix attempt: ${ls(v.resultText)}`,resultText:v.resultText,cost:k}}async function ig(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:a,mergeMethod:c,autoMerge:l,branch:d,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:g,requireApproval:v,doneLabel:k,failedLabel:T,repoName:_,jira:$,cfg:D,actorEmail:z,summary:A,prSummary:P,cost:w,testReport:j,emit:W,setStatus:L}=t;W("info",`Pushing ${d} to origin`),await ns(e,d);let V=await pa(e,d),m=`${P?.trim()?`${P.trim()}
1016
979
 
@@ -1048,7 +1011,7 @@ The pull request was closed and the branch deleted. This ticket is labeled \`${n
1048
1011
  Error: ${n.slice(0,800)}
1049
1012
 
1050
1013
  PR: ${e.prUrl}
1051
- (run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){b.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function hT(t,e,n){let r=0;for(let c of e)n(c.body)&&(r=Math.max(r,new Date(c.created).getTime()));let s=e.filter(c=>!n(c.body)&&new Date(c.created).getTime()>r),i=s.length?cs(s):"(nothing new was said - re-read the newest comments above and do only what they ask)",a=t.files.length?t.files.map(c=>`- ${c}`).join(`
1014
+ (run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){b.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function uT(t,e,n){let r=0;for(let c of e)n(c.body)&&(r=Math.max(r,new Date(c.created).getTime()));let s=e.filter(c=>!n(c.body)&&new Date(c.created).getTime()>r),i=s.length?cs(s):"(nothing new was said - re-read the newest comments above and do only what they ask)",a=t.files.length?t.files.map(c=>`- ${c}`).join(`
1052
1015
  `)+(t.more?`
1053
1016
  - (\u2026 ${t.more} more file(s))`:""):"(the commit touched no files this checkout can list)";return cr.REVISION_PROMPT+`
1054
1017
 
@@ -1064,9 +1027,9 @@ ${i.body}`),r=[],s=0;for(let i=n.length-1;i>=0;i--){if(s+=n[i].length+6,s>e){r.u
1064
1027
 
1065
1028
  ${t}
1066
1029
 
1067
- Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Le.NEEDS_INPUT_MARKER} marker).`}function pT(t){if(!t)return!1;for(let n of t.matchAll(/`([^`\n]+)`/g)){let r=n[1].trim();if(r.length>=2&&!/\s/.test(r)&&/[A-Za-z]/.test(r))return!0}let e=t.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi," ");return/[\w.-]+\/[\w./-]*[\w-]+\.[A-Za-z][A-Za-z0-9]{0,4}\b/.test(e)}function fT(t){let e=t.trim().replace(/^[#*_>\s]+/,"").replace(/[*_:.\s]+$/,"");if(!/^[A-Za-z][A-Za-z \-]*$/.test(e))return!1;let n=r=>r.replace(/[^a-z]/gi,"").toUpperCase();return n(e)===n(Le.NEEDS_INPUT_MARKER)}function ho(t){let e=t.trim().split(`
1068
- `);for(let n=0;n<e.length;n++){if(!fT(e[n]))continue;let r=e.slice(n+1).join(`
1069
- `).trim();if(r)return r}return null}function mT(t){let n=[...t.matchAll(new RegExp(`\`\`\`${Le.NEEDS_INPUT_ASK_FENCE}\\s*\\n([\\s\\S]*?)\`\`\``,"g"))],r=[];for(let i=n.length-1;i>=0&&!r.length;i--)try{let a=JSON.parse(n[i][1]);r=(Array.isArray(a.options)?a.options:[]).filter(l=>typeof l=="string"&&!!l.trim()).slice(0,5).map(l=>l.trim().slice(0,200))}catch{}return{questions:t.replace(new RegExp(`\`\`\`${Le.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function ao(t,e,n,r,s){let{questions:i,options:a}=mT(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${Le.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
1030
+ Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Le.NEEDS_INPUT_MARKER} marker).`}function hT(t){if(!t)return!1;for(let n of t.matchAll(/`([^`\n]+)`/g)){let r=n[1].trim();if(r.length>=2&&!/\s/.test(r)&&/[A-Za-z]/.test(r))return!0}let e=t.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi," ");return/[\w.-]+\/[\w./-]*[\w-]+\.[A-Za-z][A-Za-z0-9]{0,4}\b/.test(e)}function pT(t){let e=t.trim().replace(/^[#*_>\s]+/,"").replace(/[*_:.\s]+$/,"");if(!/^[A-Za-z][A-Za-z \-]*$/.test(e))return!1;let n=r=>r.replace(/[^a-z]/gi,"").toUpperCase();return n(e)===n(Le.NEEDS_INPUT_MARKER)}function ho(t){let e=t.trim().split(`
1031
+ `);for(let n=0;n<e.length;n++){if(!pT(e[n]))continue;let r=e.slice(n+1).join(`
1032
+ `).trim();if(r)return r}return null}function fT(t){let n=[...t.matchAll(new RegExp(`\`\`\`${Le.NEEDS_INPUT_ASK_FENCE}\\s*\\n([\\s\\S]*?)\`\`\``,"g"))],r=[];for(let i=n.length-1;i>=0&&!r.length;i--)try{let a=JSON.parse(n[i][1]);r=(Array.isArray(a.options)?a.options:[]).filter(l=>typeof l=="string"&&!!l.trim()).slice(0,5).map(l=>l.trim().slice(0,200))}catch{}return{questions:t.replace(new RegExp(`\`\`\`${Le.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function ao(t,e,n,r,s){let{questions:i,options:a}=fT(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${Le.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
1070
1033
 
1071
1034
  ${i}
1072
1035
 
@@ -1075,15 +1038,15 @@ Reply with your answers in a comment on this ticket - or answer on the run page
1075
1038
  Error: ${s.slice(0,800)}
1076
1039
 
1077
1040
  This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[Le.NEEDS_INPUT_LABEL]})}catch(i){b.error(`could not post failure comment to ${e}: ${i}`)}}function Vm(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function Bd(t){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,2e3):null}function ls(t){for(let e of t.split(`
1078
- `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Oa,za,Da,Le,cr,Xx,Qx,eT,Ym,Gm,rT,Zm,Fd,sT,iT,oT,oo,dT,ds=X(()=>{"use strict";Oa=E(require("node:fs"),1),za=E(require("node:path"),1),Da=require("node:crypto"),Le=E(Ne(),1);Md();Ae();no();Et();Fl();Yi();Vi();Ys();cr=E(Ne(),1);Pm();Ud();ka();Hm();Ht();is();sn();Qi();lt();Xx=`
1041
+ `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Oa,za,Da,Le,cr,Jx,Xx,Qx,Ym,Gm,nT,Zm,Fd,rT,sT,iT,oo,lT,ds=X(()=>{"use strict";Oa=E(require("node:fs"),1),za=E(require("node:path"),1),Da=require("node:crypto"),Le=E(Ne(),1);Md();Ae();no();Et();Fl();Yi();Vi();Ys();cr=E(Ne(),1);Pm();Ud();ka();Hm();Ht();is();sn();Qi();lt();Jx=`
1079
1042
 
1080
- NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,Qx=`
1043
+ NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,Xx=`
1081
1044
 
1082
- After your "## Summary of changes" section, end with one more section headed exactly "## PR summary": 4-8 short sentences in plain language for the person reviewing the pull request. Say what was built and what a user can now do, name anything you did NOT do or assumed, and anything that genuinely needs a human decision. No file paths, no function names, no jargon unless the point cannot be made without it. Complete but short.`,eT=`
1045
+ After your "## Summary of changes" section, end with one more section headed exactly "## PR summary": 4-8 short sentences in plain language for the person reviewing the pull request. Say what was built and what a user can now do, name anything you did NOT do or assumed, and anything that genuinely needs a human decision. No file paths, no function names, no jargon unless the point cannot be made without it. Complete but short.`,Qx=`
1083
1046
 
1084
- This project keeps a living go-live checklist and manual test cases on a Jira issue. If (and only if) this ticket changes what must be checked before going live, or adds user-visible behavior a human should test by hand, end with one more section headed exactly "## Go-live draft": checklist additions/changes as short imperative bullets, then manual test cases as numbered steps a non-developer can follow. Under 1500 characters total. If nothing about going live changes, OMIT the section entirely - an empty ritual entry is noise.`;Ym=5;Gm=2,rT=8,Zm=2,Fd="Your previous run on this ticket hit its wall-clock time limit - nothing failed. You are back in the SAME worktree with your uncommitted work intact and your own memory of the ticket. Check git status and your last steps, then continue exactly where you stopped - do not re-read files you already know or redo completed work. Finish the remaining work and end with the final summary the original instructions asked for.",sT="Proceed - this epic's own description is the spec for this run",iT="Stop this run - the work lives in the child tickets",oT="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";oo=new Map;dT={costUsd:0,inputTokens:0,outputTokens:0}});var fg={};De(fg,{describeGoLive:()=>yT,runGoLiveChecklist:()=>gT,uncheckedItems:()=>pg});function pg(t){return(t.match(/^[ \t]*[-*]\s*\[ \]\s+.+$/gm)??[]).map(e=>e.replace(/^[ \t]*[-*]\s*\[ \]\s+/,"").trim()).filter(Boolean).slice(0,100)}async function gT(t){let e={results:[],manualCases:[],totalItems:0,skipped:""},n="";try{n=(await t.jira.getIssue(t.issueKey))?.description??""}catch(a){return{...e,skipped:`could not read ${t.issueKey}: ${a instanceof Error?a.message:a}`}}if(!n.trim())return{...e,skipped:`${t.issueKey} has no checklist content`};let r=pg(n),s=sr(n);return s.length?{results:await An(t.repoPath,s,{perCommandTimeoutMs:t.perCommandTimeoutMs??5*6e4,onProgress:t.onProgress}),manualCases:r,totalItems:r.length,skipped:""}:{...e,totalItems:r.length,manualCases:r,skipped:r.length?"":`${t.issueKey} has no runnable commands and no open checklist items`}}function yT(t,e){let n=[];if(t.skipped)return n.push(`Go-live checklist (${e}): ${t.skipped} - deploying anyway (advisory)`),n;let r=t.results.filter(s=>s.exitCode!==0);if(t.results.length){n.push(r.length?`Go-live checklist (${e}): ${r.length} of ${t.results.length} command(s) FAILED - deploying anyway (advisory), but this is what the checklist exists to catch`:`Go-live checklist (${e}): all ${t.results.length} runnable command(s) passed \u2713`);for(let s of r)n.push(` \u2717 ${s.command} (exit ${s.exitCode})`)}if(t.manualCases.length){n.push(`Go-live checklist (${e}): ${t.manualCases.length} case(s) still need a HUMAN - nothing here guesses at them:`);for(let s of t.manualCases.slice(0,10))n.push(` \u2022 ${s}`);t.manualCases.length>10&&n.push(` \u2022 \u2026and ${t.manualCases.length-10} more on ${e}`)}return n}var mg=X(()=>{"use strict";Yi()});var Rg={};De(Rg,{executeDeploy:()=>po,findDeployDoc:()=>fo,handleDeployApproved:()=>Xd,handleDeployRejected:()=>Qd,isPendingDeploy:()=>qa,makeRedactor:()=>ps,parseFixTicketBlock:()=>Tg,parseSuggestion:()=>ru,preflightEnvironmentSteps:()=>eu,resolveWorkdir:()=>Jd,runSavedStep:()=>xT,suggestDeployFix:()=>tu,suggestDeploySteps:()=>nu});function yg(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
1047
+ This project keeps a living go-live checklist and manual test cases on a Jira issue. If (and only if) this ticket changes what must be checked before going live, or adds user-visible behavior a human should test by hand, end with one more section headed exactly "## Go-live draft": checklist additions/changes as short imperative bullets, then manual test cases as numbered steps a non-developer can follow. Under 1500 characters total. If nothing about going live changes, OMIT the section entirely - an empty ritual entry is noise.`;Ym=5;Gm=2,nT=8,Zm=2,Fd="Your previous run on this ticket hit its wall-clock time limit - nothing failed. You are back in the SAME worktree with your uncommitted work intact and your own memory of the ticket. Check git status and your last steps, then continue exactly where you stopped - do not re-read files you already know or redo completed work. Finish the remaining work and end with the final summary the original instructions asked for.",rT="Proceed - this epic's own description is the spec for this run",sT="Stop this run - the work lives in the child tickets",iT="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";oo=new Map;lT={costUsd:0,inputTokens:0,outputTokens:0}});var fg={};De(fg,{describeGoLive:()=>gT,runGoLiveChecklist:()=>mT,uncheckedItems:()=>pg});function pg(t){return(t.match(/^[ \t]*[-*]\s*\[ \]\s+.+$/gm)??[]).map(e=>e.replace(/^[ \t]*[-*]\s*\[ \]\s+/,"").trim()).filter(Boolean).slice(0,100)}async function mT(t){let e={results:[],manualCases:[],totalItems:0,skipped:""},n="";try{n=(await t.jira.getIssue(t.issueKey))?.description??""}catch(a){return{...e,skipped:`could not read ${t.issueKey}: ${a instanceof Error?a.message:a}`}}if(!n.trim())return{...e,skipped:`${t.issueKey} has no checklist content`};let r=pg(n),s=sr(n);return s.length?{results:await An(t.repoPath,s,{perCommandTimeoutMs:t.perCommandTimeoutMs??5*6e4,onProgress:t.onProgress}),manualCases:r,totalItems:r.length,skipped:""}:{...e,totalItems:r.length,manualCases:r,skipped:r.length?"":`${t.issueKey} has no runnable commands and no open checklist items`}}function gT(t,e){let n=[];if(t.skipped)return n.push(`Go-live checklist (${e}): ${t.skipped} - deploying anyway (advisory)`),n;let r=t.results.filter(s=>s.exitCode!==0);if(t.results.length){n.push(r.length?`Go-live checklist (${e}): ${r.length} of ${t.results.length} command(s) FAILED - deploying anyway (advisory), but this is what the checklist exists to catch`:`Go-live checklist (${e}): all ${t.results.length} runnable command(s) passed \u2713`);for(let s of r)n.push(` \u2717 ${s.command} (exit ${s.exitCode})`)}if(t.manualCases.length){n.push(`Go-live checklist (${e}): ${t.manualCases.length} case(s) still need a HUMAN - nothing here guesses at them:`);for(let s of t.manualCases.slice(0,10))n.push(` \u2022 ${s}`);t.manualCases.length>10&&n.push(` \u2022 \u2026and ${t.manualCases.length-10} more on ${e}`)}return n}var mg=X(()=>{"use strict";Yi()});var Rg={};De(Rg,{executeDeploy:()=>po,findDeployDoc:()=>fo,handleDeployApproved:()=>Xd,handleDeployRejected:()=>Qd,isPendingDeploy:()=>qa,makeRedactor:()=>ps,parseFixTicketBlock:()=>Tg,parseSuggestion:()=>ru,preflightEnvironmentSteps:()=>eu,resolveWorkdir:()=>Jd,runSavedStep:()=>_T,suggestDeployFix:()=>tu,suggestDeploySteps:()=>nu});function yg(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
1085
1048
  `+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
1086
- `))}function Yd(t){let e=0;return{emit:(s,i)=>{t.transport.send({type:"run.log",runId:t.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,bT)}),s!=="agent"&&b.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}function vT(t){let e=wT.exec(t);if(!e)return null;let[n,...r]=e[1].split(/\s+#\s+/),s=n.trim();return s?{command:s.slice(0,500),why:r.join(" # ").trim().slice(0,300)}:null}async function po(t){let{emit:e,setStatus:n}=Yd(t),r=t.environment;try{let s=kT(t);if(s){e("error",s),await Ct(t,`**Allwright could not deploy to \`${r.name}\`.**
1049
+ `))}function Yd(t){let e=0;return{emit:(s,i)=>{t.transport.send({type:"run.log",runId:t.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,yT)}),s!=="agent"&&b.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}function wT(t){let e=bT.exec(t);if(!e)return null;let[n,...r]=e[1].split(/\s+#\s+/),s=n.trim();return s?{command:s.slice(0,500),why:r.join(" # ").trim().slice(0,300)}:null}async function po(t){let{emit:e,setStatus:n}=Yd(t),r=t.environment;try{let s=vT(t);if(s){e("error",s),await Ct(t,`**Allwright could not deploy to \`${r.name}\`.**
1087
1050
 
1088
1051
  ${s}`),n("failed",{error:s});return}if(r.requireApproval){cm({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,projectId:t.project.id,repoName:t.project.repoName,environmentName:r.name,requestedBy:t.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${r.name}" is waiting for approval on the dashboard - no step has run yet`),await Ct(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
1089
1052
 
@@ -1091,17 +1054,17 @@ ${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed y
1091
1054
 
1092
1055
  ${i.slice(0,800)}
1093
1056
 
1094
- (run \`${t.runId}\`)`),n("failed",{error:i})}}function kT(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=Qt(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 kg(t,e,n){let r=t.environment,s=Qt(t.cfg,t.project.repoName,r.name),i=ps(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 A=$e(t.cfg,t.project,"assist"),P="error"in A?{ok:!1,error:A.error}:await ri({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:A,jira:t.jira});if(!P.ok)e("warn",`Pre-deploy audit could not run: ${P.error} - deploying anyway (advisory)`);else if(!P.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let w={};for(let j of P.audit.findings)w[j.severity]=(w[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${P.audit.findings.length} finding(s) (`+Object.entries(w).map(([j,W])=>`${W} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of P.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch(A){e("warn",`Pre-deploy audit crashed: ${A instanceof Error?A.message:String(A)} - deploying anyway`)}}if(t.project.goLiveIssueKey)try{let{runGoLiveChecklist:A,describeGoLive:P}=await Promise.resolve().then(()=>(mg(),fg));e("info",`Go-live checklist: running what can be run from ${t.project.goLiveIssueKey}`);let w=await A({jira:t.jira,issueKey:t.project.goLiveIssueKey,repoPath:t.repoPath,onProgress:j=>e("info",` ${j}`)});for(let j of P(w,t.project.goLiveIssueKey))e(w.results.some(W=>W.exitCode!==0)?"warn":"info",j)}catch(A){e("warn",`Go-live checklist could not run: ${A instanceof Error?A.message:String(A)} - deploying anyway`)}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let P=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",P),await Ct(t,`**Allwright refused to deploy to \`${r.name}\`.**
1057
+ (run \`${t.runId}\`)`),n("failed",{error:i})}}function vT(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=Qt(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 kg(t,e,n){let r=t.environment,s=Qt(t.cfg,t.project.repoName,r.name),i=ps(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 A=$e(t.cfg,t.project,"assist"),P="error"in A?{ok:!1,error:A.error}:await ri({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:A,jira:t.jira});if(!P.ok)e("warn",`Pre-deploy audit could not run: ${P.error} - deploying anyway (advisory)`);else if(!P.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let w={};for(let j of P.audit.findings)w[j.severity]=(w[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${P.audit.findings.length} finding(s) (`+Object.entries(w).map(([j,W])=>`${W} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of P.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch(A){e("warn",`Pre-deploy audit crashed: ${A instanceof Error?A.message:String(A)} - deploying anyway`)}}if(t.project.goLiveIssueKey)try{let{runGoLiveChecklist:A,describeGoLive:P}=await Promise.resolve().then(()=>(mg(),fg));e("info",`Go-live checklist: running what can be run from ${t.project.goLiveIssueKey}`);let w=await A({jira:t.jira,issueKey:t.project.goLiveIssueKey,repoPath:t.repoPath,onProgress:j=>e("info",` ${j}`)});for(let j of P(w,t.project.goLiveIssueKey))e(w.results.some(W=>W.exitCode!==0)?"warn":"info",j)}catch(A){e("warn",`Go-live checklist could not run: ${A instanceof Error?A.message:String(A)} - deploying anyway`)}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let P=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",P),await Ct(t,`**Allwright refused to deploy to \`${r.name}\`.**
1095
1058
 
1096
1059
  ${P}
1097
1060
 
1098
- (run \`${t.runId}\`)`),n("failed",{error:P,errorKind:"guard"});return}let A=await _T(t,e);if(A){await Ct(t,A.comment),n("failed",{error:A.error,...A.guard?{errorKind:"guard"}:{}});return}}let l=t.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),l=await td({repoPath:t.repoPath,repoName:t.project.repoName,envName:r.name,branch:r.branch,attached:r.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${r.name}" - running the steps in the mapped checkout as it is`),r.promotionMode==="merge_and_deploy"){let A=Rn(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${A}" into "${r.branch}"`);let P=await nd(l,A,`Deploy ${t.issueKey} to ${r.name}
1061
+ (run \`${t.runId}\`)`),n("failed",{error:P,errorKind:"guard"});return}let A=await ST(t,e);if(A){await Ct(t,A.comment),n("failed",{error:A.error,...A.guard?{errorKind:"guard"}:{}});return}}let l=t.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),l=await td({repoPath:t.repoPath,repoName:t.project.repoName,envName:r.name,branch:r.branch,attached:r.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${r.name}" - running the steps in the mapped checkout as it is`),r.promotionMode==="merge_and_deploy"){let A=Rn(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${A}" into "${r.branch}"`);let P=await nd(l,A,`Deploy ${t.issueKey} to ${r.name}
1099
1062
 
1100
1063
  Allwright run ${t.runId}`);if(!P.ok){e("error",P.reason??"merge failed"),await Ct(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
1101
1064
 
1102
1065
  ${P.reason}`),n("failed",{error:P.reason});return}P.alreadyMerged?e("info",`"${A}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await od(l,r.branch))}let p=await dt(l).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Jd(l,r.workdir),g={...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},v=0,k=r.timeoutSeconds*1e3,T=Qm(t.runId),_=()=>T.signal.aborted;try{for(let[A,P]of r.steps.entries()){if(_()){let W=`stopped from the dashboard during step ${A+1} - nothing further ran`;e("error",W),n("failed",{error:W,errorKind:"guard",deployedRef:p});return}let w=k-(Date.now()-a);if(w<=0){let W=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${A+1}`;e("error",W),await Ct(t,`**Allwright deploy to \`${r.name}\` timed out.**
1103
1066
 
1104
- ${W}`),n("timed_out",{error:W,deployedRef:p});return}e("info",`\u25B6 step ${A+1}/${r.steps.length}: ${P.name}`);let j=await Sg({command:P.run,cwd:f,env:g,timeoutMs:w,signal:T.signal,onLine:(W,L)=>{v++;let V=vT(L);V&&c.length<20&&c.push(V),v===gg&&e("warn","(output truncated - deploy log limit reached)"),!(v>=gg)&&e(W,i(L))}});if(j.timedOut){let W=`step "${P.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",W),await Ct(t,`**Allwright deploy to \`${r.name}\` timed out.**
1067
+ ${W}`),n("timed_out",{error:W,deployedRef:p});return}e("info",`\u25B6 step ${A+1}/${r.steps.length}: ${P.name}`);let j=await Sg({command:P.run,cwd:f,env:g,timeoutMs:w,signal:T.signal,onLine:(W,L)=>{v++;let V=wT(L);V&&c.length<20&&c.push(V),v===gg&&e("warn","(output truncated - deploy log limit reached)"),!(v>=gg)&&e(W,i(L))}});if(j.timedOut){let W=`step "${P.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",W),await Ct(t,`**Allwright deploy to \`${r.name}\` timed out.**
1105
1068
 
1106
1069
  ${W}`),n("timed_out",{error:W,deployedRef:p});return}if(j.code!==0){if(P.continueOnError){e("warn",`step "${P.name}" exited ${j.code} - continuing (marked continue-on-error)`);continue}let W="";try{W=i(await Kl(l))}catch{}let L=j.failures?i(j.failures):"",V=j.tail?i(j.tail):"",u=Kp(zl(`${L}
1107
1070
  ${V}`.trim(),{cwd:l})),m=`step ${A+1} "${P.name}" failed with exit code ${j.code}`+(L?`:
@@ -1138,7 +1101,7 @@ ${W.slice(0,800)}
1138
1101
  `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${A+1} "${P.name}" exit ${j.code}`+(L||V?`
1139
1102
  ${(L||V).slice(0,500)}`:"")}),c.length&&yg(e,c),n("failed",{error:m.slice(0,4e3),deployedRef:p,...c.length?{manualSteps:c}:{}});return}e("info",`\u2713 step ${A+1}/${r.steps.length}: ${P.name}`)}}finally{eg(t.runId)}if(p=await dt(l).catch(()=>"")||p,r.servePath?.trim()){let A=r.servePath.trim(),P=r.branch.trim(),w=await dt(A).catch(()=>"");if(!w)e("warn",`serving check: cannot read a git HEAD at ${A} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{p=w;let j=P?await Yl(A,P):"";if(!j)e("warn",`serving check: ${A} is at ${w.slice(0,10)}, but `+(P?`origin/${P} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${P||"commit"} could not be verified`);else if(w!==j){let W=await Jl(A,w,j),L=`The steps all succeeded, but the live checkout at ${A} is at ${w.slice(0,10)} while origin/${P} is at ${j.slice(0,10)}`+(W?` - ${W} commit(s) behind`:"")+`. Users are NOT getting the latest ${P}. 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: ${L}`),await Ct(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
1140
1103
 
1141
- ${L}`),It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${w.slice(0,10)}, origin/${P} at ${j.slice(0,10)} (${A})`}),n("failed",{error:L,deployedRef:p});return}else e("info",`serving check: ${A} is at ${w.slice(0,10)} = origin/${P} - users get this build`)}}n("posting");let $=Math.round((Date.now()-a)/1e3),D=null;r.publicUrl?.trim()&&(D=await IT(r.publicUrl.trim()),e(D?"warn":"info",D??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==hs.BRANCH_DEPLOY_ISSUE_KEY&&await Ct(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
1104
+ ${L}`),It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${w.slice(0,10)}, origin/${P} at ${j.slice(0,10)} (${A})`}),n("failed",{error:L,deployedRef:p});return}else e("info",`serving check: ${A} is at ${w.slice(0,10)} = origin/${P} - users get this build`)}}n("posting");let $=Math.round((Date.now()-a)/1e3),D=null;r.publicUrl?.trim()&&(D=await RT(r.publicUrl.trim()),e(D?"warn":"info",D??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==hs.BRANCH_DEPLOY_ISSUE_KEY&&await Ct(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
1142
1105
 
1143
1106
  `+(D?`> **Live where?** ${D}
1144
1107
 
@@ -1149,16 +1112,16 @@ ${L}`),It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.nam
1149
1112
  `:"")+(p?`Commit: \`${p.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
1150
1113
  `:"")+`${r.steps.length} step(s) in ${$}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
1151
1114
 
1152
- (run \`${t.runId}\`)`);let z=await ST(t,e,p);t.project.goLiveIssueKey&&e("info",`Go-live checklist: the human test cases on ${t.project.goLiveIssueKey} are still yours to run`),Ki(t.repoPath,t.issueKey)&&It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:p?`commit ${p.slice(0,10)}`:void 0}),c.length&&yg(e,c),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${$}s`+(z!==null?` \xB7 ${z} ticket(s) moved to "${r.deployToColumn}"`:"")+(c.length?` \xB7 ${c.length} manual step(s) left for you`:"")+(D?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...c.length?{manualSteps:c}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${$}s`)}async function ST(t,e,n){let r=t.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await t.jira.search(`project = "${t.project.jiraProjectKey}" AND status = "${r.deployFromColumn}" ORDER BY updated ASC`,50)}catch(c){return e("warn",`deploy succeeded, but listing tickets in "${r.deployFromColumn}" failed: ${c instanceof Error?c.message:c} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${r.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${r.deployFromColumn}" to "${r.deployToColumn}"`);let a=0;for(let c of i)try{if(await t.jira.addComment(c.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
1115
+ (run \`${t.runId}\`)`);let z=await kT(t,e,p);t.project.goLiveIssueKey&&e("info",`Go-live checklist: the human test cases on ${t.project.goLiveIssueKey} are still yours to run`),Ki(t.repoPath,t.issueKey)&&It(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:p?`commit ${p.slice(0,10)}`:void 0}),c.length&&yg(e,c),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${$}s`+(z!==null?` \xB7 ${z} ticket(s) moved to "${r.deployToColumn}"`:"")+(c.length?` \xB7 ${c.length} manual step(s) left for you`:"")+(D?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...c.length?{manualSteps:c}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${$}s`)}async function kT(t,e,n){let r=t.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await t.jira.search(`project = "${t.project.jiraProjectKey}" AND status = "${r.deployFromColumn}" ORDER BY updated ASC`,50)}catch(c){return e("warn",`deploy succeeded, but listing tickets in "${r.deployFromColumn}" failed: ${c instanceof Error?c.message:c} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${r.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${r.deployFromColumn}" to "${r.deployToColumn}"`);let a=0;for(let c of i)try{if(await t.jira.addComment(c.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
1153
1116
 
1154
1117
  `+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
1155
- `:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(c.key,r.deployToColumn)){e("warn",`${c.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.jira.addComment(c.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${t.runId}\`)`).catch(()=>{});continue}a++,e("info",`\u2713 ${c.key} \u2192 "${r.deployToColumn}"`)}catch(l){e("warn",`${c.key}: sweep failed (${l instanceof Error?l.message:l}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${a}/${i.length} ticket(s) to "${r.deployToColumn}"`),a}async function _T(t,e){let n=t.environment,r=n.previousEnvBranch,s=(c,l=!1)=>({error:c,guard:l,comment:`**Allwright could not deploy \`${t.issueKey}\` to \`${n.name}\`.**
1118
+ `:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(c.key,r.deployToColumn)){e("warn",`${c.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.jira.addComment(c.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${t.runId}\`)`).catch(()=>{});continue}a++,e("info",`\u2713 ${c.key} \u2192 "${r.deployToColumn}"`)}catch(l){e("warn",`${c.key}: sweep failed (${l instanceof Error?l.message:l}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${a}/${i.length} ticket(s) to "${r.deployToColumn}"`),a}async function ST(t,e){let n=t.environment,r=n.previousEnvBranch,s=(c,l=!1)=>({error:c,guard:l,comment:`**Allwright could not deploy \`${t.issueKey}\` to \`${n.name}\`.**
1156
1119
 
1157
1120
  ${c}
1158
1121
 
1159
1122
  (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await er(t.repoPath,r),await er(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 ad(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=Qe(_e()??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 rs(t.repoPath),l=Bt(c);if(!l)throw new Error(`could not parse a GitHub owner/repo from origin "${c}"`);let p=await new Xe(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.
1160
1123
 
1161
- (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 xT(t){let e=Qt(t.cfg,t.repoName,t.environmentName),n=ps(Object.values(e)),r=Jd(t.repoPath,t.workdir),s=await Sg({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:
1124
+ (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 _T(t){let e=Qt(t.cfg,t.repoName,t.environmentName),n=ps(Object.values(e)),r=Jd(t.repoPath,t.workdir),s=await Sg({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:
1162
1125
  ${s.failures.trim()}`:"",s.tail.trim()?`LAST LINES:
1163
1126
  ${s.tail.trim()}`:""].filter(Boolean);return{commandLine:t.step.run,exitCode:s.code,timedOut:s.timedOut,output:n(i.join(`
1164
1127
 
@@ -1169,13 +1132,13 @@ ${l.slice(0,800)}`),s("failed",{error:l})}}async function Qd(t,e){let n=Ra(e);if
1169
1132
 
1170
1133
  No deploy step was executed. (run \`${e}\`)`)}catch(a){b.error(`could not post rejection comment to ${n.issueKey}: ${a}`)}s("failed",{error:"deploy rejected by a reviewer"})}function fo(t){for(let e of ui.DEPLOY_DOC_CANDIDATES){let n=us.default.join(t,e);try{if(!di.default.existsSync(n))continue;let r=di.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>bg?r.slice(0,bg)+`
1171
1134
 
1172
- [\u2026document truncated\u2026]`:r}}catch{continue}}return null}function _g(t){return RT("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function RT(t,e){try{let n=(0,Ua.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function IT(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:a,resolve6:c}=await import("node:dns/promises"),[l,d]=await Promise.all([a(e.hostname).catch(()=>[]),c(e.hostname).catch(()=>[])]);n=[...l,...d]}catch{n=[]}if(!n.length)return`${e.hostname} does not resolve yet - this build is on THIS machine, but nothing points at it. Users see whatever your DNS points at today.`;let r=await import("node:os"),s=new Set(Object.values(r.networkInterfaces()).flatMap(a=>a??[]).filter(a=>!a.internal).map(a=>a.address)),i=km();return i&&s.add(i),n.some(a=>s.has(a))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine`+(i?` (this machine is ${i})`:" as far as it can tell - its own public address is not known here, so treat this as a prompt to check rather than a verdict")+". If you front it with a CDN or load balancer that is expected; otherwise this deploy changed nothing for users - they are still being served by the old server until the DNS record moves."}async function ET(t,e){let n;try{n=new URL(t)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${t}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(n.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${n.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${n.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(n.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:n.hostname,port:Number(n.port||443),servername:n.hostname,timeout:8e3},()=>{let a=i.getPeerCertificate(),c=a?.valid_to?Math.round((new Date(a.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(c)&&c>0?{name:"public-url-tls",ok:c>14,detail:`certificate valid, expires in ${c} day(s)${c<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",a=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${a.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let r=await fetch(n.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:r.status<500,detail:`HTTP ${r.status}${r.status>=300&&r.status<400?` \u2192 ${r.headers.get("location")??""}`:""}`})}catch(r){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${r instanceof Error?r.message:String(r)}`})}}function AT(t){let e=t.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],n=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return n.length?`
1135
+ [\u2026document truncated\u2026]`:r}}catch{continue}}return null}function _g(t){return TT("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function TT(t,e){try{let n=(0,Ua.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function RT(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:a,resolve6:c}=await import("node:dns/promises"),[l,d]=await Promise.all([a(e.hostname).catch(()=>[]),c(e.hostname).catch(()=>[])]);n=[...l,...d]}catch{n=[]}if(!n.length)return`${e.hostname} does not resolve yet - this build is on THIS machine, but nothing points at it. Users see whatever your DNS points at today.`;let r=await import("node:os"),s=new Set(Object.values(r.networkInterfaces()).flatMap(a=>a??[]).filter(a=>!a.internal).map(a=>a.address)),i=km();return i&&s.add(i),n.some(a=>s.has(a))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine`+(i?` (this machine is ${i})`:" as far as it can tell - its own public address is not known here, so treat this as a prompt to check rather than a verdict")+". If you front it with a CDN or load balancer that is expected; otherwise this deploy changed nothing for users - they are still being served by the old server until the DNS record moves."}async function IT(t,e){let n;try{n=new URL(t)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${t}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(n.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${n.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${n.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(n.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:n.hostname,port:Number(n.port||443),servername:n.hostname,timeout:8e3},()=>{let a=i.getPeerCertificate(),c=a?.valid_to?Math.round((new Date(a.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(c)&&c>0?{name:"public-url-tls",ok:c>14,detail:`certificate valid, expires in ${c} day(s)${c<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",a=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${a.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let r=await fetch(n.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:r.status<500,detail:`HTTP ${r.status}${r.status>=300&&r.status<400?` \u2192 ${r.headers.get("location")??""}`:""}`})}catch(r){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${r instanceof Error?r.message:String(r)}`})}}function ET(t){let e=t.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],n=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return n.length?`
1173
1136
  - absolute paths the document mentions, checked on THIS machine:
1174
1137
  ${n.map(s=>` - ${s}: ${di.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
1175
1138
  `)}`:""}function xg(t,e,n,r="",s="."){let i=wg.filter(l=>_g(l)),a=wg.filter(l=>!i.includes(l)),c=Object.keys(Qt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
1176
1139
  - available tools: ${i.join(", ")||"(none of the common ones)"}
1177
1140
  - NOT installed: ${a.join(", ")||"(none missing)"}
1178
- - secrets already stored for this environment (names only): ${c.join(", ")||"(none yet)"}`+Id()+AT(r)+to(s)}async function eu(t){let e=[];if(t.publicUrl?.trim()&&await ET(t.publicUrl.trim(),e),e.push(di.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let c=us.default.isAbsolute(t.workdir)?t.workdir:us.default.join(t.repoPath,t.workdir);e.push(di.default.existsSync(c)?{name:"workdir",ok:!0,detail:c}:{name:"workdir",ok:!1,detail:`does not exist: ${c}`})}if(t.branch){let c=Aa(t.repoPath);c.ok?e.push(c.branches.includes(t.branch)?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" - it really was asked, and answered with: ${c.branches.join(", ")||"(no branches at all)"}`}):e.push({name:"branch",ok:!1,detail:`${c.detail} Fix: ${c.fix}`})}let n=Qt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let c of t.steps)for(let l of c.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(l[1]);let s=[...r].filter(c=>!n[c]&&!process.env[c]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let c of t.steps)for(let l of c.run.split(/&&|\|\||;|\|/)){let d=l.trim().split(/\s+/),p=d.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=d.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let a=[...i].filter(c=>!_g(c));return e.push({name:"binaries",ok:a.length===0,detail:a.length?`not found on this machine: ${a.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(c=>c.ok),checks:e}}function Tg(t){let e=/```ticket\s*\n([\s\S]*?)```/i.exec(t);if(!e)return null;try{let n=JSON.parse(e[1]),r=typeof n.summary=="string"?n.summary.trim().slice(0,250):"";return r?{summary:r,description:typeof n.description=="string"?n.description.trim().slice(0,2e4):""}:null}catch{return null}}async function tu(t){let e=xg(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=Rn(ui.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,g)=>`${g+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
1141
+ - secrets already stored for this environment (names only): ${c.join(", ")||"(none yet)"}`+Id()+ET(r)+to(s)}async function eu(t){let e=[];if(t.publicUrl?.trim()&&await IT(t.publicUrl.trim(),e),e.push(di.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let c=us.default.isAbsolute(t.workdir)?t.workdir:us.default.join(t.repoPath,t.workdir);e.push(di.default.existsSync(c)?{name:"workdir",ok:!0,detail:c}:{name:"workdir",ok:!1,detail:`does not exist: ${c}`})}if(t.branch){let c=Aa(t.repoPath);c.ok?e.push(c.branches.includes(t.branch)?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" - it really was asked, and answered with: ${c.branches.join(", ")||"(no branches at all)"}`}):e.push({name:"branch",ok:!1,detail:`${c.detail} Fix: ${c.fix}`})}let n=Qt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let c of t.steps)for(let l of c.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(l[1]);let s=[...r].filter(c=>!n[c]&&!process.env[c]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let c of t.steps)for(let l of c.run.split(/&&|\|\||;|\|/)){let d=l.trim().split(/\s+/),p=d.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=d.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let a=[...i].filter(c=>!_g(c));return e.push({name:"binaries",ok:a.length===0,detail:a.length?`not found on this machine: ${a.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(c=>c.ok),checks:e}}function Tg(t){let e=/```ticket\s*\n([\s\S]*?)```/i.exec(t);if(!e)return null;try{let n=JSON.parse(e[1]),r=typeof n.summary=="string"?n.summary.trim().slice(0,250):"";return r?{summary:r,description:typeof n.description=="string"?n.description.trim().slice(0,2e4):""}:null}catch{return null}}async function tu(t){let e=xg(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=Rn(ui.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,g)=>`${g+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
1179
1142
  ${f.run}`).join(`
1180
1143
  `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let f=zl(t.errorText,{cwd:t.repoPath});return f?`
1181
1144
 
@@ -1184,39 +1147,39 @@ THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
1184
1147
  - what closes it: ${f.commands.join(" ; ")}
1185
1148
  - ${f.note}
1186
1149
  Start from this. If your own reading of the evidence agrees, say so in one line and turn it into steps; if it does NOT, say which evidence contradicts it - do not quietly produce a second, different answer to the same failure.`:""})(),evidence:Rm(Tm({errorText:t.errorText,repoPath:t.repoPath})),machineContext:e}),r=await t.agent.adapter.run({repoPath:t.repoPath,prompt:n,timeoutSeconds:240,bin:t.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,Vd.randomUUID)(),onLog:()=>{}});if(be({surface:"deploy_fix",agentId:t.agent.adapter.id,refKind:"none",refLabel:`${t.repoName} \u2192 ${t.environmentName}`,...we(r)}),!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=ru(r.resultText),i=(r.resultText.split(/```/)[0]??"").replace(/^\s*CAUSE TYPE:.*$/im,"").trim(),c=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",l=Tg(r.resultText),d=c?fo(t.repoPath):null;if(!s)return{ok:!1,steps:[],requiredSecrets:[],notes:i,error:i?"the agent diagnosed the failure (see its notes) but did not produce an applicable step list - the cause may live outside the steps":`the agent's answer was not in the expected shape. It started: "${r.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`};let p=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return p?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:p==="MACHINE"?'this is not a steps problem - the steps are right, but something on this machine is missing or misconfigured. The commands to fix it are under "WHAT A HUMAN MUST RUN" above; run them on that server, then retry the deploy. Allwright will not paste a credential into a deploy recipe to work around it.':"this is not a steps problem - the deploy failed because the code or the database is not ready (a build error, a failing test, or a migration that was never applied). Changing deploy steps cannot fix it; the diagnosis above says what a person has to change."+(l?" A fix ticket is drafted below - creating it starts the ordinary implement flow.":""),...p==="CODE"&&l?{fixTicketSummary:l.summary,fixTicketDescription:l.description}:{}}:{ok:!0,...s,notes:i||s.notes,docPath:d?.path??(c?"DEPLOY.md":""),docContent:c}}async function nu(t){let e=fo(t.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let n=xg(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=Rn(hs.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:t.environmentName,docPath:e.path,docContent:e.content,notes:t.notes.trim()||"(nothing specified)",machineContext:n}),s=await t.agent.adapter.run({repoPath:t.repoPath,prompt:r,timeoutSeconds:t.timeoutSeconds,bin:t.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,Vd.randomUUID)(),onLog:()=>{}});if(be({surface:"deploy_suggest",agentId:t.agent.adapter.id,refKind:"none",refLabel:`${t.repoName} \u2192 ${t.environmentName}`,...we(s)}),!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=ru(s.resultText);return i?{ok:!0,...i}:(b.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
1187
- `+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function ru(t){for(let e of $T(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=TT.safeParse(CT(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function $T(t){let e=[];for(let s of t.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let n=t.indexOf("{"),r=t.lastIndexOf("}");return n>=0&&r>n&&e.push(t.slice(n,r+1)),e}function CT(t){if(!t||typeof t!="object")return t;let e=t,r=(Array.isArray(t)?t:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((a,c)=>{if(typeof a=="string")return a.trim()?{name:vg(a,c),run:a.trim()}:null;if(!a||typeof a!="object")return null;let l=a,d=Gd(l.run,l.command,l.cmd,l.script,l.shell);return d?{name:(Gd(l.name,l.title,l.description)??vg(d,c)).slice(0,120),run:d,continueOnError:l.continueOnError===!0||l.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(a=>typeof a=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:Gd(e.notes,e.note,e.explanation)??""}}function Gd(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function vg(t,e){return(t.split(`
1188
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}var di,us,Ua,Zd,Vd,hs,ui,gg,bT,wT,TT,bg,wg,fs=X(()=>{"use strict";di=E(require("node:fs"),1);Ys();nn();Wp();us=E(require("node:path"),1),Ua=require("node:child_process"),Zd=E(require("node:readline"),1),Vd=require("node:crypto"),hs=E(Ne(),1);_t();Ae();Et();ui=E(Ne(),1);Fl();sn();Ht();is();Sa();Qi();$a();Ad();Pd();ds();lt();gg=4e3,bT=4e3;wT=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;TT=S.object({steps:S.array(hs.DeployStep).max(50).default([]),requiredSecrets:S.array(S.string()).max(50).default([]),notes:S.string().default("")}),bg=24e3;wg=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"]});var zg={};De(zg,{discoverSites:()=>OT,parseCaddySites:()=>jg,parseIisSites:()=>Og,parseNginxSites:()=>Mg});function iu(t){return!t||t==="_"||t==="localhost"||t.startsWith("*")||/^[\d.:[\]]+$/.test(t)?!1:t.includes(".")}function Mg(t){let e=new Map,n=0,r=-1,s=[],i=!1;for(let a of t.split(`
1150
+ `+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function ru(t){for(let e of AT(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=xT.safeParse($T(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function AT(t){let e=[];for(let s of t.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let n=t.indexOf("{"),r=t.lastIndexOf("}");return n>=0&&r>n&&e.push(t.slice(n,r+1)),e}function $T(t){if(!t||typeof t!="object")return t;let e=t,r=(Array.isArray(t)?t:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((a,c)=>{if(typeof a=="string")return a.trim()?{name:vg(a,c),run:a.trim()}:null;if(!a||typeof a!="object")return null;let l=a,d=Gd(l.run,l.command,l.cmd,l.script,l.shell);return d?{name:(Gd(l.name,l.title,l.description)??vg(d,c)).slice(0,120),run:d,continueOnError:l.continueOnError===!0||l.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(a=>typeof a=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:Gd(e.notes,e.note,e.explanation)??""}}function Gd(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function vg(t,e){return(t.split(`
1151
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}var di,us,Ua,Zd,Vd,hs,ui,gg,yT,bT,xT,bg,wg,fs=X(()=>{"use strict";di=E(require("node:fs"),1);Ys();nn();Wp();us=E(require("node:path"),1),Ua=require("node:child_process"),Zd=E(require("node:readline"),1),Vd=require("node:crypto"),hs=E(Ne(),1);_t();Ae();Et();ui=E(Ne(),1);Fl();sn();Ht();is();Sa();Qi();$a();Ad();Pd();ds();lt();gg=4e3,yT=4e3;bT=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;xT=S.object({steps:S.array(hs.DeployStep).max(50).default([]),requiredSecrets:S.array(S.string()).max(50).default([]),notes:S.string().default("")}),bg=24e3;wg=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"]});var zg={};De(zg,{discoverSites:()=>jT,parseCaddySites:()=>jg,parseIisSites:()=>Og,parseNginxSites:()=>Mg});function iu(t){return!t||t==="_"||t==="localhost"||t.startsWith("*")||/^[\d.:[\]]+$/.test(t)?!1:t.includes(".")}function Mg(t){let e=new Map,n=0,r=-1,s=[],i=!1;for(let a of t.split(`
1189
1152
  `)){let c=a.replace(/#.*$/,"").trim();if(r<0&&/^server\s*(\{|$)/.test(c)&&(r=n,s=[],i=!1),r>=0){let l=/^server_name\s+([^;]+);/.exec(c);l&&s.push(...l[1].trim().split(/\s+/)),(/^listen\s+[^;]*\bssl\b/.test(c)||/^listen\s+[^;]*:443\b/.test(c)||/^listen\s+443\b/.test(c))&&(i=!0)}if(n+=(c.match(/\{/g)??[]).length,n-=(c.match(/\}/g)??[]).length,r>=0&&n<=r&&c.includes("}")){for(let l of s.filter(iu))e.set(l,(e.get(l)??!1)||i);r=-1}}return[...e.entries()].map(([a,c])=>({host:a,ssl:c}))}function jg(t){let e=new Set,n=0;for(let r of t.split(`
1190
1153
  `)){let s=r.replace(/#.*$/,"").trim();if(n===0&&s.endsWith("{")){let i=s.slice(0,-1).trim();if(i&&!i.startsWith("(")&&!i.startsWith("@"))for(let a of i.split(",")){let c=a.trim().replace(/^https?:\/\//,"").split("/")[0].split(":")[0];iu(c)&&e.add(c)}}n+=(s.match(/\{/g)??[]).length,n-=(s.match(/\}/g)??[]).length}return[...e]}function Ig(t){return t.map(e=>{try{return su.default.readFileSync(e,"utf8")}catch{return""}}).join(`
1191
- `)}function Eg(t){let e=[];for(let n of t)try{for(let r of su.default.readdirSync(n).slice(0,200))e.push(Ag.default.join(n,r))}catch{}return e}function Og(t){let e=new Map;try{let n=JSON.parse(t),r=Array.isArray(n)?n:[n];for(let s of r){let i=s?.Bindings?.Collection??[];for(let a of i){let c=a??{},l=(c.bindingInformation??"").split(":")[2]??"";if(!iu(l))continue;let d=(c.protocol??"")==="https";e.set(l,(e.get(l)??!1)||d)}}}catch{}return[...e.entries()].map(([n,r])=>({host:n,ssl:r}))}async function jT(){try{let{stdout:t}=await Pg("powershell",["-NoProfile","-NonInteractive","-Command","Import-Module WebAdministration; Get-Website | Select-Object Name,Bindings | ConvertTo-Json -Depth 4"],{timeout:Ng,maxBuffer:4e6});return Og(t).map(e=>({host:e.host,server:"iis",ssl:e.ssl}))}catch{return[]}}async function OT(){if(process.platform==="win32")return(await jT()).slice(0,60);let t=[],e="";try{let{stdout:r,stderr:s}=await Pg("nginx",["-T"],{timeout:Ng,maxBuffer:8e6});e=r+`
1192
- `+s}catch{e=Ig(Eg(PT))}for(let r of Mg(e))t.push({host:r.host,server:"nginx",ssl:r.ssl});let n=Ig([...NT,...Eg(MT)]);for(let r of jg(n))t.some(s=>s.host===r)||t.push({host:r,server:"caddy",ssl:!0});return t.slice(0,60)}var su,Ag,$g,Cg,Pg,Ng,PT,NT,MT,Dg=X(()=>{"use strict";su=E(require("node:fs"),1),Ag=E(require("node:path"),1),$g=require("node:child_process"),Cg=require("node:util"),Pg=(0,Cg.promisify)($g.execFile),Ng=1e4;PT=["/etc/nginx/sites-enabled","/etc/nginx/conf.d"],NT=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile"],MT=["/etc/caddy/conf.d"]});var Kg={};De(Kg,{collectServerInventory:()=>KT,parseContainers:()=>Bg,parseListeningPorts:()=>lr,parseProcesses:()=>Hg,parseServices:()=>Ba});async function hi(t,e){try{let{stdout:n}=await zT(t,e,{timeout:DT,maxBuffer:4e6});return n}catch{return""}}function Ba(t){return t.split(`
1154
+ `)}function Eg(t){let e=[];for(let n of t)try{for(let r of su.default.readdirSync(n).slice(0,200))e.push(Ag.default.join(n,r))}catch{}return e}function Og(t){let e=new Map;try{let n=JSON.parse(t),r=Array.isArray(n)?n:[n];for(let s of r){let i=s?.Bindings?.Collection??[];for(let a of i){let c=a??{},l=(c.bindingInformation??"").split(":")[2]??"";if(!iu(l))continue;let d=(c.protocol??"")==="https";e.set(l,(e.get(l)??!1)||d)}}}catch{}return[...e.entries()].map(([n,r])=>({host:n,ssl:r}))}async function MT(){try{let{stdout:t}=await Pg("powershell",["-NoProfile","-NonInteractive","-Command","Import-Module WebAdministration; Get-Website | Select-Object Name,Bindings | ConvertTo-Json -Depth 4"],{timeout:Ng,maxBuffer:4e6});return Og(t).map(e=>({host:e.host,server:"iis",ssl:e.ssl}))}catch{return[]}}async function jT(){if(process.platform==="win32")return(await MT()).slice(0,60);let t=[],e="";try{let{stdout:r,stderr:s}=await Pg("nginx",["-T"],{timeout:Ng,maxBuffer:8e6});e=r+`
1155
+ `+s}catch{e=Ig(Eg(CT))}for(let r of Mg(e))t.push({host:r.host,server:"nginx",ssl:r.ssl});let n=Ig([...PT,...Eg(NT)]);for(let r of jg(n))t.some(s=>s.host===r)||t.push({host:r,server:"caddy",ssl:!0});return t.slice(0,60)}var su,Ag,$g,Cg,Pg,Ng,CT,PT,NT,Dg=X(()=>{"use strict";su=E(require("node:fs"),1),Ag=E(require("node:path"),1),$g=require("node:child_process"),Cg=require("node:util"),Pg=(0,Cg.promisify)($g.execFile),Ng=1e4;CT=["/etc/nginx/sites-enabled","/etc/nginx/conf.d"],PT=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile"],NT=["/etc/caddy/conf.d"]});var Kg={};De(Kg,{collectServerInventory:()=>HT,parseContainers:()=>Bg,parseListeningPorts:()=>lr,parseProcesses:()=>Hg,parseServices:()=>Ba});async function hi(t,e){try{let{stdout:n}=await OT(t,e,{timeout:zT,maxBuffer:4e6});return n}catch{return""}}function Ba(t){return t.split(`
1193
1156
  `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=/^(\S+)\.service\s+\S+\s+(\S+)\s+running\s+(.*)$/.exec(e);return n?{name:n[1],description:n[3].slice(0,120),active:n[2]}:null}).filter(e=>e!==null).slice(0,150)}function Bg(t){return t.split(`
1194
1157
  `).filter(Boolean).map(e=>{let[n,r="",s="",i=""]=e.split(" ");return{name:n,image:r.slice(0,120),status:s.slice(0,80),ports:i.slice(0,200)}}).filter(e=>e.name).slice(0,60)}function lr(t){let e=new Map;for(let n of t.split(`
1195
1158
  `)){if(!n.trim())continue;let s=n.trim().split(/\s+/)[3]??"",i=Number(s.slice(s.lastIndexOf(":")+1));if(!Number.isFinite(i)||i<=0)continue;let a=/users:\(\("([^"]+)",pid=(\d+)/.exec(n);e.has(i)||e.set(i,{port:i,process:a?.[1]??"",pid:a?Number(a[2]):0})}return[...e.values()].sort((n,r)=>n.port-r.port).slice(0,150)}function Hg(t){return t.split(`
1196
- `).slice(1).map(e=>{let n=/^\s*(\d+)\s+(\S+)\s+([\d.]+)\s+([\d.]+)\s+(.*)$/.exec(e);return n?{pid:Number(n[1]),user:n[2].slice(0,30),cpuPct:Number(n[3]),memPct:Number(n[4]),command:n[5].slice(0,160)}:null}).filter(e=>e!==null).slice(0,40)}function BT(){let t=[],e=LT.map(r=>({dir:r,depth:0})),n=0;for(;e.length&&t.length<Fg&&n<qT;){let{dir:r,depth:s}=e.shift();n++;let i;try{i=Lg.default.readdirSync(r,{withFileTypes:!0})}catch{continue}if(i.some(a=>a.name===".git"&&a.isDirectory())){t.push(r);continue}if(!(s>=UT))for(let a of i)a.isDirectory()&&!a.isSymbolicLink()&&!FT.has(a.name)&&!a.name.startsWith(".")&&e.push({dir:Fa.default.join(r,a.name),depth:s+1})}return t}async function HT(t){let e=new Map;for(let[s,i]of Object.entries(t.repos))e.set(Fa.default.resolve(i.path),s);let n=[...new Set([...e.keys(),...BT().map(s=>Fa.default.resolve(s))])];return(await Promise.all(n.slice(0,Fg).map(async s=>({path:s,repoName:e.get(s)??"",remoteUrl:(await hi("git",["-C",s,"config","--get","remote.origin.url"])).trim().replace(/\/\/[^@/]+@/,"//").slice(0,200),branch:(await hi("git",["-C",s,"rev-parse","--abbrev-ref","HEAD"])).trim().slice(0,80)})))).sort((s,i)=>(s.repoName?0:1)-(i.repoName?0:1)||s.path.localeCompare(i.path))}async function KT(t){let[e,n,r,s,i]=await Promise.all([HT(t),hi("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain","--no-pager"]).then(Ba),hi("docker",["ps","--format","{{.Names}} {{.Image}} {{.Status}} {{.Ports}}"]).then(Bg),hi("ss",["-tlnpH"]).then(lr),hi("ps",["axo","pid,user,pcpu,pmem,args","--sort=-pmem"]).then(Hg)]);return{checkouts:e,services:n,containers:r,ports:s,processes:i}}var Lg,Fa,Ug,qg,zT,DT,LT,UT,qT,Fg,FT,mo=X(()=>{"use strict";Lg=E(require("node:fs"),1),Fa=E(require("node:path"),1),Ug=require("node:child_process"),qg=require("node:util"),zT=(0,qg.promisify)(Ug.execFile),DT=8e3,LT=["/opt","/var/www","/srv","/home","/root"],UT=3,qT=800,Fg=60,FT=new Set(["node_modules",".git","dist","build",".next","vendor",".cache","snap"])});var cu={};De(cu,{buildManifest:()=>ty,checkAuthActivity:()=>nR,checkCronBaseline:()=>QT,checkPortsBaseline:()=>YT,checkProcessHog:()=>cR,checkUsersBaseline:()=>JT,checkWebrootIntegrity:()=>iR,checkWordpress:()=>oR,clearBaseline:()=>GT,diffHashMap:()=>Ga,diffPorts:()=>Xg,findPhpInUploads:()=>ny,hogVerdict:()=>ry,loadBaseline:()=>ms,parseNetstatListeners:()=>Jg,parsePasswd:()=>Qg,saveBaseline:()=>Nn});function au(){try{return WT.parse(JSON.parse(Ee.default.readFileSync(Ha(),"utf8")))}catch{return{baselines:{}}}}function Yg(t){Ee.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Ha()+".tmp";Ee.default.writeFileSync(e,JSON.stringify(t,null,2)+`
1197
- `,{mode:384}),Ee.default.renameSync(e,Ha()),Ee.default.chmodSync(Ha(),384)}function ms(t){let e=au().baselines[t];return e||null}function Nn(t,e){let n=au();n.baselines[t]={recordedAt:new Date().toISOString(),data:e},Yg(n)}function GT(t){let e=au(),n=Object.keys(e.baselines).filter(r=>r===t||r.startsWith(`${t}:`));if(n.length){for(let r of n)delete e.baselines[r];Yg(e)}}function Wa(t,e){return{status:"green",summary:`baseline recorded - ${e} ${t}`}}function Jg(t){let e=new Map;for(let n of t.split(`
1198
- `)){let r=/^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(n);if(!r)continue;let s=Number(r[2]),i=r[1]==="0.0.0.0"||r[1]==="[::]",a=e.get(s);e.set(s,{port:s,process:`pid ${r[3]}`,all:(a?.all??!1)||i})}return[...e.values()].sort((n,r)=>n.port-r.port).slice(0,200)}function Xg(t,e){let n=new Set(t.map(i=>i.port)),r=new Set(e.map(i=>i.port)),s=e.filter(i=>!n.has(i.port));return{added:s,removed:t.filter(i=>!r.has(i.port)),exposed:s.filter(i=>i.all)}}async function VT(){if(process.platform==="win32"){let{stdout:n}=await pi("netstat",["-ano"],{timeout:ou,maxBuffer:4e6});return Jg(n)}let{stdout:t}=await pi("ss",["-tlnpH"],{timeout:ou,maxBuffer:4e6}),e=new Set;for(let n of t.split(`
1199
- `)){let s=n.trim().split(/\s+/)[3]??"",i=/:(\d+)$/.exec(s);i&&(s.startsWith("0.0.0.0:")||s.startsWith("[::]:")||s.startsWith("*:"))&&e.add(Number(i[1]))}return lr(t).map(n=>({port:n.port,process:n.process,all:e.has(n.port)}))}async function YT(t){let e=await VT(),n=ms(t.id);if(!n)return Nn(t.id,e),Wa("listening port(s)",e.length);let r=Xg(n.data,e),s={listening:e.length,added:r.added.length,removed:r.removed.length};return r.exposed.length?{status:"red",summary:`NEW port(s) listening on every interface: ${r.exposed.map(i=>`${i.port} (${i.process})`).join(", ")}`.slice(0,300),metrics:s,excerpt:`baseline recorded ${n.recordedAt}
1159
+ `).slice(1).map(e=>{let n=/^\s*(\d+)\s+(\S+)\s+([\d.]+)\s+([\d.]+)\s+(.*)$/.exec(e);return n?{pid:Number(n[1]),user:n[2].slice(0,30),cpuPct:Number(n[3]),memPct:Number(n[4]),command:n[5].slice(0,160)}:null}).filter(e=>e!==null).slice(0,40)}function FT(){let t=[],e=DT.map(r=>({dir:r,depth:0})),n=0;for(;e.length&&t.length<Fg&&n<UT;){let{dir:r,depth:s}=e.shift();n++;let i;try{i=Lg.default.readdirSync(r,{withFileTypes:!0})}catch{continue}if(i.some(a=>a.name===".git"&&a.isDirectory())){t.push(r);continue}if(!(s>=LT))for(let a of i)a.isDirectory()&&!a.isSymbolicLink()&&!qT.has(a.name)&&!a.name.startsWith(".")&&e.push({dir:Fa.default.join(r,a.name),depth:s+1})}return t}async function BT(t){let e=new Map;for(let[s,i]of Object.entries(t.repos))e.set(Fa.default.resolve(i.path),s);let n=[...new Set([...e.keys(),...FT().map(s=>Fa.default.resolve(s))])];return(await Promise.all(n.slice(0,Fg).map(async s=>({path:s,repoName:e.get(s)??"",remoteUrl:(await hi("git",["-C",s,"config","--get","remote.origin.url"])).trim().replace(/\/\/[^@/]+@/,"//").slice(0,200),branch:(await hi("git",["-C",s,"rev-parse","--abbrev-ref","HEAD"])).trim().slice(0,80)})))).sort((s,i)=>(s.repoName?0:1)-(i.repoName?0:1)||s.path.localeCompare(i.path))}async function HT(t){let[e,n,r,s,i]=await Promise.all([BT(t),hi("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain","--no-pager"]).then(Ba),hi("docker",["ps","--format","{{.Names}} {{.Image}} {{.Status}} {{.Ports}}"]).then(Bg),hi("ss",["-tlnpH"]).then(lr),hi("ps",["axo","pid,user,pcpu,pmem,args","--sort=-pmem"]).then(Hg)]);return{checkouts:e,services:n,containers:r,ports:s,processes:i}}var Lg,Fa,Ug,qg,OT,zT,DT,LT,UT,Fg,qT,mo=X(()=>{"use strict";Lg=E(require("node:fs"),1),Fa=E(require("node:path"),1),Ug=require("node:child_process"),qg=require("node:util"),OT=(0,qg.promisify)(Ug.execFile),zT=8e3,DT=["/opt","/var/www","/srv","/home","/root"],LT=3,UT=800,Fg=60,qT=new Set(["node_modules",".git","dist","build",".next","vendor",".cache","snap"])});var cu={};De(cu,{buildManifest:()=>ty,checkAuthActivity:()=>tR,checkCronBaseline:()=>XT,checkPortsBaseline:()=>VT,checkProcessHog:()=>aR,checkUsersBaseline:()=>YT,checkWebrootIntegrity:()=>sR,checkWordpress:()=>iR,clearBaseline:()=>WT,diffHashMap:()=>Ga,diffPorts:()=>Xg,findPhpInUploads:()=>ny,hogVerdict:()=>ry,loadBaseline:()=>ms,parseNetstatListeners:()=>Jg,parsePasswd:()=>Qg,saveBaseline:()=>Nn});function au(){try{return KT.parse(JSON.parse(Ee.default.readFileSync(Ha(),"utf8")))}catch{return{baselines:{}}}}function Yg(t){Ee.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Ha()+".tmp";Ee.default.writeFileSync(e,JSON.stringify(t,null,2)+`
1160
+ `,{mode:384}),Ee.default.renameSync(e,Ha()),Ee.default.chmodSync(Ha(),384)}function ms(t){let e=au().baselines[t];return e||null}function Nn(t,e){let n=au();n.baselines[t]={recordedAt:new Date().toISOString(),data:e},Yg(n)}function WT(t){let e=au(),n=Object.keys(e.baselines).filter(r=>r===t||r.startsWith(`${t}:`));if(n.length){for(let r of n)delete e.baselines[r];Yg(e)}}function Wa(t,e){return{status:"green",summary:`baseline recorded - ${e} ${t}`}}function Jg(t){let e=new Map;for(let n of t.split(`
1161
+ `)){let r=/^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(n);if(!r)continue;let s=Number(r[2]),i=r[1]==="0.0.0.0"||r[1]==="[::]",a=e.get(s);e.set(s,{port:s,process:`pid ${r[3]}`,all:(a?.all??!1)||i})}return[...e.values()].sort((n,r)=>n.port-r.port).slice(0,200)}function Xg(t,e){let n=new Set(t.map(i=>i.port)),r=new Set(e.map(i=>i.port)),s=e.filter(i=>!n.has(i.port));return{added:s,removed:t.filter(i=>!r.has(i.port)),exposed:s.filter(i=>i.all)}}async function ZT(){if(process.platform==="win32"){let{stdout:n}=await pi("netstat",["-ano"],{timeout:ou,maxBuffer:4e6});return Jg(n)}let{stdout:t}=await pi("ss",["-tlnpH"],{timeout:ou,maxBuffer:4e6}),e=new Set;for(let n of t.split(`
1162
+ `)){let s=n.trim().split(/\s+/)[3]??"",i=/:(\d+)$/.exec(s);i&&(s.startsWith("0.0.0.0:")||s.startsWith("[::]:")||s.startsWith("*:"))&&e.add(Number(i[1]))}return lr(t).map(n=>({port:n.port,process:n.process,all:e.has(n.port)}))}async function VT(t){let e=await ZT(),n=ms(t.id);if(!n)return Nn(t.id,e),Wa("listening port(s)",e.length);let r=Xg(n.data,e),s={listening:e.length,added:r.added.length,removed:r.removed.length};return r.exposed.length?{status:"red",summary:`NEW port(s) listening on every interface: ${r.exposed.map(i=>`${i.port} (${i.process})`).join(", ")}`.slice(0,300),metrics:s,excerpt:`baseline recorded ${n.recordedAt}
1200
1163
  added: ${r.added.map(i=>`${i.port} ${i.process}${i.all?" [0.0.0.0]":""}`).join(", ")||"-"}
1201
1164
  removed: ${r.removed.map(i=>i.port).join(", ")||"-"}`}:r.added.length?{status:"amber",summary:`new port(s) since the baseline: ${r.added.map(i=>`${i.port} (${i.process})`).join(", ")}`.slice(0,300),metrics:s,excerpt:`baseline recorded ${n.recordedAt}
1202
1165
  removed: ${r.removed.map(i=>i.port).join(", ")||"-"}`}:{status:"green",summary:`${e.length} listening port(s), unchanged since ${n.recordedAt.slice(0,10)}${r.removed.length?` (${r.removed.length} closed)`:""}`,metrics:s}}function Qg(t){return t.split(`
1203
- `).map(e=>e.split(":")).filter(e=>e.length>=3&&e[0]).map(e=>({name:e[0],uid:Number(e[2])})).filter(e=>Number.isFinite(e.uid)).slice(0,500)}async function JT(t){let e=Qg(Ee.default.readFileSync("/etc/passwd","utf8")),n=ms(t.id);if(!n)return Nn(t.id,e),Wa("account(s)",e.length);let r=new Set(n.data.map(l=>l.name)),s=e.filter(l=>!r.has(l.name)),i=s.filter(l=>l.uid===0),a=n.data.filter(l=>!e.some(d=>d.name===l.name)),c={accounts:e.length,added:s.length,removed:a.length};return i.length?{status:"red",summary:`NEW uid-0 account(s): ${i.map(l=>l.name).join(", ")} - this is how persistence looks`.slice(0,300),metrics:c}:s.length?{status:"amber",summary:`new account(s) since the baseline: ${s.map(l=>`${l.name} (uid ${l.uid})`).join(", ")}`.slice(0,300),metrics:c}:{status:"green",summary:`${e.length} account(s), unchanged since ${n.recordedAt.slice(0,10)}`,metrics:c}}function XT(){let t=[];Ee.default.existsSync("/etc/crontab")&&t.push("/etc/crontab");for(let e of["/etc/cron.d","/var/spool/cron/crontabs","/var/spool/cron"])try{for(let n of Ee.default.readdirSync(e).slice(0,100)){let r=Pt.default.join(e,n);Ee.default.statSync(r).isFile()&&t.push(r)}}catch{}return t.slice(0,200)}function ey(t){let e={};for(let n of t)try{e[n]=ZT(Ee.default.readFileSync(n))}catch{}return e}function Ga(t,e){let n=Object.keys(e).filter(i=>!(i in t)),r=Object.keys(e).filter(i=>i in t&&t[i]!==e[i]),s=Object.keys(t).filter(i=>!(i in e));return{added:n,changed:r,removed:s}}async function QT(t){let e=ey(XT()),n=ms(t.id);if(!n)return Nn(t.id,e),Wa("cron file(s)",Object.keys(e).length);let r=Ga(n.data,e),s=[...r.added,...r.changed,...r.removed];return s.length?{status:"amber",summary:`cron changed since the baseline: ${s.slice(0,5).join(", ")}${s.length>5?` +${s.length-5} more`:""}`.slice(0,300),metrics:{added:r.added.length,changed:r.changed.length,removed:r.removed.length},excerpt:`baseline recorded ${n.recordedAt}
1166
+ `).map(e=>e.split(":")).filter(e=>e.length>=3&&e[0]).map(e=>({name:e[0],uid:Number(e[2])})).filter(e=>Number.isFinite(e.uid)).slice(0,500)}async function YT(t){let e=Qg(Ee.default.readFileSync("/etc/passwd","utf8")),n=ms(t.id);if(!n)return Nn(t.id,e),Wa("account(s)",e.length);let r=new Set(n.data.map(l=>l.name)),s=e.filter(l=>!r.has(l.name)),i=s.filter(l=>l.uid===0),a=n.data.filter(l=>!e.some(d=>d.name===l.name)),c={accounts:e.length,added:s.length,removed:a.length};return i.length?{status:"red",summary:`NEW uid-0 account(s): ${i.map(l=>l.name).join(", ")} - this is how persistence looks`.slice(0,300),metrics:c}:s.length?{status:"amber",summary:`new account(s) since the baseline: ${s.map(l=>`${l.name} (uid ${l.uid})`).join(", ")}`.slice(0,300),metrics:c}:{status:"green",summary:`${e.length} account(s), unchanged since ${n.recordedAt.slice(0,10)}`,metrics:c}}function JT(){let t=[];Ee.default.existsSync("/etc/crontab")&&t.push("/etc/crontab");for(let e of["/etc/cron.d","/var/spool/cron/crontabs","/var/spool/cron"])try{for(let n of Ee.default.readdirSync(e).slice(0,100)){let r=Pt.default.join(e,n);Ee.default.statSync(r).isFile()&&t.push(r)}}catch{}return t.slice(0,200)}function ey(t){let e={};for(let n of t)try{e[n]=GT(Ee.default.readFileSync(n))}catch{}return e}function Ga(t,e){let n=Object.keys(e).filter(i=>!(i in t)),r=Object.keys(e).filter(i=>i in t&&t[i]!==e[i]),s=Object.keys(t).filter(i=>!(i in e));return{added:n,changed:r,removed:s}}async function XT(t){let e=ey(JT()),n=ms(t.id);if(!n)return Nn(t.id,e),Wa("cron file(s)",Object.keys(e).length);let r=Ga(n.data,e),s=[...r.added,...r.changed,...r.removed];return s.length?{status:"amber",summary:`cron changed since the baseline: ${s.slice(0,5).join(", ")}${s.length>5?` +${s.length-5} more`:""}`.slice(0,300),metrics:{added:r.added.length,changed:r.changed.length,removed:r.removed.length},excerpt:`baseline recorded ${n.recordedAt}
1204
1167
  added: ${r.added.join(`
1205
1168
  `)||"-"}
1206
1169
  changed: ${r.changed.join(`
1207
1170
  `)||"-"}
1208
1171
  removed: ${r.removed.join(`
1209
- `)||"-"}`.slice(0,Ka)}:{status:"green",summary:`${Object.keys(e).length} cron file(s), unchanged since ${n.recordedAt.slice(0,10)}`,metrics:{files:Object.keys(e).length}}}function eR(){let t=[];for(let e of["/root/.ssh/authorized_keys","/etc/sudoers"])Ee.default.existsSync(e)&&t.push(e);try{for(let e of Ee.default.readdirSync("/home").slice(0,50)){let n=Pt.default.join("/home",e,".ssh","authorized_keys");Ee.default.existsSync(n)&&t.push(n)}}catch{}try{for(let e of Ee.default.readdirSync("/etc/sudoers.d").slice(0,50))t.push(Pt.default.join("/etc/sudoers.d",e))}catch{}return t.slice(0,120)}function tR(t,e){try{let n=Ee.default.statSync(t),r=Math.min(n.size,e*1024),s=Ee.default.openSync(t,"r"),i=Buffer.alloc(r);return Ee.default.readSync(s,i,0,r,n.size-r),Ee.default.closeSync(s),i.toString("utf8")}catch{return""}}async function nR(t,e){let n=ey(eR()),r=ms(t.id);if(!r)return Nn(t.id,n),Wa("access-grant file(s)",Object.keys(n).length);let s=Ga(r.data,n),i=[...s.added,...s.changed];if(i.length)return{status:"red",summary:`access grants changed since the baseline: ${i.slice(0,3).join(", ")}${i.length>3?` +${i.length-3} more`:""} - a new key or sudoers entry is how access persists`.slice(0,300),excerpt:`baseline recorded ${r.recordedAt}
1172
+ `)||"-"}`.slice(0,Ka)}:{status:"green",summary:`${Object.keys(e).length} cron file(s), unchanged since ${n.recordedAt.slice(0,10)}`,metrics:{files:Object.keys(e).length}}}function QT(){let t=[];for(let e of["/root/.ssh/authorized_keys","/etc/sudoers"])Ee.default.existsSync(e)&&t.push(e);try{for(let e of Ee.default.readdirSync("/home").slice(0,50)){let n=Pt.default.join("/home",e,".ssh","authorized_keys");Ee.default.existsSync(n)&&t.push(n)}}catch{}try{for(let e of Ee.default.readdirSync("/etc/sudoers.d").slice(0,50))t.push(Pt.default.join("/etc/sudoers.d",e))}catch{}return t.slice(0,120)}function eR(t,e){try{let n=Ee.default.statSync(t),r=Math.min(n.size,e*1024),s=Ee.default.openSync(t,"r"),i=Buffer.alloc(r);return Ee.default.readSync(s,i,0,r,n.size-r),Ee.default.closeSync(s),i.toString("utf8")}catch{return""}}async function tR(t,e){let n=ey(QT()),r=ms(t.id);if(!r)return Nn(t.id,n),Wa("access-grant file(s)",Object.keys(n).length);let s=Ga(r.data,n),i=[...s.added,...s.changed];if(i.length)return{status:"red",summary:`access grants changed since the baseline: ${i.slice(0,3).join(", ")}${i.length>3?` +${i.length-3} more`:""} - a new key or sudoers entry is how access persists`.slice(0,300),excerpt:`baseline recorded ${r.recordedAt}
1210
1173
  added: ${s.added.join(`
1211
1174
  `)||"-"}
1212
1175
  changed: ${s.changed.join(`
1213
- `)||"-"}`.slice(0,Ka)};let a=["/var/log/auth.log","/var/log/secure"].find(l=>Ee.default.existsSync(l)),c=0;return a&&(c=(tR(a,512).match(/Failed password|Invalid user/g)??[]).length),c>=e.failedWarnCount?{status:"amber",summary:`${c} failed-login lines in ${a}'s tail (warn at ${e.failedWarnCount}) - likely a brute-force run`,metrics:{failedLogins:c}}:{status:"green",summary:`grants unchanged since ${r.recordedAt.slice(0,10)}${a?`, ${c} failed login(s) in the log tail`:""}`,metrics:{failedLogins:c}}}function ty(t,e){let n={},r=[t],s=0;for(;r.length&&s<Wg;){let i=r.shift(),a;try{a=Ee.default.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let c of a){let l=Pt.default.join(i,c.name),d=Pt.default.relative(t,l);if(!e.some(p=>d===p||d.includes(`${p}/`)||d.includes(`/${p}`)||c.name===p)&&!c.isSymbolicLink()){if(c.isDirectory())r.push(l);else if(c.isFile()){s++;try{let p=Ee.default.statSync(l);n[d]=`${p.size}:${Math.round(p.mtimeMs)}`}catch{}if(s>=Wg)break}}}}return n}async function sR(t){try{let{stdout:e}=await pi("git",["-C",t,"rev-parse","HEAD"],{timeout:1e4});return e.trim()}catch{return""}}async function iR(t,e){if(!e.roots?.length)return{status:"error",summary:"no webroot paths configured"};let n=[];for(let a of e.roots.slice(0,10)){if(!Ee.default.existsSync(a)){n.push({root:a,status:"error",detail:"path does not exist",excerptLines:[]});continue}let c=`${t.id}:${a}`,l=await sR(a),d=ty(a,e.excludes),p=ms(c);if(!p){Nn(c,{manifest:d,gitHead:l}),n.push({root:a,status:"green",detail:`baseline recorded - ${Object.keys(d).length} files`,excerptLines:[]});continue}if(l&&p.data.gitHead&&l!==p.data.gitHead){Nn(c,{manifest:d,gitHead:l}),n.push({root:a,status:"green",detail:`moved with a deploy (${p.data.gitHead.slice(0,8)} \u2192 ${l.slice(0,8)}) - baseline refreshed`,excerptLines:[]});continue}let f=Ga(p.data.manifest,d),g=[...f.added,...f.changed,...f.removed];if(!g.length){n.push({root:a,status:"green",detail:`${Object.keys(d).length} files, unchanged since ${p.recordedAt.slice(0,10)}`,excerptLines:[]});continue}let v=[...f.changed,...f.added].filter(k=>rR.includes(Pt.default.basename(k)));n.push({root:a,status:v.length?"red":"amber",detail:v.length?`CRITICAL file(s) changed: ${v.slice(0,3).join(", ")} (+${g.length-v.length} other changes)`:`${f.added.length} added, ${f.changed.length} changed, ${f.removed.length} removed since the baseline`,excerptLines:[`== ${a} (baseline ${p.recordedAt})`,...f.added.slice(0,20).map(k=>`+ ${k}`),...f.changed.slice(0,20).map(k=>`~ ${k}`),...f.removed.slice(0,10).map(k=>`- ${k}`)]})}let s=["error","red","amber","green"].find(a=>n.some(c=>c.status===a))??"green",i=n.find(a=>a.status===s);return{status:s,summary:`${i.root}: ${i.detail}`.slice(0,300),metrics:{roots:n.map(a=>({root:a.root,status:a.status}))},excerpt:n.flatMap(a=>a.excerptLines).join(`
1214
- `).slice(0,Ka)}}function ny(t){let e=Pt.default.join(t,"wp-content","uploads"),n=[],r=[e],s=0;for(;r.length&&s<1e4&&n.length<50;){let i=r.shift(),a;try{a=Ee.default.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let c of a){s++;let l=Pt.default.join(i,c.name);c.isDirectory()?r.push(l):/\.ph(p\d?|tml)$/i.test(c.name)&&n.push(Pt.default.relative(t,l))}}return n}async function oR(t,e){if(!e.wpPaths?.length)return{status:"error",summary:"no WordPress paths configured"};let n=[],r="green",s=p=>{let f={error:0,red:1,amber:2,green:3};f[p]<f[r]&&(r=p)},i="",a={},c=`${t.id}:admins`,l=ms(c),d={};for(let p of e.wpPaths.slice(0,10)){if(!Ee.default.existsSync(Pt.default.join(p,"wp-config.php"))){s("error"),i=i||`${p}: no wp-config.php here`,n.push(`== ${p}: no wp-config.php - is this the right path?`);continue}let f=ny(p);f.length&&(s("red"),i=i||`${p}: PHP file(s) inside wp-content/uploads: ${f[0]}${f.length>1?` +${f.length-1} more`:""}`,n.push(`== ${p}: PHP in uploads (webshell signature)`,...f.slice(0,20).map(g=>` ${g}`)));try{await pi("wp",["core","verify-checksums","--path",p,"--allow-root"],{timeout:12e4,maxBuffer:1e6}),n.push(`== ${p}: core checksums verify`)}catch(g){let v=g;v.code==="ENOENT"?n.push(`== ${p}: wp-cli not installed - checksum step skipped (install wp-cli to enable it)`):(s("red"),i=i||`${p}: wp core verify-checksums FAILED - core files differ from wordpress.org`,n.push(`== ${p}: checksum failures`,(v.stderr??"").split(`
1176
+ `)||"-"}`.slice(0,Ka)};let a=["/var/log/auth.log","/var/log/secure"].find(l=>Ee.default.existsSync(l)),c=0;return a&&(c=(eR(a,512).match(/Failed password|Invalid user/g)??[]).length),c>=e.failedWarnCount?{status:"amber",summary:`${c} failed-login lines in ${a}'s tail (warn at ${e.failedWarnCount}) - likely a brute-force run`,metrics:{failedLogins:c}}:{status:"green",summary:`grants unchanged since ${r.recordedAt.slice(0,10)}${a?`, ${c} failed login(s) in the log tail`:""}`,metrics:{failedLogins:c}}}function ty(t,e){let n={},r=[t],s=0;for(;r.length&&s<Wg;){let i=r.shift(),a;try{a=Ee.default.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let c of a){let l=Pt.default.join(i,c.name),d=Pt.default.relative(t,l);if(!e.some(p=>d===p||d.includes(`${p}/`)||d.includes(`/${p}`)||c.name===p)&&!c.isSymbolicLink()){if(c.isDirectory())r.push(l);else if(c.isFile()){s++;try{let p=Ee.default.statSync(l);n[d]=`${p.size}:${Math.round(p.mtimeMs)}`}catch{}if(s>=Wg)break}}}}return n}async function rR(t){try{let{stdout:e}=await pi("git",["-C",t,"rev-parse","HEAD"],{timeout:1e4});return e.trim()}catch{return""}}async function sR(t,e){if(!e.roots?.length)return{status:"error",summary:"no webroot paths configured"};let n=[];for(let a of e.roots.slice(0,10)){if(!Ee.default.existsSync(a)){n.push({root:a,status:"error",detail:"path does not exist",excerptLines:[]});continue}let c=`${t.id}:${a}`,l=await rR(a),d=ty(a,e.excludes),p=ms(c);if(!p){Nn(c,{manifest:d,gitHead:l}),n.push({root:a,status:"green",detail:`baseline recorded - ${Object.keys(d).length} files`,excerptLines:[]});continue}if(l&&p.data.gitHead&&l!==p.data.gitHead){Nn(c,{manifest:d,gitHead:l}),n.push({root:a,status:"green",detail:`moved with a deploy (${p.data.gitHead.slice(0,8)} \u2192 ${l.slice(0,8)}) - baseline refreshed`,excerptLines:[]});continue}let f=Ga(p.data.manifest,d),g=[...f.added,...f.changed,...f.removed];if(!g.length){n.push({root:a,status:"green",detail:`${Object.keys(d).length} files, unchanged since ${p.recordedAt.slice(0,10)}`,excerptLines:[]});continue}let v=[...f.changed,...f.added].filter(k=>nR.includes(Pt.default.basename(k)));n.push({root:a,status:v.length?"red":"amber",detail:v.length?`CRITICAL file(s) changed: ${v.slice(0,3).join(", ")} (+${g.length-v.length} other changes)`:`${f.added.length} added, ${f.changed.length} changed, ${f.removed.length} removed since the baseline`,excerptLines:[`== ${a} (baseline ${p.recordedAt})`,...f.added.slice(0,20).map(k=>`+ ${k}`),...f.changed.slice(0,20).map(k=>`~ ${k}`),...f.removed.slice(0,10).map(k=>`- ${k}`)]})}let s=["error","red","amber","green"].find(a=>n.some(c=>c.status===a))??"green",i=n.find(a=>a.status===s);return{status:s,summary:`${i.root}: ${i.detail}`.slice(0,300),metrics:{roots:n.map(a=>({root:a.root,status:a.status}))},excerpt:n.flatMap(a=>a.excerptLines).join(`
1177
+ `).slice(0,Ka)}}function ny(t){let e=Pt.default.join(t,"wp-content","uploads"),n=[],r=[e],s=0;for(;r.length&&s<1e4&&n.length<50;){let i=r.shift(),a;try{a=Ee.default.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let c of a){s++;let l=Pt.default.join(i,c.name);c.isDirectory()?r.push(l):/\.ph(p\d?|tml)$/i.test(c.name)&&n.push(Pt.default.relative(t,l))}}return n}async function iR(t,e){if(!e.wpPaths?.length)return{status:"error",summary:"no WordPress paths configured"};let n=[],r="green",s=p=>{let f={error:0,red:1,amber:2,green:3};f[p]<f[r]&&(r=p)},i="",a={},c=`${t.id}:admins`,l=ms(c),d={};for(let p of e.wpPaths.slice(0,10)){if(!Ee.default.existsSync(Pt.default.join(p,"wp-config.php"))){s("error"),i=i||`${p}: no wp-config.php here`,n.push(`== ${p}: no wp-config.php - is this the right path?`);continue}let f=ny(p);f.length&&(s("red"),i=i||`${p}: PHP file(s) inside wp-content/uploads: ${f[0]}${f.length>1?` +${f.length-1} more`:""}`,n.push(`== ${p}: PHP in uploads (webshell signature)`,...f.slice(0,20).map(g=>` ${g}`)));try{await pi("wp",["core","verify-checksums","--path",p,"--allow-root"],{timeout:12e4,maxBuffer:1e6}),n.push(`== ${p}: core checksums verify`)}catch(g){let v=g;v.code==="ENOENT"?n.push(`== ${p}: wp-cli not installed - checksum step skipped (install wp-cli to enable it)`):(s("red"),i=i||`${p}: wp core verify-checksums FAILED - core files differ from wordpress.org`,n.push(`== ${p}: checksum failures`,(v.stderr??"").split(`
1215
1178
  `).slice(0,20).join(`
1216
1179
  `)))}try{let{stdout:g}=await pi("wp",["user","list","--role=administrator","--field=user_login","--path",p,"--allow-root"],{timeout:6e4}),v=g.split(`
1217
1180
  `).map(T=>T.trim()).filter(Boolean).slice(0,100);d[p]=v;let k=l?.data[p];if(k){let T=v.filter(_=>!k.includes(_));T.length&&(a[p]=T,s("red"),i=i||`${p}: NEW administrator account(s): ${T.join(", ")}`)}}catch{}}if(l){let p={...l.data};for(let[f,g]of Object.entries(d))f in p||(p[f]=g);Object.keys(p).length!==Object.keys(l.data).length&&Nn(c,p)}else Object.keys(d).length&&(Nn(c,d),n.push(`admin baseline recorded: ${Object.entries(d).map(([p,f])=>`${p}=${f.length}`).join(", ")}`));return{status:r,summary:(i||`${e.wpPaths.length} WordPress site(s) clean`).slice(0,300),metrics:{sites:e.wpPaths.length,newAdmins:Object.values(a).flat().length},excerpt:n.join(`
1218
- `).slice(0,Ka)}}function ry(t,e){let n=t.filter(i=>i.cpuPct>=e);if(!n.length)return{status:"green",note:""};let r=n.find(i=>aR.some(a=>i.command.startsWith(a)||i.command.includes(` ${a}`)));if(r)return{status:"red",note:`pid ${r.pid} at ${r.cpuPct}% runs from a scratch directory (${r.command.slice(0,120)}) - the classic miner signature`};let s=n[0];return{status:"amber",note:`pid ${s.pid} (${s.command.slice(0,120)}) at ${s.cpuPct}% CPU`}}async function cR(t,e){let{stdout:n}=await pi("ps",["axo","pid,pcpu,args","--sort=-pcpu"],{timeout:ou,maxBuffer:2e6}),r=n.split(`
1219
- `).slice(1,21).map(i=>i.trim().split(/\s+/)).filter(i=>i.length>=3).map(i=>({pid:Number(i[0]),cpuPct:Number(i[1]),command:i.slice(2).join(" ")})),s=ry(r,e.cpuPct);return{status:s.status,summary:s.note||`nothing over ${e.cpuPct}% CPU`,metrics:{top:r.slice(0,5).map(i=>({pid:i.pid,cpuPct:i.cpuPct,command:i.command.slice(0,80)}))}}}var Ee,Pt,Gg,Zg,Vg,pi,ou,Ka,WT,Ha,ZT,Wg,rR,aR,lu=X(()=>{"use strict";Ee=E(require("node:fs"),1),Pt=E(require("node:path"),1),Gg=E(require("node:crypto"),1),Zg=require("node:child_process"),Vg=require("node:util");_t();Ae();mo();pi=(0,Vg.promisify)(Zg.execFile),ou=3e4,Ka=4e3,WT=S.object({baselines:S.record(S.object({recordedAt:S.string(),data:S.unknown()})).default({})}),Ha=()=>Pt.default.join(te(),"monitor-baselines.json");ZT=t=>Gg.default.createHash("sha256").update(t).digest("hex");Wg=2e4;rR=["wp-config.php",".htaccess","index.php","web.config"];aR=["/tmp/","/dev/shm/","/var/tmp/"]});function mi(){return ec.default.join(te(),"runner.pid")}function Qa(){return ec.default.join(te(),"runner.log")}function gy(){et.default.mkdirSync(te(),{recursive:!0,mode:448});let t=et.default.openSync(Qa(),"a",384);try{et.default.chmodSync(Qa(),384)}catch{}return t}function bs(){let t=mi();if(!et.default.existsSync(t))return null;let e=Number(et.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function GR(t){try{return process.kill(t,0),!0}catch{return!1}}function yy(){try{return et.default.readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim()||null}catch{return null}}function ZR(t){let e;try{e=et.default.readFileSync(`/proc/${t}/cmdline`,"utf8")}catch{return null}return e?/allwright|ticketpilot|cli\.(js|ts|cjs|mjs)/i.test(e):null}function ws(t){return GR(t)?ZR(t)!==!1:!1}function by(t){et.default.mkdirSync(te(),{recursive:!0,mode:448}),et.default.writeFileSync(mi(),String(t),{mode:384})}function wy(t){bs()===t&&et.default.rmSync(mi(),{force:!0})}function hu(){return ec.default.join(te(),"runner.lock")}function vy(){let t;try{t=et.default.readFileSync(hu(),"utf8").trim()}catch{return null}let e,n=null;if(t.startsWith("{"))try{let r=JSON.parse(t);e=Number(r.pid),n=typeof r.boot=="string"?r.boot:null}catch{return null}else e=Number(t);return Number.isFinite(e)&&e>0?{pid:e,boot:n}:null}function gi(){let t=vy();if(!t||t.pid===process.pid)return null;let e=yy();return t.boot&&e&&t.boot!==e?null:ws(t.pid)?t.pid:null}function ky(){let t=gi();return t?{ok:!1,pid:t}:(et.default.mkdirSync(te(),{recursive:!0,mode:448}),et.default.writeFileSync(hu(),JSON.stringify({pid:process.pid,boot:yy()}),{mode:384}),{ok:!0})}function pu(){try{vy()?.pid===process.pid&&et.default.rmSync(hu(),{force:!0})}catch{}}function Sy(t){try{let e=et.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var et,ec,fu=X(()=>{"use strict";et=E(require("node:fs"),1),ec=E(require("node:path"),1);Ae()});var Ny={};De(Ny,{LEGACY_SERVICE_NAME:()=>bi,SERVICE_NAME:()=>ur,UNIT_PATH:()=>mu,buildSystemdUnit:()=>ic,detectServiceParams:()=>sc,hasSystemd:()=>oc,installService:()=>yu,installedServiceName:()=>ku,protectionDropIn:()=>vu,removeLocalConfig:()=>Cy,removeServiceUnit:()=>Py,runnerConfigPaths:()=>$y,selfHealServiceProtection:()=>QR,serviceProtection:()=>yo,stopService:()=>ac,uninstallRunner:()=>cc,uninstallService:()=>wu});function sc(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||rc.default.userInfo().username,n=t?yi.default.join("/home",t):rc.default.homedir();return{nodePath:process.execPath,scriptPath:un.default.realpathSync(process.argv[1]),user:e,home:n}}function ic(t){let e=yi.default.dirname(t.nodePath);return`[Unit]
1181
+ `).slice(0,Ka)}}function ry(t,e){let n=t.filter(i=>i.cpuPct>=e);if(!n.length)return{status:"green",note:""};let r=n.find(i=>oR.some(a=>i.command.startsWith(a)||i.command.includes(` ${a}`)));if(r)return{status:"red",note:`pid ${r.pid} at ${r.cpuPct}% runs from a scratch directory (${r.command.slice(0,120)}) - the classic miner signature`};let s=n[0];return{status:"amber",note:`pid ${s.pid} (${s.command.slice(0,120)}) at ${s.cpuPct}% CPU`}}async function aR(t,e){let{stdout:n}=await pi("ps",["axo","pid,pcpu,args","--sort=-pcpu"],{timeout:ou,maxBuffer:2e6}),r=n.split(`
1182
+ `).slice(1,21).map(i=>i.trim().split(/\s+/)).filter(i=>i.length>=3).map(i=>({pid:Number(i[0]),cpuPct:Number(i[1]),command:i.slice(2).join(" ")})),s=ry(r,e.cpuPct);return{status:s.status,summary:s.note||`nothing over ${e.cpuPct}% CPU`,metrics:{top:r.slice(0,5).map(i=>({pid:i.pid,cpuPct:i.cpuPct,command:i.command.slice(0,80)}))}}}var Ee,Pt,Gg,Zg,Vg,pi,ou,Ka,KT,Ha,GT,Wg,nR,oR,lu=X(()=>{"use strict";Ee=E(require("node:fs"),1),Pt=E(require("node:path"),1),Gg=E(require("node:crypto"),1),Zg=require("node:child_process"),Vg=require("node:util");_t();Ae();mo();pi=(0,Vg.promisify)(Zg.execFile),ou=3e4,Ka=4e3,KT=S.object({baselines:S.record(S.object({recordedAt:S.string(),data:S.unknown()})).default({})}),Ha=()=>Pt.default.join(te(),"monitor-baselines.json");GT=t=>Gg.default.createHash("sha256").update(t).digest("hex");Wg=2e4;nR=["wp-config.php",".htaccess","index.php","web.config"];oR=["/tmp/","/dev/shm/","/var/tmp/"]});function mi(){return ec.default.join(te(),"runner.pid")}function Qa(){return ec.default.join(te(),"runner.log")}function gy(){et.default.mkdirSync(te(),{recursive:!0,mode:448});let t=et.default.openSync(Qa(),"a",384);try{et.default.chmodSync(Qa(),384)}catch{}return t}function bs(){let t=mi();if(!et.default.existsSync(t))return null;let e=Number(et.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function WR(t){try{return process.kill(t,0),!0}catch{return!1}}function yy(){try{return et.default.readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim()||null}catch{return null}}function GR(t){let e;try{e=et.default.readFileSync(`/proc/${t}/cmdline`,"utf8")}catch{return null}return e?/allwright|ticketpilot|cli\.(js|ts|cjs|mjs)/i.test(e):null}function ws(t){return WR(t)?GR(t)!==!1:!1}function by(t){et.default.mkdirSync(te(),{recursive:!0,mode:448}),et.default.writeFileSync(mi(),String(t),{mode:384})}function wy(t){bs()===t&&et.default.rmSync(mi(),{force:!0})}function hu(){return ec.default.join(te(),"runner.lock")}function vy(){let t;try{t=et.default.readFileSync(hu(),"utf8").trim()}catch{return null}let e,n=null;if(t.startsWith("{"))try{let r=JSON.parse(t);e=Number(r.pid),n=typeof r.boot=="string"?r.boot:null}catch{return null}else e=Number(t);return Number.isFinite(e)&&e>0?{pid:e,boot:n}:null}function gi(){let t=vy();if(!t||t.pid===process.pid)return null;let e=yy();return t.boot&&e&&t.boot!==e?null:ws(t.pid)?t.pid:null}function ky(){let t=gi();return t?{ok:!1,pid:t}:(et.default.mkdirSync(te(),{recursive:!0,mode:448}),et.default.writeFileSync(hu(),JSON.stringify({pid:process.pid,boot:yy()}),{mode:384}),{ok:!0})}function pu(){try{vy()?.pid===process.pid&&et.default.rmSync(hu(),{force:!0})}catch{}}function Sy(t){try{let e=et.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var et,ec,fu=X(()=>{"use strict";et=E(require("node:fs"),1),ec=E(require("node:path"),1);Ae()});var Ny={};De(Ny,{LEGACY_SERVICE_NAME:()=>bi,SERVICE_NAME:()=>ur,UNIT_PATH:()=>mu,buildSystemdUnit:()=>ic,detectServiceParams:()=>sc,hasSystemd:()=>oc,installService:()=>yu,installedServiceName:()=>ku,protectionDropIn:()=>vu,removeLocalConfig:()=>Cy,removeServiceUnit:()=>Py,runnerConfigPaths:()=>$y,selfHealServiceProtection:()=>XR,serviceProtection:()=>yo,stopService:()=>ac,uninstallRunner:()=>cc,uninstallService:()=>wu});function sc(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||rc.default.userInfo().username,n=t?yi.default.join("/home",t):rc.default.homedir();return{nodePath:process.execPath,scriptPath:un.default.realpathSync(process.argv[1]),user:e,home:n}}function ic(t){let e=yi.default.dirname(t.nodePath);return`[Unit]
1220
1183
  Description=Allwright runner
1221
1184
  After=network-online.target
1222
1185
 
@@ -1245,18 +1208,18 @@ WantedBy=multi-user.target
1245
1208
  nssm start Allwright
1246
1209
  schtasks: schtasks /Create /TN Allwright /SC ONSTART /RU SYSTEM /TR "\\"${process.execPath}\\" \\"${un.default.realpathSync(process.argv[1]??"")}\\" start --foreground"
1247
1210
  Then set ALLWRIGHT_CONFIG_DIR to a stable data dir (e.g. %ProgramData%\\Allwright) so the config survives profile changes.`:"no systemd on this machine - run `allwright start` (background mode) instead");let e=sc(),n=ic(e);if(typeof process.getuid=="function"&&process.getuid()!==0){t.info("Root is needed to write the unit. Re-run as:"),t.info(' sudo env "PATH=$PATH" allwright service install'),t.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),t.info(""),t.info(`This is exactly what it will write to ${mu}:`),t.info(`
1248
- `+n);return}try{(0,ft.execFileSync)("systemctl",["disable","--now",bi]),t.info(`stopped the old ${bi} service - this one replaces it`)}catch{}let r=gi();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}un.default.writeFileSync(mu,n),(0,ft.execFileSync)("systemctl",["daemon-reload"]),(0,ft.execFileSync)("systemctl",["enable","--now",ur]),(0,ft.execFileSync)("systemctl",["restart",ur]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${ur} -f`),t.info("Status: allwright service status")}function $y(t){if(t.override)return[yi.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=yi.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function JR(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[rc.default.homedir()];return t&&e.push(yi.default.join("/home",t)),$y({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function Cy(){let t={removed:!1,paths:[],problems:[]};for(let e of JR())if(un.default.existsSync(e))try{un.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 bu(){return typeof process.getuid!="function"||process.getuid()===0}function gu(t){if(bu()){(0,ft.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,ft.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function XR(t){if(bu()){un.default.rmSync(t);return}(0,ft.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function Py(){if(!oc())return{removed:!1,absent:!0,error:""};let t=[ur,bi].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>un.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{gu(["disable",e.name])}catch{}XR(e.file)}return gu(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:bu()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function ac(){if(oc())for(let t of[ur,bi])try{gu(["stop",t])}catch{}}function cc(){let t=Py(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${Ay.RUNNER_UNINSTALL_COMMAND}`),e;let n=Cy();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function wu(t){let e=cc();e.serviceRemoved?(ac(),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 vu(t){let e=`/etc/systemd/system/${t}.service.d`;return{dir:e,file:`${e}/override.conf`,content:`[Service]
1211
+ `+n);return}try{(0,ft.execFileSync)("systemctl",["disable","--now",bi]),t.info(`stopped the old ${bi} service - this one replaces it`)}catch{}let r=gi();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}un.default.writeFileSync(mu,n),(0,ft.execFileSync)("systemctl",["daemon-reload"]),(0,ft.execFileSync)("systemctl",["enable","--now",ur]),(0,ft.execFileSync)("systemctl",["restart",ur]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${ur} -f`),t.info("Status: allwright service status")}function $y(t){if(t.override)return[yi.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=yi.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function YR(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[rc.default.homedir()];return t&&e.push(yi.default.join("/home",t)),$y({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function Cy(){let t={removed:!1,paths:[],problems:[]};for(let e of YR())if(un.default.existsSync(e))try{un.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 bu(){return typeof process.getuid!="function"||process.getuid()===0}function gu(t){if(bu()){(0,ft.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,ft.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function JR(t){if(bu()){un.default.rmSync(t);return}(0,ft.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function Py(){if(!oc())return{removed:!1,absent:!0,error:""};let t=[ur,bi].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>un.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{gu(["disable",e.name])}catch{}JR(e.file)}return gu(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:bu()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function ac(){if(oc())for(let t of[ur,bi])try{gu(["stop",t])}catch{}}function cc(){let t=Py(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${Ay.RUNNER_UNINSTALL_COMMAND}`),e;let n=Cy();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function wu(t){let e=cc();e.serviceRemoved?(ac(),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 vu(t){let e=`/etc/systemd/system/${t}.service.d`;return{dir:e,file:`${e}/override.conf`,content:`[Service]
1249
1212
  KillMode=mixed
1250
1213
  TimeoutStopSec=2h
1251
- `}}function ku(){for(let t of[ur,bi])try{if((0,ft.execFileSync)("systemctl",["show",t,"-p","LoadState"],{encoding:"utf8"}).includes("LoadState=loaded"))return t}catch{}return""}function yo(){let t=ku();if(!t)return{protected:null,fixCommand:""};let e=vu(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,ft.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 QR(){let t=yo();if(t.protected!==!1)return t.protected===!0;let e=ku();if(!e)return!1;let n=vu(e);try{return(0,ft.execFileSync)("sudo",["-n","mkdir","-p",n.dir],{stdio:"ignore"}),(0,ft.execFileSync)("sudo",["-n","tee",n.file],{input:n.content,stdio:["pipe","ignore","ignore"]}),(0,ft.execFileSync)("sudo",["-n","systemctl","daemon-reload"],{stdio:"ignore"}),yo().protected===!0}catch{return!1}}var ft,un,rc,yi,Ay,ur,mu,bi,lc=X(()=>{"use strict";ft=require("node:child_process"),un=E(require("node:fs"),1),rc=E(require("node:os"),1),yi=E(require("node:path"),1),Ay=E(Ne(),1);fu();ur="allwright",mu=`/etc/systemd/system/${ur}.service`,bi="ticketpilot-runner"});var Ky={};De(Ky,{MAX_CHAIN_DEPTH:()=>_u,breakChain:()=>Iu,breakSingleModeChain:()=>Cu,chainOf:()=>Tu,chainSessionFor:()=>fc,loadBatchPlan:()=>xu,nextMemberWillChain:()=>Pu,parsePlanAnswer:()=>Nu,recordChainSession:()=>Ru,recordSingleModeSession:()=>Au,saveBatchPlan:()=>tI,singleModeChainIntact:()=>$u,singleModeSessionFor:()=>Eu});function tI(t){wi.default.mkdirSync(Su(),{recursive:!0,mode:448}),wi.default.writeFileSync(pc.default.join(Su(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function xu(t){if(!t)return null;try{return JSON.parse(wi.default.readFileSync(pc.default.join(Su(),`${t}.json`),"utf8"))}catch{return null}}function Tu(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function fc(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=jn.get(hc(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=_u||!wi.default.existsSync(s.worktreePath)?null:s}function Ru(t,e,n,r){let s=jn.get(hc(t,e));jn.set(hc(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Iu(t,e){jn.delete(hc(t,e))}function Eu(t){let e=jn.get(bo(t));return!e||e.depth>=_u||!wi.default.existsSync(e.worktreePath)?null:e}function Au(t,e,n,r){let s=jn.get(bo(t));jn.set(bo(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function $u(t,e){return jn.get(bo(t))?.lastIssue===e}function Cu(t){jn.delete(bo(t))}function Pu(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function Nu(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]),d=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:a,chains:c,dependencies:l,reasoning:d}}var wi,pc,_u,Su,jn,hc,bo,mc=X(()=>{"use strict";wi=E(require("node:fs"),1),pc=E(require("node:path"),1);Ae();_u=3,Su=()=>pc.default.join(te(),"autopilot-plans");jn=new Map,hc=(t,e)=>`${t}:${e[0]}`;bo=t=>`${t}:__single__`});var On=me((UM,Cb)=>{"use strict";var Ab=["nodebuffer","arraybuffer","fragments"],$b=typeof Blob<"u";$b&&Ab.push("blob");Cb.exports={BINARY_TYPES:Ab,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:$b,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var vo=me((qM,Sc)=>{"use strict";var{EMPTY_BUFFER:AI}=On(),Bu=Buffer[Symbol.species];function $I(t,e){if(t.length===0)return AI;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 Bu(n.buffer,n.byteOffset,r):n}function Pb(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Nb(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function CI(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Hu(t){if(Hu.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Bu(t):ArrayBuffer.isView(t)?e=new Bu(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Hu.readOnly=!1),e}Sc.exports={concat:$I,mask:Pb,toArrayBuffer:CI,toBuffer:Hu,unmask:Nb};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Sc.exports.mask=function(e,n,r,s,i){i<48?Pb(e,n,r,s,i):t.mask(e,n,r,s,i)},Sc.exports.unmask=function(e,n){e.length<32?Nb(e,n):t.unmask(e,n)}}catch{}});var Ob=me((FM,jb)=>{"use strict";var Mb=Symbol("kDone"),Ku=Symbol("kRun"),Wu=class{constructor(e){this[Mb]=()=>{this.pending--,this[Ku]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ku]()}[Ku](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mb])}}};jb.exports=Wu});var Si=me((BM,Ub)=>{"use strict";var ko=require("zlib"),zb=vo(),PI=Ob(),{kStatusCode:Db}=On(),NI=Buffer[Symbol.species],MI=Buffer.from([0,0,255,255]),xc=Symbol("permessage-deflate"),zn=Symbol("total-length"),vi=Symbol("callback"),pr=Symbol("buffers"),ki=Symbol("error"),_c,Gu=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,!_c){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;_c=new PI(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[vi];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){_c.add(s=>{this._decompress(e,n,(i,a)=>{s(),r(i,a)})})}compress(e,n,r){_c.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"?ko.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ko.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xc]=this,this._inflate[zn]=0,this._inflate[pr]=[],this._inflate.on("error",OI),this._inflate.on("data",Lb)}this._inflate[vi]=r,this._inflate.write(e),n&&this._inflate.write(MI),this._inflate.flush(()=>{let i=this._inflate[ki];if(i){this._inflate.close(),this._inflate=null,r(i);return}let a=zb.concat(this._inflate[pr],this._inflate[zn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[zn]=0,this._inflate[pr]=[],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"?ko.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ko.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[zn]=0,this._deflate[pr]=[],this._deflate.on("data",jI)}this._deflate[vi]=r,this._deflate.write(e),this._deflate.flush(ko.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=zb.concat(this._deflate[pr],this._deflate[zn]);n&&(i=new NI(i.buffer,i.byteOffset,i.length-4)),this._deflate[vi]=null,this._deflate[zn]=0,this._deflate[pr]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ub.exports=Gu;function jI(t){this[pr].push(t),this[zn]+=t.length}function Lb(t){if(this[zn]+=t.length,this[xc]._maxPayload<1||this[zn]<=this[xc]._maxPayload){this[pr].push(t);return}this[ki]=new RangeError("Max payload size exceeded"),this[ki].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ki][Db]=1009,this.removeListener("data",Lb),this.reset()}function OI(t){if(this[xc]._inflate=null,this[ki]){this[vi](this[ki]);return}t[Db]=1007,this[vi](t)}});var _i=me((HM,Tc)=>{"use strict";var{isUtf8:qb}=require("buffer"),{hasBlob:zI}=On(),DI=[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 LI(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Zu(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 UI(t){return zI&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Tc.exports={isBlob:UI,isValidStatusCode:LI,isValidUTF8:Zu,tokenChars:DI};if(qb)Tc.exports.isValidUTF8=function(t){return t.length<24?Zu(t):qb(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Tc.exports.isValidUTF8=function(e){return e.length<32?Zu(e):t(e)}}catch{}});var Qu=me((KM,Zb)=>{"use strict";var{Writable:qI}=require("stream"),Fb=Si(),{BINARY_TYPES:FI,EMPTY_BUFFER:Bb,kStatusCode:BI,kWebSocket:HI}=On(),{concat:Vu,toArrayBuffer:KI,unmask:WI}=vo(),{isValidStatusCode:GI,isValidUTF8:Hb}=_i(),Rc=Buffer[Symbol.species],Mt=0,Kb=1,Wb=2,Gb=3,Yu=4,Ju=5,Ic=6,Xu=class extends qI{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||FI[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[HI]=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=Mt}_write(e,n,r){if(this._opcode===8&&this._state==Mt)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 Rc(r.buffer,r.byteOffset+e,r.length-e),new Rc(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 Rc(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 Mt:this.getInfo(e);break;case Kb:this.getPayloadLength16(e);break;case Wb:this.getPayloadLength64(e);break;case Gb:this.getMask();break;case Yu:this.getData(e);break;case Ju:case Ic: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[Fb.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=Kb:this._payloadLength===127?this._state=Wb: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=Gb:this._state=Yu}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yu}getData(e){let n=Bb;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&&WI(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=Ju,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Fb.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===Mt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Mt;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=Vu(r,n):this._binaryType==="arraybuffer"?s=KI(Vu(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Mt):(this._state=Ic,setImmediate(()=>{this.emit("message",s,!0),this._state=Mt,this.startLoop(e)}))}else{let s=Vu(r,n);if(!this._skipUTF8Validation&&!Hb(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ju||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Mt):(this._state=Ic,setImmediate(()=>{this.emit("message",s,!1),this._state=Mt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Bb),this.end();else{let r=e.readUInt16BE(0);if(!GI(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Rc(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hb(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=Mt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Mt):(this._state=Ic,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Mt,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[BI]=s,a}};Zb.exports=Xu});var nh=me((GM,Jb)=>{"use strict";var{Duplex:WM}=require("stream"),{randomFillSync:ZI}=require("crypto"),{types:{isUint8Array:VI}}=require("util"),Vb=Si(),{EMPTY_BUFFER:YI,kWebSocket:JI,NOOP:XI}=On(),{isBlob:xi,isValidStatusCode:QI}=_i(),{mask:Yb,toBuffer:Rs}=vo(),jt=Symbol("kByteLength"),eE=Buffer.alloc(4),Ec=8*1024,Is,Ti=Ec,Kt=0,tE=1,nE=2,eh=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=Kt,this.onerror=XI,this[JI]=void 0}static frame(e,n){let r,s=!1,i=2,a=!1;n.mask&&(r=n.maskBuffer||eE,n.generateMask?n.generateMask(r):(Ti===Ec&&(Is===void 0&&(Is=Buffer.alloc(Ec)),ZI(Is,0,Ec),Ti=0),r[0]=Is[Ti++],r[1]=Is[Ti++],r[2]=Is[Ti++],r[3]=Is[Ti++]),a=(r[0]|r[1]|r[2]|r[3])===0,i=6);let c;typeof e=="string"?(!n.mask||a)&&n[jt]!==void 0?c=n[jt]:(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 d=Buffer.allocUnsafe(s?c+i:i);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=l,l===126?d.writeUInt16BE(c,2):l===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),n.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],a?[d,e]:s?(Yb(e,r,d,i,c),[d]):(Yb(e,r,e,0,c),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=YI;else{if(typeof e!="number"||!QI(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(VI(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[jt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Kt?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):xi(e)?(s=e.size,i=!1):(e=Rs(e),s=e.length,i=Rs.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[jt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};xi(e)?this._state!==Kt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Kt?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):xi(e)?(s=e.size,i=!1):(e=Rs(e),s=e.length,i=Rs.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[jt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};xi(e)?this._state!==Kt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Kt?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}send(e,n,r){let s=this._extensions[Vb.extensionName],i=n.binary?2:1,a=n.compress,c,l;typeof e=="string"?(c=Buffer.byteLength(e),l=!1):xi(e)?(c=e.size,l=!1):(e=Rs(e),c=e.length,l=Rs.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 d={[jt]:c,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:a};xi(e)?this._state!==Kt?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Kt?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[jt],this._state=nE,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(th,this,c,s);return}this._bufferedBytes-=r[jt];let a=Rs(i);n?this.dispatch(a,n,r,s):(this._state=Kt,this.sendFrame(t.frame(a,r),s),this.dequeue())}).catch(i=>{process.nextTick(rE,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Vb.extensionName];this._bufferedBytes+=r[jt],this._state=tE,i.compress(e,r.fin,(a,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");th(this,l,s);return}this._bufferedBytes-=r[jt],this._state=Kt,r.readOnly=!1,this.sendFrame(t.frame(c,r),s),this.dequeue()})}dequeue(){for(;this._state===Kt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][jt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][jt],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)}};Jb.exports=eh;function th(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 rE(t,e,n){th(t,e,n),t.onerror(e)}});var ow=me((ZM,iw)=>{"use strict";var{kForOnEventAttribute:So,kListener:rh}=On(),Xb=Symbol("kCode"),Qb=Symbol("kData"),ew=Symbol("kError"),tw=Symbol("kMessage"),nw=Symbol("kReason"),Ri=Symbol("kTarget"),rw=Symbol("kType"),sw=Symbol("kWasClean"),Dn=class{constructor(e){this[Ri]=null,this[rw]=e}get target(){return this[Ri]}get type(){return this[rw]}};Object.defineProperty(Dn.prototype,"target",{enumerable:!0});Object.defineProperty(Dn.prototype,"type",{enumerable:!0});var Es=class extends Dn{constructor(e,n={}){super(e),this[Xb]=n.code===void 0?0:n.code,this[nw]=n.reason===void 0?"":n.reason,this[sw]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Xb]}get reason(){return this[nw]}get wasClean(){return this[sw]}};Object.defineProperty(Es.prototype,"code",{enumerable:!0});Object.defineProperty(Es.prototype,"reason",{enumerable:!0});Object.defineProperty(Es.prototype,"wasClean",{enumerable:!0});var Ii=class extends Dn{constructor(e,n={}){super(e),this[ew]=n.error===void 0?null:n.error,this[tw]=n.message===void 0?"":n.message}get error(){return this[ew]}get message(){return this[tw]}};Object.defineProperty(Ii.prototype,"error",{enumerable:!0});Object.defineProperty(Ii.prototype,"message",{enumerable:!0});var _o=class extends Dn{constructor(e,n={}){super(e),this[Qb]=n.data===void 0?null:n.data}get data(){return this[Qb]}};Object.defineProperty(_o.prototype,"data",{enumerable:!0});var sE={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[So]&&s[rh]===e&&!s[So])return;let r;if(t==="message")r=function(i,a){let c=new _o("message",{data:a?i:i.toString()});c[Ri]=this,Ac(e,this,c)};else if(t==="close")r=function(i,a){let c=new Es("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ri]=this,Ac(e,this,c)};else if(t==="error")r=function(i){let a=new Ii("error",{error:i,message:i.message});a[Ri]=this,Ac(e,this,a)};else if(t==="open")r=function(){let i=new Dn("open");i[Ri]=this,Ac(e,this,i)};else return;r[So]=!!n[So],r[rh]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[rh]===e&&!n[So]){this.removeListener(t,n);break}}};iw.exports={CloseEvent:Es,ErrorEvent:Ii,Event:Dn,EventTarget:sE,MessageEvent:_o};function Ac(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var $c=me((VM,aw)=>{"use strict";var{tokenChars:xo}=_i();function hn(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function iE(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,a,c,l=-1,d=-1,p=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),a===void 0)if(p===-1&&xo[d]===1)l===-1&&(l=f);else if(f!==0&&(d===32||d===9))p===-1&&l!==-1&&(p=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(l,p);d===44?(hn(e,v,n),n=Object.create(null)):a=v,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&xo[d]===1)l===-1&&(l=f);else if(d===32||d===9)p===-1&&l!==-1&&(p=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),hn(n,t.slice(l,p),!0),d===44&&(hn(e,a,n),n=Object.create(null),a=void 0),l=p=-1}else if(d===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(xo[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:r||(r=!0),s=!1}else if(i)if(xo[d]===1)l===-1&&(l=f);else if(d===34&&l!==-1)i=!1,p=f;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&xo[d]===1)l===-1&&(l=f);else if(l!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(l,p);r&&(v=v.replace(/\\/g,""),r=!1),hn(n,c,v),d===44&&(hn(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||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let g=t.slice(l,p);return a===void 0?hn(e,g,n):(c===void 0?hn(n,g,!0):r?hn(n,c,g.replace(/\\/g,"")):hn(n,c,g),hn(e,a,n)),e}function oE(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(", ")}aw.exports={format:oE,parse:iE}});var Mc=me((XM,ww)=>{"use strict";var aE=require("events"),cE=require("https"),lE=require("http"),dw=require("net"),dE=require("tls"),{randomBytes:uE,createHash:hE}=require("crypto"),{Duplex:YM,Readable:JM}=require("stream"),{URL:sh}=require("url"),fr=Si(),pE=Qu(),fE=nh(),{isBlob:mE}=_i(),{BINARY_TYPES:cw,CLOSE_TIMEOUT:gE,EMPTY_BUFFER:Cc,GUID:yE,kForOnEventAttribute:ih,kListener:bE,kStatusCode:wE,kWebSocket:He,NOOP:uw}=On(),{EventTarget:{addEventListener:vE,removeEventListener:kE}}=ow(),{format:SE,parse:_E}=$c(),{toBuffer:xE}=vo(),hw=Symbol("kAborted"),oh=[8,13],Ln=["CONNECTING","OPEN","CLOSING","CLOSED"],TE=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ce=class t extends aE{constructor(e,n,r){super(),this._binaryType=cw[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Cc,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]),pw(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){cw.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 pE({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 fE(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[He]=this,i[He]=this,e[He]=this,s.on("conclude",EE),s.on("drain",AE),s.on("error",$E),s.on("message",CE),s.on("ping",PE),s.on("pong",NE),i.onerror=ME,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",gw),e.on("data",Nc),e.on("end",yw),e.on("error",bw),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[fr.extensionName]&&this._extensions[fr.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){mt(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())}),mw(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){ah(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Cc,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){ah(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Cc,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){ah(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[fr.extensionName]||(s.compress=!1),this._sender.send(e||Cc,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){mt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ce,"CONNECTING",{enumerable:!0,value:Ln.indexOf("CONNECTING")});Object.defineProperty(Ce.prototype,"CONNECTING",{enumerable:!0,value:Ln.indexOf("CONNECTING")});Object.defineProperty(Ce,"OPEN",{enumerable:!0,value:Ln.indexOf("OPEN")});Object.defineProperty(Ce.prototype,"OPEN",{enumerable:!0,value:Ln.indexOf("OPEN")});Object.defineProperty(Ce,"CLOSING",{enumerable:!0,value:Ln.indexOf("CLOSING")});Object.defineProperty(Ce.prototype,"CLOSING",{enumerable:!0,value:Ln.indexOf("CLOSING")});Object.defineProperty(Ce,"CLOSED",{enumerable:!0,value:Ln.indexOf("CLOSED")});Object.defineProperty(Ce.prototype,"CLOSED",{enumerable:!0,value:Ln.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ce.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ce.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ih])return e[bE];return null},set(e){for(let n of this.listeners(t))if(n[ih]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ih]:!0})}})});Ce.prototype.addEventListener=vE;Ce.prototype.removeEventListener=kE;ww.exports=Ce;function pw(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:gE,protocolVersion:oh[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,!oh.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${oh.join(", ")})`);let i;if(e instanceof sh)i=e;else try{i=new sh(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;Pc(t,T);return}let d=a?443:80,p=uE(16).toString("base64"),f=a?cE.request:lE.request,g=new Set,v;if(s.createConnection=s.createConnection||(a?IE:RE),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new fr({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=SE({[fr.extensionName]:v.offer()})),n.length){for(let T of n){if(typeof T!="string"||!TE.test(T)||g.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.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 k;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[_,$]of Object.entries(T))r.headers[_.toLowerCase()]=$}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")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{mt(t,k,"Opening handshake has timed out")}),k.on("error",T=>{k===null||k[hw]||(k=t._req=null,Pc(t,T))}),k.on("response",T=>{let _=T.headers.location,$=T.statusCode;if(_&&s.followRedirects&&$>=300&&$<400){if(++t._redirects>s.maxRedirects){mt(t,k,"Maximum redirects exceeded");return}k.abort();let D;try{D=new sh(_,e)}catch{let A=new SyntaxError(`Invalid URL: ${_}`);Pc(t,A);return}pw(t,D,n,r)}else t.emit("unexpected-response",k,T)||mt(t,k,`Unexpected server response: ${T.statusCode}`)}),k.on("upgrade",(T,_,$)=>{if(t.emit("upgrade",T),t.readyState!==Ce.CONNECTING)return;k=t._req=null;let D=T.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){mt(t,_,"Invalid Upgrade header");return}let z=hE("sha1").update(p+yE).digest("base64");if(T.headers["sec-websocket-accept"]!==z){mt(t,_,"Invalid Sec-WebSocket-Accept header");return}let A=T.headers["sec-websocket-protocol"],P;if(A!==void 0?g.size?g.has(A)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":g.size&&(P="Server sent no subprotocol"),P){mt(t,_,P);return}A&&(t._protocol=A);let w=T.headers["sec-websocket-extensions"];if(w!==void 0){if(!v){mt(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=_E(w)}catch{mt(t,_,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(j);if(W.length!==1||W[0]!==fr.extensionName){mt(t,_,"Server indicated an extension that was not requested");return}try{v.accept(j[fr.extensionName])}catch{mt(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[fr.extensionName]=v}t.setSocket(_,$,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(k,t):k.end()}function Pc(t,e){t._readyState=Ce.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function RE(t){return t.path=t.socketPath,dw.connect(t)}function IE(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=dw.isIP(t.host)?"":t.host),dE.connect(t)}function mt(t,e,n){t._readyState=Ce.CLOSING;let r=new Error(n);Error.captureStackTrace(r,mt),e.setHeader?(e[hw]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pc,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ah(t,e,n){if(e){let r=mE(e)?e.size:xE(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Ln[t.readyState]})`);process.nextTick(n,r)}}function EE(t,e){let n=this[He];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[He]!==void 0&&(n._socket.removeListener("data",Nc),process.nextTick(fw,n._socket),t===1005?n.close():n.close(t,e))}function AE(){let t=this[He];t.isPaused||t._socket.resume()}function $E(t){let e=this[He];e._socket[He]!==void 0&&(e._socket.removeListener("data",Nc),process.nextTick(fw,e._socket),e.close(t[wE])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function lw(){this[He].emitClose()}function CE(t,e){this[He].emit("message",t,e)}function PE(t){let e=this[He];e._autoPong&&e.pong(t,!this._isServer,uw),e.emit("ping",t)}function NE(t){this[He].emit("pong",t)}function fw(t){t.resume()}function ME(t){let e=this[He];e.readyState!==Ce.CLOSED&&(e.readyState===Ce.OPEN&&(e._readyState=Ce.CLOSING,mw(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function mw(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function gw(){let t=this[He];if(this.removeListener("close",gw),this.removeListener("data",Nc),this.removeListener("end",yw),t._readyState=Ce.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[He]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",lw),t._receiver.on("finish",lw))}function Nc(t){this[He]._receiver.write(t)||this.pause()}function yw(){let t=this[He];t._readyState=Ce.CLOSING,t._receiver.end(),this.end()}function bw(){let t=this[He];this.removeListener("error",bw),this.on("error",uw),t&&(t._readyState=Ce.CLOSING,this.destroy())}});var _w=me((ej,Sw)=>{"use strict";var QM=Mc(),{Duplex:jE}=require("stream");function vw(t){t.emit("close")}function OE(){!this.destroyed&&this._writableState.finished&&this.destroy()}function kw(t){this.removeListener("error",kw),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function zE(t,e){let n=!0,r=new jE({...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(vw,r);return}let a=!1;t.once("error",function(l){a=!0,i(l)}),t.once("close",function(){a||i(s),process.nextTick(vw,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",OE),r.on("error",kw),r}Sw.exports=zE});var ch=me((tj,xw)=>{"use strict";var{tokenChars:DE}=_i();function LE(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&&DE[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}xw.exports={parse:LE}});var Cw=me((rj,$w)=>{"use strict";var UE=require("events"),jc=require("http"),{Duplex:nj}=require("stream"),{createHash:qE}=require("crypto"),Tw=$c(),As=Si(),FE=ch(),BE=Mc(),{CLOSE_TIMEOUT:HE,GUID:KE,kWebSocket:WE}=On(),GE=/^[+/0-9A-Za-z]{22}==$/,Rw=0,Iw=1,Aw=2,lh=class extends UE{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:HE,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:BE,...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=jc.createServer((r,s)=>{let i=jc.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=ZE(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=Rw}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===Aw){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(To,this);return}if(e&&this.once("close",e),this._state!==Iw)if(this._state=Iw,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(To,this):process.nextTick(To,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{To(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",Ew);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){$s(this,e,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){$s(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!GE.test(i)){$s(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){$s(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ro(n,400);return}let l=e.headers["sec-websocket-protocol"],d=new Set;if(l!==void 0)try{d=FE.parse(l)}catch{$s(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 g=new As({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=Tw.parse(p);v[As.extensionName]&&(g.accept(v[As.extensionName]),f[As.extensionName]=g)}catch{$s(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={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(g,(v,k,T,_)=>{if(!v)return Ro(n,k||401,T,_);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(g))return Ro(n,401)}this.completeUpgrade(f,i,d,e,n,r,s)}completeUpgrade(e,n,r,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[WE])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rw)return Ro(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${qE("sha1").update(n+KE).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[As.extensionName]){let f=e[As.extensionName].params,g=Tw.format({[As.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${g}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
1214
+ `}}function ku(){for(let t of[ur,bi])try{if((0,ft.execFileSync)("systemctl",["show",t,"-p","LoadState"],{encoding:"utf8"}).includes("LoadState=loaded"))return t}catch{}return""}function yo(){let t=ku();if(!t)return{protected:null,fixCommand:""};let e=vu(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,ft.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 XR(){let t=yo();if(t.protected!==!1)return t.protected===!0;let e=ku();if(!e)return!1;let n=vu(e);try{return(0,ft.execFileSync)("sudo",["-n","mkdir","-p",n.dir],{stdio:"ignore"}),(0,ft.execFileSync)("sudo",["-n","tee",n.file],{input:n.content,stdio:["pipe","ignore","ignore"]}),(0,ft.execFileSync)("sudo",["-n","systemctl","daemon-reload"],{stdio:"ignore"}),yo().protected===!0}catch{return!1}}var ft,un,rc,yi,Ay,ur,mu,bi,lc=X(()=>{"use strict";ft=require("node:child_process"),un=E(require("node:fs"),1),rc=E(require("node:os"),1),yi=E(require("node:path"),1),Ay=E(Ne(),1);fu();ur="allwright",mu=`/etc/systemd/system/${ur}.service`,bi="ticketpilot-runner"});var Ky={};De(Ky,{MAX_CHAIN_DEPTH:()=>_u,breakChain:()=>Iu,breakSingleModeChain:()=>Cu,chainOf:()=>Tu,chainSessionFor:()=>fc,loadBatchPlan:()=>xu,nextMemberWillChain:()=>Pu,parsePlanAnswer:()=>Nu,recordChainSession:()=>Ru,recordSingleModeSession:()=>Au,saveBatchPlan:()=>eI,singleModeChainIntact:()=>$u,singleModeSessionFor:()=>Eu});function eI(t){wi.default.mkdirSync(Su(),{recursive:!0,mode:448}),wi.default.writeFileSync(pc.default.join(Su(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function xu(t){if(!t)return null;try{return JSON.parse(wi.default.readFileSync(pc.default.join(Su(),`${t}.json`),"utf8"))}catch{return null}}function Tu(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function fc(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=jn.get(hc(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=_u||!wi.default.existsSync(s.worktreePath)?null:s}function Ru(t,e,n,r){let s=jn.get(hc(t,e));jn.set(hc(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Iu(t,e){jn.delete(hc(t,e))}function Eu(t){let e=jn.get(bo(t));return!e||e.depth>=_u||!wi.default.existsSync(e.worktreePath)?null:e}function Au(t,e,n,r){let s=jn.get(bo(t));jn.set(bo(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function $u(t,e){return jn.get(bo(t))?.lastIssue===e}function Cu(t){jn.delete(bo(t))}function Pu(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function Nu(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]),d=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:a,chains:c,dependencies:l,reasoning:d}}var wi,pc,_u,Su,jn,hc,bo,mc=X(()=>{"use strict";wi=E(require("node:fs"),1),pc=E(require("node:path"),1);Ae();_u=3,Su=()=>pc.default.join(te(),"autopilot-plans");jn=new Map,hc=(t,e)=>`${t}:${e[0]}`;bo=t=>`${t}:__single__`});var On=me((LM,Cb)=>{"use strict";var Ab=["nodebuffer","arraybuffer","fragments"],$b=typeof Blob<"u";$b&&Ab.push("blob");Cb.exports={BINARY_TYPES:Ab,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:$b,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var vo=me((UM,Sc)=>{"use strict";var{EMPTY_BUFFER:EI}=On(),Bu=Buffer[Symbol.species];function AI(t,e){if(t.length===0)return EI;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 Bu(n.buffer,n.byteOffset,r):n}function Pb(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Nb(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function $I(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Hu(t){if(Hu.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Bu(t):ArrayBuffer.isView(t)?e=new Bu(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Hu.readOnly=!1),e}Sc.exports={concat:AI,mask:Pb,toArrayBuffer:$I,toBuffer:Hu,unmask:Nb};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Sc.exports.mask=function(e,n,r,s,i){i<48?Pb(e,n,r,s,i):t.mask(e,n,r,s,i)},Sc.exports.unmask=function(e,n){e.length<32?Nb(e,n):t.unmask(e,n)}}catch{}});var Ob=me((qM,jb)=>{"use strict";var Mb=Symbol("kDone"),Ku=Symbol("kRun"),Wu=class{constructor(e){this[Mb]=()=>{this.pending--,this[Ku]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ku]()}[Ku](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mb])}}};jb.exports=Wu});var Si=me((FM,Ub)=>{"use strict";var ko=require("zlib"),zb=vo(),CI=Ob(),{kStatusCode:Db}=On(),PI=Buffer[Symbol.species],NI=Buffer.from([0,0,255,255]),xc=Symbol("permessage-deflate"),zn=Symbol("total-length"),vi=Symbol("callback"),pr=Symbol("buffers"),ki=Symbol("error"),_c,Gu=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,!_c){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;_c=new CI(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[vi];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){_c.add(s=>{this._decompress(e,n,(i,a)=>{s(),r(i,a)})})}compress(e,n,r){_c.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"?ko.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ko.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xc]=this,this._inflate[zn]=0,this._inflate[pr]=[],this._inflate.on("error",jI),this._inflate.on("data",Lb)}this._inflate[vi]=r,this._inflate.write(e),n&&this._inflate.write(NI),this._inflate.flush(()=>{let i=this._inflate[ki];if(i){this._inflate.close(),this._inflate=null,r(i);return}let a=zb.concat(this._inflate[pr],this._inflate[zn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[zn]=0,this._inflate[pr]=[],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"?ko.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ko.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[zn]=0,this._deflate[pr]=[],this._deflate.on("data",MI)}this._deflate[vi]=r,this._deflate.write(e),this._deflate.flush(ko.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=zb.concat(this._deflate[pr],this._deflate[zn]);n&&(i=new PI(i.buffer,i.byteOffset,i.length-4)),this._deflate[vi]=null,this._deflate[zn]=0,this._deflate[pr]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ub.exports=Gu;function MI(t){this[pr].push(t),this[zn]+=t.length}function Lb(t){if(this[zn]+=t.length,this[xc]._maxPayload<1||this[zn]<=this[xc]._maxPayload){this[pr].push(t);return}this[ki]=new RangeError("Max payload size exceeded"),this[ki].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ki][Db]=1009,this.removeListener("data",Lb),this.reset()}function jI(t){if(this[xc]._inflate=null,this[ki]){this[vi](this[ki]);return}t[Db]=1007,this[vi](t)}});var _i=me((BM,Tc)=>{"use strict";var{isUtf8:qb}=require("buffer"),{hasBlob:OI}=On(),zI=[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 DI(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Zu(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 LI(t){return OI&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Tc.exports={isBlob:LI,isValidStatusCode:DI,isValidUTF8:Zu,tokenChars:zI};if(qb)Tc.exports.isValidUTF8=function(t){return t.length<24?Zu(t):qb(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Tc.exports.isValidUTF8=function(e){return e.length<32?Zu(e):t(e)}}catch{}});var Qu=me((HM,Zb)=>{"use strict";var{Writable:UI}=require("stream"),Fb=Si(),{BINARY_TYPES:qI,EMPTY_BUFFER:Bb,kStatusCode:FI,kWebSocket:BI}=On(),{concat:Vu,toArrayBuffer:HI,unmask:KI}=vo(),{isValidStatusCode:WI,isValidUTF8:Hb}=_i(),Rc=Buffer[Symbol.species],Mt=0,Kb=1,Wb=2,Gb=3,Yu=4,Ju=5,Ic=6,Xu=class extends UI{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||qI[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[BI]=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=Mt}_write(e,n,r){if(this._opcode===8&&this._state==Mt)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 Rc(r.buffer,r.byteOffset+e,r.length-e),new Rc(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 Rc(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 Mt:this.getInfo(e);break;case Kb:this.getPayloadLength16(e);break;case Wb:this.getPayloadLength64(e);break;case Gb:this.getMask();break;case Yu:this.getData(e);break;case Ju:case Ic: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[Fb.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=Kb:this._payloadLength===127?this._state=Wb: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=Gb:this._state=Yu}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yu}getData(e){let n=Bb;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&&KI(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=Ju,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Fb.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===Mt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Mt;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=Vu(r,n):this._binaryType==="arraybuffer"?s=HI(Vu(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Mt):(this._state=Ic,setImmediate(()=>{this.emit("message",s,!0),this._state=Mt,this.startLoop(e)}))}else{let s=Vu(r,n);if(!this._skipUTF8Validation&&!Hb(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ju||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Mt):(this._state=Ic,setImmediate(()=>{this.emit("message",s,!1),this._state=Mt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Bb),this.end();else{let r=e.readUInt16BE(0);if(!WI(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Rc(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hb(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=Mt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Mt):(this._state=Ic,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Mt,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[FI]=s,a}};Zb.exports=Xu});var nh=me((WM,Jb)=>{"use strict";var{Duplex:KM}=require("stream"),{randomFillSync:GI}=require("crypto"),{types:{isUint8Array:ZI}}=require("util"),Vb=Si(),{EMPTY_BUFFER:VI,kWebSocket:YI,NOOP:JI}=On(),{isBlob:xi,isValidStatusCode:XI}=_i(),{mask:Yb,toBuffer:Rs}=vo(),jt=Symbol("kByteLength"),QI=Buffer.alloc(4),Ec=8*1024,Is,Ti=Ec,Kt=0,eE=1,tE=2,eh=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=Kt,this.onerror=JI,this[YI]=void 0}static frame(e,n){let r,s=!1,i=2,a=!1;n.mask&&(r=n.maskBuffer||QI,n.generateMask?n.generateMask(r):(Ti===Ec&&(Is===void 0&&(Is=Buffer.alloc(Ec)),GI(Is,0,Ec),Ti=0),r[0]=Is[Ti++],r[1]=Is[Ti++],r[2]=Is[Ti++],r[3]=Is[Ti++]),a=(r[0]|r[1]|r[2]|r[3])===0,i=6);let c;typeof e=="string"?(!n.mask||a)&&n[jt]!==void 0?c=n[jt]:(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 d=Buffer.allocUnsafe(s?c+i:i);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=l,l===126?d.writeUInt16BE(c,2):l===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),n.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],a?[d,e]:s?(Yb(e,r,d,i,c),[d]):(Yb(e,r,e,0,c),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=VI;else{if(typeof e!="number"||!XI(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(ZI(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[jt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Kt?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):xi(e)?(s=e.size,i=!1):(e=Rs(e),s=e.length,i=Rs.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[jt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};xi(e)?this._state!==Kt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Kt?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):xi(e)?(s=e.size,i=!1):(e=Rs(e),s=e.length,i=Rs.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[jt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};xi(e)?this._state!==Kt?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==Kt?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}send(e,n,r){let s=this._extensions[Vb.extensionName],i=n.binary?2:1,a=n.compress,c,l;typeof e=="string"?(c=Buffer.byteLength(e),l=!1):xi(e)?(c=e.size,l=!1):(e=Rs(e),c=e.length,l=Rs.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 d={[jt]:c,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:a};xi(e)?this._state!==Kt?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Kt?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[jt],this._state=tE,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(th,this,c,s);return}this._bufferedBytes-=r[jt];let a=Rs(i);n?this.dispatch(a,n,r,s):(this._state=Kt,this.sendFrame(t.frame(a,r),s),this.dequeue())}).catch(i=>{process.nextTick(nE,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Vb.extensionName];this._bufferedBytes+=r[jt],this._state=eE,i.compress(e,r.fin,(a,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");th(this,l,s);return}this._bufferedBytes-=r[jt],this._state=Kt,r.readOnly=!1,this.sendFrame(t.frame(c,r),s),this.dequeue()})}dequeue(){for(;this._state===Kt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][jt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][jt],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)}};Jb.exports=eh;function th(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 nE(t,e,n){th(t,e,n),t.onerror(e)}});var ow=me((GM,iw)=>{"use strict";var{kForOnEventAttribute:So,kListener:rh}=On(),Xb=Symbol("kCode"),Qb=Symbol("kData"),ew=Symbol("kError"),tw=Symbol("kMessage"),nw=Symbol("kReason"),Ri=Symbol("kTarget"),rw=Symbol("kType"),sw=Symbol("kWasClean"),Dn=class{constructor(e){this[Ri]=null,this[rw]=e}get target(){return this[Ri]}get type(){return this[rw]}};Object.defineProperty(Dn.prototype,"target",{enumerable:!0});Object.defineProperty(Dn.prototype,"type",{enumerable:!0});var Es=class extends Dn{constructor(e,n={}){super(e),this[Xb]=n.code===void 0?0:n.code,this[nw]=n.reason===void 0?"":n.reason,this[sw]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Xb]}get reason(){return this[nw]}get wasClean(){return this[sw]}};Object.defineProperty(Es.prototype,"code",{enumerable:!0});Object.defineProperty(Es.prototype,"reason",{enumerable:!0});Object.defineProperty(Es.prototype,"wasClean",{enumerable:!0});var Ii=class extends Dn{constructor(e,n={}){super(e),this[ew]=n.error===void 0?null:n.error,this[tw]=n.message===void 0?"":n.message}get error(){return this[ew]}get message(){return this[tw]}};Object.defineProperty(Ii.prototype,"error",{enumerable:!0});Object.defineProperty(Ii.prototype,"message",{enumerable:!0});var _o=class extends Dn{constructor(e,n={}){super(e),this[Qb]=n.data===void 0?null:n.data}get data(){return this[Qb]}};Object.defineProperty(_o.prototype,"data",{enumerable:!0});var rE={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[So]&&s[rh]===e&&!s[So])return;let r;if(t==="message")r=function(i,a){let c=new _o("message",{data:a?i:i.toString()});c[Ri]=this,Ac(e,this,c)};else if(t==="close")r=function(i,a){let c=new Es("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ri]=this,Ac(e,this,c)};else if(t==="error")r=function(i){let a=new Ii("error",{error:i,message:i.message});a[Ri]=this,Ac(e,this,a)};else if(t==="open")r=function(){let i=new Dn("open");i[Ri]=this,Ac(e,this,i)};else return;r[So]=!!n[So],r[rh]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[rh]===e&&!n[So]){this.removeListener(t,n);break}}};iw.exports={CloseEvent:Es,ErrorEvent:Ii,Event:Dn,EventTarget:rE,MessageEvent:_o};function Ac(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var $c=me((ZM,aw)=>{"use strict";var{tokenChars:xo}=_i();function hn(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function sE(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,a,c,l=-1,d=-1,p=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),a===void 0)if(p===-1&&xo[d]===1)l===-1&&(l=f);else if(f!==0&&(d===32||d===9))p===-1&&l!==-1&&(p=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(l,p);d===44?(hn(e,v,n),n=Object.create(null)):a=v,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&xo[d]===1)l===-1&&(l=f);else if(d===32||d===9)p===-1&&l!==-1&&(p=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),hn(n,t.slice(l,p),!0),d===44&&(hn(e,a,n),n=Object.create(null),a=void 0),l=p=-1}else if(d===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(xo[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:r||(r=!0),s=!1}else if(i)if(xo[d]===1)l===-1&&(l=f);else if(d===34&&l!==-1)i=!1,p=f;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&xo[d]===1)l===-1&&(l=f);else if(l!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(l,p);r&&(v=v.replace(/\\/g,""),r=!1),hn(n,c,v),d===44&&(hn(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||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let g=t.slice(l,p);return a===void 0?hn(e,g,n):(c===void 0?hn(n,g,!0):r?hn(n,c,g.replace(/\\/g,"")):hn(n,c,g),hn(e,a,n)),e}function iE(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(", ")}aw.exports={format:iE,parse:sE}});var Mc=me((JM,ww)=>{"use strict";var oE=require("events"),aE=require("https"),cE=require("http"),dw=require("net"),lE=require("tls"),{randomBytes:dE,createHash:uE}=require("crypto"),{Duplex:VM,Readable:YM}=require("stream"),{URL:sh}=require("url"),fr=Si(),hE=Qu(),pE=nh(),{isBlob:fE}=_i(),{BINARY_TYPES:cw,CLOSE_TIMEOUT:mE,EMPTY_BUFFER:Cc,GUID:gE,kForOnEventAttribute:ih,kListener:yE,kStatusCode:bE,kWebSocket:He,NOOP:uw}=On(),{EventTarget:{addEventListener:wE,removeEventListener:vE}}=ow(),{format:kE,parse:SE}=$c(),{toBuffer:_E}=vo(),hw=Symbol("kAborted"),oh=[8,13],Ln=["CONNECTING","OPEN","CLOSING","CLOSED"],xE=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ce=class t extends oE{constructor(e,n,r){super(),this._binaryType=cw[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Cc,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]),pw(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){cw.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 hE({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 pE(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[He]=this,i[He]=this,e[He]=this,s.on("conclude",IE),s.on("drain",EE),s.on("error",AE),s.on("message",$E),s.on("ping",CE),s.on("pong",PE),i.onerror=NE,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",gw),e.on("data",Nc),e.on("end",yw),e.on("error",bw),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[fr.extensionName]&&this._extensions[fr.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){mt(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())}),mw(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){ah(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Cc,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){ah(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Cc,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){ah(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[fr.extensionName]||(s.compress=!1),this._sender.send(e||Cc,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){mt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ce,"CONNECTING",{enumerable:!0,value:Ln.indexOf("CONNECTING")});Object.defineProperty(Ce.prototype,"CONNECTING",{enumerable:!0,value:Ln.indexOf("CONNECTING")});Object.defineProperty(Ce,"OPEN",{enumerable:!0,value:Ln.indexOf("OPEN")});Object.defineProperty(Ce.prototype,"OPEN",{enumerable:!0,value:Ln.indexOf("OPEN")});Object.defineProperty(Ce,"CLOSING",{enumerable:!0,value:Ln.indexOf("CLOSING")});Object.defineProperty(Ce.prototype,"CLOSING",{enumerable:!0,value:Ln.indexOf("CLOSING")});Object.defineProperty(Ce,"CLOSED",{enumerable:!0,value:Ln.indexOf("CLOSED")});Object.defineProperty(Ce.prototype,"CLOSED",{enumerable:!0,value:Ln.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ce.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ce.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ih])return e[yE];return null},set(e){for(let n of this.listeners(t))if(n[ih]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ih]:!0})}})});Ce.prototype.addEventListener=wE;Ce.prototype.removeEventListener=vE;ww.exports=Ce;function pw(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:mE,protocolVersion:oh[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,!oh.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${oh.join(", ")})`);let i;if(e instanceof sh)i=e;else try{i=new sh(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;Pc(t,T);return}let d=a?443:80,p=dE(16).toString("base64"),f=a?aE.request:cE.request,g=new Set,v;if(s.createConnection=s.createConnection||(a?RE:TE),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new fr({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=kE({[fr.extensionName]:v.offer()})),n.length){for(let T of n){if(typeof T!="string"||!xE.test(T)||g.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.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 k;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[_,$]of Object.entries(T))r.headers[_.toLowerCase()]=$}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")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{mt(t,k,"Opening handshake has timed out")}),k.on("error",T=>{k===null||k[hw]||(k=t._req=null,Pc(t,T))}),k.on("response",T=>{let _=T.headers.location,$=T.statusCode;if(_&&s.followRedirects&&$>=300&&$<400){if(++t._redirects>s.maxRedirects){mt(t,k,"Maximum redirects exceeded");return}k.abort();let D;try{D=new sh(_,e)}catch{let A=new SyntaxError(`Invalid URL: ${_}`);Pc(t,A);return}pw(t,D,n,r)}else t.emit("unexpected-response",k,T)||mt(t,k,`Unexpected server response: ${T.statusCode}`)}),k.on("upgrade",(T,_,$)=>{if(t.emit("upgrade",T),t.readyState!==Ce.CONNECTING)return;k=t._req=null;let D=T.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){mt(t,_,"Invalid Upgrade header");return}let z=uE("sha1").update(p+gE).digest("base64");if(T.headers["sec-websocket-accept"]!==z){mt(t,_,"Invalid Sec-WebSocket-Accept header");return}let A=T.headers["sec-websocket-protocol"],P;if(A!==void 0?g.size?g.has(A)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":g.size&&(P="Server sent no subprotocol"),P){mt(t,_,P);return}A&&(t._protocol=A);let w=T.headers["sec-websocket-extensions"];if(w!==void 0){if(!v){mt(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=SE(w)}catch{mt(t,_,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(j);if(W.length!==1||W[0]!==fr.extensionName){mt(t,_,"Server indicated an extension that was not requested");return}try{v.accept(j[fr.extensionName])}catch{mt(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[fr.extensionName]=v}t.setSocket(_,$,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(k,t):k.end()}function Pc(t,e){t._readyState=Ce.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function TE(t){return t.path=t.socketPath,dw.connect(t)}function RE(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=dw.isIP(t.host)?"":t.host),lE.connect(t)}function mt(t,e,n){t._readyState=Ce.CLOSING;let r=new Error(n);Error.captureStackTrace(r,mt),e.setHeader?(e[hw]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pc,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ah(t,e,n){if(e){let r=fE(e)?e.size:_E(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Ln[t.readyState]})`);process.nextTick(n,r)}}function IE(t,e){let n=this[He];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[He]!==void 0&&(n._socket.removeListener("data",Nc),process.nextTick(fw,n._socket),t===1005?n.close():n.close(t,e))}function EE(){let t=this[He];t.isPaused||t._socket.resume()}function AE(t){let e=this[He];e._socket[He]!==void 0&&(e._socket.removeListener("data",Nc),process.nextTick(fw,e._socket),e.close(t[bE])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function lw(){this[He].emitClose()}function $E(t,e){this[He].emit("message",t,e)}function CE(t){let e=this[He];e._autoPong&&e.pong(t,!this._isServer,uw),e.emit("ping",t)}function PE(t){this[He].emit("pong",t)}function fw(t){t.resume()}function NE(t){let e=this[He];e.readyState!==Ce.CLOSED&&(e.readyState===Ce.OPEN&&(e._readyState=Ce.CLOSING,mw(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function mw(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function gw(){let t=this[He];if(this.removeListener("close",gw),this.removeListener("data",Nc),this.removeListener("end",yw),t._readyState=Ce.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[He]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",lw),t._receiver.on("finish",lw))}function Nc(t){this[He]._receiver.write(t)||this.pause()}function yw(){let t=this[He];t._readyState=Ce.CLOSING,t._receiver.end(),this.end()}function bw(){let t=this[He];this.removeListener("error",bw),this.on("error",uw),t&&(t._readyState=Ce.CLOSING,this.destroy())}});var _w=me((QM,Sw)=>{"use strict";var XM=Mc(),{Duplex:ME}=require("stream");function vw(t){t.emit("close")}function jE(){!this.destroyed&&this._writableState.finished&&this.destroy()}function kw(t){this.removeListener("error",kw),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function OE(t,e){let n=!0,r=new ME({...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(vw,r);return}let a=!1;t.once("error",function(l){a=!0,i(l)}),t.once("close",function(){a||i(s),process.nextTick(vw,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",jE),r.on("error",kw),r}Sw.exports=OE});var ch=me((ej,xw)=>{"use strict";var{tokenChars:zE}=_i();function DE(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&&zE[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}xw.exports={parse:DE}});var Cw=me((nj,$w)=>{"use strict";var LE=require("events"),jc=require("http"),{Duplex:tj}=require("stream"),{createHash:UE}=require("crypto"),Tw=$c(),As=Si(),qE=ch(),FE=Mc(),{CLOSE_TIMEOUT:BE,GUID:HE,kWebSocket:KE}=On(),WE=/^[+/0-9A-Za-z]{22}==$/,Rw=0,Iw=1,Aw=2,lh=class extends LE{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:BE,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:FE,...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=jc.createServer((r,s)=>{let i=jc.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=GE(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=Rw}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===Aw){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(To,this);return}if(e&&this.once("close",e),this._state!==Iw)if(this._state=Iw,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(To,this):process.nextTick(To,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{To(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",Ew);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){$s(this,e,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){$s(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!WE.test(i)){$s(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){$s(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ro(n,400);return}let l=e.headers["sec-websocket-protocol"],d=new Set;if(l!==void 0)try{d=qE.parse(l)}catch{$s(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 g=new As({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=Tw.parse(p);v[As.extensionName]&&(g.accept(v[As.extensionName]),f[As.extensionName]=g)}catch{$s(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={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(g,(v,k,T,_)=>{if(!v)return Ro(n,k||401,T,_);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(g))return Ro(n,401)}this.completeUpgrade(f,i,d,e,n,r,s)}completeUpgrade(e,n,r,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[KE])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rw)return Ro(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${UE("sha1").update(n+HE).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[As.extensionName]){let f=e[As.extensionName].params,g=Tw.format({[As.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${g}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
1252
1215
  `).join(`\r
1253
- `)),i.removeListener("error",Ew),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(To,this)})),c(p,s)}};$w.exports=lh;function ZE(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 To(t){t._state=Aw,t.emit("close")}function Ew(){this.destroy()}function Ro(t,e,n,r){n=n||jc.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} ${jc.STATUS_CODES[e]}\r
1216
+ `)),i.removeListener("error",Ew),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(To,this)})),c(p,s)}};$w.exports=lh;function GE(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 To(t){t._state=Aw,t.emit("close")}function Ew(){this.destroy()}function Ro(t,e,n,r){n=n||jc.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} ${jc.STATUS_CODES[e]}\r
1254
1217
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
1255
1218
  `)+`\r
1256
1219
  \r
1257
- `+n)}function $s(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,$s),t.emit("wsClientError",a,n,e)}else Ro(n,r,s,i)}});var Uw={};De(Uw,{CATALOGUE:()=>gh,catalogueForPrompt:()=>yh,describeDiagnostic:()=>fA,runDiagnostic:()=>mA});function yh(){return["service_status {unit} - is a systemd service running, and why not","service_logs {unit, lines<=200} - a service's recent journal","listeners {} - what is listening on which port","disk_space {} - disk usage","dir_list {path} - list an absolute path","read_file {path, lines<=200} - the head of a file (credential stores are refused)","http_check {url} - status code and timing of one GET","git_state {path} - a checkout's branch and last commits"].join(`
1258
- `)}function fA(t){let e=gh[t.command];return e?e.describe(t.args??{}):null}async function mA(t){let e=gh[t.command];if(!e)return{ok:!1,commandLine:t.command,output:"refused: not in the catalogue"};let n=e.build(t.args??{}),r=e.describe(t.args??{});return typeof n=="string"?{ok:!1,commandLine:r,output:n}:new Promise(s=>{(0,Lw.execFile)(n[0],n.slice(1),{timeout:hA,maxBuffer:2e6},(i,a,c)=>{let l=`${a??""}${c?`
1259
- ${c}`:""}`.trim(),d=Cd(l).slice(0,pA)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:d})})})}var Lw,mh,hA,pA,zw,Dw,fh,zt,qc,gh,bh=X(()=>{"use strict";Lw=require("node:child_process"),mh=E(require("node:fs"),1);Pd();hA=1e4,pA=8e3,zw=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Dw=/^[a-zA-Z0-9@._-]{1,80}$/,fh=/^\/[^\0\n]{1,300}$/,zt=t=>typeof t=="string"?t.trim():"",qc=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},gh={service_status:{describe:t=>`systemctl status ${zt(t.unit)}`,build:t=>{let e=zt(t.unit);return Dw.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${zt(t.unit)} -n ${qc(t.lines,200,50)}`,build:t=>{let e=zt(t.unit);return Dw.test(e)?["journalctl","-u",e,"-n",String(qc(t.lines,200,50)),"--no-pager"]:"refused: that is not a plausible unit name"}},listeners:{describe:()=>"ss -ltnp (what is listening on which port)",build:()=>["ss","-ltnp"]},disk_space:{describe:()=>"df -h (disk usage)",build:()=>["df","-h"]},dir_list:{describe:t=>`ls -la ${zt(t.path)}`,build:t=>{let e=zt(t.path);return fh.test(e)?zw.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${qc(t.lines,200,100)} ${zt(t.path)}`,build:t=>{let e=zt(t.path);if(!fh.test(e))return"refused: absolute path required";if(zw.test(e))return"refused: that path can hold credentials";try{if(mh.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(qc(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${zt(t.url)}`,build:t=>{let e=zt(t.url);return/^https?:\/\/[^\s'"]{1,300}$/.test(e)?["curl","-sS","-o","/dev/null","-w","HTTP %{http_code}, %{time_total}s","--max-time","10",e]:"refused: a plain http(s) URL only"}},git_state:{describe:t=>`git -C ${zt(t.path)} status + last 3 commits`,build:t=>{let e=zt(t.path);return fh.test(e)?mh.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Xw={};De(Xw,{MANAGED_MARKER:()=>Po,caddyBlock:()=>Ai,checkoutOwner:()=>Jw,detectApp:()=>Bw,envPrepare:()=>bA,nginxBlock:()=>Ao,nodeBinDir:()=>Fw,ownsProxyFile:()=>Vw,pickPort:()=>Kw,portsClaimedByUnits:()=>Hw,resolveProxyChoice:()=>Yw,spliceCaddyBlock:()=>Zw,spliceManagedBlock:()=>vh,sudoersText:()=>Gw,unitSlug:()=>qw,unitText:()=>Ww});function qw(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Fw(t){let e=n=>{try{let r=(0,pn.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?Wt.default.dirname(r):null}catch{return null}};return t&&t!==Co.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function Bw(t){let e=Wt.default.join(t,"package.json");if(!Pe.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(Pe.default.readFileSync(e,"utf8"))}catch{return{kind:"unknown",reason:"package.json could not be parsed"}}return n.scripts?.start?{kind:"node-start"}:{kind:"static"}}function Hw(){let t=new Set;try{for(let e of Pe.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=Pe.default.readFileSync(Wt.default.join("/etc/systemd/system",e),"utf8");for(let r of n.matchAll(/^Environment=PORT=(\d+)$/gm))t.add(Number(r[1]))}catch{}}catch{}return t}async function Kw(t){let e=Hw(),n=r=>new Promise(s=>{let i=wh.default.createServer();i.once("error",()=>s(!1)),i.listen(r,"127.0.0.1",()=>i.close(()=>s(!0)))});if(t){if(!await n(t))throw new Error(`port ${t} is already in use on this machine - pick another`);return t}for(let r=3e3;r<3100;r++)if(!e.has(r)&&await n(r))return r;throw new Error("no free port found between 3000 and 3099 - pass one with --port")}function Ww(t){return`${Po}
1220
+ `+n)}function $s(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,$s),t.emit("wsClientError",a,n,e)}else Ro(n,r,s,i)}});var Uw={};De(Uw,{CATALOGUE:()=>gh,catalogueForPrompt:()=>yh,describeDiagnostic:()=>pA,runDiagnostic:()=>fA});function yh(){return["service_status {unit} - is a systemd service running, and why not","service_logs {unit, lines<=200} - a service's recent journal","listeners {} - what is listening on which port","disk_space {} - disk usage","dir_list {path} - list an absolute path","read_file {path, lines<=200} - the head of a file (credential stores are refused)","http_check {url} - status code and timing of one GET","git_state {path} - a checkout's branch and last commits"].join(`
1221
+ `)}function pA(t){let e=gh[t.command];return e?e.describe(t.args??{}):null}async function fA(t){let e=gh[t.command];if(!e)return{ok:!1,commandLine:t.command,output:"refused: not in the catalogue"};let n=e.build(t.args??{}),r=e.describe(t.args??{});return typeof n=="string"?{ok:!1,commandLine:r,output:n}:new Promise(s=>{(0,Lw.execFile)(n[0],n.slice(1),{timeout:uA,maxBuffer:2e6},(i,a,c)=>{let l=`${a??""}${c?`
1222
+ ${c}`:""}`.trim(),d=Cd(l).slice(0,hA)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:d})})})}var Lw,mh,uA,hA,zw,Dw,fh,zt,qc,gh,bh=X(()=>{"use strict";Lw=require("node:child_process"),mh=E(require("node:fs"),1);Pd();uA=1e4,hA=8e3,zw=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Dw=/^[a-zA-Z0-9@._-]{1,80}$/,fh=/^\/[^\0\n]{1,300}$/,zt=t=>typeof t=="string"?t.trim():"",qc=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},gh={service_status:{describe:t=>`systemctl status ${zt(t.unit)}`,build:t=>{let e=zt(t.unit);return Dw.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${zt(t.unit)} -n ${qc(t.lines,200,50)}`,build:t=>{let e=zt(t.unit);return Dw.test(e)?["journalctl","-u",e,"-n",String(qc(t.lines,200,50)),"--no-pager"]:"refused: that is not a plausible unit name"}},listeners:{describe:()=>"ss -ltnp (what is listening on which port)",build:()=>["ss","-ltnp"]},disk_space:{describe:()=>"df -h (disk usage)",build:()=>["df","-h"]},dir_list:{describe:t=>`ls -la ${zt(t.path)}`,build:t=>{let e=zt(t.path);return fh.test(e)?zw.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${qc(t.lines,200,100)} ${zt(t.path)}`,build:t=>{let e=zt(t.path);if(!fh.test(e))return"refused: absolute path required";if(zw.test(e))return"refused: that path can hold credentials";try{if(mh.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(qc(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${zt(t.url)}`,build:t=>{let e=zt(t.url);return/^https?:\/\/[^\s'"]{1,300}$/.test(e)?["curl","-sS","-o","/dev/null","-w","HTTP %{http_code}, %{time_total}s","--max-time","10",e]:"refused: a plain http(s) URL only"}},git_state:{describe:t=>`git -C ${zt(t.path)} status + last 3 commits`,build:t=>{let e=zt(t.path);return fh.test(e)?mh.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Xw={};De(Xw,{MANAGED_MARKER:()=>Po,caddyBlock:()=>Ai,checkoutOwner:()=>Jw,detectApp:()=>Bw,envPrepare:()=>yA,nginxBlock:()=>Ao,nodeBinDir:()=>Fw,ownsProxyFile:()=>Vw,pickPort:()=>Kw,portsClaimedByUnits:()=>Hw,resolveProxyChoice:()=>Yw,spliceCaddyBlock:()=>Zw,spliceManagedBlock:()=>vh,sudoersText:()=>Gw,unitSlug:()=>qw,unitText:()=>Ww});function qw(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Fw(t){let e=n=>{try{let r=(0,pn.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?Wt.default.dirname(r):null}catch{return null}};return t&&t!==Co.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function Bw(t){let e=Wt.default.join(t,"package.json");if(!Pe.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(Pe.default.readFileSync(e,"utf8"))}catch{return{kind:"unknown",reason:"package.json could not be parsed"}}return n.scripts?.start?{kind:"node-start"}:{kind:"static"}}function Hw(){let t=new Set;try{for(let e of Pe.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=Pe.default.readFileSync(Wt.default.join("/etc/systemd/system",e),"utf8");for(let r of n.matchAll(/^Environment=PORT=(\d+)$/gm))t.add(Number(r[1]))}catch{}}catch{}return t}async function Kw(t){let e=Hw(),n=r=>new Promise(s=>{let i=wh.default.createServer();i.once("error",()=>s(!1)),i.listen(r,"127.0.0.1",()=>i.close(()=>s(!0)))});if(t){if(!await n(t))throw new Error(`port ${t} is already in use on this machine - pick another`);return t}for(let r=3e3;r<3100;r++)if(!e.has(r)&&await n(r))return r;throw new Error("no free port found between 3000 and 3099 - pass one with --port")}function Ww(t){return`${Po}
1260
1223
  [Unit]
1261
1224
  Description=${t.repoName} ${t.envName} (Allwright-prepared)
1262
1225
  After=network-online.target
@@ -1307,7 +1270,7 @@ server {
1307
1270
  # END allwright ${t.slug}`}function vh(t,e,n){let r=`# BEGIN allwright ${e}`,s=`# END allwright ${e}`,i=t.indexOf(r);if(i!==-1){let a=t.indexOf(s,i);if(a!==-1)return t.slice(0,i)+n+t.slice(a+s.length)}return t.replace(/\s*$/,"")+`
1308
1271
 
1309
1272
  `+n+`
1310
- `}function Zw(t,e,n){return vh(t,e,n)}function Vw(t){return t.trim()===""||t.includes("# BEGIN allwright ")||t.includes(Po)}function Yw(t){let{flag:e,caddyActive:n,nginxActive:r}=t;return e!==void 0&&e!=="caddy"&&e!=="nginx"&&e!=="none"?{error:`--proxy must be caddy, nginx or none (got "${e}")`}:e==="none"?{mode:"none"}:e==="caddy"&&r&&!n?{error:"nginx is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy nginx (or stop nginx first); this command never sets up a second proxy alongside a live one."}:e==="nginx"&&n&&!r?{error:"caddy is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy caddy (or stop caddy first); this command never sets up a second proxy alongside a live one."}:e==="caddy"||e==="nginx"?{mode:e}:n?{mode:"caddy"}:r?{mode:"nginx"}:{mode:"print-both"}}function Jw(t){let e=Pe.default.statSync(t).uid;if(e===0)throw new Error(`${t} is owned by root. A web app must not run as root - chown the checkout to the user that deploys it first (sudo chown -R <user>: ${t}).`);try{return(0,pn.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return Co.default.userInfo().username}}function je(t,e){(0,pn.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function gA(t){if(t.sudoers){let e=Wt.default.join(Co.default.tmpdir(),`allwright-sudoers-${process.pid}`);Pe.default.writeFileSync(e,t.content,{mode:384});try{(0,pn.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),je(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{Pe.default.rmSync(e,{force:!0})}return}je(["mkdir","-p",Wt.default.dirname(t.path)]),je(["tee",t.path],t.content),je(["chmod",t.mode,t.path])}function yA(t){try{return Pe.default.readFileSync(t,"utf8").includes(Po)}catch{return!0}}async function bA(t){if(!Pe.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!Pe.default.existsSync(Wt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=Bw(t.dir);if(e.kind==="unknown")throw new Error(`cannot prepare this checkout: ${e.reason}. Write the service by hand, or ask in Compose - this command only automates what it can verify.`);let n=Yw({flag:t.proxy,caddyActive:$o("caddy"),nginxActive:$o("nginx")});if("error"in n)throw new Error(n.error);let r=n.mode,s=qw(t.repoName,t.envName),i=t.publicUrl?wA(t.publicUrl):"";if(e.kind==="static"){if(b.info(`${t.repoName} has no "start" script - it is a static site, and a static site needs no service: the proxy serves its files directly. Nothing to supervise.`),r==="none")return;if(!i){b.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}let _=`
1273
+ `}function Zw(t,e,n){return vh(t,e,n)}function Vw(t){return t.trim()===""||t.includes("# BEGIN allwright ")||t.includes(Po)}function Yw(t){let{flag:e,caddyActive:n,nginxActive:r}=t;return e!==void 0&&e!=="caddy"&&e!=="nginx"&&e!=="none"?{error:`--proxy must be caddy, nginx or none (got "${e}")`}:e==="none"?{mode:"none"}:e==="caddy"&&r&&!n?{error:"nginx is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy nginx (or stop nginx first); this command never sets up a second proxy alongside a live one."}:e==="nginx"&&n&&!r?{error:"caddy is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy caddy (or stop caddy first); this command never sets up a second proxy alongside a live one."}:e==="caddy"||e==="nginx"?{mode:e}:n?{mode:"caddy"}:r?{mode:"nginx"}:{mode:"print-both"}}function Jw(t){let e=Pe.default.statSync(t).uid;if(e===0)throw new Error(`${t} is owned by root. A web app must not run as root - chown the checkout to the user that deploys it first (sudo chown -R <user>: ${t}).`);try{return(0,pn.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return Co.default.userInfo().username}}function je(t,e){(0,pn.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function mA(t){if(t.sudoers){let e=Wt.default.join(Co.default.tmpdir(),`allwright-sudoers-${process.pid}`);Pe.default.writeFileSync(e,t.content,{mode:384});try{(0,pn.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),je(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{Pe.default.rmSync(e,{force:!0})}return}je(["mkdir","-p",Wt.default.dirname(t.path)]),je(["tee",t.path],t.content),je(["chmod",t.mode,t.path])}function gA(t){try{return Pe.default.readFileSync(t,"utf8").includes(Po)}catch{return!0}}async function yA(t){if(!Pe.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!Pe.default.existsSync(Wt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=Bw(t.dir);if(e.kind==="unknown")throw new Error(`cannot prepare this checkout: ${e.reason}. Write the service by hand, or ask in Compose - this command only automates what it can verify.`);let n=Yw({flag:t.proxy,caddyActive:$o("caddy"),nginxActive:$o("nginx")});if("error"in n)throw new Error(n.error);let r=n.mode,s=qw(t.repoName,t.envName),i=t.publicUrl?bA(t.publicUrl):"";if(e.kind==="static"){if(b.info(`${t.repoName} has no "start" script - it is a static site, and a static site needs no service: the proxy serves its files directly. Nothing to supervise.`),r==="none")return;if(!i){b.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}let _=`
1311
1274
  ${i} {
1312
1275
  root * ${t.dir}/<your build output>
1313
1276
  file_server
@@ -1321,32 +1284,32 @@ server {
1321
1284
  try_files $uri $uri/ =404;
1322
1285
  }
1323
1286
  }
1324
- `;r==="caddy"?(b.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),b.info(_)):r==="nginx"?(b.info("Add a server block for it under /etc/nginx yourself, for example:"),b.info($),b.info("TLS stays yours: nginx does not fetch certificates (Caddy does) - certbot when you are ready.")):(b.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The blocks would be:"),b.info(_),b.info($));return}let a=Ea(t.dir).filter(_=>!_.startsWith(s)),c=`/etc/systemd/system/${s}.service`;if(a.length&&!Pe.default.existsSync(c)){b.info(`this checkout is already supervised: ${a.join(" \xB7 ")}. Leaving it alone - remove that unit first if you want Allwright to manage this environment.`);return}if(!yA(c))throw new Error(`${c} exists and was not written by this command - refusing to overwrite a hand-written unit. Delete it yourself if you want it replaced.`);let l=Jw(t.dir),d=Fw(l);if(!d)throw new Error(`node is not on ${l}'s PATH - the service will run as ${l} (the checkout's owner), so Node must be installed for THAT user (or system-wide). Install it, then re-run.`);let p=await Kw(t.port),f=[{path:c,content:Ww({slug:s,repoName:t.repoName,envName:t.envName,dir:t.dir,user:l,port:p,nodeBin:d}),mode:"644"},{path:`/etc/sudoers.d/allwright-${s}`,content:Gw({slug:s,user:l}),mode:"440",sudoers:!0}];if(t.dryRun){b.info(`DRY RUN - nothing will be written. Planned (port ${p}, user ${l}):`);for(let _ of f)b.info(`
1287
+ `;r==="caddy"?(b.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),b.info(_)):r==="nginx"?(b.info("Add a server block for it under /etc/nginx yourself, for example:"),b.info($),b.info("TLS stays yours: nginx does not fetch certificates (Caddy does) - certbot when you are ready.")):(b.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The blocks would be:"),b.info(_),b.info($));return}let a=Ea(t.dir).filter(_=>!_.startsWith(s)),c=`/etc/systemd/system/${s}.service`;if(a.length&&!Pe.default.existsSync(c)){b.info(`this checkout is already supervised: ${a.join(" \xB7 ")}. Leaving it alone - remove that unit first if you want Allwright to manage this environment.`);return}if(!gA(c))throw new Error(`${c} exists and was not written by this command - refusing to overwrite a hand-written unit. Delete it yourself if you want it replaced.`);let l=Jw(t.dir),d=Fw(l);if(!d)throw new Error(`node is not on ${l}'s PATH - the service will run as ${l} (the checkout's owner), so Node must be installed for THAT user (or system-wide). Install it, then re-run.`);let p=await Kw(t.port),f=[{path:c,content:Ww({slug:s,repoName:t.repoName,envName:t.envName,dir:t.dir,user:l,port:p,nodeBin:d}),mode:"644"},{path:`/etc/sudoers.d/allwright-${s}`,content:Gw({slug:s,user:l}),mode:"440",sudoers:!0}];if(t.dryRun){b.info(`DRY RUN - nothing will be written. Planned (port ${p}, user ${l}):`);for(let _ of f)b.info(`
1325
1288
  --- ${_.path} (mode ${_.mode}) ---
1326
1289
  ${_.content}`);i&&r==="caddy"&&b.info(`--- appended to /etc/caddy/Caddyfile ---
1327
1290
  ${Ai({slug:s,hostname:i,port:p})}`),i&&r==="nginx"&&b.info(`--- written to /etc/nginx/{sites-available,conf.d}/allwright-${s}.conf ---
1328
1291
  `+Ao({slug:s,hostname:i,port:p})),i&&r==="print-both"&&b.info(`--- no proxy is running; one of these, whichever you pick with --proxy ---
1329
1292
  ${Ai({slug:s,hostname:i,port:p})}
1330
1293
 
1331
- ${Ao({slug:s,hostname:i,port:p})}`);return}for(let _ of f)gA(_);let g=`/etc/allwright/env.d/${s}.env`;Pe.default.existsSync(g)||(je(["install","-d","-m","755","/etc/allwright"]),je(["install","-d","-m","750","/etc/allwright/env.d"]),je(["install","-m","600","-o","root","-g","root","/dev/null",g]),b.info(`created empty ${g} - add secrets with: sudoedit ${g}`));let v=Pe.default.existsSync(Wt.default.join(t.dir,".next"))||Pe.default.existsSync(Wt.default.join(t.dir,"dist"));v||b.warn(`no build output in ${t.dir} yet - the service would exit immediately. Run your install+build once (or run the first deploy), then: sudo systemctl restart ${s}`),je(["systemctl","daemon-reload"]),je(["systemctl","reset-failed",s]),je(["systemctl","enable","--now",s]),i&&r!=="none"&&(r==="caddy"?kA({slug:s,hostname:i,port:p}):r==="nginx"?SA({slug:s,hostname:i,port:p}):(b.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The block would be:"),b.info(`
1294
+ ${Ao({slug:s,hostname:i,port:p})}`);return}for(let _ of f)mA(_);let g=`/etc/allwright/env.d/${s}.env`;Pe.default.existsSync(g)||(je(["install","-d","-m","755","/etc/allwright"]),je(["install","-d","-m","750","/etc/allwright/env.d"]),je(["install","-m","600","-o","root","-g","root","/dev/null",g]),b.info(`created empty ${g} - add secrets with: sudoedit ${g}`));let v=Pe.default.existsSync(Wt.default.join(t.dir,".next"))||Pe.default.existsSync(Wt.default.join(t.dir,"dist"));v||b.warn(`no build output in ${t.dir} yet - the service would exit immediately. Run your install+build once (or run the first deploy), then: sudo systemctl restart ${s}`),je(["systemctl","daemon-reload"]),je(["systemctl","reset-failed",s]),je(["systemctl","enable","--now",s]),i&&r!=="none"&&(r==="caddy"?vA({slug:s,hostname:i,port:p}):r==="nginx"?kA({slug:s,hostname:i,port:p}):(b.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The block would be:"),b.info(`
1332
1295
  ${Ai({slug:s,hostname:i,port:p})}
1333
1296
  `),b.info(`
1334
1297
  ${Ao({slug:s,hostname:i,port:p})}
1335
- `)));let k=v?await vA(p,3e4):!1,T=$o(s);b.info(""),b.info(`${T?"\u2713":"\u2717"} service ${s}: ${T?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&b.info(`${k?"\u2713":"\u2717"} listening on 127.0.0.1:${p}${k?"":" - not yet; check the journal"}`),b.info("\u2713 deploys may restart it without a password (sudoers drop-in installed)"),b.info(""),b.info(`Deploy steps should end with: sudo systemctl restart ${s}`),i&&b.info(`Health checks should target: http://127.0.0.1:${p}/ (and later https://${i}/)`),b.info(`DNS stays yours: point ${i||"your hostname"} at this machine when you are ready.`)}function wA(t){try{return new URL(t).hostname}catch{throw new Error(`--url must be a full URL like https://staging.example.com (got "${t}")`)}}function $o(t){try{return(0,pn.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function vA(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=wh.default.connect({port:t,host:"127.0.0.1",timeout:2e3});i.once("connect",()=>{i.destroy(),s(!0)}),i.once("error",()=>s(!1)),i.once("timeout",()=>{i.destroy(),s(!1)})}))return!0;await new Promise(s=>setTimeout(s,2e3))}return!1}function kA(t){let e="/etc/caddy/Caddyfile";if(!Pe.default.existsSync(e)||!$o("caddy")){b.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
1336
- ${Ai(t)}`);return}let n;try{n=Pe.default.readFileSync(e,"utf8")}catch{n=(0,pn.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Zw(n,t.slug,Ai(t));if(r===n){b.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=Wt.default.join(Co.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);Pe.default.writeFileSync(s,r,{mode:420});try{(0,pn.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),je(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),je(["cp",s,e]),je(["systemctl","reload","caddy"]),b.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{Pe.default.rmSync(s,{force:!0})}}function SA(t){let e=Ao(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!Pe.default.existsSync("/etc/nginx")||!$o("nginx")){b.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
1298
+ `)));let k=v?await wA(p,3e4):!1,T=$o(s);b.info(""),b.info(`${T?"\u2713":"\u2717"} service ${s}: ${T?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&b.info(`${k?"\u2713":"\u2717"} listening on 127.0.0.1:${p}${k?"":" - not yet; check the journal"}`),b.info("\u2713 deploys may restart it without a password (sudoers drop-in installed)"),b.info(""),b.info(`Deploy steps should end with: sudo systemctl restart ${s}`),i&&b.info(`Health checks should target: http://127.0.0.1:${p}/ (and later https://${i}/)`),b.info(`DNS stays yours: point ${i||"your hostname"} at this machine when you are ready.`)}function bA(t){try{return new URL(t).hostname}catch{throw new Error(`--url must be a full URL like https://staging.example.com (got "${t}")`)}}function $o(t){try{return(0,pn.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function wA(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=wh.default.connect({port:t,host:"127.0.0.1",timeout:2e3});i.once("connect",()=>{i.destroy(),s(!0)}),i.once("error",()=>s(!1)),i.once("timeout",()=>{i.destroy(),s(!1)})}))return!0;await new Promise(s=>setTimeout(s,2e3))}return!1}function vA(t){let e="/etc/caddy/Caddyfile";if(!Pe.default.existsSync(e)||!$o("caddy")){b.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
1299
+ ${Ai(t)}`);return}let n;try{n=Pe.default.readFileSync(e,"utf8")}catch{n=(0,pn.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Zw(n,t.slug,Ai(t));if(r===n){b.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=Wt.default.join(Co.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);Pe.default.writeFileSync(s,r,{mode:420});try{(0,pn.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),je(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),je(["cp",s,e]),je(["systemctl","reload","caddy"]),b.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{Pe.default.rmSync(s,{force:!0})}}function kA(t){let e=Ao(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!Pe.default.existsSync("/etc/nginx")||!$o("nginx")){b.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
1337
1300
  ${e}`),b.info(n);return}let r=Pe.default.existsSync("/etc/nginx/sites-enabled"),s=r?`/etc/nginx/sites-available/allwright-${t.slug}.conf`:`/etc/nginx/conf.d/allwright-${t.slug}.conf`,i=r?`/etc/nginx/sites-enabled/allwright-${t.slug}.conf`:null,a=null;if(Pe.default.existsSync(s)){try{a=Pe.default.readFileSync(s,"utf8")}catch{a=(0,pn.execFileSync)("sudo",["cat",s],{encoding:"utf8",timeout:1e4})}if(!Vw(a))throw new Error(`${s} exists and was not written by this command - refusing to overwrite a hand-written site. Delete it yourself if you want it replaced.`)}let c=vh(a??"",t.slug,e).replace(/^\n+/,"");if(a!==null&&c===a){b.info(`nginx already routes ${t.hostname} - unchanged`);return}let l=i?Pe.default.existsSync(i):!1;je(["mkdir","-p",Wt.default.dirname(s)]),je(["tee",s],c),je(["chmod","644",s]),i&&!l&&je(["ln","-s",s,i]);try{(0,pn.execFileSync)("sudo",["nginx","-t"],{encoding:"utf8",timeout:3e4})}catch(d){a!==null?(je(["tee",s],a),je(["chmod","644",s])):(i&&!l&&je(["rm","-f",i]),je(["rm","-f",s]));let p=d&&typeof d=="object"&&"stderr"in d&&typeof d.stderr=="string"?d.stderr.trim():String(d);throw new Error(`nginx -t rejected the new config - ${s} was ${a!==null?"restored":"removed"} and nginx was NOT reloaded. nginx said:
1338
- ${p}`)}je(["systemctl","reload","nginx"]),b.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),b.info(n)}var pn,Pe,wh,Co,Wt,Po,Qw=X(()=>{"use strict";pn=require("node:child_process"),Pe=E(require("node:fs"),1),wh=E(require("node:net"),1),Co=E(require("node:os"),1),Wt=E(require("node:path"),1);lt();$a();Po="# managed by allwright env prepare"});function xA(t,e,n){switch(t){case 1:return 8;case 2:case 13:case 14:return 4+e.readInt32LE(n);case 3:case 4:return e.readInt32LE(n);case 5:return 5+e.readInt32LE(n);case 6:return 0;case 7:return 12;case 8:return 1;case 9:return 8;case 10:return 0;case 11:{let r=e.indexOf(0,n);return r<0?-1:(r=e.indexOf(0,r+1),r<0?-1:r+1-n)}case 15:return e.readInt32LE(n);case 16:return 4;case 17:case 18:return 8;case 19:return 16;case 127:case 255:return 0;default:return-1}}function TA(t){let e=[],n=4;for(;n<t.length-1;){let r=t[n];if(n+=1,r===0)break;let s=t.indexOf(0,n);if(s<0)break;e.push(t.toString("utf8",n,s)),n=s+1;let i=xA(r,t,n);if(i<0||(n+=i,e.length>=40))break}return e}function RA(t){let e=0,n=0,r=[];for(;e+4<=t.length;){let s=t.readInt32LE(e);if(s<5||e+s>t.length)break;n===0&&(r=TA(t.subarray(e,e+s))),n+=1,e+=s}return{count:n,keys:r}}function tv(t){try{let e=mr.default.readdirSync(t);return e.some(n=>/\.bson(\.gz)?$/.test(n))?!0:e.some(n=>{let r=Fc.default.join(t,n);return mr.default.statSync(r).isDirectory()&&mr.default.readdirSync(r).some(s=>/\.bson(\.gz)?$/.test(s))})}catch{return!1}}function nv(t){let e=[];try{for(let s of mr.default.readdirSync(t)){let i=Fc.default.join(t,s);if(/\.bson(\.gz)?$/.test(s))e.push({db:"",file:s,full:i});else if(mr.default.statSync(i).isDirectory())for(let a of mr.default.readdirSync(i))/\.bson(\.gz)?$/.test(a)&&e.push({db:s,file:a,full:Fc.default.join(i,a)})}}catch(s){return{ok:!1,markdown:`Could not read the dump directory: ${s instanceof Error?s.message:s}`,tables:0}}if(!e.length)return{ok:!1,markdown:`No .bson collections found under \`${t}\` - is this a mongodump?`,tables:0};let n=[];for(let{db:s,file:i,full:a}of e.slice(0,200)){let c=(s?`${s}.`:"")+i.replace(/\.bson(\.gz)?$/,"");try{let l=mr.default.readFileSync(a);if(/\.gz$/.test(a))try{l=ev.default.gunzipSync(l,{maxOutputLength:_A})}catch{n.push({name:c,docs:"too large to count here",keys:[]});continue}let{count:d,keys:p}=RA(l);n.push({name:c,docs:d.toLocaleString(),keys:p})}catch(l){n.push({name:c,docs:`unreadable (${l instanceof Error?l.message:"error"})`,keys:[]})}}return n.sort((s,i)=>(parseInt(i.docs.replace(/,/g,""))||0)-(parseInt(s.docs.replace(/,/g,""))||0)),{ok:!0,markdown:["# Data profile (MongoDB dump, read by code - no database was connected, no mongo tools used)","",`${n.length} collection(s) found in \`${t}\`. Document counts are exact (BSON walked); fields are the FIRST document's top-level keys - Mongo documents vary, so treat them as a sample, not a schema.`,"","| Collection | Documents |","| --- | --- |",...n.map(s=>`| ${s.name} | ${s.docs} |`),"","## Fields (first document of each collection)",...n.map(s=>`- **${s.name}**: ${s.keys.join(", ")||"(empty or unreadable)"}`)].join(`
1339
- `).slice(0,6e4),tables:n.length}}var mr,Fc,ev,_A,rv=X(()=>{"use strict";mr=E(require("node:fs"),1),Fc=E(require("node:path"),1),ev=E(require("node:zlib"),1),_A=128*1024*1024});var Sh={};De(Sh,{MAX_JIRA_ISSUES:()=>ov,extractNamedBlock:()=>gr,profileDump:()=>av,profileSqlDump:()=>cv,rebirthStudyInFlight:()=>IA,runRebirthDesign:()=>qA,runRebirthStudy:()=>OA,sendRunFinished:()=>jA,shrinkWarning:()=>No,splitDesign:()=>Hc,splitSpec:()=>kh});function IA(t){return Bc.has(t)}function av(t){try{if(Ps.default.statSync(t).isDirectory())return tv(t)?nv(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 cv(t)}function cv(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=Ps.default.openSync(t,"r"),r=Ps.default.fstatSync(n).size,s=Math.min(r,32*1024*1024),i=Buffer.alloc(s);if(Ps.default.readSync(n,i,0,s,0),Ps.default.closeSync(n),/\.gz$/i.test(t))try{i=iv.default.gunzipSync(Ps.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 d of e.matchAll(/CREATE TABLE[^`"\w]*[`"]?([\w.]+)[`"]?\s*\(([\s\S]*?)\)\s*;/gi)){let f=d[2].split(`
1301
+ ${p}`)}je(["systemctl","reload","nginx"]),b.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),b.info(n)}var pn,Pe,wh,Co,Wt,Po,Qw=X(()=>{"use strict";pn=require("node:child_process"),Pe=E(require("node:fs"),1),wh=E(require("node:net"),1),Co=E(require("node:os"),1),Wt=E(require("node:path"),1);lt();$a();Po="# managed by allwright env prepare"});function _A(t,e,n){switch(t){case 1:return 8;case 2:case 13:case 14:return 4+e.readInt32LE(n);case 3:case 4:return e.readInt32LE(n);case 5:return 5+e.readInt32LE(n);case 6:return 0;case 7:return 12;case 8:return 1;case 9:return 8;case 10:return 0;case 11:{let r=e.indexOf(0,n);return r<0?-1:(r=e.indexOf(0,r+1),r<0?-1:r+1-n)}case 15:return e.readInt32LE(n);case 16:return 4;case 17:case 18:return 8;case 19:return 16;case 127:case 255:return 0;default:return-1}}function xA(t){let e=[],n=4;for(;n<t.length-1;){let r=t[n];if(n+=1,r===0)break;let s=t.indexOf(0,n);if(s<0)break;e.push(t.toString("utf8",n,s)),n=s+1;let i=_A(r,t,n);if(i<0||(n+=i,e.length>=40))break}return e}function TA(t){let e=0,n=0,r=[];for(;e+4<=t.length;){let s=t.readInt32LE(e);if(s<5||e+s>t.length)break;n===0&&(r=xA(t.subarray(e,e+s))),n+=1,e+=s}return{count:n,keys:r}}function tv(t){try{let e=mr.default.readdirSync(t);return e.some(n=>/\.bson(\.gz)?$/.test(n))?!0:e.some(n=>{let r=Fc.default.join(t,n);return mr.default.statSync(r).isDirectory()&&mr.default.readdirSync(r).some(s=>/\.bson(\.gz)?$/.test(s))})}catch{return!1}}function nv(t){let e=[];try{for(let s of mr.default.readdirSync(t)){let i=Fc.default.join(t,s);if(/\.bson(\.gz)?$/.test(s))e.push({db:"",file:s,full:i});else if(mr.default.statSync(i).isDirectory())for(let a of mr.default.readdirSync(i))/\.bson(\.gz)?$/.test(a)&&e.push({db:s,file:a,full:Fc.default.join(i,a)})}}catch(s){return{ok:!1,markdown:`Could not read the dump directory: ${s instanceof Error?s.message:s}`,tables:0}}if(!e.length)return{ok:!1,markdown:`No .bson collections found under \`${t}\` - is this a mongodump?`,tables:0};let n=[];for(let{db:s,file:i,full:a}of e.slice(0,200)){let c=(s?`${s}.`:"")+i.replace(/\.bson(\.gz)?$/,"");try{let l=mr.default.readFileSync(a);if(/\.gz$/.test(a))try{l=ev.default.gunzipSync(l,{maxOutputLength:SA})}catch{n.push({name:c,docs:"too large to count here",keys:[]});continue}let{count:d,keys:p}=TA(l);n.push({name:c,docs:d.toLocaleString(),keys:p})}catch(l){n.push({name:c,docs:`unreadable (${l instanceof Error?l.message:"error"})`,keys:[]})}}return n.sort((s,i)=>(parseInt(i.docs.replace(/,/g,""))||0)-(parseInt(s.docs.replace(/,/g,""))||0)),{ok:!0,markdown:["# Data profile (MongoDB dump, read by code - no database was connected, no mongo tools used)","",`${n.length} collection(s) found in \`${t}\`. Document counts are exact (BSON walked); fields are the FIRST document's top-level keys - Mongo documents vary, so treat them as a sample, not a schema.`,"","| Collection | Documents |","| --- | --- |",...n.map(s=>`| ${s.name} | ${s.docs} |`),"","## Fields (first document of each collection)",...n.map(s=>`- **${s.name}**: ${s.keys.join(", ")||"(empty or unreadable)"}`)].join(`
1302
+ `).slice(0,6e4),tables:n.length}}var mr,Fc,ev,SA,rv=X(()=>{"use strict";mr=E(require("node:fs"),1),Fc=E(require("node:path"),1),ev=E(require("node:zlib"),1),SA=128*1024*1024});var Sh={};De(Sh,{MAX_JIRA_ISSUES:()=>ov,extractNamedBlock:()=>gr,profileDump:()=>av,profileSqlDump:()=>cv,rebirthStudyInFlight:()=>RA,runRebirthDesign:()=>UA,runRebirthStudy:()=>jA,sendRunFinished:()=>MA,shrinkWarning:()=>No,splitDesign:()=>Hc,splitSpec:()=>kh});function RA(t){return Bc.has(t)}function av(t){try{if(Ps.default.statSync(t).isDirectory())return tv(t)?nv(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 cv(t)}function cv(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=Ps.default.openSync(t,"r"),r=Ps.default.fstatSync(n).size,s=Math.min(r,32*1024*1024),i=Buffer.alloc(s);if(Ps.default.readSync(n,i,0,s,0),Ps.default.closeSync(n),/\.gz$/i.test(t))try{i=iv.default.gunzipSync(Ps.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 d of e.matchAll(/CREATE TABLE[^`"\w]*[`"]?([\w.]+)[`"]?\s*\(([\s\S]*?)\)\s*;/gi)){let f=d[2].split(`
1340
1303
  `).map(g=>g.trim()).filter(g=>g&&!/^(PRIMARY|UNIQUE|KEY|CONSTRAINT|FOREIGN|INDEX)/i.test(g)).map(g=>g.split(/\s+/)[0].replace(/[`",]/g,"")).filter(Boolean);c.push({name:d[1],columns:f,rows:0})}for(let d of c){let p=d.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),f=0;for(let v of e.matchAll(new RegExp(`INSERT INTO [\`"]?${p}[\`"]?[^;]*;`,"gi")))f+=(v[0].match(/\),\s*\(/g)?.length??0)+1;let g=e.match(new RegExp(`COPY [\`"]?${p}[\`"]?[^\\n]*FROM stdin;\\n([\\s\\S]*?)\\n\\\\\\.`,"i"));g&&(f+=g[1].split(`
1341
1304
  `).filter(Boolean).length),d.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((d,p)=>p.rows-d.rows).map(d=>`| ${d.name} | ${d.columns.length} | ${d.rows.toLocaleString()} |`),"","## Columns",...c.map(d=>`- **${d.name}**: ${d.columns.join(", ")||"(none parsed)"}`)];return{ok:c.length>0,markdown:l.join(`
1342
- `).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 No(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 gr(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 jA(t,e,n,r){t.send({type:"rebirth.study.update",rebirthId:e,stageNumber:1,status:"in_progress",note:"",progressDone:0,progressTotal:0,artifact:"",items:[],brief:"",runFinished:{kind:n,ok:r.ok,error:(r.error??"").slice(0,2e3)},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}})}async function OA(t){let{msg:e,transport:n}=t;if(Bc.has(e.rebirthId))return{ok:!1,error:"a study is already running for this rebirth - it reports as it goes"};Bc.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??[],brief:i.brief??"",...i.proposal?{proposal:i.proposal}:{},usageDelta:a})};try{let i=$e(t.cfg,t.project,"assist");if("error"in i)return{ok:!1,error:i.error};let a=(0,Kc.randomUUID)(),c=!1,l=e.refineMessage.trim()?"rebirth_refold":"rebirth_study",d=async(_,$,D=60)=>{let z=await i.adapter.run({repoPath:t.repoPath,prompt:_,timeoutSeconds:$*60,bin:i.bin,mode:"read_only",maxTurns:D,sessionId:a,resume:c,onLog:()=>{}});return c=!0,be({surface:l,projectId:t.project.id,agentId:i.adapter.id,refKind:"rebirth",refId:e.rebirthId,...we(z)}),r={inputTokens:r.inputTokens+(z.inputTokens??0),outputTokens:r.outputTokens+(z.outputTokens??0),cacheReadTokens:r.cacheReadTokens+(z.cacheReadTokens??0),costUsd:r.costUsd+(z.costUsd??0)},z};if(e.refineMessage.trim()){let _=e.refineScope,$=(L,V)=>s({stageNumber:4,status:"in_progress",note:V,proposal:{message:e.refineMessage,scope:_,docs:L.docs??[],tickets:L.tickets??[],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}}$({working:!0},"Folding your correction into the plan - the result comes back as proposed changes for your review\u2026"),c=!1;let D=await d(MA(e.refineMessage,{brief:e.currentBrief,understanding:e.currentUnderstanding,requirements:e.currentRequirements,spec:e.currentSpec},_),60,150);if(!D.ok||!D.resultText.trim())return $({error:D.error??"the refine pass produced nothing"},"The refold failed - nothing was changed"),{ok:!1,error:D.error??"the refine pass produced nothing"};let z=gr(D.resultText,"brief"),A=gr(z.rest,"understanding"),P=gr(A.rest,"requirements"),w=L=>_==="all"||_===L,j=[],W=[];if(w("brief")&&z.block&&j.push({doc:"brief",proposed:z.block.slice(0,1e5)}),w("understanding")&&A.block&&j.push({doc:"understanding",proposed:A.block.slice(0,2e5)}),w("requirements")&&P.block&&j.push({doc:"requirements",proposed:P.block.slice(0,2e5)}),w("spec")&&P.rest.trim()){let L=kh(P.rest);L.spec.trim()&&(j.push({doc:"spec",proposed:L.spec}),W=L.tickets)}return j.length?($({docs:j,tickets:W},"Refold ready - review the proposed changes (nothing applied yet)"),{ok:!0}):($({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:"Reading the codebase - this is the long part"});let _=await d(AA(e.currentUnderstanding),20);!_.ok||!_.resultText.trim()?(s({stageNumber:1,status:"failed",note:_.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:"Codebase studied"+No(e.currentUnderstanding,_.resultText),artifact:_.resultText.trim().slice(0,1e5)})}else s({stageNumber:1,status:"skipped",note:"no code yet - map the legacy checkout on the runner (allwright repo add) and re-run the study to fold it in"}),p.push("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 _=av(e.dbDumpPath.trim());s({stageNumber:2,status:_.ok?"done":"failed",note:_.ok?`${_.tables} table(s) profiled`:"the dump could not be profiled",artifact:_.markdown})}else 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 _=e.legacyJiraKey.trim().toUpperCase(),$=Math.min(2e3,Math.max(50,e.maxJiraIssues||ov));s({stageNumber:3,status:"in_progress",note:`Reading ${_} tickets - 0/?`,progressDone:0});try{let z=(await t.jira.searchHistory(`project = ${_} ORDER BY created DESC`,{max:$,pageSize:EA,onPage:A=>s({stageNumber:3,status:"in_progress",note:`Reading ${_} tickets - ${A} read (max ${$})`,progressDone:A,progressTotal:$})})).map(A=>`${A.key} [${A.status}] ${A.summary}`);if(z.length){s({stageNumber:3,status:"in_progress",note:`Distilling ${z.length} tickets into the requirements ledger\u2026`,progressDone:z.length,progressTotal:z.length});let A=await d($A(z.join(`
1343
- `).slice(0,12e4),e.currentRequirements),12);A.ok&&A.resultText.trim()?(s({stageNumber:3,status:"done",note:`${z.length} tickets distilled`+No(e.currentRequirements,A.resultText),artifact:A.resultText.trim().slice(0,1e5),progressDone:z.length,progressTotal:z.length}),f=!0):s({stageNumber:3,status:"failed",note:A.error??"the distill pass produced nothing"})}else s({stageNumber:3,status:"skipped",note:`${_} 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 ${_} - requirements are not based on the old board`)}catch(D){s({stageNumber:3,status:"failed",note:`Jira read failed: ${D instanceof Error?D.message:D}`})}}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 g=await d(CA(e.extraContext.trim(),p,e.currentSpec,e.gdprRequired),15);if(!g.ok||!g.resultText.trim())return s({stageNumber:4,status:"failed",note:g.error??"the SPEC pass produced nothing"}),{ok:!1,error:g.error??"SPEC generation failed"};let{spec:v,tickets:k}=kh(g.resultText);s({stageNumber:4,status:"done",note:"SPEC drafted - review it, refine it in your words if something is missing, then approve"+No(e.currentSpec,v),artifact:v}),s({stageNumber:1,status:"done",note:"Writing the project understanding (plain language)\u2026"});let T=await d(PA(e.currentBrief),8);return T.ok&&T.resultText.trim()&&s({stageNumber:1,status:"done",note:"Project understanding ready - read and verify it"+No(e.currentBrief,T.resultText),brief:T.resultText.trim().slice(0,1e5)}),k.length&&s({stageNumber:6,status:"in_progress",note:`${k.length} tickets proposed by the SPEC - created on Jira after you approve`,items:k}),b.info(`rebirth study done for ${e.rebirthId}: code \u2713, data ${e.dbDumpPath?"\u2713":"skipped"}, requirements ${f?"\u2713":"skipped/failed"}, SPEC \u2713 (${k.length} tickets proposed)`),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{Bc.delete(e.rebirthId)}}function kh(t){let e=/```json\s*\n([\s\S]*?)```/.exec(t),n=[];if(e)try{n=(JSON.parse(e[1]).tickets??[]).filter(s=>typeof s.title=="string"&&s.title.trim()).slice(0,60).map(s=>({title:s.title.trim().slice(0,300),detail:typeof s.detail=="string"?s.detail.trim().slice(0,4e3):""}))}catch{}return{spec:t.replace(/```json\s*\n[\s\S]*?```/g,"").trim().slice(0,15e4),tickets:n}}function Hc(t){let e=gr(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(gr(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 qA(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:[],brief:"",design:{direction:"",screens:[],inventory:[],specs:[],partial:!0},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}});try{let s=$e(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?UA(e.spec,e.brief,e.refineMessage,e.currentStack):e.specOnly?LA(e.screenName,"",e.screenBrief,e.screenSpec):i?sv(e.screenName,e.screenBrief,e.currentDirection,e.currentScreenHtml,e.screenSpec,e.referenceScreenHtml):zA(e.spec,e.brief,e.refineMessage,e.currentDirection),timeoutSeconds:1200,bin:s.bin,mode:"read_only",maxTurns:60,sessionId:(0,Kc.randomUUID)(),onLog:()=>{}});if(be({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:"",...we(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=gr(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:[],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=gr(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:[],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,z,A)=>n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:4,status:"in_progress",note:z,progressDone:0,progressTotal:0,artifact:"",items:[],brief:"",design:D,usageDelta:A});if(i){let z=Hc(a.resultText).screens.filter(A=>A.name===e.screenName).slice(0,1);return z.length?(l({direction:"",screens:z,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 d=Hc(a.resultText);if(!d.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:d.direction,screens:[],inventory:d.inventory,specs:[],partial:!0},`Screen list ready - ${d.inventory.length} screen(s) mapped. Drawing the missing ones\u2026`,c(a));let p=d.direction||e.currentDirection,f=new Set(e.existingScreenNames),g=d.inventory.filter(D=>!f.has(D.name)),k=g.slice(0,6),T=0,_=e.referenceScreenHtml;for(let[D,z]of k.entries()){r(`Drawing "${z.name}" (${D+1}/${k.length})\u2026`);let A=await s.adapter.run({repoPath:t.repoPath,prompt:sv(z.name,z.note,p,"","",_),timeoutSeconds:900,bin:s.bin,mode:"read_only",maxTurns:40,sessionId:(0,Kc.randomUUID)(),onLog:()=>{}});be({surface:"rebirth_design",projectId:t.project.id,agentId:s.adapter.id,refKind:"rebirth",refId:e.rebirthId,refLabel:z.name,...we(A)});let P=A.ok?Hc(A.resultText).screens.find(w=>w.name===z.name):void 0;P?(T+=1,_||(_=P.html),l({direction:"",screens:[P],inventory:[],specs:[],partial:!0},`"${z.name}" is ready (${T}/${k.length}). ${D+1<k.length?"Drawing the next\u2026":""}`,c(A))):l({direction:"",screens:[],inventory:[],specs:[],partial:!0},`"${z.name}" did not come back usable - skipped (ask for it again per-screen).`,c(A))}let $=g.length-k.length;return r(`UI design ready - ${T} screen(s) drawn this run`+($>0?`, ${$} 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 Ps,iv,Kc,Bc,ov,EA,Wc,AA,$A,CA,PA,NA,MA,zA,DA,LA,UA,sv,_h=X(()=>{"use strict";Ps=E(require("node:fs"),1),iv=E(require("node:zlib"),1),Kc=require("node:crypto");Et();lt();nn();rv();Bc=new Set;ov=500,EA=50;Wc=(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.
1305
+ `).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 No(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 gr(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 MA(t,e,n,r){t.send({type:"rebirth.study.update",rebirthId:e,stageNumber:1,status:"in_progress",note:"",progressDone:0,progressTotal:0,artifact:"",items:[],brief:"",runFinished:{kind:n,ok:r.ok,error:(r.error??"").slice(0,2e3)},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}})}async function jA(t){let{msg:e,transport:n}=t;if(Bc.has(e.rebirthId))return{ok:!1,error:"a study is already running for this rebirth - it reports as it goes"};Bc.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??[],brief:i.brief??"",...i.proposal?{proposal:i.proposal}:{},usageDelta:a})};try{let i=$e(t.cfg,t.project,"assist");if("error"in i)return{ok:!1,error:i.error};let a=(0,Kc.randomUUID)(),c=!1,l=e.refineMessage.trim()?"rebirth_refold":"rebirth_study",d=async(_,$,D=60)=>{let z=await i.adapter.run({repoPath:t.repoPath,prompt:_,timeoutSeconds:$*60,bin:i.bin,mode:"read_only",maxTurns:D,sessionId:a,resume:c,onLog:()=>{}});return c=!0,be({surface:l,projectId:t.project.id,agentId:i.adapter.id,refKind:"rebirth",refId:e.rebirthId,...we(z)}),r={inputTokens:r.inputTokens+(z.inputTokens??0),outputTokens:r.outputTokens+(z.outputTokens??0),cacheReadTokens:r.cacheReadTokens+(z.cacheReadTokens??0),costUsd:r.costUsd+(z.costUsd??0)},z};if(e.refineMessage.trim()){let _=e.refineScope,$=(L,V)=>s({stageNumber:4,status:"in_progress",note:V,proposal:{message:e.refineMessage,scope:_,docs:L.docs??[],tickets:L.tickets??[],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}}$({working:!0},"Folding your correction into the plan - the result comes back as proposed changes for your review\u2026"),c=!1;let D=await d(NA(e.refineMessage,{brief:e.currentBrief,understanding:e.currentUnderstanding,requirements:e.currentRequirements,spec:e.currentSpec},_),60,150);if(!D.ok||!D.resultText.trim())return $({error:D.error??"the refine pass produced nothing"},"The refold failed - nothing was changed"),{ok:!1,error:D.error??"the refine pass produced nothing"};let z=gr(D.resultText,"brief"),A=gr(z.rest,"understanding"),P=gr(A.rest,"requirements"),w=L=>_==="all"||_===L,j=[],W=[];if(w("brief")&&z.block&&j.push({doc:"brief",proposed:z.block.slice(0,1e5)}),w("understanding")&&A.block&&j.push({doc:"understanding",proposed:A.block.slice(0,2e5)}),w("requirements")&&P.block&&j.push({doc:"requirements",proposed:P.block.slice(0,2e5)}),w("spec")&&P.rest.trim()){let L=kh(P.rest);L.spec.trim()&&(j.push({doc:"spec",proposed:L.spec}),W=L.tickets)}return j.length?($({docs:j,tickets:W},"Refold ready - review the proposed changes (nothing applied yet)"),{ok:!0}):($({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:"Reading the codebase - this is the long part"});let _=await d(EA(e.currentUnderstanding),20);!_.ok||!_.resultText.trim()?(s({stageNumber:1,status:"failed",note:_.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:"Codebase studied"+No(e.currentUnderstanding,_.resultText),artifact:_.resultText.trim().slice(0,1e5)})}else s({stageNumber:1,status:"skipped",note:"no code yet - map the legacy checkout on the runner (allwright repo add) and re-run the study to fold it in"}),p.push("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 _=av(e.dbDumpPath.trim());s({stageNumber:2,status:_.ok?"done":"failed",note:_.ok?`${_.tables} table(s) profiled`:"the dump could not be profiled",artifact:_.markdown})}else 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 _=e.legacyJiraKey.trim().toUpperCase(),$=Math.min(2e3,Math.max(50,e.maxJiraIssues||ov));s({stageNumber:3,status:"in_progress",note:`Reading ${_} tickets - 0/?`,progressDone:0});try{let z=(await t.jira.searchHistory(`project = ${_} ORDER BY created DESC`,{max:$,pageSize:IA,onPage:A=>s({stageNumber:3,status:"in_progress",note:`Reading ${_} tickets - ${A} read (max ${$})`,progressDone:A,progressTotal:$})})).map(A=>`${A.key} [${A.status}] ${A.summary}`);if(z.length){s({stageNumber:3,status:"in_progress",note:`Distilling ${z.length} tickets into the requirements ledger\u2026`,progressDone:z.length,progressTotal:z.length});let A=await d(AA(z.join(`
1306
+ `).slice(0,12e4),e.currentRequirements),12);A.ok&&A.resultText.trim()?(s({stageNumber:3,status:"done",note:`${z.length} tickets distilled`+No(e.currentRequirements,A.resultText),artifact:A.resultText.trim().slice(0,1e5),progressDone:z.length,progressTotal:z.length}),f=!0):s({stageNumber:3,status:"failed",note:A.error??"the distill pass produced nothing"})}else s({stageNumber:3,status:"skipped",note:`${_} 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 ${_} - requirements are not based on the old board`)}catch(D){s({stageNumber:3,status:"failed",note:`Jira read failed: ${D instanceof Error?D.message:D}`})}}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 g=await d($A(e.extraContext.trim(),p,e.currentSpec,e.gdprRequired),15);if(!g.ok||!g.resultText.trim())return s({stageNumber:4,status:"failed",note:g.error??"the SPEC pass produced nothing"}),{ok:!1,error:g.error??"SPEC generation failed"};let{spec:v,tickets:k}=kh(g.resultText);s({stageNumber:4,status:"done",note:"SPEC drafted - review it, refine it in your words if something is missing, then approve"+No(e.currentSpec,v),artifact:v}),s({stageNumber:1,status:"done",note:"Writing the project understanding (plain language)\u2026"});let T=await d(CA(e.currentBrief),8);return T.ok&&T.resultText.trim()&&s({stageNumber:1,status:"done",note:"Project understanding ready - read and verify it"+No(e.currentBrief,T.resultText),brief:T.resultText.trim().slice(0,1e5)}),k.length&&s({stageNumber:6,status:"in_progress",note:`${k.length} tickets proposed by the SPEC - created on Jira after you approve`,items:k}),b.info(`rebirth study done for ${e.rebirthId}: code \u2713, data ${e.dbDumpPath?"\u2713":"skipped"}, requirements ${f?"\u2713":"skipped/failed"}, SPEC \u2713 (${k.length} tickets proposed)`),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{Bc.delete(e.rebirthId)}}function kh(t){let e=/```json\s*\n([\s\S]*?)```/.exec(t),n=[];if(e)try{n=(JSON.parse(e[1]).tickets??[]).filter(s=>typeof s.title=="string"&&s.title.trim()).slice(0,60).map(s=>({title:s.title.trim().slice(0,300),detail:typeof s.detail=="string"?s.detail.trim().slice(0,4e3):""}))}catch{}return{spec:t.replace(/```json\s*\n[\s\S]*?```/g,"").trim().slice(0,15e4),tickets:n}}function Hc(t){let e=gr(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(gr(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 UA(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:[],brief:"",design:{direction:"",screens:[],inventory:[],specs:[],partial:!0},usageDelta:{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0}});try{let s=$e(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?LA(e.spec,e.brief,e.refineMessage,e.currentStack):e.specOnly?DA(e.screenName,"",e.screenBrief,e.screenSpec):i?sv(e.screenName,e.screenBrief,e.currentDirection,e.currentScreenHtml,e.screenSpec,e.referenceScreenHtml):OA(e.spec,e.brief,e.refineMessage,e.currentDirection),timeoutSeconds:1200,bin:s.bin,mode:"read_only",maxTurns:60,sessionId:(0,Kc.randomUUID)(),onLog:()=>{}});if(be({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:"",...we(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=gr(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:[],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=gr(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:[],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,z,A)=>n.send({type:"rebirth.study.update",rebirthId:e.rebirthId,stageNumber:4,status:"in_progress",note:z,progressDone:0,progressTotal:0,artifact:"",items:[],brief:"",design:D,usageDelta:A});if(i){let z=Hc(a.resultText).screens.filter(A=>A.name===e.screenName).slice(0,1);return z.length?(l({direction:"",screens:z,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 d=Hc(a.resultText);if(!d.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:d.direction,screens:[],inventory:d.inventory,specs:[],partial:!0},`Screen list ready - ${d.inventory.length} screen(s) mapped. Drawing the missing ones\u2026`,c(a));let p=d.direction||e.currentDirection,f=new Set(e.existingScreenNames),g=d.inventory.filter(D=>!f.has(D.name)),k=g.slice(0,6),T=0,_=e.referenceScreenHtml;for(let[D,z]of k.entries()){r(`Drawing "${z.name}" (${D+1}/${k.length})\u2026`);let A=await s.adapter.run({repoPath:t.repoPath,prompt:sv(z.name,z.note,p,"","",_),timeoutSeconds:900,bin:s.bin,mode:"read_only",maxTurns:40,sessionId:(0,Kc.randomUUID)(),onLog:()=>{}});be({surface:"rebirth_design",projectId:t.project.id,agentId:s.adapter.id,refKind:"rebirth",refId:e.rebirthId,refLabel:z.name,...we(A)});let P=A.ok?Hc(A.resultText).screens.find(w=>w.name===z.name):void 0;P?(T+=1,_||(_=P.html),l({direction:"",screens:[P],inventory:[],specs:[],partial:!0},`"${z.name}" is ready (${T}/${k.length}). ${D+1<k.length?"Drawing the next\u2026":""}`,c(A))):l({direction:"",screens:[],inventory:[],specs:[],partial:!0},`"${z.name}" did not come back usable - skipped (ask for it again per-screen).`,c(A))}let $=g.length-k.length;return r(`UI design ready - ${T} screen(s) drawn this run`+($>0?`, ${$} 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 Ps,iv,Kc,Bc,ov,IA,Wc,EA,AA,$A,CA,PA,NA,OA,zA,DA,LA,sv,_h=X(()=>{"use strict";Ps=E(require("node:fs"),1),iv=E(require("node:zlib"),1),Kc=require("node:crypto");Et();lt();nn();rv();Bc=new Set;ov=500,IA=50;Wc=(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.
1344
1307
 
1345
1308
  --- CURRENT ${t.toUpperCase()} ---
1346
1309
  ${e}
1347
1310
  --- END CURRENT ${t.toUpperCase()} ---
1348
1311
 
1349
- `:"";AA=t=>Wc("technical understanding",t)+`You are studying a LEGACY codebase that will be rebuilt from scratch. Read it thoroughly - this document is what the rebuild's designers work from, and what you miss stays missed.
1312
+ `:"";EA=t=>Wc("technical understanding",t)+`You are studying a LEGACY codebase that will be rebuilt from scratch. Read it thoroughly - this document is what the rebuild's designers work from, and what you miss stays missed.
1350
1313
  Write a study document with these headings:
1351
1314
  What it is: the product, in plain words.
1352
1315
  How it works: the real architecture - entry points, flows, jobs, integrations.
@@ -1356,7 +1319,7 @@ Business rules: validations, permission-gated actions (including admin-only oper
1356
1319
  Feature inventory: every user-facing feature you can find evidence of, one line each.
1357
1320
  State of the code: age, quality, dead areas, the parts that clearly caused pain.
1358
1321
  Load-bearing surprises: anything a rebuild would break if nobody knew about it.
1359
- Under 4000 words. Factual, no advice yet - the design comes later. Depth beats brevity: a reviewer must be able to CODE from this document, not merely present it. An overview that names a feature without its rules is not done.`,$A=(t,e)=>Wc("requirements ledger",e)+`Below are summaries of the legacy project's Jira tickets - years of asks, fixes and incidents. Distill them into a REQUIREMENTS LEDGER for the rebuild:
1322
+ Under 4000 words. Factual, no advice yet - the design comes later. Depth beats brevity: a reviewer must be able to CODE from this document, not merely present it. An overview that names a feature without its rules is not done.`,AA=(t,e)=>Wc("requirements ledger",e)+`Below are summaries of the legacy project's Jira tickets - years of asks, fixes and incidents. Distill them into a REQUIREMENTS LEDGER for the rebuild:
1360
1323
  Asked and shipped: what the product verifiably does because someone asked.
1361
1324
  Kept breaking: areas with repeated bug tickets - name the pattern, not every ticket.
1362
1325
  Asked but never done: real demand the rebuild could finally serve.
@@ -1365,7 +1328,7 @@ Behavioural rules in the tickets: field rules, status meanings, permission asks,
1365
1328
  Under 2000 words. Cite ticket keys inline where they anchor a claim. Depth beats brevity - this ledger is what stops the rebuild from silently dropping a rule someone fought for.
1366
1329
 
1367
1330
  TICKETS:
1368
- ${t}`,CA=(t,e=[],n="",r=!1)=>Wc("SPEC",n)+`Now write the SPEC for the rebuild, from everything you have studied (the code document, the data profile, the requirements ledger${t?", and the extra context below":""}). A human reviews and approves this document; nothing downstream starts until they do - and the BUILD works from this document, so a condition the study found but the SPEC omits will be missing from the product.
1331
+ ${t}`,$A=(t,e=[],n="",r=!1)=>Wc("SPEC",n)+`Now write the SPEC for the rebuild, from everything you have studied (the code document, the data profile, the requirements ledger${t?", and the extra context below":""}). A human reviews and approves this document; nothing downstream starts until they do - and the BUILD works from this document, so a condition the study found but the SPEC omits will be missing from the product.
1369
1332
  Headings:
1370
1333
  Goal: what the rebuilt product is, in one paragraph.
1371
1334
  Target architecture & stack: concrete choices, with one line of why each.
@@ -1381,14 +1344,14 @@ ${e.map(s=>`- ${s}`).join(`
1381
1344
  `:"")+(t?`
1382
1345
  EXTRA CONTEXT from the person who knows this project:
1383
1346
  ${t}
1384
- `:"")+'\nEnd with EXACTLY one fenced json block - the build breakdown, 8-25 right-sized tickets in dependency order, each one reviewable PR of work:\n```json\n{"tickets": [{"title": "\u2026", "detail": "2-4 sentences: what and where"}]}\n```',PA=t=>Wc("project understanding",t)+`Now write the PROJECT UNDERSTANDING - the plain-language document a project manager reads and verifies. It must be readable by someone who will never open the code:
1347
+ `:"")+'\nEnd with EXACTLY one fenced json block - the build breakdown, 8-25 right-sized tickets in dependency order, each one reviewable PR of work:\n```json\n{"tickets": [{"title": "\u2026", "detail": "2-4 sentences: what and where"}]}\n```',CA=t=>Wc("project understanding",t)+`Now write the PROJECT UNDERSTANDING - the plain-language document a project manager reads and verifies. It must be readable by someone who will never open the code:
1385
1348
  What this product is: two or three sentences anyone would understand.
1386
1349
  Who uses it and for what: the real users and their main tasks.
1387
1350
  What it keeps track of: the data, in business words (customers, devices, orders - never table names).
1388
1351
  How work flows through it: the main journeys, step by step.
1389
1352
  What is fragile or unclear: risks and open questions, honestly.
1390
1353
  What we still have not seen: gaps in this understanding.
1391
- No jargon, no file names, no framework names. Under 800 words. This document is updated every time the understanding deepens, and a person signs off on it - write it for them.`,NA={brief:"plain-language PROJECT UNDERSTANDING (the manager-facing brief)",understanding:"technical UNDERSTANDING document",requirements:"REQUIREMENTS ledger",spec:"SPEC"},MA=(t,e,n)=>`The person who KNOWS this project says something is missing or wrong:
1354
+ No jargon, no file names, no framework names. Under 800 words. This document is updated every time the understanding deepens, and a person signs off on it - write it for them.`,PA={brief:"plain-language PROJECT UNDERSTANDING (the manager-facing brief)",understanding:"technical UNDERSTANDING document",requirements:"REQUIREMENTS ledger",spec:"SPEC"},NA=(t,e,n)=>`The person who KNOWS this project says something is missing or wrong:
1392
1355
 
1393
1356
  "${t}"
1394
1357
 
@@ -1398,7 +1361,7 @@ Below are the CURRENT documents. Fold the correction INTO them - every fact they
1398
1361
 
1399
1362
  This is a DIFF-REVIEWED edit, not a rewrite - your output is PROPOSED, not applied: the person sees it as separate change hunks and approves or rejects each one. So reproduce every sentence the correction does not touch VERBATIM - same words, same order, same headings; every needless rewording becomes a junk hunk they must reject by hand. And detail is only ever ADDED or corrected, never summarized away: the updated document keeps every condition, rule, field and branch the current one records, so it is normally no shorter than the current one - if yours comes out smaller, you have dropped something; go back and restore it.
1400
1363
 
1401
- `+(n!=="all"?`SCOPE: this refold may change ONLY the ${NA[n]} - every other document is read-only context. Whatever you notice elsewhere, say it in prose; output no other document block.
1364
+ `+(n!=="all"?`SCOPE: this refold may change ONLY the ${PA[n]} - every other document is read-only context. Whatever you notice elsewhere, say it in prose; output no other document block.
1402
1365
 
1403
1366
  `:"")+`--- CURRENT PROJECT UNDERSTANDING (manager-facing brief) ---
1404
1367
  ${e.brief||"(none yet)"}
@@ -1412,7 +1375,7 @@ ${e.requirements||"(none yet)"}
1412
1375
  --- CURRENT SPEC ---
1413
1376
  ${e.spec||"(none yet)"}
1414
1377
 
1415
- `+(n==="all"?"Output, in this order:\n1. If it changes the plain-language PROJECT UNDERSTANDING (the manager-facing brief), a fenced block:\n```brief\n<the full updated project understanding, plain language>\n```\n Omit when unchanged.\n2. If the correction changes your technical UNDERSTANDING of the product/code, a fenced block:\n```understanding\n<the full updated understanding document>\n```\n Omit the block entirely when the understanding is unchanged.\n3. If it changes the REQUIREMENTS ledger, a fenced block the same way:\n```requirements\n<the full updated requirements ledger>\n```\n4. ALWAYS: the full updated SPEC - the current one with the correction folded in, same headings, same discipline - ending with the fenced json ticket breakdown again (adjusted only where the correction changes the work).":n==="spec"?"Output: the full updated SPEC - the current one with the correction folded in, same headings, same discipline - ending with the fenced json ticket breakdown again (adjusted only where the correction changes the work).":"Output: exactly one fenced block with the full updated document:\n```"+n+"\n<the full updated document>\n```");zA=(t,e,n,r)=>(n?`The person reviewing the UI design says:
1378
+ `+(n==="all"?"Output, in this order:\n1. If it changes the plain-language PROJECT UNDERSTANDING (the manager-facing brief), a fenced block:\n```brief\n<the full updated project understanding, plain language>\n```\n Omit when unchanged.\n2. If the correction changes your technical UNDERSTANDING of the product/code, a fenced block:\n```understanding\n<the full updated understanding document>\n```\n Omit the block entirely when the understanding is unchanged.\n3. If it changes the REQUIREMENTS ledger, a fenced block the same way:\n```requirements\n<the full updated requirements ledger>\n```\n4. ALWAYS: the full updated SPEC - the current one with the correction folded in, same headings, same discipline - ending with the fenced json ticket breakdown again (adjusted only where the correction changes the work).":n==="spec"?"Output: the full updated SPEC - the current one with the correction folded in, same headings, same discipline - ending with the fenced json ticket breakdown again (adjusted only where the correction changes the work).":"Output: exactly one fenced block with the full updated document:\n```"+n+"\n<the full updated document>\n```");OA=(t,e,n,r)=>(n?`The person reviewing the UI design says:
1416
1379
 
1417
1380
  "${n}"
1418
1381
 
@@ -1430,11 +1393,11 @@ ${e.slice(0,2e4)}
1430
1393
 
1431
1394
  ${r.slice(0,4e4)}
1432
1395
 
1433
- `:"Produce FIRST a fenced block with the UI DIRECTION document:\n```direction\n# UI direction\n- Palette (hex values, light/dark stance), typography (real font stacks), spacing/density, component inventory (tables, forms, nav shape), and the 3-5 design decisions that make THIS product's daily work faster. Under 700 words.\n```\n")+'Then a fenced block listing EVERY screen the finished product needs - enumerate the legacy frontend\'s routes/pages/menus AND the SPEC completely (a real product usually has 15-40; list them ALL), as JSON:\n```inventory\n[{"name":"Dashboard","note":"one line on what it is for"}, \u2026]\n```\nNames are identifiers - short, stable, unique. Do NOT write any screen HTML in this answer; screens are drawn separately, one at a time.',DA=`Each screen: ONE self-contained HTML file - all CSS inline in a <style> tag, realistic data from the product's own domain (never lorem), desktop layout that degrades sanely, NO external requests (no CDNs, no fonts, no images - use CSS shapes and unicode). NO <script> tags and NO on* attributes - they are stripped before display. The mockups are CLICKABLE like a Figma prototype, with two devices only:
1396
+ `:"Produce FIRST a fenced block with the UI DIRECTION document:\n```direction\n# UI direction\n- Palette (hex values, light/dark stance), typography (real font stacks), spacing/density, component inventory (tables, forms, nav shape), and the 3-5 design decisions that make THIS product's daily work faster. Under 700 words.\n```\n")+'Then a fenced block listing EVERY screen the finished product needs - enumerate the legacy frontend\'s routes/pages/menus AND the SPEC completely (a real product usually has 15-40; list them ALL), as JSON:\n```inventory\n[{"name":"Dashboard","note":"one line on what it is for"}, \u2026]\n```\nNames are identifiers - short, stable, unique. Do NOT write any screen HTML in this answer; screens are drawn separately, one at a time.',zA=`Each screen: ONE self-contained HTML file - all CSS inline in a <style> tag, realistic data from the product's own domain (never lorem), desktop layout that degrades sanely, NO external requests (no CDNs, no fonts, no images - use CSS shapes and unicode). NO <script> tags and NO on* attributes - they are stripped before display. The mockups are CLICKABLE like a Figma prototype, with two devices only:
1434
1397
  - Navigation: any element that would take the user to another screen gets data-screen="<exact inventory name>" (nav items, buttons, table rows, links - href="#" is fine, the attribute does the work). Use them everywhere navigation is implied.
1435
1398
  - Popups/modals/menus: draw them in the same file, hidden, opened with CSS :target - <a href="#new-invoice">New invoice</a> opens <div id="new-invoice" class="modal"> via .modal{display:none} .modal:target{display:flex}, with a close link href="#".
1436
1399
  SCOPE DISCIPLINE: draw ONLY what the screen's job needs. A simple screen stays simple - a login or forgot-password screen is its fields and a button, not a dashboard; do not invent panels, stats, tips or widgets the legacy code or the details document never had. A list screen gets its real table and filters; a form gets its real fields. Density should match the REAL screen's job - when in doubt, less.
1437
- These are design artifacts the build will consume - clean, consistent, on the direction.`,LA=(t,e,n,r)=>`You are documenting ONE screen of a legacy product being rebuilt. The legacy frontend code may be in your working directory - READ it and write facts from the code, not guesses; where the code answers nothing, say "not found in the legacy code" rather than inventing.
1400
+ These are design artifacts the build will consume - clean, consistent, on the direction.`,DA=(t,e,n,r)=>`You are documenting ONE screen of a legacy product being rebuilt. The legacy frontend code may be in your working directory - READ it and write facts from the code, not guesses; where the code answers nothing, say "not found in the legacy code" rather than inventing.
1438
1401
 
1439
1402
  THE SCREEN: "${t}"${e?` - ${e}`:""}
1440
1403
  `+(n?`The person asking adds:
@@ -1461,7 +1424,7 @@ Fold their words in - they win over the code.
1461
1424
  ## Other options
1462
1425
  - buttons, bulk actions, imports/exports (with file rules), states (empty/loading/error)
1463
1426
  \`\`\`
1464
- Markdown inside the block, factual, code-anchored. Depth beats brevity: a developer must be able to REBUILD this screen from the document alone. Where the code answers nothing, write "not found in the legacy code" - never guess.`,UA=(t,e,n,r)=>(n?`The person deciding the stack says:
1427
+ Markdown inside the block, factual, code-anchored. Depth beats brevity: a developer must be able to REBUILD this screen from the document alone. Where the code answers nothing, write "not found in the legacy code" - never guess.`,LA=(t,e,n,r)=>(n?`The person deciding the stack says:
1465
1428
 
1466
1429
  "${n}"
1467
1430
 
@@ -1507,9 +1470,9 @@ ${s.slice(0,2e4)}
1507
1470
  "${e}"
1508
1471
  Their words win.
1509
1472
 
1510
- `:"")+(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"+DA});var jo={};De(jo,{appendRebirthUploadChunk:()=>GA,beginRebirthUpload:()=>KA,rebirthUploadsDir:()=>Mo,uploadedCodeDir:()=>FA,uploadedDumpPath:()=>BA});function Mo(t){return Ge.default.join(te(),"rebirth-uploads",t.replace(/[^\w-]/g,""))}function FA(t){let e=Ge.default.join(Mo(t),"code");try{return Ie.default.readdirSync(e).length>0?e:null}catch{return null}}function BA(t){let e=Ge.default.join(Mo(t),"db");try{let n=Ie.default.readdirSync(e).filter(r=>!/\.(rar|zip|7z|tar|tgz|bz2|xz)$/i.test(r)||Ie.default.statSync(Ge.default.join(e,r)).isDirectory()).map(r=>({f:r,at:Ie.default.statSync(Ge.default.join(e,r)).mtimeMs})).sort((r,s)=>s.at-r.at);return n.length?Ge.default.join(e,n[0].f):null}catch{return null}}function HA(){let t=Date.now();for(let[e,n]of Ns)if(t-n.startedAt>36e5){try{Ie.default.closeSync(n.fd),Ie.default.rmSync(n.filePath,{force:!0})}catch{}Ns.delete(e)}}function KA(t){HA();let e=Ge.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=Ge.default.join(Mo(t.rebirthId),"incoming");Ie.default.mkdirSync(n,{recursive:!0});let r=(0,dv.randomUUID)(),s=Ge.default.join(n,`${r}-${e}`),i=Ie.default.openSync(s,"w");return Ns.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 lv(t){let e=/\.zip$/i.test(t),{stdout:n}=e?await Un("unzip",["-Z1",t],{maxBuffer:2e7}):await Un("tar",["-tzf",t],{maxBuffer:2e7});for(let r of n.split(`
1511
- `)){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 WA(t){Ie.default.closeSync(t.fd);let e=Mo(t.rebirthId);if(t.kind==="dump"){let r=Ge.default.join(e,"db");if(Ie.default.mkdirSync(r,{recursive:!0}),/\.(zip|tar\.gz|tgz)$/i.test(t.name)){await lv(t.filePath);let i=Ge.default.join(r,t.name.replace(/\.(zip|tar\.gz|tgz)$/i,""));return Ie.default.rmSync(i,{recursive:!0,force:!0}),Ie.default.mkdirSync(i,{recursive:!0}),/\.zip$/i.test(t.name)?await Un("unzip",["-q",t.filePath,"-d",i],{maxBuffer:1e7,timeout:3e5}):await Un("tar",["-xzf",t.filePath,"-C",i],{maxBuffer:1e7,timeout:3e5}),Ie.default.rmSync(t.filePath,{force:!0}),{storedPath:i,note:"dump archive extracted - the next study run profiles it (MongoDB dumps supported)"}}let s=Ge.default.join(r,t.name);return Ie.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=Ge.default.join(e,"code","docs");Ie.default.mkdirSync(r,{recursive:!0});let s=Ge.default.join(r,t.name);return Ie.default.renameSync(t.filePath,s),{storedPath:s,note:"document stored - the next study run reads it"}}await lv(t.filePath);let n=Ge.default.join(e,"code",t.kind==="docs"?"docs":t.kind);if(Ie.default.rmSync(n,{recursive:!0,force:!0}),Ie.default.mkdirSync(n,{recursive:!0}),/\.zip$/i.test(t.filePath)?await Un("unzip",["-q",t.filePath,"-d",n],{maxBuffer:1e7,timeout:3e5}):await Un("tar",["-xzf",t.filePath,"-C",n],{maxBuffer:1e7,timeout:3e5}),Ie.default.rmSync(t.filePath,{force:!0}),!Ie.default.existsSync(Ge.default.join(n,".git")))try{await Un("git",["init","-q"],{cwd:n}),await Un("git",["add","-A"],{cwd:n,maxBuffer:1e7}),await Un("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 GA(t){let e=Ns.get(t.uploadId);if(!e)return{ok:!1,error:"unknown or expired upload - start it again"};if(t.seq!==e.nextSeq){Ns.delete(t.uploadId);try{Ie.default.closeSync(e.fd),Ie.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 Ie.default.writeSync(e.fd,Buffer.from(t.dataBase64,"base64")),e.nextSeq+=1,t.last?(Ns.delete(t.uploadId),{ok:!0,...await WA(e)}):{ok:!0,storedPath:"",note:""}}catch(n){Ns.delete(t.uploadId);try{Ie.default.closeSync(e.fd)}catch{}Ie.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 Ie,Ge,dv,uv,hv,Un,Ns,Oo=X(()=>{"use strict";Ie=E(require("node:fs"),1),Ge=E(require("node:path"),1),dv=require("node:crypto"),uv=require("node:child_process"),hv=require("node:util");Ae();lt();Un=(0,hv.promisify)(uv.execFile),Ns=new Map});var xh={};De(xh,{databasesFromEnvFiles:()=>gv,executeDecommission:()=>e$,guardPath:()=>mv,planDecommission:()=>yv});async function fn(t,e,n=VA){try{let{stdout:r}=await ZA(t,e,{timeout:n,maxBuffer:4e6});return r}catch{return""}}function mv(t,e){let n=gt.default.resolve(e);if(!gt.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=gt.default.resolve(a.path);if(n===c||n.startsWith(c+gt.default.sep)||c.startsWith(n+gt.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=Dt.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(!Dt.default.existsSync(gt.default.join(n,".git")))return{ok:!1,error:`${n} is not a git checkout - this flow removes checkouts only`};let s=gt.default.resolve(process.cwd());return s===n||s.startsWith(n+gt.default.sep)?{ok:!1,error:`${n} contains this runner itself - not removable from here`}:{ok:!0,dir:n}}async function YA(t){let e=[];for(let n of["/etc/systemd/system","/usr/lib/systemd/system","/lib/systemd/system"]){let r=[];try{r=Dt.default.readdirSync(n).filter(s=>s.endsWith(".service"))}catch{continue}for(let s of r.slice(0,400)){try{if(Dt.default.readFileSync(gt.default.join(n,s),"utf8").includes(t)){let a=(await fn("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 JA(t){let e=new Map;for(let i of lr(await fn("ss",["-tlnpH"])))i.pid>0&&e.set(i.pid,[...e.get(i.pid)??[],i.port]);let n=[],r=[];try{r=Dt.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=Dt.default.readlinkSync(`/proc/${a}/cwd`),l=Dt.default.readFileSync(`/proc/${a}/cmdline`,"utf8").replaceAll("\0"," ").trim();if((c===t||c.startsWith(t+gt.default.sep)||l.includes(t+gt.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 XA(t){let e=(await fn("docker",["ps","-a","--format","{{.Names}}"])).split(`
1512
- `).filter(Boolean).slice(0,60),n=[];for(let r of e){let s=await fn("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 gv(t){let e=[],n=[],r=new Set,s=[];try{s=Dt.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=Dt.default.readFileSync(gt.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 d=new URL(`${c[1]}://${c[2]}`),p=d.pathname.replace(/^\//,"").split("?")[0];if(!p||r.has(`${l}:${p}`))continue;QA.has(d.hostname)?(r.add(`${l}:${p}`),e.push({name:p,engine:l,source:i})):n.push(`${i} names a REMOTE ${l} database "${p}" on ${d.hostname} - not offered here, clean it up where it lives`)}catch{}}}return{databases:e,warnings:n}}async function yv(t,e){let n={path:"",sizeMb:0,services:[],processes:[],containers:[],databases:[],warnings:[]},r=mv(t,e);if(!r.ok)return{ok:!1,error:r.error,...n};let s=r.dir,[i,a,c,l]=await Promise.all([fn("du",["-sm",s],3e4),YA(s),JA(s),XA(s)]),{databases:d,warnings:p}=gv(s);return{ok:!0,path:s,sizeMb:Number(i.split(" ")[0])||0,services:a,processes:c,containers:l,databases:d,warnings:p}}async function e$(t,e,n){let r=await yv(t,e.path);if(!r.ok){n({label:"Check the path",ok:!1,detail:r.error??"refused"});return}let s=r.path,i=(f,g)=>f.filter(v=>g.includes(v)),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 g=await fn("sudo",["-n","systemctl","disable","--now",`${f}.service`]).then(async()=>(await fn("systemctl",["is-active",`${f}.service`])).trim());n(g==="inactive"||g==="failed"||g==="unknown"||g===""?{label:`Stop service ${f}`,ok:!0,detail:"stopped and disabled"}:{label:`Stop service ${f}`,ok:!1,detail:`still ${g} - 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 g=r.processes.find(v=>v.pid===f)?.ports??[];try{process.kill(f,"SIGTERM"),await new Promise(v=>setTimeout(v,2e3));try{process.kill(f,0),process.kill(f,"SIGKILL")}catch{}n({label:`Stop process ${f}`,ok:!0,detail:g.length?`stopped - port${g.length>1?"s":""} ${g.join(", ")} freed`:"stopped"})}catch(v){n({label:`Stop process ${f}`,ok:!1,detail:v instanceof Error?v.message:String(v)})}}let d=i(e.containers,r.containers.map(f=>f.name));for(let f of e.containers.filter(g=>!d.includes(g)))n({label:`Remove container ${f}`,ok:!1,detail:"not in this checkout's plan - refused"});for(let f of d){let g=await fn("docker",["rm","-f",f]);n({label:`Remove container ${f}`,ok:g.trim()===f,detail:g.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 g=p.get(f);if(!g){n({label:`Drop database ${f}`,ok:!1,detail:"not named by this checkout's own env files - refused"});continue}if(g.engine==="postgres"){let k=(await fn("sudo",["-n","-u","postgres","psql","-c",`DROP DATABASE IF EXISTS "${f}"`])).includes("DROP DATABASE");n({label:`Drop database ${f}`,ok:k,detail:k?"dropped":`could not drop it from here - run: sudo -u postgres psql -c 'DROP DATABASE "${f}"'`})}else{let k=(await fn("sudo",["-n","mysql","-N","-e",`DROP DATABASE IF EXISTS \`${f}\`; SELECT 'dropped'`])).includes("dropped");n({label:`Drop database ${f}`,ok:k,detail:k?"dropped":`could not drop it from here - run: sudo mysql -e 'DROP DATABASE \`${f}\`'`})}}if(e.deleteFolder)try{Dt.default.rmSync(s,{recursive:!0,force:!0});let f=!Dt.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 Dt,gt,pv,fv,ZA,VA,QA,Th=X(()=>{"use strict";Dt=E(require("node:fs"),1),gt=E(require("node:path"),1),pv=require("node:child_process"),fv=require("node:util");mo();ZA=(0,fv.promisify)(pv.execFile),VA=15e3;QA=new Set(["localhost","127.0.0.1","::1","0.0.0.0"])});function bv(t,...e){try{return JSON.parse(Zc.default.readFileSync(Vc.default.join(t,...e),"utf8"))}catch{return null}}function Gc(t,...e){try{return Zc.default.readFileSync(Vc.default.join(t,...e),"utf8")}catch{return""}}function s$(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(Gc(t,e));if(n)return`${{postgresql:"PostgreSQL",mysql:"MySQL",sqlite:"SQLite",mongodb:"MongoDB",sqlserver:"SQL Server",cockroachdb:"CockroachDB"}[n[1]]} (Prisma)`}return""}function wv(t){let e={languages:[],frameworks:[],databases:[],docker:Oe(t,"Dockerfile"),dockerCompose:Oe(t,"docker-compose.yml")||Oe(t,"docker-compose.yaml")||Oe(t,"compose.yml")||Oe(t,"compose.yaml"),packageManager:"",monorepo:""},n=(i,a)=>{a&&!i.includes(a)&&i.push(a)},r=bv(t,"package.json");if(r){n(e.languages,Oe(t,"tsconfig.json")?"TypeScript":"JavaScript");let i={...r.dependencies,...r.devDependencies};for(let[a,c]of t$)i[a]&&n(e.frameworks,c);n(e.databases,i.prisma||i["@prisma/client"]?s$(t):"");for(let[a,c]of n$)i[a]&&n(e.databases,c);e.packageManager=Oe(t,"pnpm-lock.yaml")?"pnpm":Oe(t,"yarn.lock")?"yarn":Oe(t,"package-lock.json")?"npm":"",e.monorepo=Oe(t,"pnpm-workspace.yaml")?"pnpm workspaces":Oe(t,"turbo.json")?"turborepo":r.workspaces?"npm/yarn workspaces":""}let s=(Gc(t,"requirements.txt")+Gc(t,"pyproject.toml")).toLowerCase();if(s||Oe(t,"manage.py")){n(e.languages,"Python");for(let[i,a]of r$)(s.includes(i)||i==="django"&&Oe(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=Oe(t,"poetry.lock")?"poetry":Oe(t,"requirements.txt")?"pip":"")}return Oe(t,"go.mod")&&n(e.languages,"Go"),Oe(t,"Cargo.toml")&&n(e.languages,"Rust"),Oe(t,"composer.json")&&(n(e.languages,"PHP"),(bv(t,"composer.json")?.require??{})["laravel/framework"]&&n(e.frameworks,"Laravel")),Oe(t,"Gemfile")&&(n(e.languages,"Ruby"),Gc(t,"Gemfile").includes("rails")&&n(e.frameworks,"Rails")),(Oe(t,"pom.xml")||Oe(t,"build.gradle")||Oe(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 Zc,Vc,Oe,t$,n$,r$,vv=X(()=>{"use strict";Zc=E(require("node:fs"),1),Vc=E(require("node:path"),1),Oe=(t,...e)=>Zc.default.existsSync(Vc.default.join(t,...e));t$=[["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"]],n$=[["mongoose","MongoDB"],["mongodb","MongoDB"],["pg","PostgreSQL"],["postgres","PostgreSQL"],["mysql2","MySQL"],["mysql","MySQL"],["better-sqlite3","SQLite"],["sqlite3","SQLite"],["redis","Redis"],["ioredis","Redis"]],r$=[["django","Django"],["flask","Flask"],["fastapi","FastAPI"]]});var $v={};De($v,{buildAgentReport:()=>Av,buildSetupReport:()=>c$,claudeLoggedIn:()=>Rv,codexLoggedIn:()=>Iv,kimiLoggedIn:()=>Ev,repoCurrentBranch:()=>xv,repoDefaultBranch:()=>Tv});function xv(t){try{let e=(0,zo.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Tv(t){let e=(...s)=>{try{return(0,zo.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 Rv(t=Do.default.homedir()){if(Gt.default.existsSync(mn.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Gt.default.readFileSync(mn.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}function o$(t){try{return Gt.default.readdirSync(t).length>0}catch{return!1}}function Iv(t=Do.default.homedir()){return Gt.default.existsSync(mn.default.join(t,".codex","auth.json"))}function Ev(t=Do.default.homedir()){return o$(mn.default.join(t,".kimi","credentials"))||Gt.default.existsSync(mn.default.join(t,".kimi","credentials.json"))}async function a$(t){let e=Sv.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 i$(t,["--version"],{timeout:1e4});n=!0,r=s.trim().slice(0,60)}catch{n=!1}return Sv.set(t,{at:Date.now(),installed:n,version:r}),{installed:n,version:r}}async function Av(t){let e=Yc.REGISTERED_AGENTS.filter(r=>kv[r.id]),n=await Promise.all(e.map(async r=>{let{installed:s,version:i}=await a$(Be(t,r.id)),a=kv[r.id](Do.default.homedir());return[r.id,{installed:s,version:i,loggedIn:a}]}));return Object.fromEntries(n)}async function c$(t,e,n){let r=await Av(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=Gt.default.existsSync(c.path);return{repoName:a,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[a]:!0,pathExists:l,isGit:l&&Gt.default.existsSync(mn.default.join(c.path,".git")),currentBranch:l?xv(c.path):"",claudeMd:l&&Gt.default.existsSync(mn.default.join(c.path,"CLAUDE.md")),deployMd:l&&Gt.default.existsSync(mn.default.join(c.path,"DEPLOY.md")),testMd:l&&Gt.default.existsSync(mn.default.join(c.path,"TEST.md")),githubToken:!!Qe(t,a),githubTokenOwn:!!c.github?.token,defaultBranch:l?Tv(c.path):"",architecture:l?wv(c.path):void 0}}),i=Object.values(t.repos).find(a=>a.github?.token);return{jiraConfigured:!!t.jira,...(()=>{let a=yo();return{serviceProtected:a.protected,serviceProtectFix:a.protected===!1?a.fixCommand:""}})(),jiraEmail:t.jira?.email??"",agents:r,claude:r[Yc.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 zo,Gt,Do,mn,_v,Yc,i$,kv,Sv,Cv=X(()=>{"use strict";zo=require("node:child_process");lc();Gt=E(require("node:fs"),1),Do=E(require("node:os"),1),mn=E(require("node:path"),1),_v=require("node:util"),Yc=E(Ne(),1);Et();is();vv();i$=(0,_v.promisify)(zo.execFile);kv={"claude-code":Rv,codex:Iv,kimi:Ev},Sv=new Map});var zv={};De(zv,{discoverForMonitoring:()=>Ih});async function Nv(t,e){try{let{stdout:n}=await l$(t,e,{timeout:d$,maxBuffer:4e6});return n}catch{return""}}function m$(t){let e;try{e=Jc.default.readdirSync(t)}catch{return null}let n=null;for(let r of e.slice(0,500))if(p$.some(s=>r.endsWith(s)))try{let s=Jc.default.statSync(Rh.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 Ih(){let[t,e]=await Promise.all([Nv("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain","--no-pager"]),Nv("ss",["-tlnpH"])]),n=[];for(let c of Ba(t)){let l=c.name.replace(/\.service$/,""),d=Object.keys(Pv).find(p=>l===p||l.startsWith(p+"@")||l.startsWith(p+"-"));if(d&&n.push({name:l,kind:Pv[d]}),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 lr(e)){let l=u$[c.port];l&&!s.some(d=>d.kind===l)&&s.push({kind:l,port:c.port})}let i=[...h$];try{for(let c of Jc.default.readdirSync("/home").slice(0,20))i.push(Rh.default.join("/home",c,"backups"))}catch{}let a=[];for(let c of i){if(a.length>=f$)break;let l=m$(c);l&&a.push({path:c,...l})}return{os:{platform:process.platform,arch:process.arch,release:Mv.default.release().slice(0,60)},services:n,webServers:r,backupCandidates:a,dbHints:s}}var Jc,Mv,Rh,jv,Ov,l$,d$,Pv,u$,h$,p$,f$,Eh=X(()=>{"use strict";Jc=E(require("node:fs"),1),Mv=E(require("node:os"),1),Rh=E(require("node:path"),1),jv=require("node:child_process"),Ov=require("node:util");mo();l$=(0,Ov.promisify)(jv.execFile),d$=8e3,Pv={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"},u$={5432:"postgres",3306:"mysql",27017:"mongodb",6379:"redis"},h$=["/backups","/backup","/var/backups","/root/backups","/opt/backups","/srv/backups"],p$=[".sql",".sql.gz",".dump",".tar.gz",".tgz",".zip",".gz",".bak"],f$=20});var Uv={};De(Uv,{parseSuggestion:()=>Lv,suggestMonitorCheck:()=>y$});function Lv(t){let e=[...t.matchAll(/```json\s*\n([\s\S]*?)```/g)];for(let n=e.length-1;n>=0;n--)try{let r=g$.safeParse(JSON.parse(e[n][1]));if(r.success)return r.data}catch{}return null}async function y$(t){let e={name:"",commands:[],parseRules:{amberPattern:"",redPattern:"",greenRequires:""},notes:""},n=await Ih().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:
1473
+ `:"")+(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"+zA});var jo={};De(jo,{appendRebirthUploadChunk:()=>WA,beginRebirthUpload:()=>HA,rebirthUploadsDir:()=>Mo,uploadedCodeDir:()=>qA,uploadedDumpPath:()=>FA});function Mo(t){return Ge.default.join(te(),"rebirth-uploads",t.replace(/[^\w-]/g,""))}function qA(t){let e=Ge.default.join(Mo(t),"code");try{return Ie.default.readdirSync(e).length>0?e:null}catch{return null}}function FA(t){let e=Ge.default.join(Mo(t),"db");try{let n=Ie.default.readdirSync(e).filter(r=>!/\.(rar|zip|7z|tar|tgz|bz2|xz)$/i.test(r)||Ie.default.statSync(Ge.default.join(e,r)).isDirectory()).map(r=>({f:r,at:Ie.default.statSync(Ge.default.join(e,r)).mtimeMs})).sort((r,s)=>s.at-r.at);return n.length?Ge.default.join(e,n[0].f):null}catch{return null}}function BA(){let t=Date.now();for(let[e,n]of Ns)if(t-n.startedAt>36e5){try{Ie.default.closeSync(n.fd),Ie.default.rmSync(n.filePath,{force:!0})}catch{}Ns.delete(e)}}function HA(t){BA();let e=Ge.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=Ge.default.join(Mo(t.rebirthId),"incoming");Ie.default.mkdirSync(n,{recursive:!0});let r=(0,dv.randomUUID)(),s=Ge.default.join(n,`${r}-${e}`),i=Ie.default.openSync(s,"w");return Ns.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 lv(t){let e=/\.zip$/i.test(t),{stdout:n}=e?await Un("unzip",["-Z1",t],{maxBuffer:2e7}):await Un("tar",["-tzf",t],{maxBuffer:2e7});for(let r of n.split(`
1474
+ `)){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 KA(t){Ie.default.closeSync(t.fd);let e=Mo(t.rebirthId);if(t.kind==="dump"){let r=Ge.default.join(e,"db");if(Ie.default.mkdirSync(r,{recursive:!0}),/\.(zip|tar\.gz|tgz)$/i.test(t.name)){await lv(t.filePath);let i=Ge.default.join(r,t.name.replace(/\.(zip|tar\.gz|tgz)$/i,""));return Ie.default.rmSync(i,{recursive:!0,force:!0}),Ie.default.mkdirSync(i,{recursive:!0}),/\.zip$/i.test(t.name)?await Un("unzip",["-q",t.filePath,"-d",i],{maxBuffer:1e7,timeout:3e5}):await Un("tar",["-xzf",t.filePath,"-C",i],{maxBuffer:1e7,timeout:3e5}),Ie.default.rmSync(t.filePath,{force:!0}),{storedPath:i,note:"dump archive extracted - the next study run profiles it (MongoDB dumps supported)"}}let s=Ge.default.join(r,t.name);return Ie.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=Ge.default.join(e,"code","docs");Ie.default.mkdirSync(r,{recursive:!0});let s=Ge.default.join(r,t.name);return Ie.default.renameSync(t.filePath,s),{storedPath:s,note:"document stored - the next study run reads it"}}await lv(t.filePath);let n=Ge.default.join(e,"code",t.kind==="docs"?"docs":t.kind);if(Ie.default.rmSync(n,{recursive:!0,force:!0}),Ie.default.mkdirSync(n,{recursive:!0}),/\.zip$/i.test(t.filePath)?await Un("unzip",["-q",t.filePath,"-d",n],{maxBuffer:1e7,timeout:3e5}):await Un("tar",["-xzf",t.filePath,"-C",n],{maxBuffer:1e7,timeout:3e5}),Ie.default.rmSync(t.filePath,{force:!0}),!Ie.default.existsSync(Ge.default.join(n,".git")))try{await Un("git",["init","-q"],{cwd:n}),await Un("git",["add","-A"],{cwd:n,maxBuffer:1e7}),await Un("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 WA(t){let e=Ns.get(t.uploadId);if(!e)return{ok:!1,error:"unknown or expired upload - start it again"};if(t.seq!==e.nextSeq){Ns.delete(t.uploadId);try{Ie.default.closeSync(e.fd),Ie.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 Ie.default.writeSync(e.fd,Buffer.from(t.dataBase64,"base64")),e.nextSeq+=1,t.last?(Ns.delete(t.uploadId),{ok:!0,...await KA(e)}):{ok:!0,storedPath:"",note:""}}catch(n){Ns.delete(t.uploadId);try{Ie.default.closeSync(e.fd)}catch{}Ie.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 Ie,Ge,dv,uv,hv,Un,Ns,Oo=X(()=>{"use strict";Ie=E(require("node:fs"),1),Ge=E(require("node:path"),1),dv=require("node:crypto"),uv=require("node:child_process"),hv=require("node:util");Ae();lt();Un=(0,hv.promisify)(uv.execFile),Ns=new Map});var xh={};De(xh,{databasesFromEnvFiles:()=>gv,executeDecommission:()=>QA,guardPath:()=>mv,planDecommission:()=>yv});async function fn(t,e,n=ZA){try{let{stdout:r}=await GA(t,e,{timeout:n,maxBuffer:4e6});return r}catch{return""}}function mv(t,e){let n=gt.default.resolve(e);if(!gt.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=gt.default.resolve(a.path);if(n===c||n.startsWith(c+gt.default.sep)||c.startsWith(n+gt.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=Dt.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(!Dt.default.existsSync(gt.default.join(n,".git")))return{ok:!1,error:`${n} is not a git checkout - this flow removes checkouts only`};let s=gt.default.resolve(process.cwd());return s===n||s.startsWith(n+gt.default.sep)?{ok:!1,error:`${n} contains this runner itself - not removable from here`}:{ok:!0,dir:n}}async function VA(t){let e=[];for(let n of["/etc/systemd/system","/usr/lib/systemd/system","/lib/systemd/system"]){let r=[];try{r=Dt.default.readdirSync(n).filter(s=>s.endsWith(".service"))}catch{continue}for(let s of r.slice(0,400)){try{if(Dt.default.readFileSync(gt.default.join(n,s),"utf8").includes(t)){let a=(await fn("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 YA(t){let e=new Map;for(let i of lr(await fn("ss",["-tlnpH"])))i.pid>0&&e.set(i.pid,[...e.get(i.pid)??[],i.port]);let n=[],r=[];try{r=Dt.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=Dt.default.readlinkSync(`/proc/${a}/cwd`),l=Dt.default.readFileSync(`/proc/${a}/cmdline`,"utf8").replaceAll("\0"," ").trim();if((c===t||c.startsWith(t+gt.default.sep)||l.includes(t+gt.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 JA(t){let e=(await fn("docker",["ps","-a","--format","{{.Names}}"])).split(`
1475
+ `).filter(Boolean).slice(0,60),n=[];for(let r of e){let s=await fn("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 gv(t){let e=[],n=[],r=new Set,s=[];try{s=Dt.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=Dt.default.readFileSync(gt.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 d=new URL(`${c[1]}://${c[2]}`),p=d.pathname.replace(/^\//,"").split("?")[0];if(!p||r.has(`${l}:${p}`))continue;XA.has(d.hostname)?(r.add(`${l}:${p}`),e.push({name:p,engine:l,source:i})):n.push(`${i} names a REMOTE ${l} database "${p}" on ${d.hostname} - not offered here, clean it up where it lives`)}catch{}}}return{databases:e,warnings:n}}async function yv(t,e){let n={path:"",sizeMb:0,services:[],processes:[],containers:[],databases:[],warnings:[]},r=mv(t,e);if(!r.ok)return{ok:!1,error:r.error,...n};let s=r.dir,[i,a,c,l]=await Promise.all([fn("du",["-sm",s],3e4),VA(s),YA(s),JA(s)]),{databases:d,warnings:p}=gv(s);return{ok:!0,path:s,sizeMb:Number(i.split(" ")[0])||0,services:a,processes:c,containers:l,databases:d,warnings:p}}async function QA(t,e,n){let r=await yv(t,e.path);if(!r.ok){n({label:"Check the path",ok:!1,detail:r.error??"refused"});return}let s=r.path,i=(f,g)=>f.filter(v=>g.includes(v)),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 g=await fn("sudo",["-n","systemctl","disable","--now",`${f}.service`]).then(async()=>(await fn("systemctl",["is-active",`${f}.service`])).trim());n(g==="inactive"||g==="failed"||g==="unknown"||g===""?{label:`Stop service ${f}`,ok:!0,detail:"stopped and disabled"}:{label:`Stop service ${f}`,ok:!1,detail:`still ${g} - 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 g=r.processes.find(v=>v.pid===f)?.ports??[];try{process.kill(f,"SIGTERM"),await new Promise(v=>setTimeout(v,2e3));try{process.kill(f,0),process.kill(f,"SIGKILL")}catch{}n({label:`Stop process ${f}`,ok:!0,detail:g.length?`stopped - port${g.length>1?"s":""} ${g.join(", ")} freed`:"stopped"})}catch(v){n({label:`Stop process ${f}`,ok:!1,detail:v instanceof Error?v.message:String(v)})}}let d=i(e.containers,r.containers.map(f=>f.name));for(let f of e.containers.filter(g=>!d.includes(g)))n({label:`Remove container ${f}`,ok:!1,detail:"not in this checkout's plan - refused"});for(let f of d){let g=await fn("docker",["rm","-f",f]);n({label:`Remove container ${f}`,ok:g.trim()===f,detail:g.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 g=p.get(f);if(!g){n({label:`Drop database ${f}`,ok:!1,detail:"not named by this checkout's own env files - refused"});continue}if(g.engine==="postgres"){let k=(await fn("sudo",["-n","-u","postgres","psql","-c",`DROP DATABASE IF EXISTS "${f}"`])).includes("DROP DATABASE");n({label:`Drop database ${f}`,ok:k,detail:k?"dropped":`could not drop it from here - run: sudo -u postgres psql -c 'DROP DATABASE "${f}"'`})}else{let k=(await fn("sudo",["-n","mysql","-N","-e",`DROP DATABASE IF EXISTS \`${f}\`; SELECT 'dropped'`])).includes("dropped");n({label:`Drop database ${f}`,ok:k,detail:k?"dropped":`could not drop it from here - run: sudo mysql -e 'DROP DATABASE \`${f}\`'`})}}if(e.deleteFolder)try{Dt.default.rmSync(s,{recursive:!0,force:!0});let f=!Dt.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 Dt,gt,pv,fv,GA,ZA,XA,Th=X(()=>{"use strict";Dt=E(require("node:fs"),1),gt=E(require("node:path"),1),pv=require("node:child_process"),fv=require("node:util");mo();GA=(0,fv.promisify)(pv.execFile),ZA=15e3;XA=new Set(["localhost","127.0.0.1","::1","0.0.0.0"])});function bv(t,...e){try{return JSON.parse(Zc.default.readFileSync(Vc.default.join(t,...e),"utf8"))}catch{return null}}function Gc(t,...e){try{return Zc.default.readFileSync(Vc.default.join(t,...e),"utf8")}catch{return""}}function r$(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(Gc(t,e));if(n)return`${{postgresql:"PostgreSQL",mysql:"MySQL",sqlite:"SQLite",mongodb:"MongoDB",sqlserver:"SQL Server",cockroachdb:"CockroachDB"}[n[1]]} (Prisma)`}return""}function wv(t){let e={languages:[],frameworks:[],databases:[],docker:Oe(t,"Dockerfile"),dockerCompose:Oe(t,"docker-compose.yml")||Oe(t,"docker-compose.yaml")||Oe(t,"compose.yml")||Oe(t,"compose.yaml"),packageManager:"",monorepo:""},n=(i,a)=>{a&&!i.includes(a)&&i.push(a)},r=bv(t,"package.json");if(r){n(e.languages,Oe(t,"tsconfig.json")?"TypeScript":"JavaScript");let i={...r.dependencies,...r.devDependencies};for(let[a,c]of e$)i[a]&&n(e.frameworks,c);n(e.databases,i.prisma||i["@prisma/client"]?r$(t):"");for(let[a,c]of t$)i[a]&&n(e.databases,c);e.packageManager=Oe(t,"pnpm-lock.yaml")?"pnpm":Oe(t,"yarn.lock")?"yarn":Oe(t,"package-lock.json")?"npm":"",e.monorepo=Oe(t,"pnpm-workspace.yaml")?"pnpm workspaces":Oe(t,"turbo.json")?"turborepo":r.workspaces?"npm/yarn workspaces":""}let s=(Gc(t,"requirements.txt")+Gc(t,"pyproject.toml")).toLowerCase();if(s||Oe(t,"manage.py")){n(e.languages,"Python");for(let[i,a]of n$)(s.includes(i)||i==="django"&&Oe(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=Oe(t,"poetry.lock")?"poetry":Oe(t,"requirements.txt")?"pip":"")}return Oe(t,"go.mod")&&n(e.languages,"Go"),Oe(t,"Cargo.toml")&&n(e.languages,"Rust"),Oe(t,"composer.json")&&(n(e.languages,"PHP"),(bv(t,"composer.json")?.require??{})["laravel/framework"]&&n(e.frameworks,"Laravel")),Oe(t,"Gemfile")&&(n(e.languages,"Ruby"),Gc(t,"Gemfile").includes("rails")&&n(e.frameworks,"Rails")),(Oe(t,"pom.xml")||Oe(t,"build.gradle")||Oe(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 Zc,Vc,Oe,e$,t$,n$,vv=X(()=>{"use strict";Zc=E(require("node:fs"),1),Vc=E(require("node:path"),1),Oe=(t,...e)=>Zc.default.existsSync(Vc.default.join(t,...e));e$=[["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"]],t$=[["mongoose","MongoDB"],["mongodb","MongoDB"],["pg","PostgreSQL"],["postgres","PostgreSQL"],["mysql2","MySQL"],["mysql","MySQL"],["better-sqlite3","SQLite"],["sqlite3","SQLite"],["redis","Redis"],["ioredis","Redis"]],n$=[["django","Django"],["flask","Flask"],["fastapi","FastAPI"]]});var $v={};De($v,{buildAgentReport:()=>Av,buildSetupReport:()=>a$,claudeLoggedIn:()=>Rv,codexLoggedIn:()=>Iv,kimiLoggedIn:()=>Ev,repoCurrentBranch:()=>xv,repoDefaultBranch:()=>Tv});function xv(t){try{let e=(0,zo.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Tv(t){let e=(...s)=>{try{return(0,zo.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 Rv(t=Do.default.homedir()){if(Gt.default.existsSync(mn.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Gt.default.readFileSync(mn.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}function i$(t){try{return Gt.default.readdirSync(t).length>0}catch{return!1}}function Iv(t=Do.default.homedir()){return Gt.default.existsSync(mn.default.join(t,".codex","auth.json"))}function Ev(t=Do.default.homedir()){return i$(mn.default.join(t,".kimi","credentials"))||Gt.default.existsSync(mn.default.join(t,".kimi","credentials.json"))}async function o$(t){let e=Sv.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 s$(t,["--version"],{timeout:1e4});n=!0,r=s.trim().slice(0,60)}catch{n=!1}return Sv.set(t,{at:Date.now(),installed:n,version:r}),{installed:n,version:r}}async function Av(t){let e=Yc.REGISTERED_AGENTS.filter(r=>kv[r.id]),n=await Promise.all(e.map(async r=>{let{installed:s,version:i}=await o$(Be(t,r.id)),a=kv[r.id](Do.default.homedir());return[r.id,{installed:s,version:i,loggedIn:a}]}));return Object.fromEntries(n)}async function a$(t,e,n){let r=await Av(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=Gt.default.existsSync(c.path);return{repoName:a,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[a]:!0,pathExists:l,isGit:l&&Gt.default.existsSync(mn.default.join(c.path,".git")),currentBranch:l?xv(c.path):"",claudeMd:l&&Gt.default.existsSync(mn.default.join(c.path,"CLAUDE.md")),deployMd:l&&Gt.default.existsSync(mn.default.join(c.path,"DEPLOY.md")),testMd:l&&Gt.default.existsSync(mn.default.join(c.path,"TEST.md")),githubToken:!!Qe(t,a),githubTokenOwn:!!c.github?.token,defaultBranch:l?Tv(c.path):"",architecture:l?wv(c.path):void 0}}),i=Object.values(t.repos).find(a=>a.github?.token);return{jiraConfigured:!!t.jira,...(()=>{let a=yo();return{serviceProtected:a.protected,serviceProtectFix:a.protected===!1?a.fixCommand:""}})(),jiraEmail:t.jira?.email??"",agents:r,claude:r[Yc.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 zo,Gt,Do,mn,_v,Yc,s$,kv,Sv,Cv=X(()=>{"use strict";zo=require("node:child_process");lc();Gt=E(require("node:fs"),1),Do=E(require("node:os"),1),mn=E(require("node:path"),1),_v=require("node:util"),Yc=E(Ne(),1);Et();is();vv();s$=(0,_v.promisify)(zo.execFile);kv={"claude-code":Rv,codex:Iv,kimi:Ev},Sv=new Map});var zv={};De(zv,{discoverForMonitoring:()=>Ih});async function Nv(t,e){try{let{stdout:n}=await c$(t,e,{timeout:l$,maxBuffer:4e6});return n}catch{return""}}function f$(t){let e;try{e=Jc.default.readdirSync(t)}catch{return null}let n=null;for(let r of e.slice(0,500))if(h$.some(s=>r.endsWith(s)))try{let s=Jc.default.statSync(Rh.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 Ih(){let[t,e]=await Promise.all([Nv("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain","--no-pager"]),Nv("ss",["-tlnpH"])]),n=[];for(let c of Ba(t)){let l=c.name.replace(/\.service$/,""),d=Object.keys(Pv).find(p=>l===p||l.startsWith(p+"@")||l.startsWith(p+"-"));if(d&&n.push({name:l,kind:Pv[d]}),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 lr(e)){let l=d$[c.port];l&&!s.some(d=>d.kind===l)&&s.push({kind:l,port:c.port})}let i=[...u$];try{for(let c of Jc.default.readdirSync("/home").slice(0,20))i.push(Rh.default.join("/home",c,"backups"))}catch{}let a=[];for(let c of i){if(a.length>=p$)break;let l=f$(c);l&&a.push({path:c,...l})}return{os:{platform:process.platform,arch:process.arch,release:Mv.default.release().slice(0,60)},services:n,webServers:r,backupCandidates:a,dbHints:s}}var Jc,Mv,Rh,jv,Ov,c$,l$,Pv,d$,u$,h$,p$,Eh=X(()=>{"use strict";Jc=E(require("node:fs"),1),Mv=E(require("node:os"),1),Rh=E(require("node:path"),1),jv=require("node:child_process"),Ov=require("node:util");mo();c$=(0,Ov.promisify)(jv.execFile),l$=8e3,Pv={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"},d$={5432:"postgres",3306:"mysql",27017:"mongodb",6379:"redis"},u$=["/backups","/backup","/var/backups","/root/backups","/opt/backups","/srv/backups"],h$=[".sql",".sql.gz",".dump",".tar.gz",".tgz",".zip",".gz",".bak"],p$=20});var Uv={};De(Uv,{parseSuggestion:()=>Lv,suggestMonitorCheck:()=>g$});function Lv(t){let e=[...t.matchAll(/```json\s*\n([\s\S]*?)```/g)];for(let n=e.length-1;n>=0;n--)try{let r=m$.safeParse(JSON.parse(e[n][1]));if(r.success)return r.data}catch{}return null}async function g$(t){let e={name:"",commands:[],parseRules:{amberPattern:"",redPattern:"",greenRequires:""},notes:""},n=await Ih().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:
1513
1476
  "${t.notes.slice(0,2e3)}"
1514
1477
 
1515
1478
  FACTS about this machine (measured by code just now - never contradict them):
@@ -1530,26 +1493,26 @@ ${s}json
1530
1493
  "schedule": {"kind": "daily", "at": "06:00"},
1531
1494
  "notes": "<one sentence: what this checks and any caveat>"}
1532
1495
  ${s}
1533
- Schedule kinds: {"kind":"every","minutes":N} | {"kind":"daily","at":"HH:MM"} | {"kind":"weekly","day":0-6,"at":"HH:MM"}. Nothing outside the rules above.`,a=await t.agent.adapter.run({repoPath:t.repoPath,prompt:i,timeoutSeconds:180,bin:t.agent.bin,mode:"read_only",maxTurns:10,sessionId:(0,Dv.randomUUID)(),onLog:()=>{}});if(be({surface:"monitor_suggest",projectId:t.projectId,agentId:t.agent.adapter.id,refKind:"none",refLabel:t.notes.slice(0,80),...we(a)}),!a.ok)return{ok:!1,error:a.error??"the agent produced no output",...e};let c=Lv(a.resultText);return c?{ok:!0,...c,parseRules:c.parseRules}:{ok:!1,error:"the proposal could not be parsed - try rephrasing what you want checked",...e}}var Dv,$i,g$,qv=X(()=>{"use strict";Dv=require("node:crypto");_t();$i=E(Ne(),1);Eh();nn();g$=S.object({name:S.string().min(1).max(120),commands:S.array($i.MonitorCommand).min(1).max(20),parseRules:$i.MonitorParseRules.default({}),schedule:$i.MonitorSchedule.optional(),notes:S.string().max(2e3).default("")})});var Fe=E(require("node:fs"),1),Ms=E(require("node:os"),1),Zt=E(require("node:path"),1),Vt=require("node:child_process"),qn=require("node:crypto"),yr=E(require("node:readline/promises"),1);var Wh=E(Kh(),1),{program:j$,createCommand:O$,createArgument:z$,createOption:D$,CommanderError:L$,InvalidArgumentError:U$,InvalidOptionArgumentError:q$,Command:Gh,Argument:F$,Option:B$,Help:H$}=Wh.default;Ae();var Jo=require("node:child_process"),ut=E(require("node:fs"),1),Xo=E(require("node:path"),1);Ae();var T0=new Set(["runner.log","runner.pid"]);function R0(t){return ut.default.readdirSync(t).filter(e=>!T0.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function lp(t){let e=te();if(!ut.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=R0(e);if(!n.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=Xo.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return ut.default.writeFileSync(s,"",{mode:384}),(0,Jo.execFileSync)("tar",["-czf",s,"-C",e,...n]),ut.default.chmodSync(s,384),{file:s,entries:n}}function dp(t){let e=Xo.default.resolve(t);if(!ut.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Jo.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
1534
- `).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=te(),s;ut.default.existsSync(r)&&ut.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,ut.default.renameSync(r,s)),ut.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Jo.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of ut.default.readdirSync(r)){let a=Xo.default.join(r,i);ut.default.statSync(a).isFile()&&ut.default.chmodSync(a,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var fi=E(require("node:fs"),1),my=E(require("node:path"),1);_t();Ae();var dn=E(require("node:fs"),1),gs=E(require("node:os"),1),Za=E(require("node:path"),1),sy=E(require("node:tls"),1),iy=E(require("node:http"),1),oy=E(require("node:https"),1),ay=require("node:child_process"),cy=require("node:util"),Va=E(Ne(),1);fs();var dr=(0,cy.promisify)(ay.execFile),ys=3e4,lR=3e5,Mn=4e3;function dR(t){let e=["error","red","amber","green","skipped"];for(let n of e)if(t.includes(n))return n;return"green"}function uR(t){return Va.MONITOR_CATALOG.find(n=>n.id===t)?.os??"both"}function Ue(t){let e=Va.MONITOR_PARAM_SCHEMAS[t.type];if(!e)return{};let n=e.safeParse(t.params??{});if(n.success)return n.data;let r=e.safeParse({});return r.success?r.data:{}}var hR=new Set(["tmpfs","devtmpfs","overlay","squashfs","efivarfs","none"]),pR=["/run","/dev","/sys","/proc","/snap"];function fR(t){let e=[];for(let n of t.split(`
1535
- `).slice(1)){let r=n.trim().split(/\s+/);if(r.length<6)continue;let[s,,,i,a,...c]=r,l=c.join(" "),d=Number.parseInt(a??"",10);!l||!Number.isFinite(d)||hR.has(s??"")||pR.some(p=>l===p||l.startsWith(p+"/"))||e.push({mount:l,pct:d,freeKB:Number.parseInt(i??"0",10)||0,fs:s??""})}return e.slice(0,20)}async function mR(t){let e=Ue(t),n;try{n=(await dr("df",["-Pk"],{timeout:ys,maxBuffer:1e6})).stdout}catch(c){return{status:"error",summary:`df failed: ${c.message}`.slice(0,300)}}let r=fR(n);if(e.mounts.length&&(r=r.filter(c=>e.mounts.includes(c.mount))),!r.length)return{status:"error",summary:"no filesystems matched - check the mounts parameter"};r.sort((c,l)=>l.pct-c.pct);let s=r[0],i=(s.freeKB/1024/1024).toFixed(1);return{status:s.pct>=e.critPct?"red":s.pct>=e.warnPct?"amber":"green",summary:`${s.pct}% used on ${s.mount} (${i} GB free)${r.length>1?` - ${r.length} filesystems watched`:""}`,metrics:{mounts:r.map(c=>({mount:c.mount,pct:c.pct}))}}}function gR(t){let e=n=>{let r=t.match(new RegExp(`^${n}:\\s+(\\d+)`,"m"));return r?Number.parseInt(r[1],10):0};return{totalKB:e("MemTotal"),availableKB:e("MemAvailable"),swapTotalKB:e("SwapTotal"),swapFreeKB:e("SwapFree")}}async function yR(t){let e=Ue(t),n,r=0;try{let i=gR(dn.default.readFileSync("/proc/meminfo","utf8"));if(!i.totalKB)throw new Error("MemTotal missing");n=Math.round((i.totalKB-i.availableKB)/i.totalKB*100),r=i.swapTotalKB?Math.round((i.swapTotalKB-i.swapFreeKB)/i.swapTotalKB*100):0}catch{let i=gs.default.totalmem();n=Math.round((i-gs.default.freemem())/i*100)}let s=n>=e.critPct?"red":n>=e.warnPct?"amber":"green";return s==="green"&&r>=80&&(s="amber"),{status:s,summary:`${n}% memory used${r?`, ${r}% swap`:""}`,metrics:{usedPct:n,swapPct:r}}}async function bR(t){let e=Ue(t),[n,r,s]=gs.default.loadavg(),i=gs.default.cpus().length||1,a=(s??0)/i;return{status:a>=e.critPerCore?"red":a>=e.warnPerCore?"amber":"green",summary:`15-min load ${s?.toFixed(2)} on ${i} cores (${a.toFixed(2)}/core)`,metrics:{load1:n,load5:r,load15:s,cores:i}}}async function wR(t){let e=Ue(t),n=Math.floor(gs.default.uptime()/86400),r=dn.default.existsSync("/var/run/reboot-required"),s="";if(r)try{s=dn.default.readFileSync("/var/run/reboot-required.pkgs","utf8").trim().slice(0,Mn)}catch{}return r?{status:"amber",summary:`the OS wants a reboot (up ${n}d)`,metrics:{uptimeDays:n,rebootRequired:!0},excerpt:s}:n>=e.maxUptimeDays?{status:"amber",summary:`up ${n} days - kernels this old are usually unpatched`,metrics:{uptimeDays:n,rebootRequired:!1}}:{status:"green",summary:`up ${n}d, no reboot pending`,metrics:{uptimeDays:n,rebootRequired:!1}}}async function vR(t){let e=Ue(t);if(!e.names?.length)return{status:"error",summary:"no service names configured"};let n=[],r=[],s={};for(let i of e.names.slice(0,40)){let a="";try{a=(await dr("systemctl",["is-active",i],{timeout:ys})).stdout.trim()}catch(c){a=(c.stdout??"").trim()||"unknown"}if(s[i]=a,a!=="active")n.push(i);else try{let c=(await dr("systemctl",["show",i,"-p","NRestarts","--value"],{timeout:ys})).stdout.trim();Number.parseInt(c,10)>5&&r.push(i)}catch{}}return n.length?{status:"red",summary:`${n.length} of ${e.names.length} down: ${n.join(", ")}`.slice(0,300),metrics:{states:s}}:r.length?{status:"amber",summary:`restart-looping: ${r.join(", ")}`.slice(0,300),metrics:{states:s}}:{status:"green",summary:`all ${e.names.length} services active`,metrics:{states:s}}}function du(t,e,n=5){let r=Date.now();return new Promise((s,i)=>{let a;try{a=new URL(t)}catch{i(new Error(`not a valid URL: ${t}`));return}let l=(a.protocol==="http:"?iy.default:oy.default).get(a,{timeout:e,headers:{"user-agent":"allwright-monitor"}},d=>{let p=d.statusCode??0,f=d.headers.location;if(p>=300&&p<400&&f&&n>0){d.resume(),s(du(new URL(f,a).toString(),e,n-1));return}let g="";d.on("data",v=>{g.length<65536&&(g+=v.toString("utf8"))}),d.on("end",()=>s({status:p,ms:Date.now()-r,body:g})),d.on("error",i)});l.on("timeout",()=>l.destroy(new Error(`no answer in ${e}ms`))),l.on("error",i)})}async function kR(t){let e=Ue(t);if(!e.url)return{status:"error",summary:"no URL configured"};try{let n=await du(e.url,e.timeoutMs),r={status:n.status,ms:n.ms};return n.status>=500?{status:"red",summary:`${e.url} answered ${n.status}`,metrics:r}:n.status!==e.expectStatus?{status:"red",summary:`${e.url} answered ${n.status}, expected ${e.expectStatus}`,metrics:r}:e.expectString&&!n.body.includes(e.expectString)?{status:"amber",summary:`${e.url} is up but the expected text is missing`,metrics:r,excerpt:n.body.slice(0,500)}:n.ms>e.warnMs?{status:"amber",summary:`${e.url} answered in ${n.ms}ms (warn ${e.warnMs}ms)`,metrics:r}:{status:"green",summary:`${e.url} \u2192 ${n.status} in ${n.ms}ms`,metrics:r}}catch(n){return{status:"red",summary:`${e.url} unreachable: ${n.message}`.slice(0,300)}}}function ly(t,e){return new Promise((n,r)=>{let s=sy.default.connect({host:t,port:443,servername:t,timeout:e,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate();if(s.end(),!i||!i.valid_to){r(new Error("no certificate presented"));return}let a=new Date(i.valid_to).getTime()-Date.now();n(Math.floor(a/864e5))});s.on("timeout",()=>s.destroy(new Error(`no TLS answer in ${e}ms`))),s.on("error",r)})}async function SR(t){let e=Ue(t);if(!e.domains?.length)return{status:"error",summary:"no domains configured"};let n=[];for(let l of e.domains.slice(0,40))try{n.push({domain:l,daysLeft:await ly(l,1e4)})}catch(d){n.push({domain:l,daysLeft:null,error:d.message})}let r=n.filter(l=>l.daysLeft===null),s=n.filter(l=>l.daysLeft!==null);s.sort((l,d)=>l.daysLeft-d.daysLeft);let i={domains:n.map(l=>({domain:l.domain,daysLeft:l.daysLeft}))};if(r.length)return{status:"red",summary:`could not read the certificate on ${r.map(l=>l.domain).join(", ")}`.slice(0,300),metrics:i,excerpt:r.map(l=>`${l.domain}: ${l.error}`).join(`
1536
- `).slice(0,Mn)};let a=s[0];return{status:a.daysLeft<=e.critDays?"red":a.daysLeft<=e.warnDays?"amber":"green",summary:`${a.domain} expires in ${a.daysLeft}d${s.length>1?` (${s.length} domains watched)`:""}`,metrics:i}}function _R(t){let e=Za.default.dirname(t),n=Za.default.basename(t);if(e.includes("*"))return{newest:null,error:"wildcards are only supported in the file name, not directories"};let r;try{r=dn.default.readdirSync(e)}catch{return{newest:null,error:`directory does not exist: ${e}`}}let s=new RegExp(`^${n.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`),i=null;for(let a of r)if(s.test(a))try{let c=dn.default.statSync(Za.default.join(e,a));if(!c.isFile())continue;(!i||c.mtimeMs>i.mtimeMs)&&(i={file:a,mtimeMs:c.mtimeMs,sizeMB:c.size/1024/1024})}catch{}return{newest:i}}async function xR(t){let e=Ue(t);if(e.noBackups)return{status:"amber",summary:"this server is marked as having no backups"};if(!e.targets?.length)return{status:"error",summary:"no backup targets configured - say where backups land"};let n=[];for(let i of e.targets.slice(0,20)){let{newest:a,error:c}=_R(i.pathGlob);if(c){n.push({target:i.pathGlob,status:"error",detail:c});continue}if(!a){n.push({target:i.pathGlob,status:"red",detail:"no matching backup file at all"});continue}let l=(Date.now()-a.mtimeMs)/36e5,d=a.sizeMB;l>i.maxAgeHours?n.push({target:i.pathGlob,status:"amber",detail:`newest (${a.file}) is ${Math.round(l)}h old, expected under ${i.maxAgeHours}h`,ageHours:l,sizeMB:d}):d<i.minSizeMB?n.push({target:i.pathGlob,status:"amber",detail:`newest (${a.file}) is ${d.toFixed(1)} MB, expected at least ${i.minSizeMB} MB`,ageHours:l,sizeMB:d}):n.push({target:i.pathGlob,status:"green",detail:`${a.file}, ${Math.round(l)}h old, ${d.toFixed(1)} MB`,ageHours:l,sizeMB:d})}let r=dR(n.map(i=>i.status)),s=n.find(i=>i.status===r&&r!=="green");return{status:r,summary:s?`${s.target}: ${s.detail}`.slice(0,300):`${n.length} backup target(s) fresh and healthy`,metrics:{targets:n.map(i=>({target:i.target,status:i.status,ageHours:i.ageHours===void 0?null:Math.round(i.ageHours),sizeMB:i.sizeMB===void 0?null:Number(i.sizeMB.toFixed(1))}))},excerpt:n.map(i=>`${i.target}: ${i.detail}`).join(`
1537
- `).slice(0,Mn)}}function TR(t){let e=[];for(let n of Object.values(t.environments??{}))for(let r of Object.values(n.secrets??{}))e.push(r);return e}function RR(t,e,n){if(t!==0)return{status:"red",note:`exit code ${t}`};let r=s=>{try{return new RegExp(s,"m").test(e)}catch{return!1}};return n.redPattern&&r(n.redPattern)?{status:"red",note:"output matched the red pattern"}:n.amberPattern&&r(n.amberPattern)?{status:"amber",note:"output matched the amber pattern"}:n.greenRequires&&!e.includes(n.greenRequires)?{status:"amber",note:`output is missing "${n.greenRequires}"`}:{status:"green",note:"exit 0"}}async function IR(t,e){let n=process.platform==="win32"?"powershell":"bash";if(t.shell!==n)return{status:"skipped",summary:`this is a ${t.shell} check; this machine runs ${n}`};if(!t.commands.length)return{status:"error",summary:"custom check has no commands"};let r=ps(TR(e)),s=Date.now(),i=[];for(let a of t.commands){let c=lR-(Date.now()-s);if(c<=0)return{status:"error",summary:`time budget exhausted before "${a.name}"`,excerpt:r(i.join(`
1496
+ Schedule kinds: {"kind":"every","minutes":N} | {"kind":"daily","at":"HH:MM"} | {"kind":"weekly","day":0-6,"at":"HH:MM"}. Nothing outside the rules above.`,a=await t.agent.adapter.run({repoPath:t.repoPath,prompt:i,timeoutSeconds:180,bin:t.agent.bin,mode:"read_only",maxTurns:10,sessionId:(0,Dv.randomUUID)(),onLog:()=>{}});if(be({surface:"monitor_suggest",projectId:t.projectId,agentId:t.agent.adapter.id,refKind:"none",refLabel:t.notes.slice(0,80),...we(a)}),!a.ok)return{ok:!1,error:a.error??"the agent produced no output",...e};let c=Lv(a.resultText);return c?{ok:!0,...c,parseRules:c.parseRules}:{ok:!1,error:"the proposal could not be parsed - try rephrasing what you want checked",...e}}var Dv,$i,m$,qv=X(()=>{"use strict";Dv=require("node:crypto");_t();$i=E(Ne(),1);Eh();nn();m$=S.object({name:S.string().min(1).max(120),commands:S.array($i.MonitorCommand).min(1).max(20),parseRules:$i.MonitorParseRules.default({}),schedule:$i.MonitorSchedule.optional(),notes:S.string().max(2e3).default("")})});var Fe=E(require("node:fs"),1),Ms=E(require("node:os"),1),Zt=E(require("node:path"),1),Vt=require("node:child_process"),qn=require("node:crypto"),yr=E(require("node:readline/promises"),1);var Wh=E(Kh(),1),{program:M$,createCommand:j$,createArgument:O$,createOption:z$,CommanderError:D$,InvalidArgumentError:L$,InvalidOptionArgumentError:U$,Command:Gh,Argument:q$,Option:F$,Help:B$}=Wh.default;Ae();var Jo=require("node:child_process"),ut=E(require("node:fs"),1),Xo=E(require("node:path"),1);Ae();var T0=new Set(["runner.log","runner.pid"]);function R0(t){return ut.default.readdirSync(t).filter(e=>!T0.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function lp(t){let e=te();if(!ut.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=R0(e);if(!n.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=Xo.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return ut.default.writeFileSync(s,"",{mode:384}),(0,Jo.execFileSync)("tar",["-czf",s,"-C",e,...n]),ut.default.chmodSync(s,384),{file:s,entries:n}}function dp(t){let e=Xo.default.resolve(t);if(!ut.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Jo.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
1497
+ `).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=te(),s;ut.default.existsSync(r)&&ut.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,ut.default.renameSync(r,s)),ut.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Jo.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of ut.default.readdirSync(r)){let a=Xo.default.join(r,i);ut.default.statSync(a).isFile()&&ut.default.chmodSync(a,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var fi=E(require("node:fs"),1),my=E(require("node:path"),1);_t();Ae();var dn=E(require("node:fs"),1),gs=E(require("node:os"),1),Za=E(require("node:path"),1),sy=E(require("node:tls"),1),iy=E(require("node:http"),1),oy=E(require("node:https"),1),ay=require("node:child_process"),cy=require("node:util"),Va=E(Ne(),1);fs();var dr=(0,cy.promisify)(ay.execFile),ys=3e4,cR=3e5,Mn=4e3;function lR(t){let e=["error","red","amber","green","skipped"];for(let n of e)if(t.includes(n))return n;return"green"}function dR(t){return Va.MONITOR_CATALOG.find(n=>n.id===t)?.os??"both"}function Ue(t){let e=Va.MONITOR_PARAM_SCHEMAS[t.type];if(!e)return{};let n=e.safeParse(t.params??{});if(n.success)return n.data;let r=e.safeParse({});return r.success?r.data:{}}var uR=new Set(["tmpfs","devtmpfs","overlay","squashfs","efivarfs","none"]),hR=["/run","/dev","/sys","/proc","/snap"];function pR(t){let e=[];for(let n of t.split(`
1498
+ `).slice(1)){let r=n.trim().split(/\s+/);if(r.length<6)continue;let[s,,,i,a,...c]=r,l=c.join(" "),d=Number.parseInt(a??"",10);!l||!Number.isFinite(d)||uR.has(s??"")||hR.some(p=>l===p||l.startsWith(p+"/"))||e.push({mount:l,pct:d,freeKB:Number.parseInt(i??"0",10)||0,fs:s??""})}return e.slice(0,20)}async function fR(t){let e=Ue(t),n;try{n=(await dr("df",["-Pk"],{timeout:ys,maxBuffer:1e6})).stdout}catch(c){return{status:"error",summary:`df failed: ${c.message}`.slice(0,300)}}let r=pR(n);if(e.mounts.length&&(r=r.filter(c=>e.mounts.includes(c.mount))),!r.length)return{status:"error",summary:"no filesystems matched - check the mounts parameter"};r.sort((c,l)=>l.pct-c.pct);let s=r[0],i=(s.freeKB/1024/1024).toFixed(1);return{status:s.pct>=e.critPct?"red":s.pct>=e.warnPct?"amber":"green",summary:`${s.pct}% used on ${s.mount} (${i} GB free)${r.length>1?` - ${r.length} filesystems watched`:""}`,metrics:{mounts:r.map(c=>({mount:c.mount,pct:c.pct}))}}}function mR(t){let e=n=>{let r=t.match(new RegExp(`^${n}:\\s+(\\d+)`,"m"));return r?Number.parseInt(r[1],10):0};return{totalKB:e("MemTotal"),availableKB:e("MemAvailable"),swapTotalKB:e("SwapTotal"),swapFreeKB:e("SwapFree")}}async function gR(t){let e=Ue(t),n,r=0;try{let i=mR(dn.default.readFileSync("/proc/meminfo","utf8"));if(!i.totalKB)throw new Error("MemTotal missing");n=Math.round((i.totalKB-i.availableKB)/i.totalKB*100),r=i.swapTotalKB?Math.round((i.swapTotalKB-i.swapFreeKB)/i.swapTotalKB*100):0}catch{let i=gs.default.totalmem();n=Math.round((i-gs.default.freemem())/i*100)}let s=n>=e.critPct?"red":n>=e.warnPct?"amber":"green";return s==="green"&&r>=80&&(s="amber"),{status:s,summary:`${n}% memory used${r?`, ${r}% swap`:""}`,metrics:{usedPct:n,swapPct:r}}}async function yR(t){let e=Ue(t),[n,r,s]=gs.default.loadavg(),i=gs.default.cpus().length||1,a=(s??0)/i;return{status:a>=e.critPerCore?"red":a>=e.warnPerCore?"amber":"green",summary:`15-min load ${s?.toFixed(2)} on ${i} cores (${a.toFixed(2)}/core)`,metrics:{load1:n,load5:r,load15:s,cores:i}}}async function bR(t){let e=Ue(t),n=Math.floor(gs.default.uptime()/86400),r=dn.default.existsSync("/var/run/reboot-required"),s="";if(r)try{s=dn.default.readFileSync("/var/run/reboot-required.pkgs","utf8").trim().slice(0,Mn)}catch{}return r?{status:"amber",summary:`the OS wants a reboot (up ${n}d)`,metrics:{uptimeDays:n,rebootRequired:!0},excerpt:s}:n>=e.maxUptimeDays?{status:"amber",summary:`up ${n} days - kernels this old are usually unpatched`,metrics:{uptimeDays:n,rebootRequired:!1}}:{status:"green",summary:`up ${n}d, no reboot pending`,metrics:{uptimeDays:n,rebootRequired:!1}}}async function wR(t){let e=Ue(t);if(!e.names?.length)return{status:"error",summary:"no service names configured"};let n=[],r=[],s={};for(let i of e.names.slice(0,40)){let a="";try{a=(await dr("systemctl",["is-active",i],{timeout:ys})).stdout.trim()}catch(c){a=(c.stdout??"").trim()||"unknown"}if(s[i]=a,a!=="active")n.push(i);else try{let c=(await dr("systemctl",["show",i,"-p","NRestarts","--value"],{timeout:ys})).stdout.trim();Number.parseInt(c,10)>5&&r.push(i)}catch{}}return n.length?{status:"red",summary:`${n.length} of ${e.names.length} down: ${n.join(", ")}`.slice(0,300),metrics:{states:s}}:r.length?{status:"amber",summary:`restart-looping: ${r.join(", ")}`.slice(0,300),metrics:{states:s}}:{status:"green",summary:`all ${e.names.length} services active`,metrics:{states:s}}}function du(t,e,n=5){let r=Date.now();return new Promise((s,i)=>{let a;try{a=new URL(t)}catch{i(new Error(`not a valid URL: ${t}`));return}let l=(a.protocol==="http:"?iy.default:oy.default).get(a,{timeout:e,headers:{"user-agent":"allwright-monitor"}},d=>{let p=d.statusCode??0,f=d.headers.location;if(p>=300&&p<400&&f&&n>0){d.resume(),s(du(new URL(f,a).toString(),e,n-1));return}let g="";d.on("data",v=>{g.length<65536&&(g+=v.toString("utf8"))}),d.on("end",()=>s({status:p,ms:Date.now()-r,body:g})),d.on("error",i)});l.on("timeout",()=>l.destroy(new Error(`no answer in ${e}ms`))),l.on("error",i)})}async function vR(t){let e=Ue(t);if(!e.url)return{status:"error",summary:"no URL configured"};try{let n=await du(e.url,e.timeoutMs),r={status:n.status,ms:n.ms};return n.status>=500?{status:"red",summary:`${e.url} answered ${n.status}`,metrics:r}:n.status!==e.expectStatus?{status:"red",summary:`${e.url} answered ${n.status}, expected ${e.expectStatus}`,metrics:r}:e.expectString&&!n.body.includes(e.expectString)?{status:"amber",summary:`${e.url} is up but the expected text is missing`,metrics:r,excerpt:n.body.slice(0,500)}:n.ms>e.warnMs?{status:"amber",summary:`${e.url} answered in ${n.ms}ms (warn ${e.warnMs}ms)`,metrics:r}:{status:"green",summary:`${e.url} \u2192 ${n.status} in ${n.ms}ms`,metrics:r}}catch(n){return{status:"red",summary:`${e.url} unreachable: ${n.message}`.slice(0,300)}}}function ly(t,e){return new Promise((n,r)=>{let s=sy.default.connect({host:t,port:443,servername:t,timeout:e,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate();if(s.end(),!i||!i.valid_to){r(new Error("no certificate presented"));return}let a=new Date(i.valid_to).getTime()-Date.now();n(Math.floor(a/864e5))});s.on("timeout",()=>s.destroy(new Error(`no TLS answer in ${e}ms`))),s.on("error",r)})}async function kR(t){let e=Ue(t);if(!e.domains?.length)return{status:"error",summary:"no domains configured"};let n=[];for(let l of e.domains.slice(0,40))try{n.push({domain:l,daysLeft:await ly(l,1e4)})}catch(d){n.push({domain:l,daysLeft:null,error:d.message})}let r=n.filter(l=>l.daysLeft===null),s=n.filter(l=>l.daysLeft!==null);s.sort((l,d)=>l.daysLeft-d.daysLeft);let i={domains:n.map(l=>({domain:l.domain,daysLeft:l.daysLeft}))};if(r.length)return{status:"red",summary:`could not read the certificate on ${r.map(l=>l.domain).join(", ")}`.slice(0,300),metrics:i,excerpt:r.map(l=>`${l.domain}: ${l.error}`).join(`
1499
+ `).slice(0,Mn)};let a=s[0];return{status:a.daysLeft<=e.critDays?"red":a.daysLeft<=e.warnDays?"amber":"green",summary:`${a.domain} expires in ${a.daysLeft}d${s.length>1?` (${s.length} domains watched)`:""}`,metrics:i}}function SR(t){let e=Za.default.dirname(t),n=Za.default.basename(t);if(e.includes("*"))return{newest:null,error:"wildcards are only supported in the file name, not directories"};let r;try{r=dn.default.readdirSync(e)}catch{return{newest:null,error:`directory does not exist: ${e}`}}let s=new RegExp(`^${n.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`),i=null;for(let a of r)if(s.test(a))try{let c=dn.default.statSync(Za.default.join(e,a));if(!c.isFile())continue;(!i||c.mtimeMs>i.mtimeMs)&&(i={file:a,mtimeMs:c.mtimeMs,sizeMB:c.size/1024/1024})}catch{}return{newest:i}}async function _R(t){let e=Ue(t);if(e.noBackups)return{status:"amber",summary:"this server is marked as having no backups"};if(!e.targets?.length)return{status:"error",summary:"no backup targets configured - say where backups land"};let n=[];for(let i of e.targets.slice(0,20)){let{newest:a,error:c}=SR(i.pathGlob);if(c){n.push({target:i.pathGlob,status:"error",detail:c});continue}if(!a){n.push({target:i.pathGlob,status:"red",detail:"no matching backup file at all"});continue}let l=(Date.now()-a.mtimeMs)/36e5,d=a.sizeMB;l>i.maxAgeHours?n.push({target:i.pathGlob,status:"amber",detail:`newest (${a.file}) is ${Math.round(l)}h old, expected under ${i.maxAgeHours}h`,ageHours:l,sizeMB:d}):d<i.minSizeMB?n.push({target:i.pathGlob,status:"amber",detail:`newest (${a.file}) is ${d.toFixed(1)} MB, expected at least ${i.minSizeMB} MB`,ageHours:l,sizeMB:d}):n.push({target:i.pathGlob,status:"green",detail:`${a.file}, ${Math.round(l)}h old, ${d.toFixed(1)} MB`,ageHours:l,sizeMB:d})}let r=lR(n.map(i=>i.status)),s=n.find(i=>i.status===r&&r!=="green");return{status:r,summary:s?`${s.target}: ${s.detail}`.slice(0,300):`${n.length} backup target(s) fresh and healthy`,metrics:{targets:n.map(i=>({target:i.target,status:i.status,ageHours:i.ageHours===void 0?null:Math.round(i.ageHours),sizeMB:i.sizeMB===void 0?null:Number(i.sizeMB.toFixed(1))}))},excerpt:n.map(i=>`${i.target}: ${i.detail}`).join(`
1500
+ `).slice(0,Mn)}}function xR(t){let e=[];for(let n of Object.values(t.environments??{}))for(let r of Object.values(n.secrets??{}))e.push(r);return e}function TR(t,e,n){if(t!==0)return{status:"red",note:`exit code ${t}`};let r=s=>{try{return new RegExp(s,"m").test(e)}catch{return!1}};return n.redPattern&&r(n.redPattern)?{status:"red",note:"output matched the red pattern"}:n.amberPattern&&r(n.amberPattern)?{status:"amber",note:"output matched the amber pattern"}:n.greenRequires&&!e.includes(n.greenRequires)?{status:"amber",note:`output is missing "${n.greenRequires}"`}:{status:"green",note:"exit 0"}}async function RR(t,e){let n=process.platform==="win32"?"powershell":"bash";if(t.shell!==n)return{status:"skipped",summary:`this is a ${t.shell} check; this machine runs ${n}`};if(!t.commands.length)return{status:"error",summary:"custom check has no commands"};let r=ps(xR(e)),s=Date.now(),i=[];for(let a of t.commands){let c=cR-(Date.now()-s);if(c<=0)return{status:"error",summary:`time budget exhausted before "${a.name}"`,excerpt:r(i.join(`
1538
1501
  `).slice(-Mn))};let l=0,d="",p=t.shell==="powershell"?["powershell",["-NoProfile","-NonInteractive","-Command",a.run]]:["bash",["-lc",a.run]];try{let g=await dr(p[0],p[1],{timeout:c,maxBuffer:1e6});d=`${g.stdout}
1539
1502
  ${g.stderr}`.trim()}catch(g){let v=g;if(d=`${v.stdout??""}
1540
1503
  ${v.stderr??""}`.trim(),v.killed)return i.push(`$ ${a.name}`,d,"[killed: timed out]"),{status:"error",summary:`"${a.name}" timed out`,excerpt:r(i.join(`
1541
- `).slice(-Mn))};l=typeof v.code=="number"?v.code:1}i.push(`$ ${a.name}`,d);let f=RR(l,d,t.parseRules);if(f.status!=="green")return{status:f.status,summary:`"${a.name}": ${f.note}`.slice(0,300),excerpt:r(i.join(`
1504
+ `).slice(-Mn))};l=typeof v.code=="number"?v.code:1}i.push(`$ ${a.name}`,d);let f=TR(l,d,t.parseRules);if(f.status!=="green")return{status:f.status,summary:`"${a.name}": ${f.note}`.slice(0,300),excerpt:r(i.join(`
1542
1505
  `).slice(-Mn))}}return{status:"green",summary:`${t.commands.length} command(s) passed`,excerpt:r(i.join(`
1543
- `).slice(-Mn))}}async function ER(t,e){let n=`${t.ssl?"https":"http"}://${t.host}/`,r=0,s=0,i;try{let c=await du(n,8e3);r=c.status,s=c.ms}catch(c){i=c.message}let a=null;if(t.ssl)try{a=await ly(t.host,8e3)}catch{a=null}return{host:t.host,server:t.server,status:r,ms:s,certDays:a,error:i}}async function AR(t){let e=Ue(t),{discoverSites:n}=await Promise.resolve().then(()=>(Dg(),zg)),r=await n(),s=[...r,...e.extraHosts.filter(g=>!r.some(v=>v.host===g)).map(g=>({host:g,server:"extra",ssl:!0}))].filter(g=>!e.excludeHosts.includes(g.host));if(!s.length)return{status:"error",summary:"no sites found - no nginx/caddy vhosts on this box, and no extra hosts configured"};let i=[];for(let g=0;g<s.length;g+=5)i.push(...await Promise.all(s.slice(g,g+5).map(v=>ER(v,e))));let a=g=>g.error!==void 0||g.status>=500||g.certDays!==null&&g.certDays<=e.certCritDays,c=g=>g.status>=400&&g.status<500&&g.status!==401&&g.status!==403||g.ms>e.warnMs||g.certDays!==null&&g.certDays<=e.certWarnDays,l=i.filter(a),d=i.filter(g=>!a(g)&&c(g)),p=l.length?"red":d.length?"amber":"green",f=l.length?`${l.length} of ${i.length} sites down: ${l.map(g=>g.host).join(", ")}`.slice(0,300):d.length?`${d.length} of ${i.length} sites degraded: ${d.map(g=>g.host).join(", ")}`.slice(0,300):`${i.length} site(s) up and certified`;return{status:p,summary:f,metrics:{sites:i.map(g=>({host:g.host,server:g.server,status:g.status,ms:g.ms,certDays:g.certDays}))},excerpt:i.map(g=>`${g.host} (${g.server}): ${g.error?`UNREACHABLE - ${g.error}`:`${g.status} in ${g.ms}ms`}`+(g.certDays!==null?`, cert ${g.certDays}d`:"")).join(`
1544
- `).slice(0,Mn)}}async function $R(t,e){let n=Ue(t);if(!n.repoName||!n.envName)return{status:"error",summary:"no repo/environment named - the URL lives in that secret store"};let s=(e.environments?.[`${n.repoName}:${n.envName}`]?.secrets??{})[n.secretName];if(!s)return{status:"error",summary:`no secret "${n.secretName}" for ${n.repoName}:${n.envName} - allwright env set ${n.repoName} ${n.envName} ${n.secretName}=postgresql://\u2026`};let i=s.startsWith("postgres"),a=s.startsWith("mysql");if(!i&&!a)return{status:"error",summary:"only postgres:// and mysql:// URLs are supported"};try{let c=0,l=0,d=0;if(i){let f=`SELECT pg_database_size(current_database()), (SELECT count(*) FROM pg_stat_activity WHERE state <> 'idle'), (SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '${n.longQuerySeconds} seconds')`,{stdout:g}=await dr("bash",["-lc",`psql "$MONITOR_DB_URL" -tA -F '|' -c "${f}"`],{timeout:ys,env:{...process.env,MONITOR_DB_URL:s}}),[v,k,T]=g.trim().split("|");c=Math.round(Number(v??0)/1024/1024),l=Number(k??0),d=Number(T??0)}else{let f=new URL(s),g=`SELECT (SELECT COALESCE(SUM(data_length+index_length),0) FROM information_schema.tables), (SELECT COUNT(*) FROM information_schema.processlist), (SELECT COUNT(*) FROM information_schema.processlist WHERE command <> 'Sleep' AND time > ${n.longQuerySeconds})`,{stdout:v}=await dr("mysql",["-h",f.hostname,"-P",f.port||"3306","-u",decodeURIComponent(f.username),"-N","-B","-e",g],{timeout:ys,env:{...process.env,MYSQL_PWD:decodeURIComponent(f.password)}}),[k,T,_]=v.trim().split(/\s+/);c=Math.round(Number(k??0)/1024/1024),l=Number(T??0),d=Number(_??0)}return{status:d>0||l>=n.warnConnections?"amber":"green",summary:`${c} MB, ${l} connection(s)`+(d?`, ${d} query(ies) over ${n.longQuerySeconds}s`:""),metrics:{sizeMB:c,connections:l,longQueries:d}}}catch(c){let l=c;return l.code==="ENOENT"?{status:"error",summary:`${i?"psql":"mysql"} is not installed on this machine - the db health check needs the client`}:{status:"red",summary:`database unreachable: ${(l.stderr||l.message||"").trim()}`.slice(0,300)}}}function CR(t){return t.split(`
1545
- `).map(e=>e.split(" ")).filter(e=>e.length>=2&&e[0]).map(([e,n,r])=>({name:e,state:n??"",status:r??""})).slice(0,100)}async function PR(t){let e=Ue(t),n="";try{n=(await dr("docker",["ps","-a","--format","{{.Names}} {{.State}} {{.Status}}"],{timeout:ys,maxBuffer:1e6})).stdout}catch(d){return{status:"error",summary:`docker did not answer: ${d.message}`.slice(0,300)}}let r=CR(n),s=r.filter(d=>d.state==="restarting"||d.status.startsWith("Restarting")),i=new Map(r.map(d=>[d.name,d])),a=e.expected.filter(d=>i.get(d)?.state!=="running"),c=r.filter(d=>d.state==="running").length,l={containers:r.map(d=>({name:d.name,state:d.state}))};return a.length?{status:"red",summary:`${a.length} expected container(s) not running: ${a.join(", ")}`.slice(0,300),metrics:l}:s.length?{status:"amber",summary:`restart-looping: ${s.map(d=>d.name).join(", ")}`.slice(0,300),metrics:l}:{status:"green",summary:`${c} container(s) running`,metrics:l}}function NR(t,e){let n=t.toLowerCase(),r=e.hardPatterns.filter(c=>c&&n.includes(c.toLowerCase())),s=0,i=[],a=null;try{a=new RegExp(e.errorPattern,"i")}catch{a=null}for(let c of t.split(`
1546
- `)){let l=r.some(p=>c.toLowerCase().includes(p.toLowerCase())),d=a?a.test(c):!1;(l||d)&&(d&&s++,i.length<20&&i.push(c.slice(0,300)))}return{hard:r,errors:s,matchingLines:i}}async function MR(t){let e=Ue(t);if(!e.files?.length)return{status:"error",summary:"no log files configured"};let n=[];for(let l of e.files.slice(0,10))try{let d=dn.default.statSync(l),p=Math.min(d.size,e.tailKB*1024),f=dn.default.openSync(l,"r"),g=Buffer.alloc(p);dn.default.readSync(f,g,0,p,d.size-p),dn.default.closeSync(f);let v=NR(g.toString("utf8"),e);n.push({file:l,hard:v.hard,errors:v.errors,lines:v.matchingLines})}catch(d){n.push({file:l,hard:[],errors:0,lines:[],error:d.message})}let r=n.filter(l=>l.error),s=n.filter(l=>l.hard.length),i=n.filter(l=>l.errors>=e.warnCount),a=s.length?"red":r.length?"error":i.length?"amber":"green",c=s.length?`${s[0].file}: found ${s[0].hard.join(", ")}`.slice(0,300):r.length?`cannot read ${r.map(l=>l.file).join(", ")}`.slice(0,300):i.length?`${i[0].file}: ${i[0].errors} error-pattern lines in the tail (warn at ${e.warnCount})`.slice(0,300):`${n.length} log(s) quiet`;return{status:a,summary:c,metrics:{files:n.map(l=>({file:l.file,errors:l.errors,hard:l.hard.length}))},excerpt:n.flatMap(l=>l.lines.length?[`== ${l.file}`,...l.lines]:[]).join(`
1547
- `).slice(0,Mn)}}async function Ya(t,e=ys){let{stdout:n}=await dr("powershell",["-NoProfile","-NonInteractive","-Command",t],{timeout:e,maxBuffer:4e6});return n}function jR(t){try{let e=JSON.parse(t);return(Array.isArray(e)?e:[e]).filter(r=>r.Size>0).map(r=>({mount:r.DeviceID,pct:Math.round((r.Size-r.FreeSpace)/r.Size*100),freeKB:Math.round(r.FreeSpace/1024)})).slice(0,20)}catch{return[]}}async function OR(t){let e=Ue(t),n;try{n=jR(await Ya("Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object DeviceID,Size,FreeSpace | ConvertTo-Json"))}catch(i){return{status:"error",summary:`powershell disk query failed: ${i.message}`.slice(0,300)}}if(e.mounts.length&&(n=n.filter(i=>e.mounts.includes(i.mount))),!n.length)return{status:"error",summary:"no fixed drives found"};n.sort((i,a)=>a.pct-i.pct);let r=n[0];return{status:r.pct>=e.critPct?"red":r.pct>=e.warnPct?"amber":"green",summary:`${r.pct}% used on ${r.mount} (${(r.freeKB/1024/1024).toFixed(1)} GB free)`,metrics:{mounts:n.map(i=>({mount:i.mount,pct:i.pct}))}}}async function zR(t){let e=Ue(t);if(!e.names?.length)return{status:"error",summary:"no service names configured"};let n=[],r={};for(let s of e.names.slice(0,40))try{let i=(await Ya(`(Get-Service -Name '${s.replace(/'/g,"''")}').Status`)).trim();r[s]=i,i!=="Running"&&n.push(s)}catch{r[s]="not found",n.push(s)}return n.length?{status:"red",summary:`${n.length} of ${e.names.length} down: ${n.join(", ")}`.slice(0,300),metrics:{states:r}}:{status:"green",summary:`all ${e.names.length} services running`,metrics:{states:r}}}var DR=["HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending","HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"];async function dy(){for(let t of DR)try{if((await Ya(`Test-Path '${t}'`)).trim()==="True")return!0}catch{}return!1}async function LR(t){let e=Ue(t),n=Math.floor(gs.default.uptime()/86400);return await dy()?{status:"amber",summary:`Windows wants a reboot (up ${n}d)`,metrics:{uptimeDays:n,rebootRequired:!0}}:n>=e.maxUptimeDays?{status:"amber",summary:`up ${n} days - patches this stale usually mean a reboot is overdue`,metrics:{uptimeDays:n,rebootRequired:!1}}:{status:"green",summary:`up ${n}d, no reboot pending`,metrics:{uptimeDays:n,rebootRequired:!1}}}async function UR(t){let e=Ue(t),n=await dy(),r=null;try{let a=(await Ya("Get-HotFix | Where-Object InstalledOn | Sort-Object InstalledOn -Descending | Select-Object -First 1 -ExpandProperty InstalledOn")).trim(),c=new Date(a);Number.isNaN(c.getTime())||(r=Math.floor((Date.now()-c.getTime())/864e5))}catch{}let s=r!==null&&r>e.maxHotfixAgeDays;return{status:n||s?"amber":"green",summary:n?`updates installed, reboot pending${r!==null?` (newest hotfix ${r}d ago)`:""}`:r===null?"hotfix history unreadable - patch age unknown":s?`newest hotfix is ${r} days old (warn at ${e.maxHotfixAgeDays})`:`patched ${r}d ago, no reboot pending`,metrics:{rebootPending:n,newestHotfixDays:r}}}var qR=new Set(["memory","http_check","tls_cert","backup_freshness","custom","disk_space","services","uptime_reboot","windows_update","ports_baseline","sites"]);async function uy(t,e){let n=uR(t.type),r=process.platform==="win32",s=r?"windows":"linux";if(n!=="both"&&n!==s)return{status:"skipped",summary:`${t.type} needs ${n}; this machine is ${s}`};if(r&&!qR.has(t.type))return{status:"skipped",summary:`${t.type} has no Windows collector yet`};try{let i=()=>Promise.resolve().then(()=>(lu(),cu));switch(t.type){case"disk_space":return r?await OR(t):await mR(t);case"memory":return await yR(t);case"cpu_load":return await bR(t);case"uptime_reboot":return r?await LR(t):await wR(t);case"services":return r?await zR(t):await vR(t);case"http_check":return await kR(t);case"tls_cert":return await SR(t);case"backup_freshness":return await xR(t);case"sites":return await AR(t);case"db_health":return await $R(t,e);case"docker_containers":return await PR(t);case"log_scan":return await MR(t);case"windows_update":return await UR(t);case"ports_baseline":return await(await i()).checkPortsBaseline(t);case"users_baseline":return await(await i()).checkUsersBaseline(t);case"cron_baseline":return await(await i()).checkCronBaseline(t);case"auth_activity":return await(await i()).checkAuthActivity(t,Ue(t));case"webroot_integrity":return await(await i()).checkWebrootIntegrity(t,Ue(t));case"wordpress":return await(await i()).checkWordpress(t,Ue(t));case"process_hog":return await(await i()).checkProcessHog(t,Ue(t));case"custom":return await IR(t,e);default:return{status:"error",summary:`no collector named "${t.type}" on this runner - update it`}}}catch(i){return{status:"error",summary:`${t.type} crashed: ${i.message}`.slice(0,300)}}}lt();var FR=6e4,hy=2,BR=15*6e4,py=200,HR=S.object({lastRuns:S.record(S.object({ranAt:S.string(),status:S.string()})).default({}),queue:S.array(S.unknown()).default([])}),Ja=()=>my.default.join(te(),"monitor-state.json");function uu(){try{return HR.parse(JSON.parse(fi.default.readFileSync(Ja(),"utf8")))}catch{return{lastRuns:{},queue:[]}}}function fy(t){fi.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Ja()+".tmp";fi.default.writeFileSync(e,JSON.stringify(t,null,2)+`
1548
- `,{mode:384}),fi.default.renameSync(e,Ja()),fi.default.chmodSync(Ja(),384)}function KR(t,e){if(t.kind==="every")return null;let[n,r]=t.at.split(":").map(i=>Number.parseInt(i,10)),s=new Date(e);if(s.setHours(n??0,r??0,0,0),t.kind==="daily")return s.getTime()>e.getTime()&&s.setDate(s.getDate()-1),s;for(;s.getDay()!==t.day||s.getTime()>e.getTime();)s.setDate(s.getDate()-1),s.setHours(n??0,r??0,0,0);return s}function WR(t,e,n){let r=e?new Date(e).getTime():0;if(t.kind==="every"){let a=t.minutes*6e4,c=n.getTime()-r>=a;return{due:c,late:c&&r>0&&n.getTime()-r>=a*3}}let s=KR(t,n);if(!s)return{due:!1,late:!1};let i=r<s.getTime();return{due:i,late:i&&n.getTime()-s.getTime()>BR}}var Xa=class{constructor(e,n,r){this.transport=e;this.getCfg=n;this.onRedEpisode=r}transport;getCfg;onRedEpisode;monitors=[];timer=null;ticking=!1;inFlight=new Set;setMonitors(e){this.monitors=e;let n=e.filter(r=>r.enabled).length;e.length&&b.info(`monitoring: ${n} check(s) enabled of ${e.length} synced`)}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},FR),this.timer.unref?.(),this.tick())}stop(){this.timer&&clearInterval(this.timer),this.timer=null}async runNow(e){let n=this.monitors.find(r=>r.id===e);return n?this.inFlight.has(e)?{ok:!1,error:"that check is already running"}:(this.execute(n,!1),{ok:!0}):{ok:!1,error:`no check with id ${e} on this runner - the config may still be syncing`}}async tick(){if(!this.ticking){this.ticking=!0;try{this.flushQueue();let e=new Date,n=uu(),r=[];for(let s of this.monitors){if(!s.enabled)continue;let i=WR(s.schedule,n.lastRuns[s.id]?.ranAt,e);if(i.due){if(this.inFlight.has(s.id)){this.record(s,{status:"skipped",summary:"previous run still in progress - this slot was skipped",late:!1,durationMs:0,ranAt:e.toISOString()});continue}r.push({check:s,late:i.late})}}for(let s=0;s<r.length;s+=hy)await Promise.all(r.slice(s,s+hy).map(i=>this.execute(i.check,i.late)))}catch(e){b.warn(`monitor tick failed: ${e.message}`)}finally{this.ticking=!1}}}async execute(e,n){this.inFlight.add(e.id);let r=Date.now(),s=new Date(r).toISOString();try{let i=await uy(e,this.getCfg());this.record(e,{status:i.status,summary:i.summary.slice(0,300),metrics:i.metrics,excerpt:(i.excerpt??"").slice(0,4e3),late:n,durationMs:Date.now()-r,ranAt:s}),(i.status==="red"||i.status==="error")&&b.warn(`monitor ${e.name}: ${i.status} - ${i.summary}`)}catch(i){this.record(e,{status:"error",summary:`check crashed: ${i.message}`.slice(0,300),late:n,durationMs:Date.now()-r,ranAt:s})}finally{this.inFlight.delete(e.id)}}record(e,n){let r="";n.metrics&&(r=JSON.stringify(n.metrics),r.length>8e3&&(r=""));let s={type:"monitor.result",resultId:`${e.id}:${n.ranAt}`,checkId:e.id,ranAt:n.ranAt,status:n.status,late:n.late,summary:n.summary,metricsJson:r,excerpt:n.excerpt??"",durationMs:n.durationMs},i=uu(),a=i.lastRuns[e.id]?.status??"";if(i.lastRuns[e.id]={ranAt:n.ranAt,status:n.status},i.queue.push(s),i.queue.length>py&&(i.queue=i.queue.slice(-py)),fy(i),this.flushQueue(),(n.status==="red"||n.status==="error")&&!(a==="red"||a==="error")&&e.jiraNotify&&this.onRedEpisode)try{this.onRedEpisode(e,{status:n.status,summary:n.summary,excerpt:n.excerpt??""})}catch(d){b.warn(`monitor red-episode hook failed: ${d.message}`)}}flushQueue(){if(!this.transport.connected)return;let e=uu();if(e.queue.length){for(let n of e.queue)this.transport.send(n);e.queue=[],fy(e)}}};nn();Md();fu();var tc=E(require("node:fs"),1),go=E(require("node:path"),1),_y=E(Ne(),1);Ae();async function xy(t,e){let n=await fetch(new URL("/api/runners/enroll",t.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:t.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:nc})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=_y.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return xe(s),s}function VR(){try{let t=process.argv[1]?tc.default.realpathSync(process.argv[1]):"";for(let e of[go.default.dirname(t),go.default.dirname(go.default.dirname(t))]){let n=go.default.join(e,"package.json");if(!tc.default.existsSync(n))continue;let r=JSON.parse(tc.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var nc=VR();sn();no();function Ty(t,e,n){let r=t.repos[e]?.jira??t.jira;if(!r)return{kind:"legacy"};let s=n.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=t.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:r.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
1506
+ `).slice(-Mn))}}async function IR(t,e){let n=`${t.ssl?"https":"http"}://${t.host}/`,r=0,s=0,i;try{let c=await du(n,8e3);r=c.status,s=c.ms}catch(c){i=c.message}let a=null;if(t.ssl)try{a=await ly(t.host,8e3)}catch{a=null}return{host:t.host,server:t.server,status:r,ms:s,certDays:a,error:i}}async function ER(t){let e=Ue(t),{discoverSites:n}=await Promise.resolve().then(()=>(Dg(),zg)),r=await n(),s=[...r,...e.extraHosts.filter(g=>!r.some(v=>v.host===g)).map(g=>({host:g,server:"extra",ssl:!0}))].filter(g=>!e.excludeHosts.includes(g.host));if(!s.length)return{status:"error",summary:"no sites found - no nginx/caddy vhosts on this box, and no extra hosts configured"};let i=[];for(let g=0;g<s.length;g+=5)i.push(...await Promise.all(s.slice(g,g+5).map(v=>IR(v,e))));let a=g=>g.error!==void 0||g.status>=500||g.certDays!==null&&g.certDays<=e.certCritDays,c=g=>g.status>=400&&g.status<500&&g.status!==401&&g.status!==403||g.ms>e.warnMs||g.certDays!==null&&g.certDays<=e.certWarnDays,l=i.filter(a),d=i.filter(g=>!a(g)&&c(g)),p=l.length?"red":d.length?"amber":"green",f=l.length?`${l.length} of ${i.length} sites down: ${l.map(g=>g.host).join(", ")}`.slice(0,300):d.length?`${d.length} of ${i.length} sites degraded: ${d.map(g=>g.host).join(", ")}`.slice(0,300):`${i.length} site(s) up and certified`;return{status:p,summary:f,metrics:{sites:i.map(g=>({host:g.host,server:g.server,status:g.status,ms:g.ms,certDays:g.certDays}))},excerpt:i.map(g=>`${g.host} (${g.server}): ${g.error?`UNREACHABLE - ${g.error}`:`${g.status} in ${g.ms}ms`}`+(g.certDays!==null?`, cert ${g.certDays}d`:"")).join(`
1507
+ `).slice(0,Mn)}}async function AR(t,e){let n=Ue(t);if(!n.repoName||!n.envName)return{status:"error",summary:"no repo/environment named - the URL lives in that secret store"};let s=(e.environments?.[`${n.repoName}:${n.envName}`]?.secrets??{})[n.secretName];if(!s)return{status:"error",summary:`no secret "${n.secretName}" for ${n.repoName}:${n.envName} - allwright env set ${n.repoName} ${n.envName} ${n.secretName}=postgresql://\u2026`};let i=s.startsWith("postgres"),a=s.startsWith("mysql");if(!i&&!a)return{status:"error",summary:"only postgres:// and mysql:// URLs are supported"};try{let c=0,l=0,d=0;if(i){let f=`SELECT pg_database_size(current_database()), (SELECT count(*) FROM pg_stat_activity WHERE state <> 'idle'), (SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '${n.longQuerySeconds} seconds')`,{stdout:g}=await dr("bash",["-lc",`psql "$MONITOR_DB_URL" -tA -F '|' -c "${f}"`],{timeout:ys,env:{...process.env,MONITOR_DB_URL:s}}),[v,k,T]=g.trim().split("|");c=Math.round(Number(v??0)/1024/1024),l=Number(k??0),d=Number(T??0)}else{let f=new URL(s),g=`SELECT (SELECT COALESCE(SUM(data_length+index_length),0) FROM information_schema.tables), (SELECT COUNT(*) FROM information_schema.processlist), (SELECT COUNT(*) FROM information_schema.processlist WHERE command <> 'Sleep' AND time > ${n.longQuerySeconds})`,{stdout:v}=await dr("mysql",["-h",f.hostname,"-P",f.port||"3306","-u",decodeURIComponent(f.username),"-N","-B","-e",g],{timeout:ys,env:{...process.env,MYSQL_PWD:decodeURIComponent(f.password)}}),[k,T,_]=v.trim().split(/\s+/);c=Math.round(Number(k??0)/1024/1024),l=Number(T??0),d=Number(_??0)}return{status:d>0||l>=n.warnConnections?"amber":"green",summary:`${c} MB, ${l} connection(s)`+(d?`, ${d} query(ies) over ${n.longQuerySeconds}s`:""),metrics:{sizeMB:c,connections:l,longQueries:d}}}catch(c){let l=c;return l.code==="ENOENT"?{status:"error",summary:`${i?"psql":"mysql"} is not installed on this machine - the db health check needs the client`}:{status:"red",summary:`database unreachable: ${(l.stderr||l.message||"").trim()}`.slice(0,300)}}}function $R(t){return t.split(`
1508
+ `).map(e=>e.split(" ")).filter(e=>e.length>=2&&e[0]).map(([e,n,r])=>({name:e,state:n??"",status:r??""})).slice(0,100)}async function CR(t){let e=Ue(t),n="";try{n=(await dr("docker",["ps","-a","--format","{{.Names}} {{.State}} {{.Status}}"],{timeout:ys,maxBuffer:1e6})).stdout}catch(d){return{status:"error",summary:`docker did not answer: ${d.message}`.slice(0,300)}}let r=$R(n),s=r.filter(d=>d.state==="restarting"||d.status.startsWith("Restarting")),i=new Map(r.map(d=>[d.name,d])),a=e.expected.filter(d=>i.get(d)?.state!=="running"),c=r.filter(d=>d.state==="running").length,l={containers:r.map(d=>({name:d.name,state:d.state}))};return a.length?{status:"red",summary:`${a.length} expected container(s) not running: ${a.join(", ")}`.slice(0,300),metrics:l}:s.length?{status:"amber",summary:`restart-looping: ${s.map(d=>d.name).join(", ")}`.slice(0,300),metrics:l}:{status:"green",summary:`${c} container(s) running`,metrics:l}}function PR(t,e){let n=t.toLowerCase(),r=e.hardPatterns.filter(c=>c&&n.includes(c.toLowerCase())),s=0,i=[],a=null;try{a=new RegExp(e.errorPattern,"i")}catch{a=null}for(let c of t.split(`
1509
+ `)){let l=r.some(p=>c.toLowerCase().includes(p.toLowerCase())),d=a?a.test(c):!1;(l||d)&&(d&&s++,i.length<20&&i.push(c.slice(0,300)))}return{hard:r,errors:s,matchingLines:i}}async function NR(t){let e=Ue(t);if(!e.files?.length)return{status:"error",summary:"no log files configured"};let n=[];for(let l of e.files.slice(0,10))try{let d=dn.default.statSync(l),p=Math.min(d.size,e.tailKB*1024),f=dn.default.openSync(l,"r"),g=Buffer.alloc(p);dn.default.readSync(f,g,0,p,d.size-p),dn.default.closeSync(f);let v=PR(g.toString("utf8"),e);n.push({file:l,hard:v.hard,errors:v.errors,lines:v.matchingLines})}catch(d){n.push({file:l,hard:[],errors:0,lines:[],error:d.message})}let r=n.filter(l=>l.error),s=n.filter(l=>l.hard.length),i=n.filter(l=>l.errors>=e.warnCount),a=s.length?"red":r.length?"error":i.length?"amber":"green",c=s.length?`${s[0].file}: found ${s[0].hard.join(", ")}`.slice(0,300):r.length?`cannot read ${r.map(l=>l.file).join(", ")}`.slice(0,300):i.length?`${i[0].file}: ${i[0].errors} error-pattern lines in the tail (warn at ${e.warnCount})`.slice(0,300):`${n.length} log(s) quiet`;return{status:a,summary:c,metrics:{files:n.map(l=>({file:l.file,errors:l.errors,hard:l.hard.length}))},excerpt:n.flatMap(l=>l.lines.length?[`== ${l.file}`,...l.lines]:[]).join(`
1510
+ `).slice(0,Mn)}}async function Ya(t,e=ys){let{stdout:n}=await dr("powershell",["-NoProfile","-NonInteractive","-Command",t],{timeout:e,maxBuffer:4e6});return n}function MR(t){try{let e=JSON.parse(t);return(Array.isArray(e)?e:[e]).filter(r=>r.Size>0).map(r=>({mount:r.DeviceID,pct:Math.round((r.Size-r.FreeSpace)/r.Size*100),freeKB:Math.round(r.FreeSpace/1024)})).slice(0,20)}catch{return[]}}async function jR(t){let e=Ue(t),n;try{n=MR(await Ya("Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object DeviceID,Size,FreeSpace | ConvertTo-Json"))}catch(i){return{status:"error",summary:`powershell disk query failed: ${i.message}`.slice(0,300)}}if(e.mounts.length&&(n=n.filter(i=>e.mounts.includes(i.mount))),!n.length)return{status:"error",summary:"no fixed drives found"};n.sort((i,a)=>a.pct-i.pct);let r=n[0];return{status:r.pct>=e.critPct?"red":r.pct>=e.warnPct?"amber":"green",summary:`${r.pct}% used on ${r.mount} (${(r.freeKB/1024/1024).toFixed(1)} GB free)`,metrics:{mounts:n.map(i=>({mount:i.mount,pct:i.pct}))}}}async function OR(t){let e=Ue(t);if(!e.names?.length)return{status:"error",summary:"no service names configured"};let n=[],r={};for(let s of e.names.slice(0,40))try{let i=(await Ya(`(Get-Service -Name '${s.replace(/'/g,"''")}').Status`)).trim();r[s]=i,i!=="Running"&&n.push(s)}catch{r[s]="not found",n.push(s)}return n.length?{status:"red",summary:`${n.length} of ${e.names.length} down: ${n.join(", ")}`.slice(0,300),metrics:{states:r}}:{status:"green",summary:`all ${e.names.length} services running`,metrics:{states:r}}}var zR=["HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending","HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"];async function dy(){for(let t of zR)try{if((await Ya(`Test-Path '${t}'`)).trim()==="True")return!0}catch{}return!1}async function DR(t){let e=Ue(t),n=Math.floor(gs.default.uptime()/86400);return await dy()?{status:"amber",summary:`Windows wants a reboot (up ${n}d)`,metrics:{uptimeDays:n,rebootRequired:!0}}:n>=e.maxUptimeDays?{status:"amber",summary:`up ${n} days - patches this stale usually mean a reboot is overdue`,metrics:{uptimeDays:n,rebootRequired:!1}}:{status:"green",summary:`up ${n}d, no reboot pending`,metrics:{uptimeDays:n,rebootRequired:!1}}}async function LR(t){let e=Ue(t),n=await dy(),r=null;try{let a=(await Ya("Get-HotFix | Where-Object InstalledOn | Sort-Object InstalledOn -Descending | Select-Object -First 1 -ExpandProperty InstalledOn")).trim(),c=new Date(a);Number.isNaN(c.getTime())||(r=Math.floor((Date.now()-c.getTime())/864e5))}catch{}let s=r!==null&&r>e.maxHotfixAgeDays;return{status:n||s?"amber":"green",summary:n?`updates installed, reboot pending${r!==null?` (newest hotfix ${r}d ago)`:""}`:r===null?"hotfix history unreadable - patch age unknown":s?`newest hotfix is ${r} days old (warn at ${e.maxHotfixAgeDays})`:`patched ${r}d ago, no reboot pending`,metrics:{rebootPending:n,newestHotfixDays:r}}}var UR=new Set(["memory","http_check","tls_cert","backup_freshness","custom","disk_space","services","uptime_reboot","windows_update","ports_baseline","sites"]);async function uy(t,e){let n=dR(t.type),r=process.platform==="win32",s=r?"windows":"linux";if(n!=="both"&&n!==s)return{status:"skipped",summary:`${t.type} needs ${n}; this machine is ${s}`};if(r&&!UR.has(t.type))return{status:"skipped",summary:`${t.type} has no Windows collector yet`};try{let i=()=>Promise.resolve().then(()=>(lu(),cu));switch(t.type){case"disk_space":return r?await jR(t):await fR(t);case"memory":return await gR(t);case"cpu_load":return await yR(t);case"uptime_reboot":return r?await DR(t):await bR(t);case"services":return r?await OR(t):await wR(t);case"http_check":return await vR(t);case"tls_cert":return await kR(t);case"backup_freshness":return await _R(t);case"sites":return await ER(t);case"db_health":return await AR(t,e);case"docker_containers":return await CR(t);case"log_scan":return await NR(t);case"windows_update":return await LR(t);case"ports_baseline":return await(await i()).checkPortsBaseline(t);case"users_baseline":return await(await i()).checkUsersBaseline(t);case"cron_baseline":return await(await i()).checkCronBaseline(t);case"auth_activity":return await(await i()).checkAuthActivity(t,Ue(t));case"webroot_integrity":return await(await i()).checkWebrootIntegrity(t,Ue(t));case"wordpress":return await(await i()).checkWordpress(t,Ue(t));case"process_hog":return await(await i()).checkProcessHog(t,Ue(t));case"custom":return await RR(t,e);default:return{status:"error",summary:`no collector named "${t.type}" on this runner - update it`}}}catch(i){return{status:"error",summary:`${t.type} crashed: ${i.message}`.slice(0,300)}}}lt();var qR=6e4,hy=2,FR=15*6e4,py=200,BR=S.object({lastRuns:S.record(S.object({ranAt:S.string(),status:S.string()})).default({}),queue:S.array(S.unknown()).default([])}),Ja=()=>my.default.join(te(),"monitor-state.json");function uu(){try{return BR.parse(JSON.parse(fi.default.readFileSync(Ja(),"utf8")))}catch{return{lastRuns:{},queue:[]}}}function fy(t){fi.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Ja()+".tmp";fi.default.writeFileSync(e,JSON.stringify(t,null,2)+`
1511
+ `,{mode:384}),fi.default.renameSync(e,Ja()),fi.default.chmodSync(Ja(),384)}function HR(t,e){if(t.kind==="every")return null;let[n,r]=t.at.split(":").map(i=>Number.parseInt(i,10)),s=new Date(e);if(s.setHours(n??0,r??0,0,0),t.kind==="daily")return s.getTime()>e.getTime()&&s.setDate(s.getDate()-1),s;for(;s.getDay()!==t.day||s.getTime()>e.getTime();)s.setDate(s.getDate()-1),s.setHours(n??0,r??0,0,0);return s}function KR(t,e,n){let r=e?new Date(e).getTime():0;if(t.kind==="every"){let a=t.minutes*6e4,c=n.getTime()-r>=a;return{due:c,late:c&&r>0&&n.getTime()-r>=a*3}}let s=HR(t,n);if(!s)return{due:!1,late:!1};let i=r<s.getTime();return{due:i,late:i&&n.getTime()-s.getTime()>FR}}var Xa=class{constructor(e,n,r){this.transport=e;this.getCfg=n;this.onRedEpisode=r}transport;getCfg;onRedEpisode;monitors=[];timer=null;ticking=!1;inFlight=new Set;setMonitors(e){this.monitors=e;let n=e.filter(r=>r.enabled).length;e.length&&b.info(`monitoring: ${n} check(s) enabled of ${e.length} synced`)}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},qR),this.timer.unref?.(),this.tick())}stop(){this.timer&&clearInterval(this.timer),this.timer=null}async runNow(e){let n=this.monitors.find(r=>r.id===e);return n?this.inFlight.has(e)?{ok:!1,error:"that check is already running"}:(this.execute(n,!1),{ok:!0}):{ok:!1,error:`no check with id ${e} on this runner - the config may still be syncing`}}async tick(){if(!this.ticking){this.ticking=!0;try{this.flushQueue();let e=new Date,n=uu(),r=[];for(let s of this.monitors){if(!s.enabled)continue;let i=KR(s.schedule,n.lastRuns[s.id]?.ranAt,e);if(i.due){if(this.inFlight.has(s.id)){this.record(s,{status:"skipped",summary:"previous run still in progress - this slot was skipped",late:!1,durationMs:0,ranAt:e.toISOString()});continue}r.push({check:s,late:i.late})}}for(let s=0;s<r.length;s+=hy)await Promise.all(r.slice(s,s+hy).map(i=>this.execute(i.check,i.late)))}catch(e){b.warn(`monitor tick failed: ${e.message}`)}finally{this.ticking=!1}}}async execute(e,n){this.inFlight.add(e.id);let r=Date.now(),s=new Date(r).toISOString();try{let i=await uy(e,this.getCfg());this.record(e,{status:i.status,summary:i.summary.slice(0,300),metrics:i.metrics,excerpt:(i.excerpt??"").slice(0,4e3),late:n,durationMs:Date.now()-r,ranAt:s}),(i.status==="red"||i.status==="error")&&b.warn(`monitor ${e.name}: ${i.status} - ${i.summary}`)}catch(i){this.record(e,{status:"error",summary:`check crashed: ${i.message}`.slice(0,300),late:n,durationMs:Date.now()-r,ranAt:s})}finally{this.inFlight.delete(e.id)}}record(e,n){let r="";n.metrics&&(r=JSON.stringify(n.metrics),r.length>8e3&&(r=""));let s={type:"monitor.result",resultId:`${e.id}:${n.ranAt}`,checkId:e.id,ranAt:n.ranAt,status:n.status,late:n.late,summary:n.summary,metricsJson:r,excerpt:n.excerpt??"",durationMs:n.durationMs},i=uu(),a=i.lastRuns[e.id]?.status??"";if(i.lastRuns[e.id]={ranAt:n.ranAt,status:n.status},i.queue.push(s),i.queue.length>py&&(i.queue=i.queue.slice(-py)),fy(i),this.flushQueue(),(n.status==="red"||n.status==="error")&&!(a==="red"||a==="error")&&e.jiraNotify&&this.onRedEpisode)try{this.onRedEpisode(e,{status:n.status,summary:n.summary,excerpt:n.excerpt??""})}catch(d){b.warn(`monitor red-episode hook failed: ${d.message}`)}}flushQueue(){if(!this.transport.connected)return;let e=uu();if(e.queue.length){for(let n of e.queue)this.transport.send(n);e.queue=[],fy(e)}}};nn();Md();fu();var tc=E(require("node:fs"),1),go=E(require("node:path"),1),_y=E(Ne(),1);Ae();async function xy(t,e){let n=await fetch(new URL("/api/runners/enroll",t.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:t.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:nc})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=_y.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return xe(s),s}function ZR(){try{let t=process.argv[1]?tc.default.realpathSync(process.argv[1]):"";for(let e of[go.default.dirname(t),go.default.dirname(go.default.dirname(t))]){let n=go.default.join(e,"package.json");if(!tc.default.existsSync(n))continue;let r=JSON.parse(tc.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var nc=ZR();sn();no();function Ty(t,e,n){let r=t.repos[e]?.jira??t.jira;if(!r)return{kind:"legacy"};let s=n.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=t.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:r.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
1549
1512
 
1550
1513
  allwright jira user-add ${s}
1551
1514
 
1552
- It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}function Ry(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function Iy(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}is();var YR=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function Ey(t,e){let n=!1;return{text:t.replace(YR,(s,i)=>{let a=Number(i);return a<1||a>e.length?s:(n=!0,e[a-1])}),changed:n}}lc();var My=E(Ne(),1);function jy(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(My.NEEDS_INPUT_LABEL))}function Oy(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
1515
+ It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}function Ry(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function Iy(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}is();var VR=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function Ey(t,e){let n=!1;return{text:t.replace(VR,(s,i)=>{let a=Number(i);return a<1||a>e.length?s:(n=!0,e[a-1])}),changed:n}}lc();var My=E(Ne(),1);function jy(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(My.NEEDS_INPUT_LABEL))}function Oy(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
1553
1516
  ${i.replace(/\n+/g," ")}`:""}`}).join(`
1554
1517
  `);return`You are looking at this repository to help sequence work on the Jira epic ${t} ("${e}"). These child tickets are still pending:
1555
1518
 
@@ -1560,7 +1523,7 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
1560
1523
  Answer with ONLY a fenced json block, nothing after it:
1561
1524
  \`\`\`json
1562
1525
  {"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
1563
- \`\`\``}function zy(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"}}}Sa();Vi();wa();var hr=E(Ne(),1);Ae();no();ds();fs();sn();Qi();ds();Ht();is();Sa();Et();var dc=E(require("node:fs"),1),Dy=E(require("node:path"),1);Ae();var eI=1440*6e4,Ly=()=>Dy.default.join(te(),"agent-overrides.json");function Uy(){try{return JSON.parse(dc.default.readFileSync(Ly(),"utf8"))}catch{return{}}}function qy(t){dc.default.mkdirSync(te(),{recursive:!0,mode:448}),dc.default.writeFileSync(Ly(),JSON.stringify(t,null,2),{mode:384})}var Fy=(t,e)=>`${t}:${e}`;function By(t,e,n){let r=(n??"").trim();if(!r)return;let s=Uy();s[Fy(t,e)]={agentId:r,at:new Date().toISOString()},qy(s)}function Hy(t,e){let n=Uy(),r=Fy(t,e),s=n[r];return!s||(delete n[r],qy(n),Date.now()-Date.parse(s.at)>eI)?"":s.agentId}function uc(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}}}wa();lt();mc();var Wy=24*3600*1e3,gc=14,nI=gc*24*3600*1e3,rI=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]);function Gy(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 yc=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!!Li(this.cfg,e)}get jiraless(){return Ui(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)}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=Ef(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=$e(this.cfg,n,"assist");if("error"in s){b.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ri({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 w=Date.parse(e.pausedUntil);Number.isFinite(w)&&(this.autopilotPausedUntil=w);return}let n=e.item;if(!n)return;let r=this.rules.find(w=>w.id===n.ruleId&&w.enabled),s=this.projects.find(w=>w.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=uc(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,d=Gy(l,n.agentId);b.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:"")+(d.agentId?` -> agent ${d.agentId}`:""));let p=this.jiraOf(a),f="";try{f=(await p.getIssue(n.issueKey))?.summary??""}catch(w){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${w instanceof Error?w.message:String(w)}`});return}let g=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!g.accepted||!g.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:g.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:g.runId});let v=`${r.id}:${n.issueKey}`;this.inFlight.add(v);let k=this.resolveClaudeProfile(g.runId,g.claudeProfile),T=!!(n.batchId&&n.branchOverride),_=n.batchId?xu(n.batchId):null,$=!n.continueBranch&&!T?Tu(_,n.issueKey):null,D=$?fc(n.batchId,$,n.issueKey):null,z=T&&n.continueBranch?Eu(n.batchId):null,A=D??z,P=Pu($,n.issueKey)||T&&n.remainingInBatch>0;this.enqueueForRepo(c.path,async()=>{try{await lo({runId:g.runId,rule:d.rule,project:a,issueKey:n.issueKey,repoPath:c.path,cfg:this.cfg,jira:p,transport:this.transport,claudeConfigDir:k,actorEmail:g.actorEmail,continueBranch:n.continueBranch,...A?{chain:{sessionId:A.sessionId,worktreePath:A.worktreePath}}:{},keepWorktree:P,onChainSession:$?w=>Ru(n.batchId,$,n.issueKey,w):T&&P?w=>Au(n.batchId,n.issueKey,w,!!z):void 0}),$&&!fc(n.batchId,$,$[$.indexOf(n.issueKey)+1]??"")&&$.indexOf(n.issueKey)<$.length-1&&Iu(n.batchId,$),T&&!$u(n.batchId,n.issueKey)&&Cu(n.batchId)}finally{this.inFlight.delete(v)}})}async sweepGitHubApprovals(){let e=Object.values(Xi());if(!e.length)return;let n=_e()??this.cfg,r=new Map,s=i=>{let a=Qe(n,i);if(!a)return null;let c=r.get(a);return c||r.set(a,c=new Xe(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,d;try{[l,d]=await Promise.all([a.getReviews(i.owner,i.repo,i.prNumber),a.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){b.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!d){let v=`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.**
1526
+ \`\`\``}function zy(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"}}}Sa();Vi();wa();var hr=E(Ne(),1);Ae();no();ds();fs();sn();Qi();ds();Ht();is();Sa();Et();var dc=E(require("node:fs"),1),Dy=E(require("node:path"),1);Ae();var QR=1440*6e4,Ly=()=>Dy.default.join(te(),"agent-overrides.json");function Uy(){try{return JSON.parse(dc.default.readFileSync(Ly(),"utf8"))}catch{return{}}}function qy(t){dc.default.mkdirSync(te(),{recursive:!0,mode:448}),dc.default.writeFileSync(Ly(),JSON.stringify(t,null,2),{mode:384})}var Fy=(t,e)=>`${t}:${e}`;function By(t,e,n){let r=(n??"").trim();if(!r)return;let s=Uy();s[Fy(t,e)]={agentId:r,at:new Date().toISOString()},qy(s)}function Hy(t,e){let n=Uy(),r=Fy(t,e),s=n[r];return!s||(delete n[r],qy(n),Date.now()-Date.parse(s.at)>QR)?"":s.agentId}function uc(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}}}wa();lt();mc();var Wy=24*3600*1e3,gc=14,tI=gc*24*3600*1e3,nI=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]);function Gy(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 yc=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!!Li(this.cfg,e)}get jiraless(){return Ui(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)}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=Ef(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=$e(this.cfg,n,"assist");if("error"in s){b.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ri({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 w=Date.parse(e.pausedUntil);Number.isFinite(w)&&(this.autopilotPausedUntil=w);return}let n=e.item;if(!n)return;let r=this.rules.find(w=>w.id===n.ruleId&&w.enabled),s=this.projects.find(w=>w.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=uc(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,d=Gy(l,n.agentId);b.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:"")+(d.agentId?` -> agent ${d.agentId}`:""));let p=this.jiraOf(a),f="";try{f=(await p.getIssue(n.issueKey))?.summary??""}catch(w){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${w instanceof Error?w.message:String(w)}`});return}let g=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!g.accepted||!g.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:g.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:g.runId});let v=`${r.id}:${n.issueKey}`;this.inFlight.add(v);let k=this.resolveClaudeProfile(g.runId,g.claudeProfile),T=!!(n.batchId&&n.branchOverride),_=n.batchId?xu(n.batchId):null,$=!n.continueBranch&&!T?Tu(_,n.issueKey):null,D=$?fc(n.batchId,$,n.issueKey):null,z=T&&n.continueBranch?Eu(n.batchId):null,A=D??z,P=Pu($,n.issueKey)||T&&n.remainingInBatch>0;this.enqueueForRepo(c.path,async()=>{try{await lo({runId:g.runId,rule:d.rule,project:a,issueKey:n.issueKey,repoPath:c.path,cfg:this.cfg,jira:p,transport:this.transport,claudeConfigDir:k,actorEmail:g.actorEmail,continueBranch:n.continueBranch,...A?{chain:{sessionId:A.sessionId,worktreePath:A.worktreePath}}:{},keepWorktree:P,onChainSession:$?w=>Ru(n.batchId,$,n.issueKey,w):T&&P?w=>Au(n.batchId,n.issueKey,w,!!z):void 0}),$&&!fc(n.batchId,$,$[$.indexOf(n.issueKey)+1]??"")&&$.indexOf(n.issueKey)<$.length-1&&Iu(n.batchId,$),T&&!$u(n.batchId,n.issueKey)&&Cu(n.batchId)}finally{this.inFlight.delete(v)}})}async sweepGitHubApprovals(){let e=Object.values(Xi());if(!e.length)return;let n=_e()??this.cfg,r=new Map,s=i=>{let a=Qe(n,i);if(!a)return null;let c=r.get(a);return c||r.set(a,c=new Xe(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,d;try{[l,d]=await Promise.all([a.getReviews(i.owner,i.repo,i.prNumber),a.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){b.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!d){let v=`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.**
1564
1527
 
1565
1528
  ${v}
1566
1529
 
@@ -1590,7 +1553,7 @@ Note: the "${c.jiraTransitionOnMerge}" transition failed: ${g instanceof Error?g
1590
1553
 
1591
1554
  PR: ${c.prUrl} (merged at \`${d.headSha.slice(0,10)}\`)${f}
1592
1555
 
1593
- (run \`${c.runId}\`)`)}catch(g){b.warn(`could not post merge comment to ${c.issueKey}: ${g instanceof Error?g.message:g}`);continue}this.transport.send({type:"run.log",runId:c.runId,seq:2e5,level:"info",message:d.mergedBy?`Decided on GitHub: PR #${c.prNumber} merged by ${d.mergedBy}`:`Decided on GitHub: PR #${c.prNumber} merged`,ts:new Date().toISOString()}),this.transport.send({type:"run.status",runId:c.runId,status:"succeeded",note:d.mergedBy?`merged on GitHub by ${d.mergedBy} at ${d.headSha.slice(0,10)}`:`merged on GitHub at ${d.headSha.slice(0,10)}`}),b.info(`PR #${c.prNumber} for ${c.issueKey} merged - ticket and run updated`),Ji(c.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${hr.NEEDS_INPUT_LABEL}"`,10)}catch(s){b.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!n.length)return;let r=os();for(let s of n){let i=Object.values(r).filter(c=>c.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[hr.NEEDS_INPUT_LABEL]}).catch(()=>{}),b.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let a=null;for(let c of i){let l=`resume:${c.runId}`;if(this.inFlight.has(l))continue;if(Date.now()-new Date(c.createdAt).getTime()>nI){this.inFlight.add(l),this.abandonStaleInput(c,e).finally(()=>this.inFlight.delete(l));continue}try{a=a??await this.jiraOf(e).getIssue(s.key)}catch(k){b.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let d=new Date(c.questionsPostedAt).getTime(),p=a.comments.filter(k=>!$t(k.body)&&new Date(k.created).getTime()>d);if(!p.length)continue;let f=cs(p),g=a.attachments;this.inFlight.add(l),b.info(`reply received on ${s.key} - resuming run ${c.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[hr.NEEDS_INPUT_LABEL]}).catch(k=>{b.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:k=>this.findRuleForResume(k)};c.kind==="implement"?this.enqueueForRepo(c.baseRepoPath??c.repoPath,async()=>{try{await Wd(c,f,g,v)}finally{this.inFlight.delete(l)}}):this.enqueueForRepo(c.repoPath,async()=>{try{await Kd(c,f,g,v)}finally{this.inFlight.delete(l)}})}}}findRuleForResume(e){let n=this.rules.find(i=>i.id===e),r=n&&this.projects.find(i=>i.id===n.projectId),s=r&&this.cfg.repos[r.repoName]?.path;return n&&r&&s?{rule:n,project:r,repoPath:s}:null}async answerPendingInput(e,n,r){let s=dm(e);if(!s)return{ok:!1,note:"",error:"this run is not waiting for an answer on this server - it may have been answered already, or abandoned after 14 days without a reply"};let i=`resume:${e}`;if(this.inFlight.has(i))return{ok:!1,note:"",error:"an answer for this run is already being applied"};this.inFlight.add(i);let a=this.jiraFor(s.repoName??""),c=[];try{c=(await a.getIssue(s.issueKey)).attachments,await a.addComment(s.issueKey,`**Answered on the Allwright dashboard${r?` by ${r}`:""}.**
1556
+ (run \`${c.runId}\`)`)}catch(g){b.warn(`could not post merge comment to ${c.issueKey}: ${g instanceof Error?g.message:g}`);continue}this.transport.send({type:"run.log",runId:c.runId,seq:2e5,level:"info",message:d.mergedBy?`Decided on GitHub: PR #${c.prNumber} merged by ${d.mergedBy}`:`Decided on GitHub: PR #${c.prNumber} merged`,ts:new Date().toISOString()}),this.transport.send({type:"run.status",runId:c.runId,status:"succeeded",note:d.mergedBy?`merged on GitHub by ${d.mergedBy} at ${d.headSha.slice(0,10)}`:`merged on GitHub at ${d.headSha.slice(0,10)}`}),b.info(`PR #${c.prNumber} for ${c.issueKey} merged - ticket and run updated`),Ji(c.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${hr.NEEDS_INPUT_LABEL}"`,10)}catch(s){b.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!n.length)return;let r=os();for(let s of n){let i=Object.values(r).filter(c=>c.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[hr.NEEDS_INPUT_LABEL]}).catch(()=>{}),b.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let a=null;for(let c of i){let l=`resume:${c.runId}`;if(this.inFlight.has(l))continue;if(Date.now()-new Date(c.createdAt).getTime()>tI){this.inFlight.add(l),this.abandonStaleInput(c,e).finally(()=>this.inFlight.delete(l));continue}try{a=a??await this.jiraOf(e).getIssue(s.key)}catch(k){b.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let d=new Date(c.questionsPostedAt).getTime(),p=a.comments.filter(k=>!$t(k.body)&&new Date(k.created).getTime()>d);if(!p.length)continue;let f=cs(p),g=a.attachments;this.inFlight.add(l),b.info(`reply received on ${s.key} - resuming run ${c.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[hr.NEEDS_INPUT_LABEL]}).catch(k=>{b.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:k=>this.findRuleForResume(k)};c.kind==="implement"?this.enqueueForRepo(c.baseRepoPath??c.repoPath,async()=>{try{await Wd(c,f,g,v)}finally{this.inFlight.delete(l)}}):this.enqueueForRepo(c.repoPath,async()=>{try{await Kd(c,f,g,v)}finally{this.inFlight.delete(l)}})}}}findRuleForResume(e){let n=this.rules.find(i=>i.id===e),r=n&&this.projects.find(i=>i.id===n.projectId),s=r&&this.cfg.repos[r.repoName]?.path;return n&&r&&s?{rule:n,project:r,repoPath:s}:null}async answerPendingInput(e,n,r){let s=dm(e);if(!s)return{ok:!1,note:"",error:"this run is not waiting for an answer on this server - it may have been answered already, or abandoned after 14 days without a reply"};let i=`resume:${e}`;if(this.inFlight.has(i))return{ok:!1,note:"",error:"an answer for this run is already being applied"};this.inFlight.add(i);let a=this.jiraFor(s.repoName??""),c=[];try{c=(await a.getIssue(s.issueKey)).attachments,await a.addComment(s.issueKey,`**Answered on the Allwright dashboard${r?` by ${r}`:""}.**
1594
1557
 
1595
1558
  ${n}
1596
1559
 
@@ -1602,7 +1565,7 @@ ${c.reason}`+(i.requestedByAccountId?`
1602
1565
 
1603
1566
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
1604
1567
 
1605
- (run \`${c.runId}\`)`).catch(d=>b.warn(`could not post refusal to ${i.issueKey}: ${d}`)),b.warn(`deploy refused for ${i.issueKey}: ${c.reason}`)):c.reason&&b.warn(`deploy claim rejected for ${i.issueKey}: ${c.reason}`);continue}let l=c.environment;this.inFlight.add(a),b.info(`claimed deploy ${c.runId}: ${i.issueKey} \u2192 ${l.name}`),this.enqueue(this.envQueues,l.id,async()=>{try{await po({runId:c.runId,project:n,environment:l,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(n),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(a)}})}}async matchCommentDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),a=r.keyword.toLowerCase(),c=Date.now()-Wy,l=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),d=this.fixedEnvironmentName(s.environmentId),p=[];for(let f of i){let g=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&g.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let v of g.comments){if(!v.body.toLowerCase().includes(a)||$t(v.body)||new Date(v.created).getTime()<c||!v.id)continue;let k=s.envSelection==="fixed"?d:sI(v.body,r.keyword,l);p.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(k?` \u2192 ${k}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),a=this.fixedEnvironmentName(s.environmentId),c=[];for(let l of i){let d=await this.jiraOf(n).lastEnteredStatus(l.key,r.status);d&&c.push({issueKey:l.key,summary:l.summary,environmentName:a,requestedByAccountId:d.authorAccountId??void 0,requestedByDisplayName:d.author,dedupKey:`deploy:status:${e.id}:${l.key}:${d.at}`,fingerprint:`moved to "${r.status}" by ${d.author} at ${d.at}`})}return c}fixedEnvironmentName(e){return e?this.environments.find(n=>n.id===e)?.name??"":""}async matchLabelTrigger(e,n){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${hr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(n).search(s,10)).map(a=>({issueKey:a.key,summary:a.summary,components:a.components,fingerprint:`label "${r.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${hr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(n).search(s,10),a=r.keyword.toLowerCase(),c=[];for(let l of i){let p=[...(await this.jiraOf(n).getIssue(l.key)).comments].reverse().find(f=>f.body.toLowerCase().includes(a)&&!$t(f.body));p&&c.push({issueKey:l.key,components:l.components,summary:l.summary,fingerprint:`comment keyword "${r.keyword}" by ${p.author} at ${p.created}`,triggeredByAccountId:p.authorAccountId??void 0})}return c}async diagnoseRule(e,n){let r=e.trigger;if(e.action.type==="deploy"){let l=r.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n),d=l.filter(p=>p.environmentName);return{matchedCount:d.length,excludedCount:l.length-d.length,excludedSample:l.filter(p=>!p.environmentName).slice(0,5).map(p=>p.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[l,d]=await Promise.all([this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:l.length,excludedCount:d.length,excludedSample:d.slice(0,5).map(p=>p.key)}}let s=r.keyword.toLowerCase(),[i,a]=await Promise.all([this.matchCommentTrigger(e,n),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),c=[];for(let l of a)(await this.jiraOf(n).getIssue(l.key)).comments.some(p=>p.body.toLowerCase().includes(s))&&c.push(l.key);return{matchedCount:i.length,excludedCount:c.length,excludedSample:c.slice(0,5)}}enqueueForRepo(e,n){this.enqueue(this.repoQueues,e,n)}runOnRepoQueue(e,n){this.enqueue(this.repoQueues,e,n)}runOnEnvironmentQueue(e,n){this.enqueue(this.envQueues,e,n)}enqueue(e,n,r){let i=(e.get(n)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(a=>{b.error(`run crashed: ${a instanceof Error?a.stack:a}`)});e.set(n,i)}};function sI(t,e,n){let r=t.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=t.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let a of i){let c=n.find(l=>l.toLowerCase()===a.toLowerCase());if(c)return c}for(let a of i)if(!rI.has(a.toLowerCase()))return a;return""}Ad();Et();var Zy=E(require("node:fs"),1),Vy=E(require("node:path"),1),Mu=require("node:crypto");sn();Et();ds();nn();var iI=`This repository is in the middle of a git merge: the base branch moved and some files conflict with the change on this branch. Your ONLY job is to resolve those conflicts.
1568
+ (run \`${c.runId}\`)`).catch(d=>b.warn(`could not post refusal to ${i.issueKey}: ${d}`)),b.warn(`deploy refused for ${i.issueKey}: ${c.reason}`)):c.reason&&b.warn(`deploy claim rejected for ${i.issueKey}: ${c.reason}`);continue}let l=c.environment;this.inFlight.add(a),b.info(`claimed deploy ${c.runId}: ${i.issueKey} \u2192 ${l.name}`),this.enqueue(this.envQueues,l.id,async()=>{try{await po({runId:c.runId,project:n,environment:l,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(n),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(a)}})}}async matchCommentDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),a=r.keyword.toLowerCase(),c=Date.now()-Wy,l=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),d=this.fixedEnvironmentName(s.environmentId),p=[];for(let f of i){let g=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&g.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let v of g.comments){if(!v.body.toLowerCase().includes(a)||$t(v.body)||new Date(v.created).getTime()<c||!v.id)continue;let k=s.envSelection==="fixed"?d:rI(v.body,r.keyword,l);p.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(k?` \u2192 ${k}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),a=this.fixedEnvironmentName(s.environmentId),c=[];for(let l of i){let d=await this.jiraOf(n).lastEnteredStatus(l.key,r.status);d&&c.push({issueKey:l.key,summary:l.summary,environmentName:a,requestedByAccountId:d.authorAccountId??void 0,requestedByDisplayName:d.author,dedupKey:`deploy:status:${e.id}:${l.key}:${d.at}`,fingerprint:`moved to "${r.status}" by ${d.author} at ${d.at}`})}return c}fixedEnvironmentName(e){return e?this.environments.find(n=>n.id===e)?.name??"":""}async matchLabelTrigger(e,n){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${hr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(n).search(s,10)).map(a=>({issueKey:a.key,summary:a.summary,components:a.components,fingerprint:`label "${r.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${hr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(n).search(s,10),a=r.keyword.toLowerCase(),c=[];for(let l of i){let p=[...(await this.jiraOf(n).getIssue(l.key)).comments].reverse().find(f=>f.body.toLowerCase().includes(a)&&!$t(f.body));p&&c.push({issueKey:l.key,components:l.components,summary:l.summary,fingerprint:`comment keyword "${r.keyword}" by ${p.author} at ${p.created}`,triggeredByAccountId:p.authorAccountId??void 0})}return c}async diagnoseRule(e,n){let r=e.trigger;if(e.action.type==="deploy"){let l=r.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n),d=l.filter(p=>p.environmentName);return{matchedCount:d.length,excludedCount:l.length-d.length,excludedSample:l.filter(p=>!p.environmentName).slice(0,5).map(p=>p.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[l,d]=await Promise.all([this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:l.length,excludedCount:d.length,excludedSample:d.slice(0,5).map(p=>p.key)}}let s=r.keyword.toLowerCase(),[i,a]=await Promise.all([this.matchCommentTrigger(e,n),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),c=[];for(let l of a)(await this.jiraOf(n).getIssue(l.key)).comments.some(p=>p.body.toLowerCase().includes(s))&&c.push(l.key);return{matchedCount:i.length,excludedCount:c.length,excludedSample:c.slice(0,5)}}enqueueForRepo(e,n){this.enqueue(this.repoQueues,e,n)}runOnRepoQueue(e,n){this.enqueue(this.repoQueues,e,n)}runOnEnvironmentQueue(e,n){this.enqueue(this.envQueues,e,n)}enqueue(e,n,r){let i=(e.get(n)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(a=>{b.error(`run crashed: ${a instanceof Error?a.stack:a}`)});e.set(n,i)}};function rI(t,e,n){let r=t.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=t.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let a of i){let c=n.find(l=>l.toLowerCase()===a.toLowerCase());if(c)return c}for(let a of i)if(!nI.has(a.toLowerCase()))return a;return""}Ad();Et();var Zy=E(require("node:fs"),1),Vy=E(require("node:path"),1),Mu=require("node:crypto");sn();Et();ds();nn();var sI=`This repository is in the middle of a git merge: the base branch moved and some files conflict with the change on this branch. Your ONLY job is to resolve those conflicts.
1606
1569
 
1607
1570
  Rules:
1608
1571
  - Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
@@ -1611,10 +1574,10 @@ Rules:
1611
1574
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
1612
1575
 
1613
1576
  Conflicted files:
1614
- `;async function Yy(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:a}=t,c=Vy.default.join(En(),`conflict-${(0,Mu.randomUUID)().slice(0,8)}`),l=!1;try{a("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Gi(n,c,r),l=!0;let d=await rd(c,s);if(d.ok&&d.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(!d.ok&&d.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${d.reason}`};let p={},f=!1;if(!d.ok){let k=d.conflicts;a("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let T=tt(t.agentId);if(!T)return await nr(c),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let _=Jn(t.agentId,"edit_no_shell");if(_)return await nr(c),{ok:!1,note:`${_} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};a("info",`Asking ${T.displayName} to resolve only those files`);let $=-1,D=setInterval(()=>{id(c,k).then(P=>{let w=k.filter(j=>!P.includes(j));w.length!==$&&($=w.length,a("info",`Conflict progress: ${w.length}/${k.length} resolved`+(w.length?` \xB7 clean: ${w.join(", ")}`:"")+(P.length?` \xB7 still conflicted: ${P.join(", ")}`:"")))}).catch(()=>{})},12e3),z=await co(T,{repoPath:c,prompt:iI+k.map(P=>`- ${P}`).join(`
1577
+ `;async function Yy(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:a}=t,c=Vy.default.join(En(),`conflict-${(0,Mu.randomUUID)().slice(0,8)}`),l=!1;try{a("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Gi(n,c,r),l=!0;let d=await rd(c,s);if(d.ok&&d.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(!d.ok&&d.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${d.reason}`};let p={},f=!1;if(!d.ok){let k=d.conflicts;a("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let T=tt(t.agentId);if(!T)return await nr(c),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let _=Jn(t.agentId,"edit_no_shell");if(_)return await nr(c),{ok:!1,note:`${_} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};a("info",`Asking ${T.displayName} to resolve only those files`);let $=-1,D=setInterval(()=>{id(c,k).then(P=>{let w=k.filter(j=>!P.includes(j));w.length!==$&&($=w.length,a("info",`Conflict progress: ${w.length}/${k.length} resolved`+(w.length?` \xB7 clean: ${w.join(", ")}`:"")+(P.length?` \xB7 still conflicted: ${P.join(", ")}`:"")))}).catch(()=>{})},12e3),z=await co(T,{repoPath:c,prompt:sI+k.map(P=>`- ${P}`).join(`
1615
1578
  `),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,Mu.randomUUID)(),onLog:(P,w)=>a(P,w)},(P,w)=>a(P==="warn"?"warn":P,w));if(clearInterval(D),p={costUsd:z.costUsd,inputTokens:z.inputTokens,outputTokens:z.outputTokens},be({surface:"run_conflict_resolve",agentId:t.agentId,refKind:"run",refLabel:t.issueKey,...we(z)}),!z.ok)return await nr(c),{ok:!1,...p,note:`The agent could not do the resolution: ${z.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let A=await ma(c);if(A.length)return await nr(c),{ok:!1,...p,note:`The agent left conflict markers in ${A.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 sd(c,`${i}: merge ${s}, conflicts resolved by the agent
1616
1579
 
1617
- Resolved via Allwright`)}let g=await tr(c,s);if(!g.ok){let k=g.forbidden.length?`the merged result touches protected paths (${g.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${g.files} files, ${g.insertions+g.deletions} lines; limits ${Xn}/${Qn})`;return await nr(c),{ok:!1,...p,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await ns(c,r);let v=await dt(c);return a("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(d){return await nr(c).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${d instanceof Error?d.message.slice(0,300):String(d)}`}}finally{l&&(await rn(n,c).catch(()=>{}),Zy.default.rmSync(c,{recursive:!0,force:!0}))}}var ju=E(require("node:fs"),1),Jy=E(require("node:path"),1),Ou=require("node:crypto");sn();Et();ds();nn();Yi();function oI(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
1580
+ Resolved via Allwright`)}let g=await tr(c,s);if(!g.ok){let k=g.forbidden.length?`the merged result touches protected paths (${g.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${g.files} files, ${g.insertions+g.deletions} lines; limits ${Xn}/${Qn})`;return await nr(c),{ok:!1,...p,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await ns(c,r);let v=await dt(c);return a("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(d){return await nr(c).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${d instanceof Error?d.message.slice(0,300):String(d)}`}}finally{l&&(await rn(n,c).catch(()=>{}),Zy.default.rmSync(c,{recursive:!0,force:!0}))}}var ju=E(require("node:fs"),1),Jy=E(require("node:path"),1),Ou=require("node:crypto");sn();Et();ds();nn();Yi();function iI(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
1618
1581
  ${r.tail.slice(-2e3)}`).join(`
1619
1582
 
1620
1583
  `);return`You are on the pull-request branch for ticket ${t}. The work itself is done and under review - do NOT redo or extend it. The repository's documented TEST.md commands were executed by the runner and ${e.length} failed:
@@ -1627,7 +1590,7 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
1627
1590
  - If a failure is clearly pre-existing on the base branch and unrelated to this PR's change, leave the code alone and say so in one sentence.
1628
1591
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
1629
1592
  - You have no shell; the runner re-runs every documented command after you finish.
1630
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}function aI(t,e){return`You are on the pull-request branch for ticket ${t}. The work itself is done and under review - do NOT redo or extend it. An audit of this change raised ONE finding:
1593
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}function oI(t,e){return`You are on the pull-request branch for ticket ${t}. The work itself is done and under review - do NOT redo or extend it. An audit of this change raised ONE finding:
1631
1594
 
1632
1595
  TITLE: ${e.title}
1633
1596
 
@@ -1639,26 +1602,26 @@ Your ONLY job is to address that finding, with the smallest change possible.
1639
1602
  - 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.
1640
1603
  - Do not ask questions; if you cannot fix it safely, say what you found and stop.
1641
1604
  - You have no shell; the runner re-runs the documented tests after you finish.
1642
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Xy(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:a,onLog:c}=t,l=Jy.default.join(En(),`testfix-${(0,Ou.randomUUID)().slice(0,8)}`),d=!1;try{let p=tt(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Jn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};c("info",`Preparing a worktree on ${r} for the test fix`),await er(n,r),await Gi(n,l,r),d=!0,await Qs(l,`origin/${r}`);let g=await dt(l);c("info",`Asking ${p.displayName} to fix ${a.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await co(p,{repoPath:l,prompt:t.finding?aI(i,t.finding):oI(i,a),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Ou.randomUUID)(),onLog:(j,W)=>c(j,W)},(j,W)=>c(j==="warn"?"warn":j,W)),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(be({surface:"run_testfix",agentId:t.agentId,refKind:"run",refLabel:i,...we(v)}),!v.ok)return{ok:!1,...k,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let T=await Xs(l);for(let j of T.refused)c("warn",`${In} entry refused: ${j}`);let _=!0;try{await ts(l,t.finding?`${i}: ${t.finding.title.slice(0,60)}
1605
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Xy(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:a,onLog:c}=t,l=Jy.default.join(En(),`testfix-${(0,Ou.randomUUID)().slice(0,8)}`),d=!1;try{let p=tt(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Jn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};c("info",`Preparing a worktree on ${r} for the test fix`),await er(n,r),await Gi(n,l,r),d=!0,await Qs(l,`origin/${r}`);let g=await dt(l);c("info",`Asking ${p.displayName} to fix ${a.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await co(p,{repoPath:l,prompt:t.finding?oI(i,t.finding):iI(i,a),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Ou.randomUUID)(),onLog:(j,W)=>c(j,W)},(j,W)=>c(j==="warn"?"warn":j,W)),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(be({surface:"run_testfix",agentId:t.agentId,refKind:"run",refLabel:i,...we(v)}),!v.ok)return{ok:!1,...k,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let T=await Xs(l);for(let j of T.refused)c("warn",`${In} entry refused: ${j}`);let _=!0;try{await ts(l,t.finding?`${i}: ${t.finding.title.slice(0,60)}
1643
1606
 
1644
1607
  Allwright finding-fix run`:`${i}: fix failing TEST.md commands
1645
1608
 
1646
1609
  Allwright test-fix run`)}catch{_=!1}if(!_){let j=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return c("info",j),{ok:!0,...k,remaining:a,note:j}}let $=await tr(l,s);if(!$.ok){await Qs(l,g);let j=$.forbidden.length?`the fixed result touches protected paths (${$.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${$.files} files, ${$.insertions+$.deletions} lines; limits ${Xn}/${Qn})`;return{ok:!1,...k,note:`Nothing was pushed: ${j}. The fix commit was discarded; the PR is unchanged.`}}let D=a,z,A,P=ni(l);if(P){let j=sr(ju.default.readFileSync(P,"utf8"));if(j.length){c("info",`Re-running ${j.length} documented test command(s)`);let W=await An(l,j,{perCommandTimeoutMs:15*6e4});for(let L of W)c(L.exitCode===0?"info":"warn",`${L.exitCode===0?"PASS":"FAIL"} ${L.command} (exit ${L.exitCode})`+(L.exitCode===0?"":`
1647
- ${L.tail.slice(-1500)}`));D=W.filter(L=>L.exitCode!==0).slice(0,20).map(L=>({command:L.command.slice(0,500),exitCode:L.exitCode,tail:L.tail.slice(-4e3)})),A=W.length,z=W.length-D.length}}await ns(l,r);let w=await dt(l);return c("info",`Pushed the fix to ${r} (${w.slice(0,7)})`),{ok:!0,...k,headSha:w,remaining:D,testsPassed:z,testsTotal:A,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{d&&(await rn(n,l).catch(()=>{}),ju.default.rmSync(l,{recursive:!0,force:!0}))}}Ys();Ht();var vs=E(require("node:fs"),1),Qy=E(require("node:path"),1);_t();Ae();var cI=S.object({role:S.enum(["user","agent"]),text:S.string(),steps:S.array(S.string()).default([]),files:S.array(S.string()).default([]),at:S.string().default(""),ms:S.number().int().nonnegative().default(0),tokens:S.number().int().nonnegative().default(0)}),lI=S.object({sessionId:S.string(),projectId:S.string(),title:S.string().default(""),updatedAt:S.string(),ownerUserId:S.string().default(""),agentId:S.string().default(""),messages:S.array(cI).default([]),createdTickets:S.array(S.object({key:S.string(),summary:S.string()})).default([])}),dI=S.record(lI),uI=40,hI=200,zu=2e4,pI=30,fI=2e3,eb=8,tb=255;function nb(){return Qy.default.join(te(),"chat-sessions.json")}function ks(){let t=nb();if(!vs.default.existsSync(t))return{};try{return dI.parse(JSON.parse(vs.default.readFileSync(t,"utf8")))}catch{return{}}}function Du(t){vs.default.mkdirSync(te(),{recursive:!0,mode:448});let e=nb(),n=e+".tmp";vs.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1648
- `,{mode:384}),vs.default.renameSync(n,e),vs.default.chmodSync(e,384)}function Lu(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function rb(t,e){e.messages=e.messages.slice(-hI),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(uI))delete t[r.sessionId];Du(t)}function sb(t,e,n,r=[],s=new Date().toISOString(),i="",a=""){let c=ks(),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),Lu(l),l.messages.push({role:"user",text:n.slice(0,zu),steps:[],files:r.slice(0,eb).map(d=>d.slice(0,tb)),at:s,ms:0,tokens:0}),rb(c,l)}function bc(t){let e=ks(),n=e[t];if(!n)return;let r=n.messages.length;Lu(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,Du(e))}function ib(t,e,n,r,s=[],i=[],a={},c="",l=""){let d=ks(),f=d[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),Lu(f),f.messages.push({role:"user",text:n.slice(0,zu),steps:[],files:i.slice(0,eb).map(g=>g.slice(0,tb)),at:a.askedAt||new Date().toISOString(),ms:0,tokens:0},{role:"agent",text:r.slice(0,zu),steps:s.slice(0,pI).map(g=>g.slice(0,fI)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(a.ms??0)),tokens:Math.max(0,Math.round(a.tokens??0))}),rb(d,f)}function ob(t){return Object.values(ks()).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 Ss(t){return ks()[t]??null}function wc(t,e){if(!t||!e.length)return;let n=ks(),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(),Du(n)}function ab(t){if(!t)return"";let e=ks()[t];return e?.createdTickets.length?`
1610
+ ${L.tail.slice(-1500)}`));D=W.filter(L=>L.exitCode!==0).slice(0,20).map(L=>({command:L.command.slice(0,500),exitCode:L.exitCode,tail:L.tail.slice(-4e3)})),A=W.length,z=W.length-D.length}}await ns(l,r);let w=await dt(l);return c("info",`Pushed the fix to ${r} (${w.slice(0,7)})`),{ok:!0,...k,headSha:w,remaining:D,testsPassed:z,testsTotal:A,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{d&&(await rn(n,l).catch(()=>{}),ju.default.rmSync(l,{recursive:!0,force:!0}))}}Ys();Ht();var vs=E(require("node:fs"),1),Qy=E(require("node:path"),1);_t();Ae();var aI=S.object({role:S.enum(["user","agent"]),text:S.string(),steps:S.array(S.string()).default([]),files:S.array(S.string()).default([]),at:S.string().default(""),ms:S.number().int().nonnegative().default(0),tokens:S.number().int().nonnegative().default(0)}),cI=S.object({sessionId:S.string(),projectId:S.string(),title:S.string().default(""),updatedAt:S.string(),ownerUserId:S.string().default(""),agentId:S.string().default(""),messages:S.array(aI).default([]),createdTickets:S.array(S.object({key:S.string(),summary:S.string()})).default([])}),lI=S.record(cI),dI=40,uI=200,zu=2e4,hI=30,pI=2e3,eb=8,tb=255;function nb(){return Qy.default.join(te(),"chat-sessions.json")}function ks(){let t=nb();if(!vs.default.existsSync(t))return{};try{return lI.parse(JSON.parse(vs.default.readFileSync(t,"utf8")))}catch{return{}}}function Du(t){vs.default.mkdirSync(te(),{recursive:!0,mode:448});let e=nb(),n=e+".tmp";vs.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1611
+ `,{mode:384}),vs.default.renameSync(n,e),vs.default.chmodSync(e,384)}function Lu(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function rb(t,e){e.messages=e.messages.slice(-uI),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(dI))delete t[r.sessionId];Du(t)}function sb(t,e,n,r=[],s=new Date().toISOString(),i="",a=""){let c=ks(),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),Lu(l),l.messages.push({role:"user",text:n.slice(0,zu),steps:[],files:r.slice(0,eb).map(d=>d.slice(0,tb)),at:s,ms:0,tokens:0}),rb(c,l)}function bc(t){let e=ks(),n=e[t];if(!n)return;let r=n.messages.length;Lu(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,Du(e))}function ib(t,e,n,r,s=[],i=[],a={},c="",l=""){let d=ks(),f=d[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),Lu(f),f.messages.push({role:"user",text:n.slice(0,zu),steps:[],files:i.slice(0,eb).map(g=>g.slice(0,tb)),at:a.askedAt||new Date().toISOString(),ms:0,tokens:0},{role:"agent",text:r.slice(0,zu),steps:s.slice(0,hI).map(g=>g.slice(0,pI)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(a.ms??0)),tokens:Math.max(0,Math.round(a.tokens??0))}),rb(d,f)}function ob(t){return Object.values(ks()).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 Ss(t){return ks()[t]??null}function wc(t,e){if(!t||!e.length)return;let n=ks(),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(),Du(n)}function ab(t){if(!t)return"";let e=ks()[t];return e?.createdTickets.length?`
1649
1612
 
1650
- 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.":""}Et();nn();lt();var cb=36,lb=60;function db(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 mI=`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:
1613
+ 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.":""}Et();nn();lt();var cb=36,lb=60;function db(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 fI=`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:
1651
1614
  Goal: what the user is trying to achieve.
1652
1615
  Decided: choices already made, including ones you talked them out of - each as one line.
1653
1616
  Constraints: rules, preferences and corrections the user gave you.
1654
1617
  Repo facts: what you learned about this codebase that is worth not re-reading.
1655
1618
  Open: what is still unresolved right now.
1656
- Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function ub(t,e,n){let r=Ss(e);if(!r)return null;let s=$e(n,t.project,"chat",r.agentId);if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:mI,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}});be({surface:"chat_compact",projectId:t.project.id,userId:r.ownerUserId??"",agentId:r.agentId??"",refKind:"chat",refId:e,refLabel:r.title??"",...we(i)});let a=i.ok?i.resultText.trim():"";return a?a.slice(0,6e3):null}catch(i){return b.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var gI=`A Jira ticket is being created from this conversation, and the agent that IMPLEMENTS it will see only the ticket - never this chat. Write the context it should inherit, under 300 words, plain statements under these headings (skip a heading with nothing under it):
1619
+ Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function ub(t,e,n){let r=Ss(e);if(!r)return null;let s=$e(n,t.project,"chat",r.agentId);if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:fI,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}});be({surface:"chat_compact",projectId:t.project.id,userId:r.ownerUserId??"",agentId:r.agentId??"",refKind:"chat",refId:e,refLabel:r.title??"",...we(i)});let a=i.ok?i.resultText.trim():"";return a?a.slice(0,6e3):null}catch(i){return b.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var mI=`A Jira ticket is being created from this conversation, and the agent that IMPLEMENTS it will see only the ticket - never this chat. Write the context it should inherit, under 300 words, plain statements under these headings (skip a heading with nothing under it):
1657
1620
  Decisions: what was decided, including approaches considered and REJECTED (and why).
1658
1621
  Relevant code: files, symbols and places examined here that the work will touch or must not miss - exact paths.
1659
1622
  Constraints: rules, preferences and corrections the user stated.
1660
1623
  Watch out: anything discovered here that would waste the implementer's time to rediscover.
1661
- Do NOT restate the ticket's own story or acceptance criteria - the ticket already says that. No preamble, no closing, no ticket block.`;async function hb(t,e,n){let r=Ss(e);if(!r)return null;let s=$e(n,t.project,"chat",r.agentId);if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:gI,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}});be({surface:"chat_capsule",projectId:t.project.id,userId:r.ownerUserId??"",agentId:r.agentId??"",refKind:"chat",refId:e,refLabel:r.title??"",...we(i)});let a=i.ok?i.resultText.trim():"";return a?a.slice(0,2500):null}catch(i){return b.warn(`ticket context capsule failed: ${i instanceof Error?i.message:i}`),null}}var pb=`
1624
+ Do NOT restate the ticket's own story or acceptance criteria - the ticket already says that. No preamble, no closing, no ticket block.`;async function hb(t,e,n){let r=Ss(e);if(!r)return null;let s=$e(n,t.project,"chat",r.agentId);if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:mI,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}});be({surface:"chat_capsule",projectId:t.project.id,userId:r.ownerUserId??"",agentId:r.agentId??"",refKind:"chat",refId:e,refLabel:r.title??"",...we(i)});let a=i.ok?i.resultText.trim():"";return a?a.slice(0,2500):null}catch(i){return b.warn(`ticket context capsule failed: ${i instanceof Error?i.message:i}`),null}}var pb=`
1662
1625
 
1663
1626
  TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
1664
1627
  1. When you ASK the user something and the sensible answers are countable, end with:
@@ -1671,12 +1634,12 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
1671
1634
  ["\u2026", "\u2026"]
1672
1635
  \`\`\`
1673
1636
  1 to 3 short suggestions, written AS THE USER (first person, imperative) - they are typed into the user's box, not yours. Skip the block entirely when nothing obvious follows; a wrong guess costs the user more than no guess.
1674
- Never emit both blocks in one reply, and never let either replace the actual answer.`;Ud();ka();var wo=E(require("node:fs"),1),fb=E(require("node:path"),1);_t();Ae();var yI=S.object({at:S.string(),projectId:S.string(),sessionId:S.string(),userId:S.string(),userName:S.string(),ask:S.string(),commands:S.array(S.string())}),bI=500,wI=200,vc=500;function mb(){return fb.default.join(te(),"operator-log.json")}function gb(){try{return S.array(yI).parse(JSON.parse(wo.default.readFileSync(mb(),"utf8")))}catch{return[]}}function yb(t){let e=gb();e.push({at:new Date().toISOString(),projectId:t.projectId,sessionId:t.sessionId,userId:t.userId.slice(0,vc),userName:t.userName.slice(0,vc),ask:t.ask.split(`
1675
- `)[0].slice(0,vc),commands:t.commands.slice(0,wI).map(r=>r.slice(0,vc))}),wo.default.mkdirSync(te(),{recursive:!0,mode:448});let n=mb();wo.default.writeFileSync(n+".tmp",JSON.stringify(e.slice(-bI),null,2)+`
1676
- `,{mode:384}),wo.default.renameSync(n+".tmp",n)}function bb(){return gb()}var _s=E(require("node:fs"),1),Nt=E(require("node:path"),1),Uu=300,vI=4,wb=512*1024,kI=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),vb=/\.mdx?$/i;function kb(t){let e=Nt.default.resolve(t),n=[],r=(s,i)=>{if(i>vI||n.length>=Uu)return;let a;try{a=_s.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Uu)return;if(!c.isFile()||!vb.test(c.name))continue;let l=Nt.default.join(s,c.name);try{let d=_s.default.statSync(l);n.push({path:Nt.default.relative(e,l).split(Nt.default.sep).join("/"),sizeBytes:d.size,updatedAt:d.mtime.toISOString()})}catch{}}for(let c of a){if(n.length>=Uu)return;!c.isDirectory()||c.isSymbolicLink()||kI.has(c.name)||c.name.startsWith(".")||r(Nt.default.join(s,c.name),i+1)}};return r(e,0),n}function Sb(t,e){let n=Nt.default.resolve(t);if(!vb.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=Nt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+Nt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=_s.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return _s.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+Nt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let a;try{a=_s.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=_s.default.readFileSync(s,"utf8"),l=Buffer.byteLength(c,"utf8")>wb;return{ok:!0,path:Nt.default.relative(i,s).split(Nt.default.sep).join("/"),content:l?c.slice(0,wb):c,truncated:l}}catch(c){return{ok:!1,error:c instanceof Error?c.message:"could not read the file"}}}var ve=E(Ne(),1);var kc=E(require("node:fs"),1),_b=E(require("node:path"),1);_t();Ae();var SI=S.object({id:S.string(),name:S.string().default(""),jiraProjectKey:S.string().default(""),repoName:S.string().default(""),jiraSiteUrl:S.string().default("")}),_I=S.array(SI);function xb(){return _b.default.join(te(),"synced-projects.json")}function Tb(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));kc.default.mkdirSync(te(),{recursive:!0}),kc.default.writeFileSync(xb(),JSON.stringify(e,null,2),{mode:384})}catch{}}function xI(){try{let t=_I.safeParse(JSON.parse(kc.default.readFileSync(xb(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Rb(t){return xI().find(e=>e.repoName===t)??null}ds();Qi();fs();var Fu=E(require("node:fs"),1),xs=E(require("node:path"),1),Ib=require("node:child_process"),Ts=E(Ne(),1);Ae();fs();var TI=15e4,qu=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function RI(t){let e=xs.default.join(t,"node_modules",".bin","prisma");return Fu.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function II(t,e){if(!(0,Ts.isSelfMigrationFilename)(e))return null;let n=xs.default.join(t,Ts.SELF_MIGRATION_DIR),r=xs.default.resolve(n,e),s=xs.default.relative(n,r);return s!==e||s.startsWith("..")||xs.default.isAbsolute(s)?null:r}async function Eb(t){let{file:e}=t,n=II(t.repoPath,e);if(!n)return qu(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!Fu.default.existsSync(n))return qu(e,{name:"file",ok:!1,detail:`${Ts.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Ts.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Qt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return qu(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=xs.default.join(t.repoPath,"apps","api"),{bin:a,prefix:c}=RI(i),l=ps([s]),d=await EI(a,[...c,"db","execute","--url",s,"--file",n],i),p=l(d.output).slice(-8e3);return d.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${d.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${d.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Ts.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function EI(t,e,n){return new Promise(r=>{(0,Ib.execFile)(t,e,{cwd:n,timeout:TI,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,a)=>{let c=[i,a].filter(Boolean).join(`
1677
- `).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 VE=E(_w(),1),YE=E($c(),1),JE=E(Si(),1),XE=E(Qu(),1),QE=E(nh(),1),eA=E(ch(),1),Pw=E(Mc(),1),tA=E(Cw(),1);var dh=Pw.default;var Io=E(require("node:crypto"),1),Ot=E(Ne(),1);lt();function nA(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Oc(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 rA(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 d=Ot.ProjectConfig.safeParse(l);d.success?r.push(d.data):Oc(n,"project","",d.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let d=Ot.RuleConfig.safeParse(l);d.success?s.push(d.data):Oc(n,"rule",nA(l),d.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let d=Ot.EnvironmentConfig.safeParse(l);d.success?i.push(d.data):Oc(n,"environment","",d.error.issues[0]?.message??"invalid shape")}let a=[];for(let l of Array.isArray(e.monitors)?e.monitors:[]){let d=Ot.MonitorCheckConfig.safeParse(l);d.success?a.push(d.data):Oc(n,"monitor check","",d.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 sA=2e4,iA=6e4,oA=5e3,zc=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===dh.OPEN}connect(){if(this.closed)return;b.info(`connecting to control plane at ${this.wsUrl}`);let e=new dh(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Ot.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()})},sA)}),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,Ot.parseServerMsg)(r)}catch(i){let a=rA(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,iA)}),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==="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>=oA){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=Io.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=Io.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:Io.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=Io.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,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical",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})}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 Dc=E(require("node:fs"),1),Ei=E(require("node:path"),1),uh=require("node:child_process"),aA=/\.mdx?$/i,Nw=6,cA=/^[\w.\- ()]+$/;function lA(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ei.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!aA.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Nw)return{ok:!1,error:`path deeper than ${Nw} levels`};for(let a of r)if(a==="."||a===".."||!cA.test(a))return{ok:!1,error:`invalid path segment "${a}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ei.default.resolve(t),i=Ei.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ei.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function hh(t){let e=lA(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Dc.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Dc.default.mkdirSync(Ei.default.dirname(e.abs),{recursive:!0}),Dc.default.writeFileSync(e.abs,t.content.endsWith(`
1637
+ Never emit both blocks in one reply, and never let either replace the actual answer.`;Ud();ka();var wo=E(require("node:fs"),1),fb=E(require("node:path"),1);_t();Ae();var gI=S.object({at:S.string(),projectId:S.string(),sessionId:S.string(),userId:S.string(),userName:S.string(),ask:S.string(),commands:S.array(S.string())}),yI=500,bI=200,vc=500;function mb(){return fb.default.join(te(),"operator-log.json")}function gb(){try{return S.array(gI).parse(JSON.parse(wo.default.readFileSync(mb(),"utf8")))}catch{return[]}}function yb(t){let e=gb();e.push({at:new Date().toISOString(),projectId:t.projectId,sessionId:t.sessionId,userId:t.userId.slice(0,vc),userName:t.userName.slice(0,vc),ask:t.ask.split(`
1638
+ `)[0].slice(0,vc),commands:t.commands.slice(0,bI).map(r=>r.slice(0,vc))}),wo.default.mkdirSync(te(),{recursive:!0,mode:448});let n=mb();wo.default.writeFileSync(n+".tmp",JSON.stringify(e.slice(-yI),null,2)+`
1639
+ `,{mode:384}),wo.default.renameSync(n+".tmp",n)}function bb(){return gb()}var _s=E(require("node:fs"),1),Nt=E(require("node:path"),1),Uu=300,wI=4,wb=512*1024,vI=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),vb=/\.mdx?$/i;function kb(t){let e=Nt.default.resolve(t),n=[],r=(s,i)=>{if(i>wI||n.length>=Uu)return;let a;try{a=_s.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Uu)return;if(!c.isFile()||!vb.test(c.name))continue;let l=Nt.default.join(s,c.name);try{let d=_s.default.statSync(l);n.push({path:Nt.default.relative(e,l).split(Nt.default.sep).join("/"),sizeBytes:d.size,updatedAt:d.mtime.toISOString()})}catch{}}for(let c of a){if(n.length>=Uu)return;!c.isDirectory()||c.isSymbolicLink()||vI.has(c.name)||c.name.startsWith(".")||r(Nt.default.join(s,c.name),i+1)}};return r(e,0),n}function Sb(t,e){let n=Nt.default.resolve(t);if(!vb.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=Nt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+Nt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=_s.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return _s.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+Nt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let a;try{a=_s.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=_s.default.readFileSync(s,"utf8"),l=Buffer.byteLength(c,"utf8")>wb;return{ok:!0,path:Nt.default.relative(i,s).split(Nt.default.sep).join("/"),content:l?c.slice(0,wb):c,truncated:l}}catch(c){return{ok:!1,error:c instanceof Error?c.message:"could not read the file"}}}var ve=E(Ne(),1);var kc=E(require("node:fs"),1),_b=E(require("node:path"),1);_t();Ae();var kI=S.object({id:S.string(),name:S.string().default(""),jiraProjectKey:S.string().default(""),repoName:S.string().default(""),jiraSiteUrl:S.string().default("")}),SI=S.array(kI);function xb(){return _b.default.join(te(),"synced-projects.json")}function Tb(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));kc.default.mkdirSync(te(),{recursive:!0}),kc.default.writeFileSync(xb(),JSON.stringify(e,null,2),{mode:384})}catch{}}function _I(){try{let t=SI.safeParse(JSON.parse(kc.default.readFileSync(xb(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Rb(t){return _I().find(e=>e.repoName===t)??null}ds();Qi();fs();var Fu=E(require("node:fs"),1),xs=E(require("node:path"),1),Ib=require("node:child_process"),Ts=E(Ne(),1);Ae();fs();var xI=15e4,qu=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function TI(t){let e=xs.default.join(t,"node_modules",".bin","prisma");return Fu.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function RI(t,e){if(!(0,Ts.isSelfMigrationFilename)(e))return null;let n=xs.default.join(t,Ts.SELF_MIGRATION_DIR),r=xs.default.resolve(n,e),s=xs.default.relative(n,r);return s!==e||s.startsWith("..")||xs.default.isAbsolute(s)?null:r}async function Eb(t){let{file:e}=t,n=RI(t.repoPath,e);if(!n)return qu(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!Fu.default.existsSync(n))return qu(e,{name:"file",ok:!1,detail:`${Ts.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Ts.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Qt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return qu(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=xs.default.join(t.repoPath,"apps","api"),{bin:a,prefix:c}=TI(i),l=ps([s]),d=await II(a,[...c,"db","execute","--url",s,"--file",n],i),p=l(d.output).slice(-8e3);return d.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${d.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${d.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Ts.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function II(t,e,n){return new Promise(r=>{(0,Ib.execFile)(t,e,{cwd:n,timeout:xI,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,a)=>{let c=[i,a].filter(Boolean).join(`
1640
+ `).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 ZE=E(_w(),1),VE=E($c(),1),YE=E(Si(),1),JE=E(Qu(),1),XE=E(nh(),1),QE=E(ch(),1),Pw=E(Mc(),1),eA=E(Cw(),1);var dh=Pw.default;var Io=E(require("node:crypto"),1),Ot=E(Ne(),1);lt();function tA(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Oc(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 nA(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 d=Ot.ProjectConfig.safeParse(l);d.success?r.push(d.data):Oc(n,"project","",d.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let d=Ot.RuleConfig.safeParse(l);d.success?s.push(d.data):Oc(n,"rule",tA(l),d.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let d=Ot.EnvironmentConfig.safeParse(l);d.success?i.push(d.data):Oc(n,"environment","",d.error.issues[0]?.message??"invalid shape")}let a=[];for(let l of Array.isArray(e.monitors)?e.monitors:[]){let d=Ot.MonitorCheckConfig.safeParse(l);d.success?a.push(d.data):Oc(n,"monitor check","",d.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 rA=2e4,sA=6e4,iA=5e3,zc=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===dh.OPEN}connect(){if(this.closed)return;b.info(`connecting to control plane at ${this.wsUrl}`);let e=new dh(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Ot.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()})},rA)}),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,Ot.parseServerMsg)(r)}catch(i){let a=nA(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,sA)}),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==="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>=iA){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=Io.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=Io.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:Io.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=Io.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,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical",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})}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 Dc=E(require("node:fs"),1),Ei=E(require("node:path"),1),uh=require("node:child_process"),oA=/\.mdx?$/i,Nw=6,aA=/^[\w.\- ()]+$/;function cA(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ei.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!oA.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Nw)return{ok:!1,error:`path deeper than ${Nw} levels`};for(let a of r)if(a==="."||a===".."||!aA.test(a))return{ok:!1,error:`invalid path segment "${a}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ei.default.resolve(t),i=Ei.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ei.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function hh(t){let e=cA(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Dc.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Dc.default.mkdirSync(Ei.default.dirname(e.abs),{recursive:!0}),Dc.default.writeFileSync(e.abs,t.content.endsWith(`
1678
1641
  `)?t.content:t.content+`
1679
- `);let n=i=>new Promise((a,c)=>{(0,uh.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(l,d,p)=>l?c(new Error(p||l.message)):a())}),r="";try{r=await new Promise((i,a)=>(0,uh.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(c,l,d)=>c?a(new Error(d||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 Cs=E(require("node:fs"),1),ph=E(require("node:path"),1),Lc=require("node:child_process"),jw=require("node:util");Ae();no();fs();is();Et();sn();var Ow=E(Ne(),1),Mw=(0,jw.promisify)(Lc.execFile);function dA(t){try{return new URL(t).host}catch{return t}}function uA(t){try{return(0,Lc.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Uc(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=dA(a.baseUrl),g=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 ${g} 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 v=new We(a);try{let k=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${g})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(T){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Eo(T)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Eo(k)}`})}}}let l=t.repos[e.repoName];if(l&&Cs.default.existsSync(l.path)){let f=ph.default.join(l.path,"CLAUDE.md"),g=Cs.default.existsSync(f)&&Cs.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:g,detail:g?"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.",...g?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let v=fo(l.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!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(!Cs.default.existsSync(l.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${l.path}`});else{let f=Cs.default.existsSync(ph.default.join(l.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${l.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let d=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of d){let g=Be(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await Mw(g,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:v,ok:!1,detail:`cannot run "${g}" for agent "${f}": ${Eo(k)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await Mw("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: ${Eo(f)}`})}let p=Qe(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 ${Ow.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(()=>(Ht(),ss)),g=new f(p),v=await g.whoami(),k=l&&Cs.default.existsSync(l.path)?uA(l.path):null,T=k?Bt(k):null;if(!T)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let _=await g.repoAccess(T.owner,T.repo);s.push({name:"github-token",ok:_.ok&&_.canPush,detail:_.ok?_.canPush?`${v} has push access to ${T.owner}/${T.repo}`:`${v} can read ${T.owner}/${T.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${T.owner}/${T.repo}: ${_.error}`,..._.ok&&_.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:Eo(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 g=Qt(t,e.repoName,f.name),v=f.requiredSecrets.filter(k=>!g[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function Eo(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}lt();$a();mc();bh();var b$=300,Fv=9e5,w$=45e3,Bv=6,v$="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.",k$="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.",S$=15e4,_$=3e5;function x$(t){try{let{packs:e,lessons:n}=ti("compose",t),r=[e.map(s=>`### ${s.name}
1642
+ `);let n=i=>new Promise((a,c)=>{(0,uh.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(l,d,p)=>l?c(new Error(p||l.message)):a())}),r="";try{r=await new Promise((i,a)=>(0,uh.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(c,l,d)=>c?a(new Error(d||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 Cs=E(require("node:fs"),1),ph=E(require("node:path"),1),Lc=require("node:child_process"),jw=require("node:util");Ae();no();fs();is();Et();sn();var Ow=E(Ne(),1),Mw=(0,jw.promisify)(Lc.execFile);function lA(t){try{return new URL(t).host}catch{return t}}function dA(t){try{return(0,Lc.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Uc(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=lA(a.baseUrl),g=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 ${g} 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 v=new We(a);try{let k=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${g})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(T){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Eo(T)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Eo(k)}`})}}}let l=t.repos[e.repoName];if(l&&Cs.default.existsSync(l.path)){let f=ph.default.join(l.path,"CLAUDE.md"),g=Cs.default.existsSync(f)&&Cs.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:g,detail:g?"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.",...g?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let v=fo(l.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!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(!Cs.default.existsSync(l.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${l.path}`});else{let f=Cs.default.existsSync(ph.default.join(l.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${l.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let d=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of d){let g=Be(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await Mw(g,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:v,ok:!1,detail:`cannot run "${g}" for agent "${f}": ${Eo(k)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await Mw("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: ${Eo(f)}`})}let p=Qe(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 ${Ow.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(()=>(Ht(),ss)),g=new f(p),v=await g.whoami(),k=l&&Cs.default.existsSync(l.path)?dA(l.path):null,T=k?Bt(k):null;if(!T)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let _=await g.repoAccess(T.owner,T.repo);s.push({name:"github-token",ok:_.ok&&_.canPush,detail:_.ok?_.canPush?`${v} has push access to ${T.owner}/${T.repo}`:`${v} can read ${T.owner}/${T.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${T.owner}/${T.repo}: ${_.error}`,..._.ok&&_.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:Eo(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 g=Qt(t,e.repoName,f.name),v=f.requiredSecrets.filter(k=>!g[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function Eo(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}lt();$a();mc();bh();var y$=300,Fv=9e5,b$=45e3,Bv=6,w$="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.",v$="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.",k$=15e4,S$=3e5;function _$(t){try{let{packs:e,lessons:n}=ti("compose",t),r=[e.map(s=>`### ${s.name}
1680
1643
  ${s.content}`).join(`
1681
1644
 
1682
1645
  `).slice(0,4e3),n.trim().slice(-4e3)].filter(Boolean).join(`
@@ -1684,14 +1647,14 @@ ${s.content}`).join(`
1684
1647
  `).trim();return r?`
1685
1648
  HOUSE RULES FOR TICKETS here - taught by this team, follow them over the generic guidance above when they conflict:
1686
1649
  ${r}
1687
- `:""}catch{return""}}function T$(t){let e=t.map(r=>r.trim()).filter(Boolean).join(`
1650
+ `:""}catch{return""}}function x$(t){let e=t.map(r=>r.trim()).filter(Boolean).join(`
1688
1651
 
1689
1652
  `);return`**This answer is incomplete** - the agent ran out of turns before it finished. Below is what it had worked out so far; ask a narrower question, or make it a ticket so a full run can take it.
1690
1653
 
1691
1654
  ${e.length>8e3?`\u2026
1692
1655
 
1693
1656
  ${e.slice(-8e3)}`:e}`}var qe=new Gh;qe.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(nc);function Hv(t){b.info(`Create the token at ${ve.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of ve.GITHUB_TOKEN_PERMISSIONS.steps)b.info(` - ${e}`);b.info(ve.GITHUB_TOKEN_PERMISSIONS.note),b.info(`Then paste it below for ${t}.`)}qe.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",Ms.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=yr.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=Ry(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=Iy(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=_l.parse({controlPlaneUrl:r,runnerName:t.name,jira:c});if(l.jira){let d=await new We(l.jira).myself();b.info(`Jira credential OK - authenticated as ${d.displayName}`)}l=await xy(l,s),b.info(`Enrolled as runner "${l.runnerName}" (${l.runnerId})`),b.info(`Credentials saved to ${Sn()} (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 Ah=qe.command("repo").description("Map control-plane repo names to local checkouts");Ah.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=he(),s=Zt.default.resolve(e.replace(/^~(?=\/|$)/,Ms.default.homedir()));if(!n.force){if(!Fe.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(!Fe.default.existsSync(Zt.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(()=>(sn(),mf));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?`)}Lt()||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.`)});Ah.command("list").description("Show configured repo mappings").action(()=>{let t=he(),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 Kv=qe.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Kv.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=he(),n=e.claudeProfiles[t]?.configDir??`${Sn().replace(/runner\.json$/,"")}claude-profiles/${t}`;Fe.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,Vt.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}".`),Lt()});Kv.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=he(),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=Fe.default.existsSync(r.configDir)&&Fe.default.readdirSync(r.configDir).length>0;b.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Ah.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=he();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 $h=qe.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");$h.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(`
1694
- `+ic(sc()));return}yu(b)});$h.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(()=>wu(b));$h.command("status").description("systemctl status for the runner service").action(()=>{(0,Vt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});qe.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,Vt.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 Ci=qe.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ci.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=he();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=Rb(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 We(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 We(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.`)}Lt();return}catch{b.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let a=yr.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 g={baseUrl:l,email:p,apiToken:f},v=await new We(g).myself();b.info(`Jira credential OK - authenticated as ${v.displayName} on ${l}`),e.repos[t].jira=g,xe(e),b.info(`Saved: repo "${t}" now polls ${l} (other repos keep the runner-wide credential)`),Lt()}finally{a.close()}});Ci.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=he(),e=yr.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 We(c).myself();t.jira=c,xe(t),b.info(`Jira credential OK - authenticated as ${l.displayName} on ${s}`),b.info(`Saved to ${Sn()} (mode 600, this machine only). Repo overrides are untouched.`),Lt()}finally{e.close()}});Ci.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=he();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)"}`)});Ci.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=he(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yr.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(d=>d.jira)].filter(d=>!!d),c=new Set,l=!1;for(let d of a)if(!c.has(d.baseUrl)){c.add(d.baseUrl);try{let p=await new We({baseUrl:d.baseUrl,email:s,apiToken:i}).myself();b.info(`${d.baseUrl}: OK - authenticated as ${p.displayName}`),l=!0}catch{b.warn(`${d.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()}});Ci.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=he(),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}`)});Ci.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=he(),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 Pi=qe.command("github").description("GitHub credential for implement-mode rules");Pi.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=yr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Hv("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(()=>(Ht(),ss)),s=await new r(n).whoami(),i=he();i.github={token:n,login:s},xe(i),b.info(`GitHub token OK - authenticated as ${s}`),b.info(`Saved to ${Sn()} (mode 600, this machine only)`)}finally{e.close()}});Pi.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=he();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&&Fe.default.existsSync(r))try{let i=(0,Vt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),a=Bt(i);if(a){let{GitHubClient:c}=await Promise.resolve().then(()=>(Ht(),ss)),l=new c(n),d=await l.repoAccess(a.owner,a.repo);if(d.ok&&d.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=yr.default.createInterface({input:process.stdin,output:process.stdout});try{Hv(`"${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(()=>(Ht(),ss)),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()}});Pi.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=he(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yr.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(()=>(Ht(),ss)),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()}});Pi.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=he(),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`)});Pi.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=he(),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.`)});Pi.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=he();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 Ch=qe.command("audit").description("Recurring specialist audits on this runner");Ch.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=he();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.`)});Ch.command("schedules").description("List scheduled audits").action(()=>{let t=he();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`)});Ch.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=he(),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 Ph=qe.command("deploy").description("Deployment settings for this machine");Ph.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=he();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."),Lt()});Ph.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=he();t.deploy={enabled:!1},xe(t),b.info("deployments DISABLED on this runner"),Lt()});Ph.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=he();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 Xc=qe.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Xc.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=he(),s=Yo(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 d=c.slice(0,l).trim();i.secrets[d]=c.slice(l+1),a.push(d)}r.environments[s]=i,xe(r),b.info(`stored ${a.length} secret(s) for ${s}: ${a.join(", ")}`),b.info(`Saved to ${Sn()} (mode 600, this machine only)`),Lt()});Xc.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=he().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(()=>(Qw(),Xw));await a({repoName:t,envName:e,dir:Zt.default.resolve(i.replace(/^~(?=\/|$)/,Ms.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});Xc.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=he(),s=Yo(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}`)});Xc.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=he(),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)"}`)});qe.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=lp(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 ${Zt.default.basename(e.file)}`)}catch(e){b.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});qe.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=bs();if(e&&ws(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=dp(t);b.info(`Restored ${n.restored.length} entries into ${te()}`),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}});qe.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=he(),s=ve.REGISTERED_AGENTS.map(a=>a.id);if(t==="list"){for(let a of ve.REGISTERED_AGENTS){let c=Be(r,a.id),l=r.agents[a.id]?.bin?" (set here)":" (default: its own id)",d="";try{d=(0,Vt.execFileSync)(c,["--version"],{timeout:1e4,encoding:"utf8"}).trim().slice(0,60)}catch{d="not runnable on this machine"}b.info(`${a.id}: ${c}${l} - ${d}`)}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).`),Lt();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,Vt.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.`),Lt()});qe.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=he();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."),Lt();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=bb();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});qe.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=he(),e=Object.keys(t.repos),n=Ui(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 Uc(t,i),c=!Li(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 d=l.ok?"PASS":"FAIL";(l.ok?b.info:b.error)(`[${d}] ${l.name}: ${l.detail}`),s&&=l.ok}}s||(process.exitCode=1)});function Lt(){let t=bs()??gi();if(t&&ws(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?Sy(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 R$(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=ky();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",pu);let n=t.jira?new We(t.jira):Od(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let y=r.get(u);return y||(y=new We(m),r.set(u,y)),y},i=new Map,a=(u,m)=>{let y=Ty(_e()??t,u,m);switch(y.kind){case"legacy":return{jira:s(u),authored:!1};case"self":return{jira:s(u),authored:!0};case"missing":return{error:y.error};case"user":{let x=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,C=i.get(x);return C||(C=new We(y.creds),i.set(x,C)),{jira:C,authored:!0}}}},c=new URL("/api/runner/ws",t.controlPlaneUrl);c.protocol=c.protocol==="https:"?"wss:":"ws:";let l=[],d=[],p=[],f,g=null,v={cfg:t,jiraFor:s,transport:null},k=new Set,T=async(u,m,y)=>{if(!(m.length<2))for(let x=0;x<m.length;x++){let{text:C,changed:M}=Ey(y[x]??"",m);M&&await u.updateDescription(m[x],C).then(()=>b.info(`Compose: rewrote sibling ticket refs in ${m[x]} to real keys`)).catch(Y=>b.warn(`Compose: could not rewrite refs in ${m[x]}: ${Y instanceof Error?Y.message:Y}`))}},_=u=>{let m=l.find(x=>x.id===u),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},$=u=>{let m=l.find(C=>C.id===u),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${y} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let x=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${x}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},D={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(u,m)=>{let y=_(u),x=p.find(C=>C.projectId===u&&C.name===m);return y&&x?{...y,environment:x}:null}},z=new Map,A=new Set,P=null,w=new zc(c.toString(),t.runnerToken,{runnerVersion:nc},{onConfig:u=>{l=u.projects,Tb(u.projects),d=u.rules,p=u.environments,vm(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments),P?.setMonitors(u.monitors)},onDeployFix:async u=>{let m=_(u.projectId);if(!m){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(u.projectId)});return}let y=$e(t,m.project,"assist");if("error"in y){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`investigating failed deploy of "${u.environmentName}" (step: ${u.failedStep||"?"})`);let x=await tu({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,failedStep:u.failedStep,errorText:u.errorText,cfg:t});w.sendDeploySuggestResult(u.requestId,x)},onProjectTest:async u=>{let m=l.find(x=>x.id===u.projectId);if(!m){w.sendProjectTestResult(u.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}b.info(`running connection test for project "${m.name}"`);let y=await Uc(_e()??t,m,p.filter(x=>x.projectId===m.id),d.filter(x=>x.projectId===m.id).map(x=>"agent"in x.action?x.action.agent:"").filter(Boolean));w.sendProjectTestResult(u.requestId,y.every(x=>x.ok),y)},onRuleDiagnose:async u=>{let m=d.find(F=>F.id===u.ruleId),y=m&&l.find(F=>F.id===m.projectId);if(!m||!y){w.sendRuleDiagnoseResult(u.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 "${m.name}"`);let x=await Uc(_e()??t,y,m.action.type==="deploy"?p.filter(F=>F.projectId===y.id):[]),C=m.action.type==="implement"?x:x.filter(F=>F.name!=="github-token"),{matchedCount:M,excludedCount:Y,excludedSample:H}=await f.diagnoseRule(m,y);w.sendRuleDiagnoseResult(u.requestId,{checks:C,matchedCount:M,excludedCount:Y,excludedSample:H})},onCancel:u=>{Xm(u)?b.info(`run ${u} stopped from the dashboard`):b.warn(`cancel requested for run ${u}, but nothing is running under that id here - it likely finished already`)},onApproved:(u,m)=>{if(qa(u)){Xd(D,u).catch(y=>b.error(`deploy approval crashed for ${u}: ${y instanceof Error?y.stack:y}`));return}uo(v,u,m).catch(y=>b.error(`approval handling crashed for ${u}: ${y instanceof Error?y.stack:y}`))},onRetryPush:u=>{let m=xa(u),y=()=>cg(v,u).catch(x=>b.error(`retry push crashed for ${u}: ${x instanceof Error?x.stack:x}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:u=>{if(qa(u)){Qd(D,u).catch(m=>b.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}ag(v,u).catch(m=>b.error(`rejection handling crashed for ${u}: ${m instanceof Error?m.stack:m}`))},onDeployStart:u=>{let m=`${u.runId}#${u.attempt}`;if(k.has(m))return;k.add(m);let y=_(u.projectId);if(!y){let x=$(u.projectId);b.error(`deploy ${u.runId}: ${x}`),w.send({type:"run.status",runId:u.runId,status:"failed",error:x});return}b.info(`deploy ${u.runId} requested from the dashboard: ${u.issueKey} \u2192 ${u.environment.name}`),f.runOnEnvironmentQueue(u.environment.id,()=>po({runId:u.runId,project:y.project,environment:u.environment,issueKey:u.issueKey,issueSummary:u.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:w,requestedBy:u.requestedBy}).catch(x=>b.error(`deploy crashed for ${u.runId}: ${x instanceof Error?x.stack:x}`)))},onDeploySuggest:async u=>{let m=_(u.projectId);if(!m){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(u.projectId)});return}let y=$e(t,m.project,"assist");if("error"in y){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`asking ${y.adapter.displayName} for "${u.environmentName}" deploy steps in ${m.repoPath}`);let x=await nu({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,notes:u.notes,timeoutSeconds:u.timeoutSeconds,cfg:t});w.sendDeploySuggestResult(u.requestId,x)},onEnvPreflight:async u=>{let m=_(u.projectId);if(!m){w.sendEnvPreflightResult(u.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await eu({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,requiredSecrets:u.requiredSecrets,workdir:u.workdir,branch:u.branch,publicUrl:u.publicUrl,cfg:t});w.sendEnvPreflightResult(u.requestId,y)},onSelfMigrationApply:async u=>{let m=_(u.projectId);if(!m){w.sendSelfMigrationApplyResult(u.requestId,{ok:!1,file:u.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:$(u.projectId)});return}b.info(`applying migration ${u.file} for "${u.environmentName}"`);let y=await Eb({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,file:u.file,urlSecret:u.urlSecret,cfg:t});b.info(y.ok?`migration ${u.file} applied`:`migration ${u.file} failed: ${y.error}`),w.sendSelfMigrationApplyResult(u.requestId,y)},onAutopilotPlan:async u=>{try{let m=_(u.projectId);if(!m){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:$(u.projectId)});return}let y=s(m.project.repoName),x=[];for(let N of u.issueKeys)try{let Z=await y.getIssue(N);x.push(`${N}: ${Z.summary}
1657
+ `+ic(sc()));return}yu(b)});$h.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(()=>wu(b));$h.command("status").description("systemctl status for the runner service").action(()=>{(0,Vt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});qe.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,Vt.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 Ci=qe.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ci.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=he();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=Rb(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 We(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 We(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.`)}Lt();return}catch{b.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let a=yr.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 g={baseUrl:l,email:p,apiToken:f},v=await new We(g).myself();b.info(`Jira credential OK - authenticated as ${v.displayName} on ${l}`),e.repos[t].jira=g,xe(e),b.info(`Saved: repo "${t}" now polls ${l} (other repos keep the runner-wide credential)`),Lt()}finally{a.close()}});Ci.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=he(),e=yr.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 We(c).myself();t.jira=c,xe(t),b.info(`Jira credential OK - authenticated as ${l.displayName} on ${s}`),b.info(`Saved to ${Sn()} (mode 600, this machine only). Repo overrides are untouched.`),Lt()}finally{e.close()}});Ci.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=he();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)"}`)});Ci.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=he(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yr.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(d=>d.jira)].filter(d=>!!d),c=new Set,l=!1;for(let d of a)if(!c.has(d.baseUrl)){c.add(d.baseUrl);try{let p=await new We({baseUrl:d.baseUrl,email:s,apiToken:i}).myself();b.info(`${d.baseUrl}: OK - authenticated as ${p.displayName}`),l=!0}catch{b.warn(`${d.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()}});Ci.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=he(),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}`)});Ci.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=he(),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 Pi=qe.command("github").description("GitHub credential for implement-mode rules");Pi.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=yr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Hv("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(()=>(Ht(),ss)),s=await new r(n).whoami(),i=he();i.github={token:n,login:s},xe(i),b.info(`GitHub token OK - authenticated as ${s}`),b.info(`Saved to ${Sn()} (mode 600, this machine only)`)}finally{e.close()}});Pi.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=he();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&&Fe.default.existsSync(r))try{let i=(0,Vt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),a=Bt(i);if(a){let{GitHubClient:c}=await Promise.resolve().then(()=>(Ht(),ss)),l=new c(n),d=await l.repoAccess(a.owner,a.repo);if(d.ok&&d.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=yr.default.createInterface({input:process.stdin,output:process.stdout});try{Hv(`"${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(()=>(Ht(),ss)),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()}});Pi.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=he(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yr.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(()=>(Ht(),ss)),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()}});Pi.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=he(),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`)});Pi.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=he(),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.`)});Pi.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=he();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 Ch=qe.command("audit").description("Recurring specialist audits on this runner");Ch.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=he();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.`)});Ch.command("schedules").description("List scheduled audits").action(()=>{let t=he();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`)});Ch.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=he(),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 Ph=qe.command("deploy").description("Deployment settings for this machine");Ph.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=he();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."),Lt()});Ph.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=he();t.deploy={enabled:!1},xe(t),b.info("deployments DISABLED on this runner"),Lt()});Ph.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=he();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 Xc=qe.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Xc.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=he(),s=Yo(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 d=c.slice(0,l).trim();i.secrets[d]=c.slice(l+1),a.push(d)}r.environments[s]=i,xe(r),b.info(`stored ${a.length} secret(s) for ${s}: ${a.join(", ")}`),b.info(`Saved to ${Sn()} (mode 600, this machine only)`),Lt()});Xc.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=he().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(()=>(Qw(),Xw));await a({repoName:t,envName:e,dir:Zt.default.resolve(i.replace(/^~(?=\/|$)/,Ms.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});Xc.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=he(),s=Yo(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}`)});Xc.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=he(),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)"}`)});qe.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=lp(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 ${Zt.default.basename(e.file)}`)}catch(e){b.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});qe.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=bs();if(e&&ws(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=dp(t);b.info(`Restored ${n.restored.length} entries into ${te()}`),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}});qe.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=he(),s=ve.REGISTERED_AGENTS.map(a=>a.id);if(t==="list"){for(let a of ve.REGISTERED_AGENTS){let c=Be(r,a.id),l=r.agents[a.id]?.bin?" (set here)":" (default: its own id)",d="";try{d=(0,Vt.execFileSync)(c,["--version"],{timeout:1e4,encoding:"utf8"}).trim().slice(0,60)}catch{d="not runnable on this machine"}b.info(`${a.id}: ${c}${l} - ${d}`)}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).`),Lt();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,Vt.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.`),Lt()});qe.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=he();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."),Lt();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=bb();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});qe.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=he(),e=Object.keys(t.repos),n=Ui(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 Uc(t,i),c=!Li(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 d=l.ok?"PASS":"FAIL";(l.ok?b.info:b.error)(`[${d}] ${l.name}: ${l.detail}`),s&&=l.ok}}s||(process.exitCode=1)});function Lt(){let t=bs()??gi();if(t&&ws(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?Sy(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 T$(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=ky();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",pu);let n=t.jira?new We(t.jira):Od(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let y=r.get(u);return y||(y=new We(m),r.set(u,y)),y},i=new Map,a=(u,m)=>{let y=Ty(_e()??t,u,m);switch(y.kind){case"legacy":return{jira:s(u),authored:!1};case"self":return{jira:s(u),authored:!0};case"missing":return{error:y.error};case"user":{let x=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,C=i.get(x);return C||(C=new We(y.creds),i.set(x,C)),{jira:C,authored:!0}}}},c=new URL("/api/runner/ws",t.controlPlaneUrl);c.protocol=c.protocol==="https:"?"wss:":"ws:";let l=[],d=[],p=[],f,g=null,v={cfg:t,jiraFor:s,transport:null},k=new Set,T=async(u,m,y)=>{if(!(m.length<2))for(let x=0;x<m.length;x++){let{text:C,changed:M}=Ey(y[x]??"",m);M&&await u.updateDescription(m[x],C).then(()=>b.info(`Compose: rewrote sibling ticket refs in ${m[x]} to real keys`)).catch(Y=>b.warn(`Compose: could not rewrite refs in ${m[x]}: ${Y instanceof Error?Y.message:Y}`))}},_=u=>{let m=l.find(x=>x.id===u),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},$=u=>{let m=l.find(C=>C.id===u),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${y} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let x=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${x}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},D={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(u,m)=>{let y=_(u),x=p.find(C=>C.projectId===u&&C.name===m);return y&&x?{...y,environment:x}:null}},z=new Map,A=new Set,P=null,w=new zc(c.toString(),t.runnerToken,{runnerVersion:nc},{onConfig:u=>{l=u.projects,Tb(u.projects),d=u.rules,p=u.environments,vm(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments),P?.setMonitors(u.monitors)},onDeployFix:async u=>{let m=_(u.projectId);if(!m){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(u.projectId)});return}let y=$e(t,m.project,"assist");if("error"in y){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`investigating failed deploy of "${u.environmentName}" (step: ${u.failedStep||"?"})`);let x=await tu({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,failedStep:u.failedStep,errorText:u.errorText,cfg:t});w.sendDeploySuggestResult(u.requestId,x)},onProjectTest:async u=>{let m=l.find(x=>x.id===u.projectId);if(!m){w.sendProjectTestResult(u.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}b.info(`running connection test for project "${m.name}"`);let y=await Uc(_e()??t,m,p.filter(x=>x.projectId===m.id),d.filter(x=>x.projectId===m.id).map(x=>"agent"in x.action?x.action.agent:"").filter(Boolean));w.sendProjectTestResult(u.requestId,y.every(x=>x.ok),y)},onRuleDiagnose:async u=>{let m=d.find(F=>F.id===u.ruleId),y=m&&l.find(F=>F.id===m.projectId);if(!m||!y){w.sendRuleDiagnoseResult(u.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 "${m.name}"`);let x=await Uc(_e()??t,y,m.action.type==="deploy"?p.filter(F=>F.projectId===y.id):[]),C=m.action.type==="implement"?x:x.filter(F=>F.name!=="github-token"),{matchedCount:M,excludedCount:Y,excludedSample:H}=await f.diagnoseRule(m,y);w.sendRuleDiagnoseResult(u.requestId,{checks:C,matchedCount:M,excludedCount:Y,excludedSample:H})},onCancel:u=>{Xm(u)?b.info(`run ${u} stopped from the dashboard`):b.warn(`cancel requested for run ${u}, but nothing is running under that id here - it likely finished already`)},onApproved:(u,m)=>{if(qa(u)){Xd(D,u).catch(y=>b.error(`deploy approval crashed for ${u}: ${y instanceof Error?y.stack:y}`));return}uo(v,u,m).catch(y=>b.error(`approval handling crashed for ${u}: ${y instanceof Error?y.stack:y}`))},onRetryPush:u=>{let m=xa(u),y=()=>cg(v,u).catch(x=>b.error(`retry push crashed for ${u}: ${x instanceof Error?x.stack:x}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:u=>{if(qa(u)){Qd(D,u).catch(m=>b.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}ag(v,u).catch(m=>b.error(`rejection handling crashed for ${u}: ${m instanceof Error?m.stack:m}`))},onDeployStart:u=>{let m=`${u.runId}#${u.attempt}`;if(k.has(m))return;k.add(m);let y=_(u.projectId);if(!y){let x=$(u.projectId);b.error(`deploy ${u.runId}: ${x}`),w.send({type:"run.status",runId:u.runId,status:"failed",error:x});return}b.info(`deploy ${u.runId} requested from the dashboard: ${u.issueKey} \u2192 ${u.environment.name}`),f.runOnEnvironmentQueue(u.environment.id,()=>po({runId:u.runId,project:y.project,environment:u.environment,issueKey:u.issueKey,issueSummary:u.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:w,requestedBy:u.requestedBy}).catch(x=>b.error(`deploy crashed for ${u.runId}: ${x instanceof Error?x.stack:x}`)))},onDeploySuggest:async u=>{let m=_(u.projectId);if(!m){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(u.projectId)});return}let y=$e(t,m.project,"assist");if("error"in y){w.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}b.info(`asking ${y.adapter.displayName} for "${u.environmentName}" deploy steps in ${m.repoPath}`);let x=await nu({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,notes:u.notes,timeoutSeconds:u.timeoutSeconds,cfg:t});w.sendDeploySuggestResult(u.requestId,x)},onEnvPreflight:async u=>{let m=_(u.projectId);if(!m){w.sendEnvPreflightResult(u.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await eu({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,requiredSecrets:u.requiredSecrets,workdir:u.workdir,branch:u.branch,publicUrl:u.publicUrl,cfg:t});w.sendEnvPreflightResult(u.requestId,y)},onSelfMigrationApply:async u=>{let m=_(u.projectId);if(!m){w.sendSelfMigrationApplyResult(u.requestId,{ok:!1,file:u.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:$(u.projectId)});return}b.info(`applying migration ${u.file} for "${u.environmentName}"`);let y=await Eb({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,file:u.file,urlSecret:u.urlSecret,cfg:t});b.info(y.ok?`migration ${u.file} applied`:`migration ${u.file} failed: ${y.error}`),w.sendSelfMigrationApplyResult(u.requestId,y)},onAutopilotPlan:async u=>{try{let m=_(u.projectId);if(!m){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:$(u.projectId)});return}let y=s(m.project.repoName),x=[];for(let N of u.issueKeys)try{let Z=await y.getIssue(N);x.push(`${N}: ${Z.summary}
1695
1658
  ${(Z.description||"").slice(0,500)}`)}catch{x.push(`${N}: (could not read from Jira)`)}let C=$e(t,m.project,"assist");if("error"in C){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:C.error});return}let M=`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.
1696
1659
 
1697
1660
  `+x.join(`
@@ -1705,7 +1668,7 @@ Rules:
1705
1668
  - "order": every key exactly once. Prerequisites before the work that needs them.
1706
1669
  - "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.
1707
1670
  - "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
1708
- - "reasoning": 2-3 short lines a person can check your plan against.`,Y=await C.adapter.run({repoPath:m.repoPath,prompt:M,timeoutSeconds:90,bin:C.bin,mode:"read_only",maxTurns:3,model:C.adapter.fastModel,sessionId:(0,qn.randomUUID)(),onLog:()=>{}});be({surface:"autopilot_plan",projectId:m.project.id,agentId:C.adapter.id,refKind:"none",refLabel:`${u.issueKeys.length} tickets`,...we(Y)});let H=Nu(Y.resultText,u.issueKeys);if(!H){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:F}=await Promise.resolve().then(()=>(mc(),Ky));F({batchId:u.batchId,projectId:u.projectId,order:H.order,chains:H.chains,dependencies:H.dependencies,reasoning:H.reasoning}),w.sendAutopilotPlanResult(u.requestId,{ok:!0,...H})}catch(m){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async u=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(bh(),Uw)),y=await m({command:u.command,args:u.args});b.info(`chat diagnostic (user-approved): ${y.commandLine}`),w.sendChatDiagnosticResult(u.requestId,y)}catch(m){w.sendChatDiagnosticResult(u.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatStepRun:async u=>{let m=D.lookup(u.projectId,u.environmentName);if(!m){w.sendChatStepRunResult(u.requestId,{ok:!1,error:`this runner has no environment "${u.environmentName}" for that project`});return}let{environment:y}=m,x=y.steps[u.stepIndex];if(!x||x.name!==u.stepName){w.sendChatStepRunResult(u.requestId,{ok:!1,error:`step ${u.stepIndex+1} of "${y.name}" is ${x?`"${x.name}"`:"not there"} on this machine, not "${u.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let C=`${u.projectId}:${y.name}:${u.stepIndex}`;if(A.has(C)){w.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:"that step is already running here - wait for it to finish"});return}A.add(C),b.info(`chat step re-run (user-approved): [${y.name}] ${x.name}`);try{let{runSavedStep:M}=await Promise.resolve().then(()=>(fs(),Rg)),Y=await M({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:y.name,workdir:y.workdir,branch:y.branch,step:x,cfg:t,timeoutMs:Math.min(y.timeoutSeconds*1e3,_$)});w.sendChatStepRunResult(u.requestId,{ok:!0,stepName:x.name,...Y})}catch(M){w.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:M instanceof Error?M.message:String(M)})}finally{A.delete(C)}},onChatCancel:u=>{let m=z.get(u.turnId);m&&(m.abort(),b.info(`chat turn ${u.turnId} stopped from the dashboard`))},onChatTurn:async u=>{let m=_(u.projectId);if(!m){w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:u.sessionId??"",reply:"",error:$(u.projectId)});return}let y=u.sessionId||(0,qn.randomUUID)(),x=!u.sessionId,C=u.sessionId?Ss(u.sessionId):null,M=C?.agentId||u.agentId||m.project.defaultAgent||ve.DEFAULT_AGENT_ID;if(!x&&u.userId){let ze=C?.ownerUserId??"";if(ze&&ze!==u.userId){w.sendChatTurnResult(u.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 Y=u.operator===!0;if(Y&&!t.operatorEnabled){w.sendChatTurnResult(u.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 H=x?0:C?.messages.length??0,F=!1,N=0,Z="";if(!x&&H>=cb){let ze=await ub(m,y,t);if(ze)F=!0,N=H,Z=ze,y=(0,qn.randomUUID)(),x=!0,b.info(`chat compacted: ${H} message(s) summarized into a fresh session`);else if(H>=lb){w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let U=u.files.length?Am(m.repoPath,u.requestId,u.files):null,ie=(0,ve.replyPreferenceAppendix)({language:u.replyLanguage,languageInstruction:u.replyLanguageInstruction,style:u.replyStyle})+(0,ve.pendingMigrationsAppendix)(u.pendingMigrations)+(0,ve.monitorChecksAppendix)(u.monitorChecks)+(0,ve.deployTargetsAppendix)(u.environments)+(0,ve.savedStepChecksAppendix)(u.environmentSteps)+(0,ve.composeCommandAppendix)(u.command)+ab(u.sessionId??""),fe=x$(m.repoPath)+rr("compose",m.repoPath,{summary:u.message,ruleName:""});ja(m,t);let ge="```",ke=x?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1671
+ - "reasoning": 2-3 short lines a person can check your plan against.`,Y=await C.adapter.run({repoPath:m.repoPath,prompt:M,timeoutSeconds:90,bin:C.bin,mode:"read_only",maxTurns:3,model:C.adapter.fastModel,sessionId:(0,qn.randomUUID)(),onLog:()=>{}});be({surface:"autopilot_plan",projectId:m.project.id,agentId:C.adapter.id,refKind:"none",refLabel:`${u.issueKeys.length} tickets`,...we(Y)});let H=Nu(Y.resultText,u.issueKeys);if(!H){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:F}=await Promise.resolve().then(()=>(mc(),Ky));F({batchId:u.batchId,projectId:u.projectId,order:H.order,chains:H.chains,dependencies:H.dependencies,reasoning:H.reasoning}),w.sendAutopilotPlanResult(u.requestId,{ok:!0,...H})}catch(m){w.sendAutopilotPlanResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async u=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(bh(),Uw)),y=await m({command:u.command,args:u.args});b.info(`chat diagnostic (user-approved): ${y.commandLine}`),w.sendChatDiagnosticResult(u.requestId,y)}catch(m){w.sendChatDiagnosticResult(u.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatStepRun:async u=>{let m=D.lookup(u.projectId,u.environmentName);if(!m){w.sendChatStepRunResult(u.requestId,{ok:!1,error:`this runner has no environment "${u.environmentName}" for that project`});return}let{environment:y}=m,x=y.steps[u.stepIndex];if(!x||x.name!==u.stepName){w.sendChatStepRunResult(u.requestId,{ok:!1,error:`step ${u.stepIndex+1} of "${y.name}" is ${x?`"${x.name}"`:"not there"} on this machine, not "${u.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let C=`${u.projectId}:${y.name}:${u.stepIndex}`;if(A.has(C)){w.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:"that step is already running here - wait for it to finish"});return}A.add(C),b.info(`chat step re-run (user-approved): [${y.name}] ${x.name}`);try{let{runSavedStep:M}=await Promise.resolve().then(()=>(fs(),Rg)),Y=await M({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:y.name,workdir:y.workdir,branch:y.branch,step:x,cfg:t,timeoutMs:Math.min(y.timeoutSeconds*1e3,S$)});w.sendChatStepRunResult(u.requestId,{ok:!0,stepName:x.name,...Y})}catch(M){w.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:M instanceof Error?M.message:String(M)})}finally{A.delete(C)}},onChatCancel:u=>{let m=z.get(u.turnId);m&&(m.abort(),b.info(`chat turn ${u.turnId} stopped from the dashboard`))},onChatTurn:async u=>{let m=_(u.projectId);if(!m){w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:u.sessionId??"",reply:"",error:$(u.projectId)});return}let y=u.sessionId||(0,qn.randomUUID)(),x=!u.sessionId,C=u.sessionId?Ss(u.sessionId):null,M=C?.agentId||u.agentId||m.project.defaultAgent||ve.DEFAULT_AGENT_ID;if(!x&&u.userId){let ze=C?.ownerUserId??"";if(ze&&ze!==u.userId){w.sendChatTurnResult(u.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 Y=u.operator===!0;if(Y&&!t.operatorEnabled){w.sendChatTurnResult(u.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 H=x?0:C?.messages.length??0,F=!1,N=0,Z="";if(!x&&H>=cb){let ze=await ub(m,y,t);if(ze)F=!0,N=H,Z=ze,y=(0,qn.randomUUID)(),x=!0,b.info(`chat compacted: ${H} message(s) summarized into a fresh session`);else if(H>=lb){w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let U=u.files.length?Am(m.repoPath,u.requestId,u.files):null,ie=(0,ve.replyPreferenceAppendix)({language:u.replyLanguage,languageInstruction:u.replyLanguageInstruction,style:u.replyStyle})+(0,ve.pendingMigrationsAppendix)(u.pendingMigrations)+(0,ve.monitorChecksAppendix)(u.monitorChecks)+(0,ve.deployTargetsAppendix)(u.environments)+(0,ve.savedStepChecksAppendix)(u.environmentSteps)+(0,ve.composeCommandAppendix)(u.command)+ab(u.sessionId??""),fe=_$(m.repoPath)+rr("compose",m.repoPath,{summary:u.message,ruleName:""});ja(m,t);let ge="```",ke=x?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1709
1672
 
1710
1673
  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.
1711
1674
  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.
@@ -1726,7 +1689,7 @@ ${Z}
1726
1689
  ${u.userName||"The user"} says: ${u.message}`+(U?.section??""):ie+ve.TICKET_RULES_APPENDIX+`
1727
1690
 
1728
1691
  `+fe+`
1729
- ${u.userName||"The user"} says: ${u.message}`+(U?.section??""),st=0,Se=0,yt=new Date;sb(u.projectId,y,u.message,u.files.map(ze=>ze.name),yt.toISOString(),u.userId,M),w.send({type:"chat.session",requestId:u.requestId,sessionId:y});let Ni=[],Qc=[],oe;try{let ze=$e(t,m.project,Y?"operator":"chat",M);if("error"in ze){bc(y),w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:ze.error});return}let br=new AbortController;z.set(u.requestId,br);let Gv=Date.now(),Nh={repoPath:m.repoPath,prompt:ke,signal:br.signal,timeoutSeconds:b$,bin:ze.bin,mode:Y?"operator":"read_only_web",maxTurns:25,model:u.model||ze.adapter.fastModel,sessionId:y,resume:!x,onLog:(Ze,bt)=>{Ze==="agent"&&(Ni.push(bt.slice(0,4e3)),w.send({type:"chat.stream",requestId:u.requestId,seq:st++,text:bt.slice(0,8e3)}))},onTool:(Ze,bt)=>{Y&&(Qc.push(`${Ze}: ${bt}`),Ni.push(`${Ze}: ${bt}`.slice(0,4e3))),w.send({type:"chat.activity",requestId:u.requestId,seq:Se++,verb:Ze,target:bt})},onUsage:Ze=>{w.send({type:"chat.usage",requestId:u.requestId,inputTokens:Math.round(Ze.inputTokens),outputTokens:Math.round(Ze.outputTokens),cacheReadTokens:Ze.cacheReadTokens===void 0?void 0:Math.round(Ze.cacheReadTokens),turns:Ze.turns})}};oe=await ze.adapter.run(Nh);let el=0;for(;!oe.ok&&oe.turnLimitHit&&!oe.cancelled&&ze.adapter.capabilities.sessionResume&&el<Bv;){let Ze=Fv-(Date.now()-Gv);if(Ze<w$)break;el++,b.info(`chat turn ${u.requestId}: turn limit hit - resuming the same session (resume ${el}/${Bv}, ${Math.round(Ze/1e3)}s left)`);let bt=await ze.adapter.run({...Nh,prompt:Ze<=S$?v$:k$,resume:!0,timeoutSeconds:Math.floor(Ze/1e3)});bt.costUsd+=oe.costUsd,bt.inputTokens+=oe.inputTokens,bt.outputTokens+=oe.outputTokens,bt.cacheReadTokens+=oe.cacheReadTokens,oe=bt}!oe.ok&&(oe.turnLimitHit||oe.timedOut)&&!oe.resultText.trim()&&Ni.length&&(oe.resultText=T$(Ni))}finally{if(z.delete(u.requestId),U&&Fe.default.rmSync(U.dir,{recursive:!0,force:!0}),Y&&Qc.length)try{yb({projectId:u.projectId,sessionId:y,userId:u.userId,userName:u.userName,ask:u.message,commands:Qc})}catch(ze){b.warn(`operator ledger write failed: ${ze instanceof Error?ze.message:ze}`)}}if(oe.cancelled){bc(y),w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:oe.inputTokens,outputTokens:oe.outputTokens,cacheReadTokens:oe.cacheReadTokens});return}if(!oe.ok&&oe.timedOut&&(oe.error=`this has been running for ${Math.round(Fv/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.`),oe.ok||oe.resultText.trim()){let ze=Ni.filter(br=>br.trim()&&!oe.resultText.trim().startsWith(br.trim()));oe.ok||(oe.resultText=`${oe.resultText.trim()}
1692
+ ${u.userName||"The user"} says: ${u.message}`+(U?.section??""),st=0,Se=0,yt=new Date;sb(u.projectId,y,u.message,u.files.map(ze=>ze.name),yt.toISOString(),u.userId,M),w.send({type:"chat.session",requestId:u.requestId,sessionId:y});let Ni=[],Qc=[],oe;try{let ze=$e(t,m.project,Y?"operator":"chat",M);if("error"in ze){bc(y),w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:ze.error});return}let br=new AbortController;z.set(u.requestId,br);let Gv=Date.now(),Nh={repoPath:m.repoPath,prompt:ke,signal:br.signal,timeoutSeconds:y$,bin:ze.bin,mode:Y?"operator":"read_only_web",maxTurns:25,model:u.model||ze.adapter.fastModel,sessionId:y,resume:!x,onLog:(Ze,bt)=>{Ze==="agent"&&(Ni.push(bt.slice(0,4e3)),w.send({type:"chat.stream",requestId:u.requestId,seq:st++,text:bt.slice(0,8e3)}))},onTool:(Ze,bt)=>{Y&&(Qc.push(`${Ze}: ${bt}`),Ni.push(`${Ze}: ${bt}`.slice(0,4e3))),w.send({type:"chat.activity",requestId:u.requestId,seq:Se++,verb:Ze,target:bt})},onUsage:Ze=>{w.send({type:"chat.usage",requestId:u.requestId,inputTokens:Math.round(Ze.inputTokens),outputTokens:Math.round(Ze.outputTokens),cacheReadTokens:Ze.cacheReadTokens===void 0?void 0:Math.round(Ze.cacheReadTokens),turns:Ze.turns})}};oe=await ze.adapter.run(Nh);let el=0;for(;!oe.ok&&oe.turnLimitHit&&!oe.cancelled&&ze.adapter.capabilities.sessionResume&&el<Bv;){let Ze=Fv-(Date.now()-Gv);if(Ze<b$)break;el++,b.info(`chat turn ${u.requestId}: turn limit hit - resuming the same session (resume ${el}/${Bv}, ${Math.round(Ze/1e3)}s left)`);let bt=await ze.adapter.run({...Nh,prompt:Ze<=k$?w$:v$,resume:!0,timeoutSeconds:Math.floor(Ze/1e3)});bt.costUsd+=oe.costUsd,bt.inputTokens+=oe.inputTokens,bt.outputTokens+=oe.outputTokens,bt.cacheReadTokens+=oe.cacheReadTokens,oe=bt}!oe.ok&&(oe.turnLimitHit||oe.timedOut)&&!oe.resultText.trim()&&Ni.length&&(oe.resultText=x$(Ni))}finally{if(z.delete(u.requestId),U&&Fe.default.rmSync(U.dir,{recursive:!0,force:!0}),Y&&Qc.length)try{yb({projectId:u.projectId,sessionId:y,userId:u.userId,userName:u.userName,ask:u.message,commands:Qc})}catch(ze){b.warn(`operator ledger write failed: ${ze instanceof Error?ze.message:ze}`)}}if(oe.cancelled){bc(y),w.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:oe.inputTokens,outputTokens:oe.outputTokens,cacheReadTokens:oe.cacheReadTokens});return}if(!oe.ok&&oe.timedOut&&(oe.error=`this has been running for ${Math.round(Fv/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.`),oe.ok||oe.resultText.trim()){let ze=Ni.filter(br=>br.trim()&&!oe.resultText.trim().startsWith(br.trim()));oe.ok||(oe.resultText=`${oe.resultText.trim()}
1730
1693
 
1731
1694
  ---
1732
1695
  _Unfinished: ${oe.error||"the turn ended early"}._`),ib(u.projectId,y,u.message,oe.resultText,ze,u.files.map(br=>br.name),{askedAt:yt.toISOString(),ms:Date.now()-yt.getTime(),tokens:(oe.inputTokens??0)+(oe.outputTokens??0)},u.userId,M)}else bc(y);let Wv=(oe.inputTokens??0)+(oe.cacheReadTokens??0);w.sendChatTurnResult(u.requestId,{contextTokens:Wv,contextLimit:db(oe.model||u.model||""),compacted:F,compactedMessages:N,ok:oe.ok,sessionId:y,reply:oe.resultText,outputTruncated:!!oe.outputTruncated,error:oe.ok?void 0:oe.error??"the agent produced no reply",inputTokens:oe.inputTokens,outputTokens:oe.outputTokens,cacheReadTokens:oe.cacheReadTokens,costUsd:oe.costUsd,model:oe.model??""})},onChatList:u=>{w.sendChatListResult(u.requestId,ob(u.projectId))},onRepoDocs:u=>{let m=_(u.projectId);if(!m){w.sendRepoDocsResult(u.requestId,{ok:!1,docs:[],error:$(u.projectId)});return}w.sendRepoDocsResult(u.requestId,{ok:!0,docs:kb(m.repoPath)})},onRepoDocRead:u=>{let m=_(u.projectId);if(!m){w.sendRepoDocReadResult(u.requestId,{ok:!1,path:u.path,content:"",truncated:!1,error:$(u.projectId)});return}let y=Sb(m.repoPath,u.path);w.sendRepoDocReadResult(u.requestId,{ok:y.ok,path:y.ok?y.path:u.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:u=>{let m=Ss(u.sessionId);w.sendChatLoadResult(u.requestId,{ok:m!==null,projectId:m?.projectId??"",ownerUserId:m?.ownerUserId??"",agentId:m?.agentId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async u=>{let m=_(u.projectId);if(!m){w.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:$(u.projectId)});return}try{let y=s(m.project.repoName),x;try{x=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,1e3)}catch{x=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,1e3)}let C=await y.boardColumns(m.project.jiraProjectKey),M;if(C){M=C.map(F=>({name:F.name,issues:[]}));let H=new Map;for(let F of x){let N=C.findIndex(U=>U.statusIds.includes(F.statusId)),Z={key:F.key,summary:F.summary,labels:F.labels,components:F.components};if(N>=0)M[N].issues.push(Z);else{let U=H.get(F.status)??[];U.push(Z),H.set(F.status,U)}}for(let[F,N]of H)M.push({name:F,issues:N})}else{let H=ie=>ie.trim().toLowerCase(),F=new Map,N=new Map;for(let ie of x){let fe=H(ie.status);F.has(fe)||F.set(fe,ie.status.trim());let ge=N.get(fe)??[];ge.push({key:ie.key,summary:ie.summary,labels:ie.labels,components:ie.components}),N.set(fe,ge)}let Z=[];try{Z=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let U=[];for(let ie of Z){let fe=H(ie);!U.includes(fe)&&N.has(fe)&&U.push(fe)}for(let ie of N.keys())U.includes(ie)||U.push(ie);M=U.map(ie=>({name:F.get(ie)??ie,issues:N.get(ie)??[]}))}let Y=t.repos[m.project.repoName]?.jira??t.jira;w.sendBoardFetchResult(u.requestId,{ok:!0,browseBaseUrl:(Y?.baseUrl??"").replace(/\/+$/,""),columns:M})}catch(y){w.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async u=>{let m=_(u.projectId);if(!m){w.sendBoardTriggerResult(u.requestId,{ok:!1,error:$(u.projectId)});return}try{let y=s(m.project.repoName);u.agentId&&By(u.projectId,u.issueKey,u.agentId);let x=u.comment.trim()?a(m.project.repoName,u.requestedByEmail):{jira:y,authored:!1};if(x.error!==void 0){w.sendBoardTriggerResult(u.requestId,{ok:!1,error:x.error});return}if(u.reimplement){let C=await y.getIssue(u.issueKey),M=C.comments.filter(F=>$t(F.body)),Y=M.length?Math.max(...M.map(F=>new Date(F.created).getTime())):0;if(!C.comments.some(F=>!$t(F.body)&&new Date(F.created).getTime()>Y)){w.sendBoardTriggerResult(u.requestId,{ok:!1,error:`${u.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await y.editLabels(u.issueKey,{remove:["agent-implemented"]})}u.removeLabel.trim()&&await y.editLabels(u.issueKey,{remove:[u.removeLabel.trim()]}),u.comment.trim()&&await x.jira.addTriggerComment(u.issueKey,`${u.comment.trim()}`+(!x.authored&&u.requestedBy?`
@@ -1839,4 +1802,4 @@ HOW TO ANSWER. You have READ-ONLY access to this repository and no shell: you ca
1839
1802
 
1840
1803
  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.`,C=await y.adapter.run({repoPath:m.repoPath,prompt:x,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,qn.randomUUID)(),onLog:()=>{}});be({surface:"setup_ask",projectId:u.projectId,agentId:y.adapter.id,refKind:"none",...we(C)});let M=C.resultText.trim();w.sendSetupAskResult(u.requestId,M?{ok:!0,answer:M}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){w.sendSetupAskResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async u=>{try{let m=_(u.projectId);if(!m){w.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md",x=await hh({repoPath:m.repoPath,relPath:y,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});x.ok&&b.info(`Setup: wrote human-approved ${y} to ${m.repoPath} - ${x.note}`),w.sendSetupClaudeMdSaveResult(u.requestId,x)}catch(m){w.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async u=>{try{let m=_(u.projectId);if(!m){w.sendRepoDocSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await hh({repoPath:m.repoPath,relPath:u.relPath,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${u.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&b.info(`Saved approved doc ${u.relPath} into ${m.repoPath}`),w.sendRepoDocSaveResult(u.requestId,y)}catch(m){w.sendRepoDocSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:u=>{try{w.sendAuditStatsResult(u.requestId,{ok:!0,byProject:If(u.projectIds,u.since)})}catch(m){w.sendAuditStatsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async u=>{if(!process.env.INVOCATION_ID){w.sendRunnerUpdateResult(u.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{let x=u.version?.trim()?`allwright@${u.version.trim()}`:"allwright@latest";b.info(`Installing ${x}`);let C=Zt.default.dirname(process.execPath),M=Fe.default.existsSync(Zt.default.join(C,"npm"))?Zt.default.join(C,"npm"):"npm";(0,Vt.execFile)(M,["install","-g",x],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(Y,H,F)=>{if(Y){w.sendRunnerUpdateResult(u.requestId,{ok:!1,error:`npm install failed: ${(F||Y.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}w.sendRunnerUpdateResult(u.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){m();return}if(g){w.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;w.sendRunnerUpdateResult(u.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`),g=setInterval(()=>{f.idle&&(clearInterval(g),g=null,m())},5e3)},onRunnerUninstall:u=>{if(!f.idle){w.sendRunnerUninstallResult(u.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=cc()}catch(x){w.sendRunnerUninstallResult(u.requestId,{ok:!1,error:x instanceof Error?x.message:String(x)});return}let y=m.problems.length===0;if(w.sendRunnerUninstallResult(u.requestId,{ok:y,error:y?void 0:m.problems.join("; "),note:y?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!y){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(()=>{ac(),process.exit(0)},1500)},onTestFix:async u=>{let m=y=>w.sendTestFixResult(u.requestId,{ok:!1,note:y});try{let y=ii(u.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let x=t.repos[y.repoName];if(!x){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let C=Qe(t,y.repoName);if(!C){m("no GitHub token on this runner for that repo");return}let M=await new Xe(C).getPullRequest(y.owner,y.repo,y.prNumber);if(!M){m("that pull request no longer exists on GitHub");return}if(M.merged||M.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let Y=l.find(Z=>Z.repoName===y.repoName),H=y.nextDecisionSeq??1e5,F=(Z,U)=>{w.send({type:"run.log",runId:u.runId,seq:H++,ts:new Date().toISOString(),level:Z,message:U}),y.nextDecisionSeq=H,At(y)},N=await Xy({cfg:t,repoPath:x.path,branch:y.branch,baseBranch:M.baseRef||"main",issueKey:y.issueKey,agentId:Y?.defaultAgent||ve.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:u.failedTests,...u.finding?{finding:{title:u.finding.title,detail:u.finding.detail}}:{},timeoutSeconds:900,onLog:F});N.ok&&N.headSha&&(y.headSha=N.headSha,At(y),w.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:N.headSha,failedTests:N.remaining??[],...N.testsPassed!==void 0?{testsPassed:N.testsPassed}:{},...N.testsTotal!==void 0?{testsTotal:N.testsTotal}:{}})),It(x.path,{issueKey:y.issueKey,runId:u.runId,title:u.finding?N.ok?N.headSha?`finding fixed on the PR: ${u.finding.title.slice(0,80)}`:`finding declined by the agent: ${u.finding.title.slice(0,80)}`:"dashboard finding fix failed":N.ok?N.headSha?(N.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:N.note.slice(0,500)}),w.sendTestFixResult(u.requestId,N)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async u=>{try{let m=await f.answerPendingInput(u.runId,u.text,u.answeredBy);w.sendRunAnswerResult(u.requestId,m)}catch(m){w.sendRunAnswerResult(u.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async u=>{let m=y=>w.sendResolveConflictResult(u.requestId,{ok:!1,note:y});try{let y=ii(u.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let x=t.repos[y.repoName];if(!x){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let C=Qe(t,y.repoName);if(!C){m("no GitHub token on this runner for that repo");return}let M=await new Xe(C).getPullRequest(y.owner,y.repo,y.prNumber);if(!M){m("that pull request no longer exists on GitHub");return}if(!M.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let Y=l.find(Z=>Z.repoName===y.repoName),H=y.nextDecisionSeq??1e5,F=(Z,U)=>{w.send({type:"run.log",runId:u.runId,seq:H++,ts:new Date().toISOString(),level:Z,message:U}),y.nextDecisionSeq=H,At(y)},N=await Yy({cfg:t,repoPath:x.path,branch:y.branch,baseBranch:M.baseRef,issueKey:y.issueKey,agentId:Y?.defaultAgent||ve.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:F});N.ok&&N.headSha&&(y.headSha=N.headSha,y.conflictNotified=!1,At(y),w.send({type:"run.pr.conflict",runId:u.runId,conflicted:!1}),w.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:N.headSha})),w.sendResolveConflictResult(u.requestId,N)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:u=>{try{let m=x=>{try{return Fe.default.existsSync(x)&&Fe.default.readdirSync(x).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([x,C])=>({agent:"claude-code",name:x,loggedIn:m(C.configDir)}));w.sendAgentProfilesResult(u.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(Zt.default.join(Ms.default.homedir(),".claude")),agentsWithoutProfiles:ve.REGISTERED_AGENTS.filter(x=>!x.capabilities.loginProfiles).map(x=>x.id)})}catch(m){w.sendAgentProfilesResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async u=>{try{let m=await n.searchUsers(u.query);w.sendJiraUsersResult(u.requestId,{ok:!0,users:m})}catch(m){w.sendJiraUsersResult(u.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}},onMonitorRun:async u=>{let m=P?await P.runNow(u.checkId):{ok:!1,error:"monitoring is not ready yet on this runner"};w.send({type:"monitor.run.result",requestId:u.requestId,ok:m.ok,...m.error?{error:m.error}:{}})},onMonitorRebaseline:async u=>{try{let{clearBaseline:m}=await Promise.resolve().then(()=>(lu(),cu));m(u.checkId),w.send({type:"monitor.rebaseline.result",requestId:u.requestId,ok:!0}),P&&P.runNow(u.checkId)}catch(m){w.send({type:"monitor.rebaseline.result",requestId:u.requestId,ok:!1,error:m instanceof Error?m.message:String(m)})}},onMonitorSuggest:async u=>{let m=y=>w.send({type:"monitor.suggest.result",requestId:u.requestId,ok:!1,error:y,name:"",commands:[],parseRules:{amberPattern:"",redPattern:"",greenRequires:""},notes:""});try{let y=_(u.projectId);if(!y)return m($(u.projectId));let x=$e(t,y.project,"assist");if("error"in x)return m(x.error);let{suggestMonitorCheck:C}=await Promise.resolve().then(()=>(qv(),Uv)),M=await C({agent:x,repoPath:y.repoPath,projectId:u.projectId,notes:u.notes});w.send({type:"monitor.suggest.result",requestId:u.requestId,ok:M.ok,...M.error?{error:M.error}:{},name:M.name,commands:M.commands,parseRules:M.parseRules,...M.schedule?{schedule:M.schedule}:{},notes:M.notes})}catch(y){m(y instanceof Error?y.message:String(y))}},onMonitorDiscover:async u=>{try{let{discoverForMonitoring:m}=await Promise.resolve().then(()=>(Eh(),zv)),y=await m();w.send({type:"monitor.discover.result",requestId:u.requestId,ok:!0,...y})}catch(m){w.send({type:"monitor.discover.result",requestId:u.requestId,ok:!1,error:m instanceof Error?m.message:String(m),os:{platform:"",arch:"",release:""},services:[],webServers:[],backupCandidates:[],dbHints:[]})}}});v.transport=w,f=new yc(t,s,w),f.setExternalBusy(()=>z.size);let j=Object.values(os()).filter(u=>u.kind==="implement").map(u=>u.repoPath);Xl(Object.values(t.repos).map(u=>u.path),j).catch(()=>{}),P=new Xa(w,()=>_e()??t,(u,m)=>{let y=l.find(x=>x.id===u.projectId);if(!y){b.warn(`monitor ${u.name}: jiraNotify is on but no linked project - no ticket filed`);return}(async()=>{try{let x=await s(y.repoName).createIssue(y.jiraProjectKey,`[Monitoring] ${u.name} is ${m.status.toUpperCase()}`,`${m.summary}
1841
1804
 
1842
- `+(m.excerpt?"```\n"+m.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 ${u.name}: red episode filed as ${x.key}`)}catch(x){b.warn(`monitor ${u.name}: could not file the red-episode ticket: ${x instanceof Error?x.message:x}`)}})()}),Bp(w),w.start(),f.start(),P.start();let W=()=>{b.info("shutting down"),g&&clearInterval(g),w.stop(),wy(process.pid),pu(),process.exit(0)},L=!1,V=()=>{if(L){b.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),W();return}if(L=!0,f.stop(),f.idle){W();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 u=setInterval(()=>{f.idle&&(clearInterval(u),W())},3e3)};process.on("SIGINT",V),process.on("SIGTERM",V),process.on("SIGHUP",()=>{try{let u=he();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new We(u.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(u){b.error(`config reload failed - keeping the running config: ${u instanceof Error?u.message:String(u)}`)}})}qe.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=he();if(t.foreground){R$(e);return}let n=bs();if(n&&ws(n)){b.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=gi();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=gy(),i=(0,Vt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),by(i.pid),b.info(`Runner started in the background (pid ${i.pid}).`),b.info(`Logs: ${Qa()}`),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(()=>(lc(),Ny)),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{}});qe.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=bs();if(!e||!ws(e)){b.info("no background runner is running"),e&&Fe.default.rmSync(mi(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Fe.default.rmSync(mi(),{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.`)});qe.command("status").description("Check whether the background runner is running").action(()=>{let t=bs();t&&ws(t)?b.info(`running in the background (pid ${t})`):b.info("not running")});qe.parseAsync().catch(t=>{b.error(t instanceof Error?t.message:String(t)),process.exit(1)});
1805
+ `+(m.excerpt?"```\n"+m.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 ${u.name}: red episode filed as ${x.key}`)}catch(x){b.warn(`monitor ${u.name}: could not file the red-episode ticket: ${x instanceof Error?x.message:x}`)}})()}),Bp(w),w.start(),f.start(),P.start();let W=()=>{b.info("shutting down"),g&&clearInterval(g),w.stop(),wy(process.pid),pu(),process.exit(0)},L=!1,V=()=>{if(L){b.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),W();return}if(L=!0,f.stop(),f.idle){W();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 u=setInterval(()=>{f.idle&&(clearInterval(u),W())},3e3)};process.on("SIGINT",V),process.on("SIGTERM",V),process.on("SIGHUP",()=>{try{let u=he();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new We(u.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(u){b.error(`config reload failed - keeping the running config: ${u instanceof Error?u.message:String(u)}`)}})}qe.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=he();if(t.foreground){T$(e);return}let n=bs();if(n&&ws(n)){b.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=gi();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=gy(),i=(0,Vt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),by(i.pid),b.info(`Runner started in the background (pid ${i.pid}).`),b.info(`Logs: ${Qa()}`),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(()=>(lc(),Ny)),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{}});qe.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=bs();if(!e||!ws(e)){b.info("no background runner is running"),e&&Fe.default.rmSync(mi(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Fe.default.rmSync(mi(),{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.`)});qe.command("status").description("Check whether the background runner is running").action(()=>{let t=bs();t&&ws(t)?b.info(`running in the background (pid ${t})`):b.info("not running")});qe.parseAsync().catch(t=>{b.error(t instanceof Error?t.message:String(t)),process.exit(1)});