@weppy/roblox-mcp 2.14.2 → 2.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/index.js +21 -4
- package/package.json +1 -1
- package/roblox-plugin/WeppyRobloxMCP.rbxm +0 -0
package/dist/index.js
CHANGED
|
@@ -146,7 +146,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
146
146
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of t.seen.entries()){let s=o[1];if(e===o[0]){a(o);continue}if(t.external){let l=t.external.registry.get(o[0])?.id;if(e!==o[0]&&l){a(o);continue}}if(t.metadataRegistry.get(o[0])?.id){a(o);continue}if(s.cycle){a(o);continue}if(s.count>1&&t.reused==="ref"){a(o);continue}}}function Ka(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=o=>{let s=t.seen.get(o);if(s.ref===null)return;let c=s.def??s.schema,l={...c},u=s.ref;if(s.ref=null,u){r(u);let p=t.seen.get(u),f=p.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,l),o._zod.parent===u)for(let g in c)g==="$ref"||g==="allOf"||g in l||delete c[g];if(f.$ref&&p.def)for(let g in c)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(c[g])===JSON.stringify(p.def[g])&&delete c[g]}let d=o._zod.parent;if(d&&d!==u){r(d);let p=t.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let f in c)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(c[f])===JSON.stringify(p.def[f])&&delete c[f]}t.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(let o of[...t.seen.entries()].reverse())r(o[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let o=t.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(o)}Object.assign(i,n.def??n.schema);let a=t.external?.defs??{};for(let o of t.seen.entries()){let s=o[1];s.def&&s.defId&&(a[s.defId]=s.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:sl(e,"input",t.processors),output:sl(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function mn(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return mn(r.element,n);if(r.type==="set")return mn(r.valueType,n);if(r.type==="lazy")return mn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return mn(r.innerType,n);if(r.type==="intersection")return mn(r.left,n)||mn(r.right,n);if(r.type==="record"||r.type==="map")return mn(r.keyType,n)||mn(r.valueType,n);if(r.type==="pipe")return mn(r.in,n)||mn(r.out,n);if(r.type==="object"){for(let i in r.shape)if(mn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(mn(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(mn(i,n))return!0;return!!(r.rest&&mn(r.rest,n))}return!1}var cC=(t,e={})=>n=>{let r=Za({...n,processors:e});return Ce(t,r),Ga(r,t),Ka(r,t)},sl=(t,e,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Za({...i??{},target:a,io:e,processors:n});return Ce(t,o),Ga(o,t),Ka(o,t)};var oX={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lC=(t,e,n,r)=>{let i=n;i.type="string";let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=t._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof o=="number"&&(i.maxLength=o),s&&(i.format=oX[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let u=[...c];u.length===1?i.pattern=u[0].source:u.length>1&&(i.allOf=[...u.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},uC=(t,e,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=t._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number",typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a=="number"&&(i.minimum=a,typeof u=="number"&&e.target!=="draft-04"&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o=="number"&&(i.maximum=o,typeof l=="number"&&e.target!=="draft-04"&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},dC=(t,e,n,r)=>{n.type="boolean"},pC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},fC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},mC=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},gC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},hC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},yC=(t,e,n,r)=>{n.not={}},vC=(t,e,n,r)=>{},bC=(t,e,n,r)=>{},_C=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},xC=(t,e,n,r)=>{let i=t._zod.def,a=Ad(i.entries);a.every(o=>typeof o=="number")&&(n.type="number"),a.every(o=>typeof o=="string")&&(n.type="string"),n.enum=a},SC=(t,e,n,r)=>{let i=t._zod.def,a=[];for(let o of i.values)if(o===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let o=a[0];n.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[o]:n.const=o}else a.every(o=>typeof o=="number")&&(n.type="number"),a.every(o=>typeof o=="string")&&(n.type="string"),a.every(o=>typeof o=="boolean")&&(n.type="boolean"),a.every(o=>o===null)&&(n.type="null"),n.enum=a},wC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},IC=(t,e,n,r)=>{let i=n,a=t._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},CC=(t,e,n,r)=>{let i=n,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:c}=t._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(i,a)},PC=(t,e,n,r)=>{n.type="boolean"},kC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},RC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},EC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},TC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},AC=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},OC=(t,e,n,r)=>{let i=n,a=t._zod.def,{minimum:o,maximum:s}=t._zod.bag;typeof o=="number"&&(i.minItems=o),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=Ce(a.element,e,{...r,path:[...r.path,"items"]})},DC=(t,e,n,r)=>{let i=n,a=t._zod.def;i.type="object",i.properties={};let o=a.shape;for(let l in o)i.properties[l]=Ce(o[l],e,{...r,path:[...r.path,"properties",l]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{let u=a.shape[l]._zod;return e.io==="input"?u.optin===void 0:u.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Ce(a.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},ov=(t,e,n,r)=>{let i=t._zod.def,a=i.inclusive===!1,o=i.options.map((s,c)=>Ce(s,e,{...r,path:[...r.path,a?"oneOf":"anyOf",c]}));a?n.oneOf=o:n.anyOf=o},$C=(t,e,n,r)=>{let i=t._zod.def,a=Ce(i.left,e,{...r,path:[...r.path,"allOf",0]}),o=Ce(i.right,e,{...r,path:[...r.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c},NC=(t,e,n,r)=>{let i=n,a=t._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,f)=>Ce(p,e,{...r,path:[...r.path,o,f]})),l=a.rest?Ce(a.rest,e,{...r,path:[...r.path,s,...e.target==="openapi-3.0"?[a.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,l&&(i.items=l)):e.target==="openapi-3.0"?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=t._zod.bag;typeof u=="number"&&(i.minItems=u),typeof d=="number"&&(i.maxItems=d)},jC=(t,e,n,r)=>{let i=n,a=t._zod.def;i.type="object";let o=a.keyType,c=o._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let u=Ce(a.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Ce(a.keyType,e,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Ce(a.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let l=o._zod.values;if(l){let u=[...l].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(i.required=u)}},MC=(t,e,n,r)=>{let i=t._zod.def,a=Ce(i.innerType,e,r),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},LC=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType},zC=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},UC=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},FC=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},qC=(t,e,n,r)=>{let i=t._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Ce(a,e,r);let o=e.seen.get(t);o.ref=a},BC=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType,n.readOnly=!0},VC=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType},sv=(t,e,n,r)=>{let i=t._zod.def;Ce(i.innerType,e,r);let a=e.seen.get(t);a.ref=i.innerType},WC=(t,e,n,r)=>{let i=t._zod.innerType;Ce(i,e,r);let a=e.seen.get(t);a.ref=i},av={string:lC,number:uC,boolean:dC,bigint:pC,symbol:fC,null:mC,undefined:gC,void:hC,never:yC,any:vC,unknown:bC,date:_C,enum:xC,literal:SC,nan:wC,template_literal:IC,file:CC,success:PC,custom:kC,function:RC,transform:EC,map:TC,set:AC,array:OC,object:DC,union:ov,intersection:$C,tuple:NC,record:jC,nullable:MC,nonoptional:LC,default:zC,prefault:UC,catch:FC,pipe:qC,readonly:BC,promise:VC,optional:sv,lazy:WC};function cl(t,e){if("_idmap"in t){let r=t,i=Za({...e,processors:av}),a={};for(let c of r._idmap.entries()){let[l,u]=c;Ce(u,i)}let o={},s={registry:r,uri:e?.uri,defs:a};i.external=s;for(let c of r._idmap.entries()){let[l,u]=c;Ga(i,u),o[l]=Ka(i,u)}if(Object.keys(a).length>0){let c=i.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[c]:a}}return{schemas:o}}let n=Za({...e,processors:av});return Ce(t,n),Ga(n,t),Ka(n,t)}var cv=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=Za({processors:av,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return Ce(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),Ga(this.ctx,e);let r=Ka(this.ctx,e),{"~standard":i,...a}=r;return a}};var qN={};function ll(t){return!!t._zod}function Ja(t,e){return ll(t)?Xo(t,e):t.safeParse(e)}function lv(t){if(!t)return;let e;if(ll(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function WN(t){if(ll(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var R={};en(R,{$brand:()=>Ed,$input:()=>_y,$output:()=>by,NEVER:()=>zg,TimePrecision:()=>Iy,ZodAny:()=>p0,ZodArray:()=>h0,ZodBase64:()=>Ev,ZodBase64URL:()=>Tv,ZodBigInt:()=>gl,ZodBigIntFormat:()=>Dv,ZodBoolean:()=>ml,ZodCIDRv4:()=>kv,ZodCIDRv6:()=>Rv,ZodCUID:()=>_v,ZodCUID2:()=>xv,ZodCatch:()=>j0,ZodCodec:()=>zv,ZodCustom:()=>kp,ZodCustomStringFormat:()=>pl,ZodDate:()=>Sp,ZodDefault:()=>T0,ZodDiscriminatedUnion:()=>v0,ZodE164:()=>Av,ZodEmail:()=>yv,ZodEmoji:()=>vv,ZodEnum:()=>ul,ZodError:()=>pX,ZodExactOptional:()=>k0,ZodFile:()=>C0,ZodFirstPartyTypeKind:()=>G0,ZodFunction:()=>W0,ZodGUID:()=>vp,ZodIPv4:()=>Cv,ZodIPv6:()=>Pv,ZodISODate:()=>pv,ZodISODateTime:()=>dv,ZodISODuration:()=>mv,ZodISOTime:()=>fv,ZodIntersection:()=>b0,ZodIssueCode:()=>mX,ZodJWT:()=>Ov,ZodKSUID:()=>Iv,ZodLazy:()=>q0,ZodLiteral:()=>I0,ZodMAC:()=>c0,ZodMap:()=>S0,ZodNaN:()=>L0,ZodNanoID:()=>bv,ZodNever:()=>m0,ZodNonOptional:()=>Mv,ZodNull:()=>d0,ZodNullable:()=>E0,ZodNumber:()=>fl,ZodNumberFormat:()=>ps,ZodObject:()=>wp,ZodOptional:()=>jv,ZodPipe:()=>Lv,ZodPrefault:()=>O0,ZodPromise:()=>V0,ZodReadonly:()=>z0,ZodRealError:()=>En,ZodRecord:()=>Pp,ZodSet:()=>w0,ZodString:()=>dl,ZodStringFormat:()=>Oe,ZodSuccess:()=>N0,ZodSymbol:()=>l0,ZodTemplateLiteral:()=>F0,ZodTransform:()=>P0,ZodTuple:()=>_0,ZodType:()=>ee,ZodULID:()=>Sv,ZodURL:()=>xp,ZodUUID:()=>mi,ZodUndefined:()=>u0,ZodUnion:()=>Ip,ZodUnknown:()=>f0,ZodVoid:()=>g0,ZodXID:()=>wv,ZodXor:()=>y0,_ZodString:()=>hv,_default:()=>A0,_function:()=>Gj,any:()=>Tj,array:()=>se,base64:()=>fj,base64url:()=>mj,bigint:()=>Cj,boolean:()=>ht,catch:()=>M0,check:()=>Kj,cidrv4:()=>dj,cidrv6:()=>pj,clone:()=>qt,codec:()=>Wj,coerce:()=>K0,config:()=>at,core:()=>Xn,cuid:()=>rj,cuid2:()=>ij,custom:()=>Uv,date:()=>Oj,decode:()=>t0,decodeAsync:()=>r0,describe:()=>Jj,discriminatedUnion:()=>Cp,e164:()=>gj,email:()=>ZN,emoji:()=>tj,encode:()=>e0,encodeAsync:()=>n0,endsWith:()=>as,enum:()=>Wt,exactOptional:()=>R0,file:()=>Fj,flattenError:()=>Bc,float32:()=>xj,float64:()=>Sj,formatError:()=>Vc,fromJSONSchema:()=>nM,function:()=>Gj,getErrorMap:()=>hX,globalRegistry:()=>Tt,gt:()=>Mr,gte:()=>Bt,guid:()=>GN,hash:()=>_j,hex:()=>bj,hostname:()=>vj,httpUrl:()=>ej,includes:()=>rs,instanceof:()=>Xj,int:()=>gv,int32:()=>wj,int64:()=>Pj,intersection:()=>yl,ipv4:()=>cj,ipv6:()=>uj,iso:()=>Ya,json:()=>eM,jwt:()=>hj,keyof:()=>Dj,ksuid:()=>sj,lazy:()=>B0,length:()=>Ha,literal:()=>q,locales:()=>rl,looseObject:()=>Vt,looseRecord:()=>Mj,lowercase:()=>ts,lt:()=>jr,lte:()=>fn,mac:()=>lj,map:()=>Lj,maxLength:()=>Wa,maxSize:()=>Qi,meta:()=>Yj,mime:()=>os,minLength:()=>fi,minSize:()=>Lr,multipleOf:()=>Xi,nan:()=>Vj,nanoid:()=>nj,nativeEnum:()=>Uj,negative:()=>fp,never:()=>$v,nonnegative:()=>gp,nonoptional:()=>$0,nonpositive:()=>mp,normalize:()=>ss,null:()=>hl,nullable:()=>bp,nullish:()=>qj,number:()=>xe,object:()=>z,optional:()=>qe,overwrite:()=>dr,parse:()=>JC,parseAsync:()=>YC,partialRecord:()=>jj,pipe:()=>_p,positive:()=>pp,prefault:()=>D0,preprocess:()=>Rp,prettifyError:()=>Vg,promise:()=>Zj,property:()=>hp,readonly:()=>U0,record:()=>Le,refine:()=>H0,regex:()=>es,regexes:()=>Rn,registry:()=>Wd,safeDecode:()=>a0,safeDecodeAsync:()=>s0,safeEncode:()=>i0,safeEncodeAsync:()=>o0,safeParse:()=>XC,safeParseAsync:()=>QC,set:()=>zj,setErrorMap:()=>gX,size:()=>Va,slugify:()=>ol,startsWith:()=>is,strictObject:()=>$j,string:()=>P,stringFormat:()=>yj,stringbool:()=>Qj,success:()=>Bj,superRefine:()=>Z0,symbol:()=>Rj,templateLiteral:()=>Hj,toJSONSchema:()=>cl,toLowerCase:()=>ls,toUpperCase:()=>us,transform:()=>Nv,treeifyError:()=>Bg,trim:()=>cs,tuple:()=>x0,uint32:()=>Ij,uint64:()=>kj,ulid:()=>aj,undefined:()=>Ej,union:()=>Te,unknown:()=>De,uppercase:()=>ns,url:()=>QN,util:()=>A,uuid:()=>KN,uuidv4:()=>JN,uuidv6:()=>YN,uuidv7:()=>XN,void:()=>Aj,xid:()=>oj,xor:()=>Nj});var yp={};en(yp,{ZodAny:()=>p0,ZodArray:()=>h0,ZodBase64:()=>Ev,ZodBase64URL:()=>Tv,ZodBigInt:()=>gl,ZodBigIntFormat:()=>Dv,ZodBoolean:()=>ml,ZodCIDRv4:()=>kv,ZodCIDRv6:()=>Rv,ZodCUID:()=>_v,ZodCUID2:()=>xv,ZodCatch:()=>j0,ZodCodec:()=>zv,ZodCustom:()=>kp,ZodCustomStringFormat:()=>pl,ZodDate:()=>Sp,ZodDefault:()=>T0,ZodDiscriminatedUnion:()=>v0,ZodE164:()=>Av,ZodEmail:()=>yv,ZodEmoji:()=>vv,ZodEnum:()=>ul,ZodExactOptional:()=>k0,ZodFile:()=>C0,ZodFunction:()=>W0,ZodGUID:()=>vp,ZodIPv4:()=>Cv,ZodIPv6:()=>Pv,ZodIntersection:()=>b0,ZodJWT:()=>Ov,ZodKSUID:()=>Iv,ZodLazy:()=>q0,ZodLiteral:()=>I0,ZodMAC:()=>c0,ZodMap:()=>S0,ZodNaN:()=>L0,ZodNanoID:()=>bv,ZodNever:()=>m0,ZodNonOptional:()=>Mv,ZodNull:()=>d0,ZodNullable:()=>E0,ZodNumber:()=>fl,ZodNumberFormat:()=>ps,ZodObject:()=>wp,ZodOptional:()=>jv,ZodPipe:()=>Lv,ZodPrefault:()=>O0,ZodPromise:()=>V0,ZodReadonly:()=>z0,ZodRecord:()=>Pp,ZodSet:()=>w0,ZodString:()=>dl,ZodStringFormat:()=>Oe,ZodSuccess:()=>N0,ZodSymbol:()=>l0,ZodTemplateLiteral:()=>F0,ZodTransform:()=>P0,ZodTuple:()=>_0,ZodType:()=>ee,ZodULID:()=>Sv,ZodURL:()=>xp,ZodUUID:()=>mi,ZodUndefined:()=>u0,ZodUnion:()=>Ip,ZodUnknown:()=>f0,ZodVoid:()=>g0,ZodXID:()=>wv,ZodXor:()=>y0,_ZodString:()=>hv,_default:()=>A0,_function:()=>Gj,any:()=>Tj,array:()=>se,base64:()=>fj,base64url:()=>mj,bigint:()=>Cj,boolean:()=>ht,catch:()=>M0,check:()=>Kj,cidrv4:()=>dj,cidrv6:()=>pj,codec:()=>Wj,cuid:()=>rj,cuid2:()=>ij,custom:()=>Uv,date:()=>Oj,describe:()=>Jj,discriminatedUnion:()=>Cp,e164:()=>gj,email:()=>ZN,emoji:()=>tj,enum:()=>Wt,exactOptional:()=>R0,file:()=>Fj,float32:()=>xj,float64:()=>Sj,function:()=>Gj,guid:()=>GN,hash:()=>_j,hex:()=>bj,hostname:()=>vj,httpUrl:()=>ej,instanceof:()=>Xj,int:()=>gv,int32:()=>wj,int64:()=>Pj,intersection:()=>yl,ipv4:()=>cj,ipv6:()=>uj,json:()=>eM,jwt:()=>hj,keyof:()=>Dj,ksuid:()=>sj,lazy:()=>B0,literal:()=>q,looseObject:()=>Vt,looseRecord:()=>Mj,mac:()=>lj,map:()=>Lj,meta:()=>Yj,nan:()=>Vj,nanoid:()=>nj,nativeEnum:()=>Uj,never:()=>$v,nonoptional:()=>$0,null:()=>hl,nullable:()=>bp,nullish:()=>qj,number:()=>xe,object:()=>z,optional:()=>qe,partialRecord:()=>jj,pipe:()=>_p,prefault:()=>D0,preprocess:()=>Rp,promise:()=>Zj,readonly:()=>U0,record:()=>Le,refine:()=>H0,set:()=>zj,strictObject:()=>$j,string:()=>P,stringFormat:()=>yj,stringbool:()=>Qj,success:()=>Bj,superRefine:()=>Z0,symbol:()=>Rj,templateLiteral:()=>Hj,transform:()=>Nv,tuple:()=>x0,uint32:()=>Ij,uint64:()=>kj,ulid:()=>aj,undefined:()=>Ej,union:()=>Te,unknown:()=>De,url:()=>QN,uuid:()=>KN,uuidv4:()=>JN,uuidv6:()=>YN,uuidv7:()=>XN,void:()=>Aj,xid:()=>oj,xor:()=>Nj});var uv={};en(uv,{endsWith:()=>as,gt:()=>Mr,gte:()=>Bt,includes:()=>rs,length:()=>Ha,lowercase:()=>ts,lt:()=>jr,lte:()=>fn,maxLength:()=>Wa,maxSize:()=>Qi,mime:()=>os,minLength:()=>fi,minSize:()=>Lr,multipleOf:()=>Xi,negative:()=>fp,nonnegative:()=>gp,nonpositive:()=>mp,normalize:()=>ss,overwrite:()=>dr,positive:()=>pp,property:()=>hp,regex:()=>es,size:()=>Va,slugify:()=>ol,startsWith:()=>is,toLowerCase:()=>ls,toUpperCase:()=>us,trim:()=>cs,uppercase:()=>ns});var Ya={};en(Ya,{ZodISODate:()=>pv,ZodISODateTime:()=>dv,ZodISODuration:()=>mv,ZodISOTime:()=>fv,date:()=>ZC,datetime:()=>HC,duration:()=>KC,time:()=>GC});var dv=S("ZodISODateTime",(t,e)=>{bh.init(t,e),Oe.init(t,e)});function HC(t){return Cy(dv,t)}var pv=S("ZodISODate",(t,e)=>{_h.init(t,e),Oe.init(t,e)});function ZC(t){return Py(pv,t)}var fv=S("ZodISOTime",(t,e)=>{xh.init(t,e),Oe.init(t,e)});function GC(t){return ky(fv,t)}var mv=S("ZodISODuration",(t,e)=>{Sh.init(t,e),Oe.init(t,e)});function KC(t){return Ry(mv,t)}var HN=(t,e)=>{jd.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Vc(t,n)},flatten:{value:n=>Bc(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Uc,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Uc,2)}},isEmpty:{get(){return t.issues.length===0}}})},pX=S("ZodError",HN),En=S("ZodError",HN,{Parent:Error});var JC=Wc(En),YC=Zc(En),XC=Kc(En),QC=Jc(En),e0=Wg(En),t0=Hg(En),n0=Zg(En),r0=Gg(En),i0=Kg(En),a0=Jg(En),o0=Yg(En),s0=Xg(En);var ee=S("ZodType",(t,e)=>(K.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:sl(t,"input"),output:sl(t,"output")}}),t.toJSONSchema=cC(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(A.mergeDefs(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),t.with=t.check,t.clone=(n,r)=>qt(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>JC(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>XC(t,n,r),t.parseAsync=async(n,r)=>YC(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>QC(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>e0(t,n,r),t.decode=(n,r)=>t0(t,n,r),t.encodeAsync=async(n,r)=>n0(t,n,r),t.decodeAsync=async(n,r)=>r0(t,n,r),t.safeEncode=(n,r)=>i0(t,n,r),t.safeDecode=(n,r)=>a0(t,n,r),t.safeEncodeAsync=async(n,r)=>o0(t,n,r),t.safeDecodeAsync=async(n,r)=>s0(t,n,r),t.refine=(n,r)=>t.check(H0(n,r)),t.superRefine=n=>t.check(Z0(n)),t.overwrite=n=>t.check(dr(n)),t.optional=()=>qe(t),t.exactOptional=()=>R0(t),t.nullable=()=>bp(t),t.nullish=()=>qe(bp(t)),t.nonoptional=n=>$0(t,n),t.array=()=>se(t),t.or=n=>Te([t,n]),t.and=n=>yl(t,n),t.transform=n=>_p(t,Nv(n)),t.default=n=>A0(t,n),t.prefault=n=>D0(t,n),t.catch=n=>M0(t,n),t.pipe=n=>_p(t,n),t.readonly=()=>U0(t),t.describe=n=>{let r=t.clone();return Tt.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Tt.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Tt.get(t);let r=t.clone();return Tt.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),hv=S("_ZodString",(t,e)=>{Ba.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,i,a)=>lC(t,r,i,a);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(es(...r)),t.includes=(...r)=>t.check(rs(...r)),t.startsWith=(...r)=>t.check(is(...r)),t.endsWith=(...r)=>t.check(as(...r)),t.min=(...r)=>t.check(fi(...r)),t.max=(...r)=>t.check(Wa(...r)),t.length=(...r)=>t.check(Ha(...r)),t.nonempty=(...r)=>t.check(fi(1,...r)),t.lowercase=r=>t.check(ts(r)),t.uppercase=r=>t.check(ns(r)),t.trim=()=>t.check(cs()),t.normalize=(...r)=>t.check(ss(...r)),t.toLowerCase=()=>t.check(ls()),t.toUpperCase=()=>t.check(us()),t.slugify=()=>t.check(ol())}),dl=S("ZodString",(t,e)=>{Ba.init(t,e),hv.init(t,e),t.email=n=>t.check(Hd(yv,n)),t.url=n=>t.check(al(xp,n)),t.jwt=n=>t.check(dp(Ov,n)),t.emoji=n=>t.check(Yd(vv,n)),t.guid=n=>t.check(il(vp,n)),t.uuid=n=>t.check(Zd(mi,n)),t.uuidv4=n=>t.check(Gd(mi,n)),t.uuidv6=n=>t.check(Kd(mi,n)),t.uuidv7=n=>t.check(Jd(mi,n)),t.nanoid=n=>t.check(Xd(bv,n)),t.guid=n=>t.check(il(vp,n)),t.cuid=n=>t.check(Qd(_v,n)),t.cuid2=n=>t.check(ep(xv,n)),t.ulid=n=>t.check(tp(Sv,n)),t.base64=n=>t.check(cp(Ev,n)),t.base64url=n=>t.check(lp(Tv,n)),t.xid=n=>t.check(np(wv,n)),t.ksuid=n=>t.check(rp(Iv,n)),t.ipv4=n=>t.check(ip(Cv,n)),t.ipv6=n=>t.check(ap(Pv,n)),t.cidrv4=n=>t.check(op(kv,n)),t.cidrv6=n=>t.check(sp(Rv,n)),t.e164=n=>t.check(up(Av,n)),t.datetime=n=>t.check(HC(n)),t.date=n=>t.check(ZC(n)),t.time=n=>t.check(GC(n)),t.duration=n=>t.check(KC(n))});function P(t){return xy(dl,t)}var Oe=S("ZodStringFormat",(t,e)=>{Ee.init(t,e),hv.init(t,e)}),yv=S("ZodEmail",(t,e)=>{uh.init(t,e),Oe.init(t,e)});function ZN(t){return Hd(yv,t)}var vp=S("ZodGUID",(t,e)=>{ch.init(t,e),Oe.init(t,e)});function GN(t){return il(vp,t)}var mi=S("ZodUUID",(t,e)=>{lh.init(t,e),Oe.init(t,e)});function KN(t){return Zd(mi,t)}function JN(t){return Gd(mi,t)}function YN(t){return Kd(mi,t)}function XN(t){return Jd(mi,t)}var xp=S("ZodURL",(t,e)=>{dh.init(t,e),Oe.init(t,e)});function QN(t){return al(xp,t)}function ej(t){return al(xp,{protocol:/^https?$/,hostname:Rn.domain,...A.normalizeParams(t)})}var vv=S("ZodEmoji",(t,e)=>{ph.init(t,e),Oe.init(t,e)});function tj(t){return Yd(vv,t)}var bv=S("ZodNanoID",(t,e)=>{fh.init(t,e),Oe.init(t,e)});function nj(t){return Xd(bv,t)}var _v=S("ZodCUID",(t,e)=>{mh.init(t,e),Oe.init(t,e)});function rj(t){return Qd(_v,t)}var xv=S("ZodCUID2",(t,e)=>{gh.init(t,e),Oe.init(t,e)});function ij(t){return ep(xv,t)}var Sv=S("ZodULID",(t,e)=>{hh.init(t,e),Oe.init(t,e)});function aj(t){return tp(Sv,t)}var wv=S("ZodXID",(t,e)=>{yh.init(t,e),Oe.init(t,e)});function oj(t){return np(wv,t)}var Iv=S("ZodKSUID",(t,e)=>{vh.init(t,e),Oe.init(t,e)});function sj(t){return rp(Iv,t)}var Cv=S("ZodIPv4",(t,e)=>{wh.init(t,e),Oe.init(t,e)});function cj(t){return ip(Cv,t)}var c0=S("ZodMAC",(t,e)=>{Ch.init(t,e),Oe.init(t,e)});function lj(t){return wy(c0,t)}var Pv=S("ZodIPv6",(t,e)=>{Ih.init(t,e),Oe.init(t,e)});function uj(t){return ap(Pv,t)}var kv=S("ZodCIDRv4",(t,e)=>{Ph.init(t,e),Oe.init(t,e)});function dj(t){return op(kv,t)}var Rv=S("ZodCIDRv6",(t,e)=>{kh.init(t,e),Oe.init(t,e)});function pj(t){return sp(Rv,t)}var Ev=S("ZodBase64",(t,e)=>{Rh.init(t,e),Oe.init(t,e)});function fj(t){return cp(Ev,t)}var Tv=S("ZodBase64URL",(t,e)=>{Eh.init(t,e),Oe.init(t,e)});function mj(t){return lp(Tv,t)}var Av=S("ZodE164",(t,e)=>{Th.init(t,e),Oe.init(t,e)});function gj(t){return up(Av,t)}var Ov=S("ZodJWT",(t,e)=>{Ah.init(t,e),Oe.init(t,e)});function hj(t){return dp(Ov,t)}var pl=S("ZodCustomStringFormat",(t,e)=>{Oh.init(t,e),Oe.init(t,e)});function yj(t,e,n={}){return ds(pl,t,e,n)}function vj(t){return ds(pl,"hostname",Rn.hostname,t)}function bj(t){return ds(pl,"hex",Rn.hex,t)}function _j(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,i=Rn[r];if(!i)throw new Error(`Unrecognized hash format: ${r}`);return ds(pl,r,i,e)}var fl=S("ZodNumber",(t,e)=>{Ud.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,i,a)=>uC(t,r,i,a),t.gt=(r,i)=>t.check(Mr(r,i)),t.gte=(r,i)=>t.check(Bt(r,i)),t.min=(r,i)=>t.check(Bt(r,i)),t.lt=(r,i)=>t.check(jr(r,i)),t.lte=(r,i)=>t.check(fn(r,i)),t.max=(r,i)=>t.check(fn(r,i)),t.int=r=>t.check(gv(r)),t.safe=r=>t.check(gv(r)),t.positive=r=>t.check(Mr(0,r)),t.nonnegative=r=>t.check(Bt(0,r)),t.negative=r=>t.check(jr(0,r)),t.nonpositive=r=>t.check(fn(0,r)),t.multipleOf=(r,i)=>t.check(Xi(r,i)),t.step=(r,i)=>t.check(Xi(r,i)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function xe(t){return Ey(fl,t)}var ps=S("ZodNumberFormat",(t,e)=>{Dh.init(t,e),fl.init(t,e)});function gv(t){return Ay(ps,t)}function xj(t){return Oy(ps,t)}function Sj(t){return Dy(ps,t)}function wj(t){return $y(ps,t)}function Ij(t){return Ny(ps,t)}var ml=S("ZodBoolean",(t,e)=>{Qc.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>dC(t,n,r,i)});function ht(t){return jy(ml,t)}var gl=S("ZodBigInt",(t,e)=>{Fd.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,i,a)=>pC(t,r,i,a),t.gte=(r,i)=>t.check(Bt(r,i)),t.min=(r,i)=>t.check(Bt(r,i)),t.gt=(r,i)=>t.check(Mr(r,i)),t.gte=(r,i)=>t.check(Bt(r,i)),t.min=(r,i)=>t.check(Bt(r,i)),t.lt=(r,i)=>t.check(jr(r,i)),t.lte=(r,i)=>t.check(fn(r,i)),t.max=(r,i)=>t.check(fn(r,i)),t.positive=r=>t.check(Mr(BigInt(0),r)),t.negative=r=>t.check(jr(BigInt(0),r)),t.nonpositive=r=>t.check(fn(BigInt(0),r)),t.nonnegative=r=>t.check(Bt(BigInt(0),r)),t.multipleOf=(r,i)=>t.check(Xi(r,i));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function Cj(t){return Ly(gl,t)}var Dv=S("ZodBigIntFormat",(t,e)=>{$h.init(t,e),gl.init(t,e)});function Pj(t){return Uy(Dv,t)}function kj(t){return Fy(Dv,t)}var l0=S("ZodSymbol",(t,e)=>{Nh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>fC(t,n,r,i)});function Rj(t){return qy(l0,t)}var u0=S("ZodUndefined",(t,e)=>{jh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>gC(t,n,r,i)});function Ej(t){return By(u0,t)}var d0=S("ZodNull",(t,e)=>{Mh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>mC(t,n,r,i)});function hl(t){return Vy(d0,t)}var p0=S("ZodAny",(t,e)=>{Lh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>vC(t,n,r,i)});function Tj(){return Wy(p0)}var f0=S("ZodUnknown",(t,e)=>{zh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>bC(t,n,r,i)});function De(){return Hy(f0)}var m0=S("ZodNever",(t,e)=>{Uh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>yC(t,n,r,i)});function $v(t){return Zy(m0,t)}var g0=S("ZodVoid",(t,e)=>{Fh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>hC(t,n,r,i)});function Aj(t){return Gy(g0,t)}var Sp=S("ZodDate",(t,e)=>{qh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,i,a)=>_C(t,r,i,a),t.min=(r,i)=>t.check(Bt(r,i)),t.max=(r,i)=>t.check(fn(r,i));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});function Oj(t){return Ky(Sp,t)}var h0=S("ZodArray",(t,e)=>{Bh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>OC(t,n,r,i),t.element=e.element,t.min=(n,r)=>t.check(fi(n,r)),t.nonempty=n=>t.check(fi(1,n)),t.max=(n,r)=>t.check(Wa(n,r)),t.length=(n,r)=>t.check(Ha(n,r)),t.unwrap=()=>t.element});function se(t,e){return sC(h0,t,e)}function Dj(t){let e=t._zod.def.shape;return Wt(Object.keys(e))}var wp=S("ZodObject",(t,e)=>{oC.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>DC(t,n,r,i),A.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Wt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:$v()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>A.extend(t,n),t.safeExtend=n=>A.safeExtend(t,n),t.merge=n=>A.merge(t,n),t.pick=n=>A.pick(t,n),t.omit=n=>A.omit(t,n),t.partial=(...n)=>A.partial(jv,t,n[0]),t.required=(...n)=>A.required(Mv,t,n[0])});function z(t,e){let n={type:"object",shape:t??{},...A.normalizeParams(e)};return new wp(n)}function $j(t,e){return new wp({type:"object",shape:t,catchall:$v(),...A.normalizeParams(e)})}function Vt(t,e){return new wp({type:"object",shape:t,catchall:De(),...A.normalizeParams(e)})}var Ip=S("ZodUnion",(t,e)=>{el.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>ov(t,n,r,i),t.options=e.options});function Te(t,e){return new Ip({type:"union",options:t,...A.normalizeParams(e)})}var y0=S("ZodXor",(t,e)=>{Ip.init(t,e),Vh.init(t,e),t._zod.processJSONSchema=(n,r,i)=>ov(t,n,r,i),t.options=e.options});function Nj(t,e){return new y0({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var v0=S("ZodDiscriminatedUnion",(t,e)=>{Ip.init(t,e),Wh.init(t,e)});function Cp(t,e,n){return new v0({type:"union",options:e,discriminator:t,...A.normalizeParams(n)})}var b0=S("ZodIntersection",(t,e)=>{Hh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>$C(t,n,r,i)});function yl(t,e){return new b0({type:"intersection",left:t,right:e})}var _0=S("ZodTuple",(t,e)=>{qd.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>NC(t,n,r,i),t.rest=n=>t.clone({...t._zod.def,rest:n})});function x0(t,e,n){let r=e instanceof K,i=r?n:e,a=r?e:null;return new _0({type:"tuple",items:t,rest:a,...A.normalizeParams(i)})}var Pp=S("ZodRecord",(t,e)=>{Zh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>jC(t,n,r,i),t.keyType=e.keyType,t.valueType=e.valueType});function Le(t,e,n){return new Pp({type:"record",keyType:t,valueType:e,...A.normalizeParams(n)})}function jj(t,e,n){let r=qt(t);return r._zod.values=void 0,new Pp({type:"record",keyType:r,valueType:e,...A.normalizeParams(n)})}function Mj(t,e,n){return new Pp({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(n)})}var S0=S("ZodMap",(t,e)=>{Gh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>TC(t,n,r,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Lr(...n)),t.nonempty=n=>t.check(Lr(1,n)),t.max=(...n)=>t.check(Qi(...n)),t.size=(...n)=>t.check(Va(...n))});function Lj(t,e,n){return new S0({type:"map",keyType:t,valueType:e,...A.normalizeParams(n)})}var w0=S("ZodSet",(t,e)=>{Kh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>AC(t,n,r,i),t.min=(...n)=>t.check(Lr(...n)),t.nonempty=n=>t.check(Lr(1,n)),t.max=(...n)=>t.check(Qi(...n)),t.size=(...n)=>t.check(Va(...n))});function zj(t,e){return new w0({type:"set",valueType:t,...A.normalizeParams(e)})}var ul=S("ZodEnum",(t,e)=>{Jh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,i,a)=>xC(t,r,i,a),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,i)=>{let a={};for(let o of r)if(n.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ul({...e,checks:[],...A.normalizeParams(i),entries:a})},t.exclude=(r,i)=>{let a={...e.entries};for(let o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new ul({...e,checks:[],...A.normalizeParams(i),entries:a})}});function Wt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ul({type:"enum",entries:n,...A.normalizeParams(e)})}function Uj(t,e){return new ul({type:"enum",entries:t,...A.normalizeParams(e)})}var I0=S("ZodLiteral",(t,e)=>{Yh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>SC(t,n,r,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function q(t,e){return new I0({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var C0=S("ZodFile",(t,e)=>{Xh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>CC(t,n,r,i),t.min=(n,r)=>t.check(Lr(n,r)),t.max=(n,r)=>t.check(Qi(n,r)),t.mime=(n,r)=>t.check(os(Array.isArray(n)?n:[n],r))});function Fj(t){return Xy(C0,t)}var P0=S("ZodTransform",(t,e)=>{Qh.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>EC(t,n,r,i),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new La(t.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(A.issue(a,n.value,e));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),n.issues.push(A.issue(o))}};let i=e.transform(n.value,n);return i instanceof Promise?i.then(a=>(n.value=a,n)):(n.value=i,n)}});function Nv(t){return new P0({type:"transform",transform:t})}var jv=S("ZodOptional",(t,e)=>{Bd.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>sv(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function qe(t){return new jv({type:"optional",innerType:t})}var k0=S("ZodExactOptional",(t,e)=>{ey.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>sv(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function R0(t){return new k0({type:"optional",innerType:t})}var E0=S("ZodNullable",(t,e)=>{ty.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>MC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function bp(t){return new E0({type:"nullable",innerType:t})}function qj(t){return qe(bp(t))}var T0=S("ZodDefault",(t,e)=>{ny.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>zC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function A0(t,e){return new T0({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var O0=S("ZodPrefault",(t,e)=>{ry.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>UC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function D0(t,e){return new O0({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var Mv=S("ZodNonOptional",(t,e)=>{iy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>LC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function $0(t,e){return new Mv({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var N0=S("ZodSuccess",(t,e)=>{ay.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>PC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function Bj(t){return new N0({type:"success",innerType:t})}var j0=S("ZodCatch",(t,e)=>{oy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>FC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function M0(t,e){return new j0({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var L0=S("ZodNaN",(t,e)=>{sy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>wC(t,n,r,i)});function Vj(t){return Yy(L0,t)}var Lv=S("ZodPipe",(t,e)=>{cy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>qC(t,n,r,i),t.in=e.in,t.out=e.out});function _p(t,e){return new Lv({type:"pipe",in:t,out:e})}var zv=S("ZodCodec",(t,e)=>{Lv.init(t,e),tl.init(t,e)});function Wj(t,e,n){return new zv({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}var z0=S("ZodReadonly",(t,e)=>{ly.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>BC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function U0(t){return new z0({type:"readonly",innerType:t})}var F0=S("ZodTemplateLiteral",(t,e)=>{uy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>IC(t,n,r,i)});function Hj(t,e){return new F0({type:"template_literal",parts:t,...A.normalizeParams(e)})}var q0=S("ZodLazy",(t,e)=>{fy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>WC(t,n,r,i),t.unwrap=()=>t._zod.def.getter()});function B0(t){return new q0({type:"lazy",getter:t})}var V0=S("ZodPromise",(t,e)=>{py.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>VC(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function Zj(t){return new V0({type:"promise",innerType:t})}var W0=S("ZodFunction",(t,e)=>{dy.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>RC(t,n,r,i)});function Gj(t){return new W0({type:"function",input:Array.isArray(t?.input)?x0(t?.input):t?.input??se(De()),output:t?.output??De()})}var kp=S("ZodCustom",(t,e)=>{my.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,r,i)=>kC(t,n,r,i)});function Kj(t){let e=new Ae({check:"custom"});return e._zod.check=t,e}function Uv(t,e){return Qy(kp,t??(()=>!0),e)}function H0(t,e={}){return ev(kp,t,e)}function Z0(t){return tv(t)}var Jj=nv,Yj=rv;function Xj(t,e={}){let n=new kp({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...A.normalizeParams(e)});return n._zod.bag.Class=t,n._zod.check=r=>{r.value instanceof t||r.issues.push({code:"invalid_type",expected:t.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var Qj=(...t)=>iv({Codec:zv,Boolean:ml,String:dl},...t);function eM(t){let e=B0(()=>Te([P(t),xe(),ht(),hl(),se(e),Le(P(),e)]));return e}function Rp(t,e){return _p(Nv(t),e)}var mX={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function gX(t){at({customError:t})}function hX(){return at().customError}var G0;G0||(G0={});var M={...yp,...uv,iso:Ya},yX=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function vX(t,e){let n=t.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function bX(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=t.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let r=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let i=n[1];if(!i||!e.defs[i])throw new Error(`Reference not found: ${t}`);return e.defs[i]}throw new Error(`Reference not found: ${t}`)}function tM(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return M.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let i=t.$ref;if(e.refs.has(i))return e.refs.get(i);if(e.processing.has(i))return M.lazy(()=>{if(!e.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return e.refs.get(i)});e.processing.add(i);let a=bX(i,e),o=nn(a,e);return e.refs.set(i,o),e.processing.delete(i),o}if(t.enum!==void 0){let i=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&i.length===1&&i[0]===null)return M.null();if(i.length===0)return M.never();if(i.length===1)return M.literal(i[0]);if(i.every(o=>typeof o=="string"))return M.enum(i);let a=i.map(o=>M.literal(o));return a.length<2?a[0]:M.union([a[0],a[1],...a.slice(2)])}if(t.const!==void 0)return M.literal(t.const);let n=t.type;if(Array.isArray(n)){let i=n.map(a=>{let o={...t,type:a};return tM(o,e)});return i.length===0?M.never():i.length===1?i[0]:M.union(i)}if(!n)return M.any();let r;switch(n){case"string":{let i=M.string();if(t.format){let a=t.format;a==="email"?i=i.check(M.email()):a==="uri"||a==="uri-reference"?i=i.check(M.url()):a==="uuid"||a==="guid"?i=i.check(M.uuid()):a==="date-time"?i=i.check(M.iso.datetime()):a==="date"?i=i.check(M.iso.date()):a==="time"?i=i.check(M.iso.time()):a==="duration"?i=i.check(M.iso.duration()):a==="ipv4"?i=i.check(M.ipv4()):a==="ipv6"?i=i.check(M.ipv6()):a==="mac"?i=i.check(M.mac()):a==="cidr"?i=i.check(M.cidrv4()):a==="cidr-v6"?i=i.check(M.cidrv6()):a==="base64"?i=i.check(M.base64()):a==="base64url"?i=i.check(M.base64url()):a==="e164"?i=i.check(M.e164()):a==="jwt"?i=i.check(M.jwt()):a==="emoji"?i=i.check(M.emoji()):a==="nanoid"?i=i.check(M.nanoid()):a==="cuid"?i=i.check(M.cuid()):a==="cuid2"?i=i.check(M.cuid2()):a==="ulid"?i=i.check(M.ulid()):a==="xid"?i=i.check(M.xid()):a==="ksuid"&&(i=i.check(M.ksuid()))}typeof t.minLength=="number"&&(i=i.min(t.minLength)),typeof t.maxLength=="number"&&(i=i.max(t.maxLength)),t.pattern&&(i=i.regex(new RegExp(t.pattern))),r=i;break}case"number":case"integer":{let i=n==="integer"?M.number().int():M.number();typeof t.minimum=="number"&&(i=i.min(t.minimum)),typeof t.maximum=="number"&&(i=i.max(t.maximum)),typeof t.exclusiveMinimum=="number"?i=i.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(i=i.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?i=i.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(i=i.lt(t.maximum)),typeof t.multipleOf=="number"&&(i=i.multipleOf(t.multipleOf)),r=i;break}case"boolean":{r=M.boolean();break}case"null":{r=M.null();break}case"object":{let i={},a=t.properties||{},o=new Set(t.required||[]);for(let[c,l]of Object.entries(a)){let u=nn(l,e);i[c]=o.has(c)?u:u.optional()}if(t.propertyNames){let c=nn(t.propertyNames,e),l=t.additionalProperties&&typeof t.additionalProperties=="object"?nn(t.additionalProperties,e):M.any();if(Object.keys(i).length===0){r=M.record(c,l);break}let u=M.object(i).passthrough(),d=M.looseRecord(c,l);r=M.intersection(u,d);break}if(t.patternProperties){let c=t.patternProperties,l=Object.keys(c),u=[];for(let p of l){let f=nn(c[p],e),m=M.string().regex(new RegExp(p));u.push(M.looseRecord(m,f))}let d=[];if(Object.keys(i).length>0&&d.push(M.object(i).passthrough()),d.push(...u),d.length===0)r=M.object({}).passthrough();else if(d.length===1)r=d[0];else{let p=M.intersection(d[0],d[1]);for(let f=2;f<d.length;f++)p=M.intersection(p,d[f]);r=p}break}let s=M.object(i);t.additionalProperties===!1?r=s.strict():typeof t.additionalProperties=="object"?r=s.catchall(nn(t.additionalProperties,e)):r=s.passthrough();break}case"array":{let i=t.prefixItems,a=t.items;if(i&&Array.isArray(i)){let o=i.map(c=>nn(c,e)),s=a&&typeof a=="object"&&!Array.isArray(a)?nn(a,e):void 0;s?r=M.tuple(o).rest(s):r=M.tuple(o),typeof t.minItems=="number"&&(r=r.check(M.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(M.maxLength(t.maxItems)))}else if(Array.isArray(a)){let o=a.map(c=>nn(c,e)),s=t.additionalItems&&typeof t.additionalItems=="object"?nn(t.additionalItems,e):void 0;s?r=M.tuple(o).rest(s):r=M.tuple(o),typeof t.minItems=="number"&&(r=r.check(M.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(M.maxLength(t.maxItems)))}else if(a!==void 0){let o=nn(a,e),s=M.array(o);typeof t.minItems=="number"&&(s=s.min(t.minItems)),typeof t.maxItems=="number"&&(s=s.max(t.maxItems)),r=s}else r=M.array(M.any());break}default:throw new Error(`Unsupported type: ${n}`)}return t.description&&(r=r.describe(t.description)),t.default!==void 0&&(r=r.default(t.default)),r}function nn(t,e){if(typeof t=="boolean")return t?M.any():M.never();let n=tM(t,e),r=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let s=t.anyOf.map(l=>nn(l,e)),c=M.union(s);n=r?M.intersection(n,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let s=t.oneOf.map(l=>nn(l,e)),c=M.xor(s);n=r?M.intersection(n,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)n=r?n:M.any();else{let s=r?n:nn(t.allOf[0],e),c=r?0:1;for(let l=c;l<t.allOf.length;l++)s=M.intersection(s,nn(t.allOf[l],e));n=s}t.nullable===!0&&e.version==="openapi-3.0"&&(n=M.nullable(n)),t.readOnly===!0&&(n=M.readonly(n));let i={},a=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of a)s in t&&(i[s]=t[s]);let o=["contentEncoding","contentMediaType","contentSchema"];for(let s of o)s in t&&(i[s]=t[s]);for(let s of Object.keys(t))yX.has(s)||(i[s]=t[s]);return Object.keys(i).length>0&&e.registry.add(n,i),n}function nM(t,e){if(typeof t=="boolean")return t?M.any():M.never();let n=vX(t,e?.defaultTarget),r=t.$defs||t.definitions||{},i={version:n,defs:r,refs:new Map,processing:new Set,rootSchema:t,registry:e?.registry??Tt};return nn(t,i)}var K0={};en(K0,{bigint:()=>wX,boolean:()=>SX,date:()=>IX,number:()=>xX,string:()=>_X});function _X(t){return Sy(dl,t)}function xX(t){return Ty(fl,t)}function SX(t){return My(ml,t)}function wX(t){return zy(gl,t)}function IX(t){return Jy(Sp,t)}at(gy());var Y0="2025-11-25";var rM=[Y0,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Xa="io.modelcontextprotocol/related-task",qv="2.0",Ht=Uv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),iM=Te([P(),xe().int()]),aM=P(),zDe=Vt({ttl:Te([xe(),hl()]).optional(),pollInterval:xe().optional()}),PX=z({ttl:xe().optional()}),kX=z({taskId:P()}),X0=Vt({progressToken:iM.optional(),[Xa]:kX.optional()}),Qn=z({_meta:X0.optional()}),Ep=Qn.extend({task:PX.optional()}),oM=t=>Ep.safeParse(t).success,Zt=z({method:P(),params:Qn.loose().optional()}),pr=z({_meta:X0.optional()}),fr=z({method:P(),params:pr.loose().optional()}),Gt=Vt({_meta:X0.optional()}),Bv=Te([P(),xe().int()]),sM=z({jsonrpc:q(qv),id:Bv,...Zt.shape}).strict(),Q0=t=>sM.safeParse(t).success,cM=z({jsonrpc:q(qv),...fr.shape}).strict(),lM=t=>cM.safeParse(t).success,eP=z({jsonrpc:q(qv),id:Bv,result:Gt}).strict(),Tp=t=>eP.safeParse(t).success;var ge;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ge||(ge={}));var tP=z({jsonrpc:q(qv),id:Bv.optional(),error:z({code:xe().int(),message:P(),data:De().optional()})}).strict();var uM=t=>tP.safeParse(t).success;var dM=Te([sM,cM,eP,tP]),UDe=Te([eP,tP]),Vv=Gt.strict(),RX=pr.extend({requestId:Bv.optional(),reason:P().optional()}),Wv=fr.extend({method:q("notifications/cancelled"),params:RX}),EX=z({src:P(),mimeType:P().optional(),sizes:se(P()).optional(),theme:Wt(["light","dark"]).optional()}),Ap=z({icons:se(EX).optional()}),vl=z({name:P(),title:P().optional()}),pM=vl.extend({...vl.shape,...Ap.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),TX=yl(z({applyDefaults:ht().optional()}),Le(P(),De())),AX=Rp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,yl(z({form:TX.optional(),url:Ht.optional()}),Le(P(),De()).optional())),OX=Vt({list:Ht.optional(),cancel:Ht.optional(),requests:Vt({sampling:Vt({createMessage:Ht.optional()}).optional(),elicitation:Vt({create:Ht.optional()}).optional()}).optional()}),DX=Vt({list:Ht.optional(),cancel:Ht.optional(),requests:Vt({tools:Vt({call:Ht.optional()}).optional()}).optional()}),$X=z({experimental:Le(P(),Ht).optional(),sampling:z({context:Ht.optional(),tools:Ht.optional()}).optional(),elicitation:AX.optional(),roots:z({listChanged:ht().optional()}).optional(),tasks:OX.optional()}),NX=Qn.extend({protocolVersion:P(),capabilities:$X,clientInfo:pM}),nP=Zt.extend({method:q("initialize"),params:NX});var jX=z({experimental:Le(P(),Ht).optional(),logging:Ht.optional(),completions:Ht.optional(),prompts:z({listChanged:ht().optional()}).optional(),resources:z({subscribe:ht().optional(),listChanged:ht().optional()}).optional(),tools:z({listChanged:ht().optional()}).optional(),tasks:DX.optional()}),MX=Gt.extend({protocolVersion:P(),capabilities:jX,serverInfo:pM,instructions:P().optional()}),rP=fr.extend({method:q("notifications/initialized"),params:pr.optional()});var Hv=Zt.extend({method:q("ping"),params:Qn.optional()}),LX=z({progress:xe(),total:qe(xe()),message:qe(P())}),zX=z({...pr.shape,...LX.shape,progressToken:iM}),Zv=fr.extend({method:q("notifications/progress"),params:zX}),UX=Qn.extend({cursor:aM.optional()}),Op=Zt.extend({params:UX.optional()}),Dp=Gt.extend({nextCursor:aM.optional()}),FX=Wt(["working","input_required","completed","failed","cancelled"]),$p=z({taskId:P(),status:FX,ttl:Te([xe(),hl()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:qe(xe()),statusMessage:qe(P())}),bl=Gt.extend({task:$p}),qX=pr.merge($p),Np=fr.extend({method:q("notifications/tasks/status"),params:qX}),Gv=Zt.extend({method:q("tasks/get"),params:Qn.extend({taskId:P()})}),Kv=Gt.merge($p),Jv=Zt.extend({method:q("tasks/result"),params:Qn.extend({taskId:P()})}),FDe=Gt.loose(),Yv=Op.extend({method:q("tasks/list")}),Xv=Dp.extend({tasks:se($p)}),Qv=Zt.extend({method:q("tasks/cancel"),params:Qn.extend({taskId:P()})}),fM=Gt.merge($p),mM=z({uri:P(),mimeType:qe(P()),_meta:Le(P(),De()).optional()}),gM=mM.extend({text:P()}),iP=P().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),hM=mM.extend({blob:iP}),jp=Wt(["user","assistant"]),_l=z({audience:se(jp).optional(),priority:xe().min(0).max(1).optional(),lastModified:Ya.datetime({offset:!0}).optional()}),yM=z({...vl.shape,...Ap.shape,uri:P(),description:qe(P()),mimeType:qe(P()),annotations:_l.optional(),_meta:qe(Vt({}))}),BX=z({...vl.shape,...Ap.shape,uriTemplate:P(),description:qe(P()),mimeType:qe(P()),annotations:_l.optional(),_meta:qe(Vt({}))}),aP=Op.extend({method:q("resources/list")}),VX=Dp.extend({resources:se(yM)}),WX=Op.extend({method:q("resources/templates/list")}),HX=Dp.extend({resourceTemplates:se(BX)}),oP=Qn.extend({uri:P()}),ZX=oP,sP=Zt.extend({method:q("resources/read"),params:ZX}),GX=Gt.extend({contents:se(Te([gM,hM]))}),KX=fr.extend({method:q("notifications/resources/list_changed"),params:pr.optional()}),JX=oP,YX=Zt.extend({method:q("resources/subscribe"),params:JX}),XX=oP,QX=Zt.extend({method:q("resources/unsubscribe"),params:XX}),eQ=pr.extend({uri:P()}),tQ=fr.extend({method:q("notifications/resources/updated"),params:eQ}),nQ=z({name:P(),description:qe(P()),required:qe(ht())}),rQ=z({...vl.shape,...Ap.shape,description:qe(P()),arguments:qe(se(nQ)),_meta:qe(Vt({}))}),iQ=Op.extend({method:q("prompts/list")}),aQ=Dp.extend({prompts:se(rQ)}),oQ=Qn.extend({name:P(),arguments:Le(P(),P()).optional()}),sQ=Zt.extend({method:q("prompts/get"),params:oQ}),cP=z({type:q("text"),text:P(),annotations:_l.optional(),_meta:Le(P(),De()).optional()}),lP=z({type:q("image"),data:iP,mimeType:P(),annotations:_l.optional(),_meta:Le(P(),De()).optional()}),uP=z({type:q("audio"),data:iP,mimeType:P(),annotations:_l.optional(),_meta:Le(P(),De()).optional()}),cQ=z({type:q("tool_use"),name:P(),id:P(),input:Le(P(),De()),_meta:Le(P(),De()).optional()}),lQ=z({type:q("resource"),resource:Te([gM,hM]),annotations:_l.optional(),_meta:Le(P(),De()).optional()}),uQ=yM.extend({type:q("resource_link")}),dP=Te([cP,lP,uP,uQ,lQ]),dQ=z({role:jp,content:dP}),pQ=Gt.extend({description:P().optional(),messages:se(dQ)}),fQ=fr.extend({method:q("notifications/prompts/list_changed"),params:pr.optional()}),mQ=z({title:P().optional(),readOnlyHint:ht().optional(),destructiveHint:ht().optional(),idempotentHint:ht().optional(),openWorldHint:ht().optional()}),gQ=z({taskSupport:Wt(["required","optional","forbidden"]).optional()}),vM=z({...vl.shape,...Ap.shape,description:P().optional(),inputSchema:z({type:q("object"),properties:Le(P(),Ht).optional(),required:se(P()).optional()}).catchall(De()),outputSchema:z({type:q("object"),properties:Le(P(),Ht).optional(),required:se(P()).optional()}).catchall(De()).optional(),annotations:mQ.optional(),execution:gQ.optional(),_meta:Le(P(),De()).optional()}),pP=Op.extend({method:q("tools/list")}),hQ=Dp.extend({tools:se(vM)}),eb=Gt.extend({content:se(dP).default([]),structuredContent:Le(P(),De()).optional(),isError:ht().optional()}),qDe=eb.or(Gt.extend({toolResult:De()})),yQ=Ep.extend({name:P(),arguments:Le(P(),De()).optional()}),Mp=Zt.extend({method:q("tools/call"),params:yQ}),vQ=fr.extend({method:q("notifications/tools/list_changed"),params:pr.optional()}),BDe=z({autoRefresh:ht().default(!0),debounceMs:xe().int().nonnegative().default(300)}),Lp=Wt(["debug","info","notice","warning","error","critical","alert","emergency"]),bQ=Qn.extend({level:Lp}),fP=Zt.extend({method:q("logging/setLevel"),params:bQ}),_Q=pr.extend({level:Lp,logger:P().optional(),data:De()}),xQ=fr.extend({method:q("notifications/message"),params:_Q}),SQ=z({name:P().optional()}),wQ=z({hints:se(SQ).optional(),costPriority:xe().min(0).max(1).optional(),speedPriority:xe().min(0).max(1).optional(),intelligencePriority:xe().min(0).max(1).optional()}),IQ=z({mode:Wt(["auto","required","none"]).optional()}),CQ=z({type:q("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:se(dP).default([]),structuredContent:z({}).loose().optional(),isError:ht().optional(),_meta:Le(P(),De()).optional()}),PQ=Cp("type",[cP,lP,uP]),Fv=Cp("type",[cP,lP,uP,cQ,CQ]),kQ=z({role:jp,content:Te([Fv,se(Fv)]),_meta:Le(P(),De()).optional()}),RQ=Ep.extend({messages:se(kQ),modelPreferences:wQ.optional(),systemPrompt:P().optional(),includeContext:Wt(["none","thisServer","allServers"]).optional(),temperature:xe().optional(),maxTokens:xe().int(),stopSequences:se(P()).optional(),metadata:Ht.optional(),tools:se(vM).optional(),toolChoice:IQ.optional()}),EQ=Zt.extend({method:q("sampling/createMessage"),params:RQ}),mP=Gt.extend({model:P(),stopReason:qe(Wt(["endTurn","stopSequence","maxTokens"]).or(P())),role:jp,content:PQ}),gP=Gt.extend({model:P(),stopReason:qe(Wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:jp,content:Te([Fv,se(Fv)])}),TQ=z({type:q("boolean"),title:P().optional(),description:P().optional(),default:ht().optional()}),AQ=z({type:q("string"),title:P().optional(),description:P().optional(),minLength:xe().optional(),maxLength:xe().optional(),format:Wt(["email","uri","date","date-time"]).optional(),default:P().optional()}),OQ=z({type:Wt(["number","integer"]),title:P().optional(),description:P().optional(),minimum:xe().optional(),maximum:xe().optional(),default:xe().optional()}),DQ=z({type:q("string"),title:P().optional(),description:P().optional(),enum:se(P()),default:P().optional()}),$Q=z({type:q("string"),title:P().optional(),description:P().optional(),oneOf:se(z({const:P(),title:P()})),default:P().optional()}),NQ=z({type:q("string"),title:P().optional(),description:P().optional(),enum:se(P()),enumNames:se(P()).optional(),default:P().optional()}),jQ=Te([DQ,$Q]),MQ=z({type:q("array"),title:P().optional(),description:P().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:z({type:q("string"),enum:se(P())}),default:se(P()).optional()}),LQ=z({type:q("array"),title:P().optional(),description:P().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:z({anyOf:se(z({const:P(),title:P()}))}),default:se(P()).optional()}),zQ=Te([MQ,LQ]),UQ=Te([NQ,jQ,zQ]),FQ=Te([UQ,TQ,AQ,OQ]),qQ=Ep.extend({mode:q("form").optional(),message:P(),requestedSchema:z({type:q("object"),properties:Le(P(),FQ),required:se(P()).optional()})}),BQ=Ep.extend({mode:q("url"),message:P(),elicitationId:P(),url:P().url()}),VQ=Te([qQ,BQ]),WQ=Zt.extend({method:q("elicitation/create"),params:VQ}),HQ=pr.extend({elicitationId:P()}),ZQ=fr.extend({method:q("notifications/elicitation/complete"),params:HQ}),tb=Gt.extend({action:Wt(["accept","decline","cancel"]),content:Rp(t=>t===null?void 0:t,Le(P(),Te([P(),xe(),ht(),se(P())])).optional())}),GQ=z({type:q("ref/resource"),uri:P()});var KQ=z({type:q("ref/prompt"),name:P()}),JQ=Qn.extend({ref:Te([KQ,GQ]),argument:z({name:P(),value:P()}),context:z({arguments:Le(P(),P()).optional()}).optional()}),YQ=Zt.extend({method:q("completion/complete"),params:JQ});var XQ=Gt.extend({completion:Vt({values:se(P()).max(100),total:qe(xe().int()),hasMore:qe(ht())})}),QQ=z({uri:P().startsWith("file://"),name:P().optional(),_meta:Le(P(),De()).optional()}),eee=Zt.extend({method:q("roots/list"),params:Qn.optional()}),hP=Gt.extend({roots:se(QQ)}),tee=fr.extend({method:q("notifications/roots/list_changed"),params:pr.optional()}),VDe=Te([Hv,nP,YQ,fP,sQ,iQ,aP,WX,sP,YX,QX,Mp,pP,Gv,Jv,Yv,Qv]),WDe=Te([Wv,Zv,rP,tee,Np]),HDe=Te([Vv,mP,gP,tb,hP,Kv,Xv,bl]),ZDe=Te([Hv,EQ,WQ,eee,Gv,Jv,Yv,Qv]),GDe=Te([Wv,Zv,xQ,tQ,KX,vQ,fQ,Np,ZQ]),KDe=Te([Vv,MX,XQ,pQ,aQ,VX,HX,GX,eb,hQ,Kv,Xv,bl]),ie=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===ge.UrlElicitationRequired&&r){let i=r;if(i.elicitations)return new J0(i.elicitations,n)}return new t(e,n,r)}},J0=class extends ie{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(ge.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Qa(t){return t==="completed"||t==="failed"||t==="cancelled"}var nee=Symbol("Let zodToJsonSchema decide on which parser to use");var E$e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yP(t){let n=lv(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=WN(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function vP(t,e){let n=Ja(t,e);if(!n.success)throw n.error;return n.data}var cee=6e4,nb=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Wv,n=>{this._oncancel(n)}),this.setNotificationHandler(Zv,n=>{this._onprogress(n)}),this.setRequestHandler(Hv,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Gv,async(n,r)=>{let i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new ie(ge.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Jv,async(n,r)=>{let i=async()=>{let a=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,r.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),s.type==="response")u(c);else{let d=c,p=new ie(d.error.code,d.error.message,d.error.data);u(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let o=await this._taskStore.getTask(a,r.sessionId);if(!o)throw new ie(ge.InvalidParams,`Task not found: ${a}`);if(!Qa(o.status))return await this._waitForTaskUpdate(a,r.signal),await i();if(Qa(o.status)){let s=await this._taskStore.getTaskResult(a,r.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[Xa]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(Yv,async(n,r)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new ie(ge.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Qv,async(n,r)=>{try{let i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new ie(ge.InvalidParams,`Task not found: ${n.params.taskId}`);if(Qa(i.status))throw new ie(ge.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let a=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!a)throw new ie(ge.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof ie?i:new ie(ge.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),ie.fromError(ge.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=a=>{r?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),Tp(a)||uM(a)?this._onresponse(a):Q0(a)?this._onrequest(a,o):lM(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let n=ie.fromError(ge.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,a=e.params?._meta?.[Xa]?.taskId;if(r===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:ge.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=oM(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{let d={relatedRequestId:e.id};a&&(d.relatedTask={taskId:a}),await this.notification(u,d)},sendRequest:async(u,d,p)=>{let f={...p,relatedRequestId:e.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});let m=f.relatedTask?.taskId??a;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,l)).then(async u=>{if(o.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async u=>{if(o.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:ge.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,i=Number(n),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Tp(e))r(e);else{let o=new ie(e.error.code,e.error.message,e.error.data);r(o)}return}let i=this._responseHandlers.get(n);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let a=!1;if(Tp(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,n))}}if(a||this._progressHandlers.delete(n),Tp(e))i(e);else{let o=ie.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:i}=r??{};if(!i){try{yield{type:"result",result:await this.request(e,n,r)}}catch(o){yield{type:"error",error:o instanceof ie?o:new ie(ge.InternalError,String(o))}}return}let a;try{let o=await this.request(e,bl,r);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new ie(ge.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},r);if(yield{type:"taskStatus",task:s},Qa(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)}:s.status==="failed"?yield{type:"error",error:new ie(ge.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new ie(ge.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),r?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof ie?o:new ie(ge.InternalError,String(o))}}}request(e,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=r??{};return new Promise((l,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(b){d(b);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Xa]:c}});let m=b=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(b)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));let x=b instanceof ie?b:new ie(ge.RequestTimeout,String(b));u(x)};this._responseHandlers.set(p,b=>{if(!r?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=Ja(n,b.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});let g=r?.timeout??cee,y=()=>m(ie.fromError(ge.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,r?.maxTotalTimeout,y,r?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=x=>{let I=this._responseHandlers.get(p);I?I(x):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(p),u(x)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(b=>{this._cleanupTimeout(p),u(b)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Kv,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Xv,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},fM,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Xa]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Xa]:n.relatedTask}}}),this._transport?.send(s,n).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};n?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Xa]:n.relatedTask}}}),await this._transport.send(o,n)}setRequestHandler(e,n){let r=yP(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(i,a)=>{let o=vP(e,i);return Promise.resolve(n(o,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=yP(e);this._notificationHandlers.set(r,i=>{let a=vP(e,i);return Promise.resolve(n(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,i)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let i of r)if(i.type==="request"&&Q0(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new ie(ge.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(r=i.pollInterval)}catch{}return new Promise((i,a)=>{if(n.aborted){a(new ie(ge.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,r);n.addEventListener("abort",()=>{clearTimeout(o),a(new ie(ge.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await r.createTask(i,e.id,{method:e.method,params:e.params},n)},getTask:async i=>{let a=await r.getTask(i,n);if(!a)throw new ie(ge.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await r.storeTaskResult(i,a,o,n);let s=await r.getTask(i,n);if(s){let c=Np.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Qa(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>r.getTaskResult(i,n),updateTaskStatus:async(i,a,o)=>{let s=await r.getTask(i,n);if(!s)throw new ie(ge.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Qa(s.status))throw new ie(ge.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(i,a,o,n);let c=await r.getTask(i,n);if(c){let l=Np.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Qa(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>r.listTasks(i,n)}}};function bM(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function _M(t,e){let n={...t};for(let r in e){let i=r,a=e[i];if(a===void 0)continue;let o=n[i];bM(o)&&bM(a)?n[i]={...o,...a}:n[i]=a}return n}var oz=Ft(rR(),1),sz=Ft(az(),1);function Xae(){let t=new oz.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sz.default)(t),t}var zb=class{constructor(e){this._ajv=e??Xae()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Ub=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function cz(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function lz(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Fb=class extends nb{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Lp.options.map((r,i)=>[r,i])),this.isMessageIgnored=(r,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new zb,this.setRequestHandler(nP,r=>this._oninitialize(r)),this.setNotificationHandler(rP,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fP,async(r,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=r.params,s=Lp.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ub(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_M(this._capabilities,e)}setRequestHandler(e,n){let i=lv(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(ll(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let s=async(c,l)=>{let u=Ja(Mp,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new ie(ge.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=u.data,p=await Promise.resolve(n(c,l));if(d.task){let m=Ja(bl,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new ie(ge.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=Ja(eb,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new ie(ge.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){lz(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&cz(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:rM.includes(n)?n:Y0,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Vv)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],i=Array.isArray(r.content)?r.content:[r.content],a=i.some(l=>l.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=o?Array.isArray(o.content)?o.content:[o.content]:[],c=s.some(l=>l.type==="tool_use");if(a){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(i.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},gP,n):this.request({method:"sampling/createMessage",params:e},mP,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},tb,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:i},tb,n);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new ie(ge.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof ie?o:new ie(ge.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},hP,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import dz from"node:process";var qb=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
147
147
|
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Qae(n)}clear(){this._buffer=void 0}};function Qae(t){return dM.parse(JSON.parse(t))}function uz(t){return JSON.stringify(t)+`
|
|
148
148
|
`}var Bb=class{constructor(e=dz.stdin,n=dz.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new qb,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=uz(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};var dR={name:"query_instances",description:"Query Roblox instances: get, children, find child/descendant, wait for child, class info, search by name/class. [PRO] file_tree, project_structure, descendants, ancestors, search by property/tag.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","children","find_child","find_descendant","wait_for_child","class_info","search_name","search_class","search_property","search_tag","file_tree","project_structure","descendants","ancestors"],description:"Query action to perform. Basic: get, children, find_child, find_descendant, wait_for_child, class_info, search_name, search_class. [PRO]: search_property, search_tag, file_tree, project_structure, descendants, ancestors."},path:{type:"string",description:'Instance path to query (e.g., "game.Workspace.Part"). Used by: get, children, find_child, find_descendant, wait_for_child, descendants, ancestors.'},sessionDebugId:{type:"string",description:"Optional same Studio/plugin session debug identity for resolving duplicate-named path targets. Used by: get, children, descendants, ancestors."},siblingIndex:{type:"number",description:"Optional 1-based same-name sibling index fallback for resolving duplicate-named path targets. Used by: get, children, descendants, ancestors."},childName:{type:"string",description:"Name of the child instance to find. Used by: find_child, wait_for_child."},descendantName:{type:"string",description:"Name of the descendant instance to find. Used by: find_descendant."},className:{type:"string",description:"Roblox class name. Used by: find_child/find_descendant (optional filter), class_info (required), search_class (required)."},recursive:{type:"boolean",description:"If true, returns all descendants instead of just immediate children. Used by: children. Default: false."},maxDepth:{type:"number",description:"Maximum depth for recursive traversal. Used by: children (default: 10), file_tree (default: 5)."},timeout:{type:"number",description:"Maximum time to wait in seconds. Used by: wait_for_child. Default: 5. Maximum: 30."},root:{type:"string",description:'Root path to search/scan from. Used by: search_name, search_class, search_property, search_tag, file_tree, project_structure. Default: "game".'},query:{type:"string",description:"Search pattern for name search (supports * and ? wildcards). Used by: search_name."},propertyName:{type:"string",description:"[PRO] Property name to search by. Used by: search_property."},propertyValue:{description:"[PRO] Property value to match. Used by: search_property."},tag:{type:"string",description:"[PRO] Tag string to search by (case-sensitive). Used by: search_tag."},includeServices:{type:"boolean",description:'[PRO] Include Roblox services when root is "game". Used by: file_tree. Default: true.'},includeSubclasses:{type:"boolean",description:"Include subclasses in class search (e.g., BasePart finds Part, MeshPart). Used by: search_class. Default: true."},caseSensitive:{type:"boolean",description:"Case-sensitive name search. Used by: search_name. Default: false."},maxResults:{type:"number",description:"Maximum results to return. Used by: search_name, search_class, search_property, search_tag, descendants. Default: 100."},depth:{type:"number",description:"[PRO] Maximum depth for project structure traversal. Used by: project_structure. Default: 3."},placeId:{type:"number",description:"Optional Studio target selector. When multiple Studio clients are connected, route this call to the active client for this Roblox placeId. If no matching active client exists, the call fails instead of falling back to another Place."},clientId:{type:"string",description:"Optional Studio target selector. Routes this call to the exact connected WEPPY Plugin client. Takes precedence over targetAlias and placeId."},targetAlias:{type:"string",description:"Optional Studio target selector. Routes this call to the connected WEPPY Studio target alias shown in Dashboard/Plugin, such as studio-1. Takes precedence over placeId."}},allOf:[{if:{properties:{action:{const:"get"}}},then:{required:["path"]}},{if:{properties:{action:{const:"children"}}},then:{required:["path"]}},{if:{properties:{action:{const:"find_child"}}},then:{required:["path","childName"]}},{if:{properties:{action:{const:"find_descendant"}}},then:{required:["path","descendantName"]}},{if:{properties:{action:{const:"wait_for_child"}}},then:{required:["path","childName"]}},{if:{properties:{action:{const:"class_info"}}},then:{required:["className"]}},{if:{properties:{action:{const:"search_name"}}},then:{required:["query"]}},{if:{properties:{action:{const:"search_class"}}},then:{required:["className"]}},{if:{properties:{action:{const:"search_property"}}},then:{required:["propertyName"]}},{if:{properties:{action:{const:"search_tag"}}},then:{required:["tag"]}},{if:{properties:{action:{const:"descendants"}}},then:{required:["path"]}},{if:{properties:{action:{const:"ancestors"}}},then:{required:["path"]}}],required:["action"]}};var pR={name:"mutate_instances",description:"Create, delete, clone, move, rename, or pivot instances. [PRO] create_tree, mass_create, mass_delete, mass_duplicate, smart_duplicate, scatter.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","create_with_props","delete","clone","move","rename","pivot","create_tree","mass_create","mass_delete","mass_duplicate","smart_duplicate","scatter"],description:"Mutation action. Basic: create, create_with_props, delete, clone, move, rename, pivot. [PRO]: create_tree, mass_create, mass_delete, mass_duplicate, smart_duplicate, scatter."},contextId:{type:"string",description:"Optional execution context identifier. Used to continue an existing context for mutating actions."},contextSummary:{type:"object",properties:{intent:{type:"string"},affectedAreas:{type:"array",items:{type:"object",required:["kind","target","label"],properties:{kind:{type:"string",enum:["script","instance","property","system","gameplay","ui","terrain","lighting","asset","other"]},target:{type:"string"},label:{type:"string"}}}},testScenario:{type:"string"},expectedBehavior:{type:"string"},observedBehavior:{type:"string"}},description:"Optional structured execution context attached to this tool call."},replayMetadata:{type:"object",properties:{mode:{type:"string"},timeout:{type:"number"},seed:{type:"number"},inputRefs:{type:"array",items:{type:"string"}},setupRefs:{type:"array",items:{type:"string"}},assertionRefs:{type:"array",items:{type:"string"}},artifactRefs:{type:"array",items:{type:"string"}}},description:"Optional replay-ready metadata attached to this tool call."},className:{type:"string",description:"Roblox class name (e.g., Part, Script, Folder). Used by: create, create_with_props."},parent:{type:"string",description:"Parent path for new instance. Used by: create, create_with_props."},name:{type:"string",description:"Name for the instance. Used by: create (optional), create_with_props (required)."},properties:{type:"object",description:"Properties to set on the instance. Supports Vector3, Color3, CFrame, UDim2, Enum types. Used by: create (optional), create_with_props (required).",additionalProperties:!0},path:{type:"string",description:"Instance path to operate on. Used by: delete, clone (as sourcePath), move, rename, pivot, smart_duplicate."},sessionDebugId:{type:"string",description:"Optional same Studio/plugin session debug identity for verifying a duplicate-named target. Used by: delete, clone, move, rename, pivot, smart_duplicate."},siblingIndex:{type:"number",description:"Optional 1-based same-name sibling index fallback for verifying a duplicate-named target. Used by: delete, clone, move, rename, pivot, smart_duplicate."},sourcePath:{type:"string",description:"Source instance path to clone from. Used by: clone. Alternative to path."},targetParent:{type:"string",description:"Target parent for cloned/duplicated instances. Used by: clone, mass_duplicate, smart_duplicate."},newName:{type:"string",description:"New name for instance. Used by: rename (required), clone (optional)."},newParent:{type:"string",description:"New parent path to move instance to. Used by: move."},position:{type:"object",description:"Target position as Vector3 {x, y, z}. Used by: pivot.",required:["x","y","z"],properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},cframe:{type:"array",description:"Target CFrame as 12-number array [x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22]. Used by: pivot.",minItems:12,maxItems:12,items:{type:"number"}},offset:{type:"object",description:"Relative offset to move by (ignores position/cframe). Used by: pivot, smart_duplicate.",required:["x","y","z"],properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},tree:{type:"object",description:"[PRO] Instance tree specification for hierarchical creation. Used by: create_tree.",additionalProperties:!0},instances:{type:"array",description:"[PRO] Array of instance specifications for batch creation. Used by: mass_create. Each item: {className, name, parentPath, properties?}.",items:{type:"object",required:["className","name","parentPath"],properties:{className:{type:"string"},name:{type:"string"},parentPath:{type:"string"},properties:{type:"object",additionalProperties:!0}}}},paths:{type:"array",description:"[PRO] Array of instance paths. Used by: mass_delete, mass_duplicate.",items:{type:"string"}},count:{type:"number",description:"[PRO] Number of copies to create. Used by: smart_duplicate, scatter."},templatePaths:{type:"array",description:"Template instance paths to clone. Used by: scatter. Multiple templates are picked uniformly at random.",items:{type:"string"}},region:{type:"object",description:"Placement region {min, max} in world studs (XZ used for sampling, Y bounds the ground raycast). Used by: scatter.",required:["min","max"],properties:{min:{type:"object",required:["x","y","z"],properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},max:{type:"object",required:["x","y","z"],properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}}},seed:{type:"number",description:"Deterministic placement seed. Used by: scatter."},maxSlope:{type:"number",description:"Maximum ground slope in degrees for placement. Used by: scatter. Default: 30."},avoidWater:{type:"boolean",description:"Skip points whose ground is Water. Used by: scatter. Default: true."},alignToNormal:{type:"boolean",description:"Align instances to the surface normal (yaw jitter always applies). Used by: scatter. Default: false."},scaleJitter:{type:"object",description:"Uniform scale jitter range. Used by: scatter. Default: {min: 0.85, max: 1.25}.",properties:{min:{type:"number"},max:{type:"number"}}},minSpacing:{type:"number",description:"Minimum distance between placements in studs. Used by: scatter."},parentName:{type:"string",description:"Folder name that groups the results. Used by: scatter. Default: WeppyScatter_<seed>."},placeId:{type:"number",description:"Optional Studio target selector. When multiple Studio clients are connected, route this call to the active client for this Roblox placeId. If no matching active client exists, the call fails instead of falling back to another Place."},clientId:{type:"string",description:"Optional Studio target selector. Routes this call to the exact connected WEPPY Plugin client. Takes precedence over targetAlias and placeId."},targetAlias:{type:"string",description:"Optional Studio target selector. Routes this call to the connected WEPPY Studio target alias shown in Dashboard/Plugin, such as studio-1. Takes precedence over placeId."}},allOf:[{if:{properties:{action:{const:"create"}}},then:{required:["className","parent"]}},{if:{properties:{action:{const:"create_with_props"}}},then:{required:["className","parent","name","properties"]}},{if:{properties:{action:{const:"delete"}}},then:{required:["path"]}},{if:{properties:{action:{const:"clone"}}},then:{required:["sourcePath"]}},{if:{properties:{action:{const:"move"}}},then:{required:["path","newParent"]}},{if:{properties:{action:{const:"rename"}}},then:{required:["path","newName"]}},{if:{properties:{action:{const:"pivot"}}},then:{required:["path"]}},{if:{properties:{action:{const:"create_tree"}}},then:{required:["parent","tree"]}},{if:{properties:{action:{const:"mass_create"}}},then:{required:["instances"]}},{if:{properties:{action:{const:"mass_delete"}}},then:{required:["paths"]}},{if:{properties:{action:{const:"mass_duplicate"}}},then:{required:["paths"]}},{if:{properties:{action:{const:"smart_duplicate"}}},then:{required:["path","offset"]}},{if:{properties:{action:{const:"scatter"}}},then:{required:["templatePaths","region","count"]}}],required:["action"]}};var fR={name:"manage_properties",description:"Get/set properties, attributes, and tags on instances. [PRO] set_calculated, set_relative, mass_set, mass_get, modify_children.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set","get_all","set_multiple","get_attr","set_attr","get_all_attrs","delete_attr","add_tag","remove_tag","check_tag","get_tags","get_tagged","set_calculated","set_relative","mass_set","mass_get","modify_children"],description:"Property action. Basic: get, set, get_all, set_multiple, get_attr, set_attr, get_all_attrs, delete_attr, add_tag, remove_tag, check_tag, get_tags, get_tagged. [PRO]: set_calculated, set_relative, mass_set, mass_get, modify_children."},contextId:{type:"string",description:"Optional execution context identifier. Used to continue an existing context for mutating actions."},contextSummary:{type:"object",properties:{intent:{type:"string"},affectedAreas:{type:"array",items:{type:"object",required:["kind","target","label"],properties:{kind:{type:"string",enum:["script","instance","property","system","gameplay","ui","terrain","lighting","asset","other"]},target:{type:"string"},label:{type:"string"}}}},testScenario:{type:"string"},expectedBehavior:{type:"string"},observedBehavior:{type:"string"}},description:"Optional structured execution context attached to this tool call."},replayMetadata:{type:"object",properties:{mode:{type:"string"},timeout:{type:"number"},seed:{type:"number"},inputRefs:{type:"array",items:{type:"string"}},setupRefs:{type:"array",items:{type:"string"}},assertionRefs:{type:"array",items:{type:"string"}},artifactRefs:{type:"array",items:{type:"string"}}},description:"Optional replay-ready metadata attached to this tool call."},path:{type:"string",description:"Instance path. Used by: get, set, get_all, set_multiple, get_attr, set_attr, get_all_attrs, delete_attr, add_tag, remove_tag, check_tag, get_tags, set_calculated, set_relative."},property:{type:"string",description:'Property name (e.g., "Size", "Position", "Anchored"). Used by: get, set.'},value:{description:"Value to set. Supports primitives, Vector3 {x,y,z}, Color3 {r,g,b} (0-255), CFrame (12-number array), UDim2 {xScale,xOffset,yScale,yOffset}, Enum strings. Used by: set, set_attr, set_relative."},properties:{type:"object",description:"Dictionary of property names to values. Used by: set_multiple.",additionalProperties:!0},attribute:{type:"string",description:"Attribute name. Used by: get_attr, set_attr, delete_attr."},tag:{type:"string",description:"Tag string (case-sensitive). Used by: add_tag, remove_tag, check_tag."},tagName:{type:"string",description:"Tag to search for. Used by: get_tagged."},root:{type:"string",description:"Root path to filter get_tagged results. Used by: get_tagged."},maxResults:{type:"number",description:"Maximum results for get_tagged. Default: 100."},expression:{type:"string",description:'[PRO] Mathematical expression to evaluate. Used by: set_calculated. Example: "baseValue * multiplier".'},variables:{type:"object",description:'[PRO] Variable name to value/path mapping. Used by: set_calculated. Example: {"baseValue": "workspace.Config.BaseValue", "multiplier": 2}.',additionalProperties:!0},operation:{type:"string",description:"[PRO] Mathematical operation for relative property change. Used by: set_relative.",enum:["add","subtract","multiply","divide"]},amount:{description:"[PRO] Value for relative operation. Can be number, Vector3, etc. Used by: set_relative. Alias for value in set_relative context."},paths:{type:"array",description:"[PRO] Array of instance paths for bulk operations. Used by: mass_set, mass_get.",items:{type:"string"}},parentPath:{type:"string",description:"[PRO] Parent path whose children will be modified. Used by: modify_children."},modifications:{type:"object",description:"[PRO] Properties to set on children. Used by: modify_children. Contains propertyName, propertyValue, filter, recursive.",properties:{propertyName:{type:"string",description:"Property name to set on all children."},propertyValue:{description:"Value to set on all children."},filter:{type:"string",description:"Optional class name filter for children."},recursive:{type:"boolean",description:"If true, modifies all descendants. Default: false."}}},propertyName:{type:"string",description:"[PRO] Property name for mass operations or set_calculated/set_relative. Used by: mass_set, mass_get, set_calculated, set_relative, modify_children."},propertyValue:{description:"[PRO] Property value for mass_set and modify_children."},filter:{type:"string",description:"[PRO] Class name filter for modify_children."},recursive:{type:"boolean",description:"[PRO] Modify all descendants, not just immediate children. Used by: modify_children. Default: false."},includeReadOnly:{type:"boolean",description:"Include read-only properties. Used by: get_all. Default: false."},placeId:{type:"number",description:"Optional Studio target selector. When multiple Studio clients are connected, route this call to the active client for this Roblox placeId. If no matching active client exists, the call fails instead of falling back to another Place."},clientId:{type:"string",description:"Optional Studio target selector. Routes this call to the exact connected WEPPY Plugin client. Takes precedence over targetAlias and placeId."},targetAlias:{type:"string",description:"Optional Studio target selector. Routes this call to the connected WEPPY Studio target alias shown in Dashboard/Plugin, such as studio-1. Takes precedence over placeId."}},allOf:[{if:{properties:{action:{const:"get"}}},then:{required:["path","property"]}},{if:{properties:{action:{const:"set"}}},then:{required:["path","property","value"]}},{if:{properties:{action:{const:"get_all"}}},then:{required:["path"]}},{if:{properties:{action:{const:"set_multiple"}}},then:{required:["path","properties"]}},{if:{properties:{action:{const:"get_attr"}}},then:{required:["path","attribute"]}},{if:{properties:{action:{const:"set_attr"}}},then:{required:["path","value","attribute"]}},{if:{properties:{action:{const:"get_all_attrs"}}},then:{required:["path"]}},{if:{properties:{action:{const:"delete_attr"}}},then:{required:["path","attribute"]}},{if:{properties:{action:{const:"add_tag"}}},then:{required:["path","tag"]}},{if:{properties:{action:{const:"remove_tag"}}},then:{required:["path","tag"]}},{if:{properties:{action:{const:"check_tag"}}},then:{required:["path","tag"]}},{if:{properties:{action:{const:"get_tags"}}},then:{required:["path"]}},{if:{properties:{action:{const:"get_tagged"}}},then:{required:["tagName"]}},{if:{properties:{action:{const:"set_calculated"}}},then:{required:["path","expression","propertyName"]}},{if:{properties:{action:{const:"set_relative"}}},then:{required:["path","operation","propertyName"]}},{if:{properties:{action:{const:"mass_set"}}},then:{required:["paths","propertyName","propertyValue"]}},{if:{properties:{action:{const:"mass_get"}}},then:{required:["paths","propertyName"]}},{if:{properties:{action:{const:"modify_children"}}},then:{required:["parentPath"]}}],required:["action"]}};var mR={name:"manage_scripts",description:"Manage script source code: read, write, create, delete, edit lines, search, and validate Luau syntax. [PRO] replace across scripts.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get_source","set_source","create","delete","edit_replace","edit_insert","edit_delete","search","replace","get_dependencies","validate"],description:"Script action. Basic: get_source, set_source, create, delete, edit_replace, edit_insert, edit_delete, search, get_dependencies, validate. [PRO]: replace."},contextId:{type:"string",description:"Optional execution context identifier. Used to continue an existing context for mutating actions."},contextSummary:{type:"object",properties:{intent:{type:"string"},affectedAreas:{type:"array",items:{type:"object",required:["kind","target","label"],properties:{kind:{type:"string",enum:["script","instance","property","system","gameplay","ui","terrain","lighting","asset","other"]},target:{type:"string"},label:{type:"string"}}}},testScenario:{type:"string"},expectedBehavior:{type:"string"},observedBehavior:{type:"string"}},description:"Optional structured execution context attached to this tool call."},replayMetadata:{type:"object",properties:{mode:{type:"string"},timeout:{type:"number"},seed:{type:"number"},inputRefs:{type:"array",items:{type:"string"}},setupRefs:{type:"array",items:{type:"string"}},assertionRefs:{type:"array",items:{type:"string"}},artifactRefs:{type:"array",items:{type:"string"}}},description:"Optional replay-ready metadata attached to this tool call."},path:{type:"string",description:"Path to the script instance. Used by: get_source, set_source, delete, edit_replace, edit_insert, edit_delete, search, get_dependencies, replace, validate."},source:{type:"string",description:"Script source code. Used by: set_source (required), create (optional initial source), validate (one of source or path is required)."},validate:{type:"boolean",description:"Requests full validation details when Dashboard script write validation is enabled. Used by: set_source, edit_replace, edit_insert, edit_delete."},scriptType:{type:"string",description:"Type of script to create. Used by: create.",enum:["Script","LocalScript","ModuleScript"]},parent:{type:"string",description:"Parent path for new script. Used by: create."},name:{type:"string",description:"Name for new script. Used by: create."},startLine:{type:"number",description:"Starting line number, 1-based inclusive. Used by: get_source (paired with endLine), edit_replace, edit_delete. get_source requires an integer.",minimum:1},endLine:{type:"number",description:"Ending line number, 1-based inclusive. Used by: get_source (paired with startLine), edit_replace, edit_delete. get_source requires an integer.",minimum:1},newLines:{type:"string",description:"New content to replace specified lines. Used by: edit_replace. Can be multi-line."},lines:{type:"string",description:"Content to insert after afterLine. Used by: edit_insert. Can be multi-line. Alias for content."},afterLine:{type:"number",description:"Line number after which to insert. Used by: edit_insert. Use 0 to insert at beginning."},content:{type:"string",description:"Content to insert. Used by: edit_insert. Can be multi-line."},pattern:{type:"string",description:"Search pattern (plain text or Lua pattern). Used by: search, replace."},replacement:{type:"string",description:"[PRO] Replacement text. Used by: replace."},caseSensitive:{type:"boolean",description:"Case-sensitive search. Used by: search. Default: false."},wholeWord:{type:"boolean",description:"Match whole words only. Used by: search. Default: false."},usePattern:{type:"boolean",description:"Treat pattern as Lua pattern instead of plain text. Used by: search, replace. Default: false."},dryRun:{type:"boolean",description:"[PRO] Show what would be replaced without making changes. Used by: replace. Default: false."},maxResults:{type:"number",description:"Maximum results to return. Used by: search. Default: 100."},placeId:{type:"number",description:"Optional Studio target selector. When multiple Studio clients are connected, route this call to the active client for this Roblox placeId. If no matching active client exists, the call fails instead of falling back to another Place."},clientId:{type:"string",description:"Optional Studio target selector. Routes this call to the exact connected WEPPY Plugin client. Takes precedence over targetAlias and placeId."},targetAlias:{type:"string",description:"Optional Studio target selector. Routes this call to the connected WEPPY Studio target alias shown in Dashboard/Plugin, such as studio-1. Takes precedence over placeId."}},allOf:[{if:{properties:{action:{const:"get_source"}}},then:{required:["path"]}},{if:{properties:{action:{const:"set_source"}}},then:{required:["path","source"]}},{if:{properties:{action:{const:"create"}}},then:{required:["scriptType","parent"]}},{if:{properties:{action:{const:"delete"}}},then:{required:["path"]}},{if:{properties:{action:{const:"edit_replace"}}},then:{required:["path","startLine","endLine","newLines"]}},{if:{properties:{action:{const:"edit_insert"}}},then:{required:["path","afterLine","content"]}},{if:{properties:{action:{const:"edit_delete"}}},then:{required:["path","startLine","endLine"]}},{if:{properties:{action:{const:"search"}}},then:{required:["path","pattern"]}},{if:{properties:{action:{const:"replace"}}},then:{required:["path","pattern","replacement"]}},{if:{properties:{action:{const:"get_dependencies"}}},then:{required:["path"]}}],required:["action"]}};var gR={name:"manage_ui",description:"Create / update / verify Roblox in-game UI (ScreenGui / Frame / TextLabel / \u2026). Always start with `design_brief`. For ambiguous input, it inspects Studio context and returns candidate brief patches; Do not dump enum lists at the user. Pass relevant repository evidence in `projectContext`; explicit screen job, visual thesis, forbidden defaults, tokens, and approved assets determine the direction without a built-in subject preset. `design_brief` returns a primary-view-first Design Contract and an advisory Layout Plan with neutral regions, AnchorPoint strategy, and responsive behavior; it is not a hard tree preset or style quota. A calling agent may declare provider-neutral image generation capability through `agentCapabilities`; missing or unavailable capability must use the explicit existing, user-provided, Creator Store, or assetless fallback. Keep the returned `brief_id`, `design_contract`, and `layout_plan` through creation, update, preview, and check. The asset recommendation gate considers user references, project assets, existing UI, and user-approved `manage_assets.search` intent; do not use a recommendation until the user accepts it. After each meaningful create or update, preview the representative primary view and submit a calling-agent critic verdict (`recompose`, `refine`, or `approved`) with `visualReview`. Read `primary_visual_verdict`, `functional_safe`, `responsive_requirement`, `responsive_ready`, `required_dimensions`, and `readiness` separately from mutation success. Responsive evidence blocks readiness only when the Design Contract marks it required. Read `weppy://ui-studio/guide` for the authoring workflow, `weppy://ui-studio/tokens` for optional visual examples, and `weppy://ui-studio/functional-rules` for machine-readable advisory evidence rules. Design Check permits `priority_high` only for observed functional visual failures such as meaningful overlap, unreadable content, invalid geometry, or primary-view occlusion; style-only findings remain medium or low.\n",inputSchema:{type:"object",properties:{action:{type:"string",enum:["design_brief","create_tree","update","delete","preview","check"],description:`UI action. [PRO]: design_brief, create_tree, update, delete, preview, check.
|
|
149
|
-
`},contextId:{type:"string",description:"Optional execution context identifier. Used to continue an existing context for mutating actions."},contextSummary:{type:"object",properties:{intent:{type:"string"},affectedAreas:{type:"array",items:{type:"object",required:["kind","target","label"],properties:{kind:{type:"string",enum:["script","instance","property","system","gameplay","ui","terrain","lighting","asset","other"]},target:{type:"string"},label:{type:"string"}}}},testScenario:{type:"string"},expectedBehavior:{type:"string"},observedBehavior:{type:"string"}},description:"Optional structured execution context attached to this tool call."},replayMetadata:{type:"object",properties:{mode:{type:"string"},timeout:{type:"number"},seed:{type:"number"},inputRefs:{type:"array",items:{type:"string"}},setupRefs:{type:"array",items:{type:"string"}},assertionRefs:{type:"array",items:{type:"string"}},artifactRefs:{type:"array",items:{type:"string"}}},description:"Optional replay-ready metadata attached to this tool call."},brief:{type:"object",description:"Complete or partial design_brief object. Used by: design_brief (optional; partial allowed).",properties:{purpose:{type:"string",enum:["button","HUD","menu","modal","toast","card","form"]},platform:{type:"string",enum:["mobile","desktop","console","all"]},tone:{type:"string",enum:["modern","retro","casual","dark","minimalist","playful"]},reference_assets:{type:"array",description:"User-provided reference images or Roblox asset IDs. User references outrank existing UI images and Creator Store search candidates in the asset recommendation gate.",items:{type:"object",required:["type","value"],properties:{type:{type:"string",enum:["rbxassetid","image_url"]},value:{type:"string"}}}},resolution_targets:{type:"object",properties:{primary:{type:"string",enum:["1080p","720p","1440p"]},safezone:{type:"string",enum:["tv90","mobile_notch","none"]}}},color_palette:{type:"object",description:'Use tokens_ref only when source="tokens", and custom only when source="custom". The server accepts the branch selected by source.',properties:{source:{type:"string",enum:["tokens","custom"]},tokens_ref:{type:"string",description:"Key under `palettes` in `weppy://ui-studio/tokens` (e.g. modern_dark, brutalist_concrete, cottagecore_warm). Read tokens for the full menu and each palette's mood / pairs_with / avoid_for metadata before choosing."},custom:{type:"object",additionalProperties:{type:"string"}}}},accessibility:{type:"object",properties:{min_text_size:{type:"number"},contrast_ratio:{type:"number"}}}}},projectContext:{type:"object",description:"Optional project-specific design evidence used by design_brief. Explicit user and experience evidence determines recommendations; WEPPY does not infer a subject preset.",properties:{screen_job:{type:"string"},primary_action:{type:"string"},visual_thesis:{type:"string"},signature_motif:{type:"string"},content_hierarchy:{type:"array",items:{type:"string"}},required_states:{type:"array",items:{type:"string"}},forbidden_defaults:{type:"array",items:{type:"string"}},presentation_mode:{type:"string",enum:["non_modal_overlay","modal_overlay","fullscreen_navigation","diegetic"]},focal_region:{type:"string"},responsive_requirement:{type:"string",description:"Whether responsive profile coverage is advisory or required for readiness. Defaults to recommended.",enum:["recommended","required"]},imagery_strategy:{type:"object",description:"Project evidence for required, optional, or intentionally absent imagery.",required:["family","intent","evidence"],properties:{family:{type:"string",enum:["symbol_set","content_thumbnail","identity_visual","illustrative_backdrop","diegetic_surface","no_imagery"]},intent:{type:"string",enum:["required","optional","intentional_none"]},evidence:{type:"array",items:{type:"string"}}}},surface_roles:{type:"array",items:{type:"string",enum:["primary_action","secondary_action","navigation","persistent_status","transient_status","resource_display","contextual_information","identity","spatial_information","slot_action","contextual_action","objective_tracker","decoration"]}},layout_preferences:{type:"array",description:"Optional role-specific layout preferences. Explicit user and project evidence outrank WEPPY fallback values.",items:{type:"object",required:["role"],properties:{role:{type:"string",enum:["primary_action","secondary_action","navigation","persistent_status","transient_status","resource_display","contextual_information","identity","spatial_information","slot_action","contextual_action","objective_tracker","decoration"]},placement_band:{type:"string"},flow_axis:{type:"string",enum:["row","column","radial","single","free"]},surface_mode:{type:"string",enum:["transparent_group","individual_chrome","bounded_group","shared_surface","backdrop"]},avoid_regions:{type:"array",items:{type:"string"}},wrap_policy:{type:"string",enum:["no_wrap","condense","reflow","paginate","collapse"]},decision_source:{type:"string",enum:["explicit_user","project_evidence","existing_ui","weppy_fallback"]}}}},shape_language:{type:"object",properties:{container_edges:{type:"string"},semantic_shapes:{type:"array",items:{type:"object",required:["role","intent"],properties:{role:{type:"string"},intent:{type:"string"}}}}}},target_profiles:{type:"array",items:{type:"object",required:["id","tier","viewport_class","orientation","input_modes","evidence"],properties:{id:{type:"string"},tier:{type:"string",enum:["primary","secondary","compatibility","excluded"]},viewport_class:{type:"string",enum:["small","medium","large","custom"]},width:{type:"number"},height:{type:"number"},orientation:{type:"string",enum:["portrait","landscape","any"]},input_modes:{type:"array",items:{type:"string",enum:["touch","keyboard_mouse","gamepad","mixed"]}},safe_area_policy:{type:"string"},evidence:{type:"array",items:{type:"string"}}}}},platform_distribution:{type:"array",items:{type:"object",required:["platform","evidence"],properties:{platform:{type:"string",enum:["computer","phone","tablet","console","vr","unknown"]},share:{type:"number"},evidence:{type:"string"}}}},asset_search_intent:{type:"string",description:"Optional user-approved Creator Store search intent. WEPPY does not synthesize subject queries when omitted."},design_tokens:{type:"object",additionalProperties:!0},approved_assets:{type:"array",items:{type:"object",required:["label","asset_id","review_status"],properties:{label:{type:"string"},asset_id:{type:"string"},asset_type:{type:"string",enum:["image","decal","icon","model","unknown"]},role:{type:"string"},asset_role:{type:"string"},review_status:{type:"string",enum:["approved","reviewed"]},evidence:{type:"string"}}}}}},agentCapabilities:{type:"object",description:"Optional provider-neutral capability declaration from the calling agent after it inspects callable tools and output channels. Do not infer these values from a model or client name. Used by: design_brief.",properties:{image_generation:{type:"string",enum:["available","unavailable","unknown"]},local_image_output:{type:"string",enum:["available","unavailable","unknown"]},image_review:{type:"string",enum:["available","unavailable","unknown"]},evidence:{type:"array",description:"Short non-secret evidence such as callable tool and local output channel names. Never include provider credentials.",items:{type:"string"}}}},briefId:{type:"string",description:"Accepted brief identifier returned by design_brief. Used by: create_tree/update (required), preview/check (optional)."},viewportMode:{type:"string",description:"Viewport review mode. selected_profiles uses profileIds from the accepted Design Contract. Used by: preview, check.",enum:["current","selected_profiles"]},profileIds:{type:"array",description:"Selected Design Contract target profile IDs. Used by: preview, check.",items:{type:"string"}},tree:{type:"object",description:`Declarative UI tree JSON. The root must be ScreenGui.
|
|
149
|
+
`},contextId:{type:"string",description:"Optional execution context identifier. Used to continue an existing context for mutating actions."},contextSummary:{type:"object",properties:{intent:{type:"string"},affectedAreas:{type:"array",items:{type:"object",required:["kind","target","label"],properties:{kind:{type:"string",enum:["script","instance","property","system","gameplay","ui","terrain","lighting","asset","other"]},target:{type:"string"},label:{type:"string"}}}},testScenario:{type:"string"},expectedBehavior:{type:"string"},observedBehavior:{type:"string"}},description:"Optional structured execution context attached to this tool call."},replayMetadata:{type:"object",properties:{mode:{type:"string"},timeout:{type:"number"},seed:{type:"number"},inputRefs:{type:"array",items:{type:"string"}},setupRefs:{type:"array",items:{type:"string"}},assertionRefs:{type:"array",items:{type:"string"}},artifactRefs:{type:"array",items:{type:"string"}}},description:"Optional replay-ready metadata attached to this tool call."},brief:{type:"object",description:"Complete or partial design_brief object. Used by: design_brief (optional; partial allowed).",properties:{purpose:{type:"string",enum:["button","HUD","menu","modal","toast","card","form"]},platform:{type:"string",enum:["mobile","desktop","console","all"]},tone:{type:"string",enum:["modern","retro","casual","dark","minimalist","playful"]},reference_assets:{type:"array",description:"User-provided reference images or Roblox asset IDs. User references outrank existing UI images and Creator Store search candidates in the asset recommendation gate.",items:{type:"object",required:["type","value"],properties:{type:{type:"string",enum:["rbxassetid","image_url"]},value:{type:"string"}}}},resolution_targets:{type:"object",properties:{primary:{type:"string",enum:["1080p","720p","1440p"]},safezone:{type:"string",enum:["tv90","mobile_notch","none"]}}},color_palette:{type:"object",description:'Use tokens_ref only when source="tokens", and custom only when source="custom". The server accepts the branch selected by source.',properties:{source:{type:"string",enum:["tokens","custom"]},tokens_ref:{type:"string",description:"Key under `palettes` in `weppy://ui-studio/tokens` (e.g. modern_dark, brutalist_concrete, cottagecore_warm). Read tokens for the full menu and each palette's mood / pairs_with / avoid_for metadata before choosing."},custom:{type:"object",additionalProperties:{type:"string"}}}},accessibility:{type:"object",properties:{min_text_size:{type:"number"},contrast_ratio:{type:"number"}}}}},projectContext:{type:"object",description:"Optional project-specific design evidence used by design_brief. Explicit user and experience evidence determines recommendations; WEPPY does not infer a subject preset.",properties:{screen_job:{type:"string"},primary_action:{type:"string"},visual_thesis:{type:"string"},signature_motif:{type:"string"},content_hierarchy:{type:"array",items:{type:"string"}},required_states:{type:"array",items:{type:"string"}},forbidden_defaults:{type:"array",items:{type:"string"}},presentation_mode:{type:"string",enum:["non_modal_overlay","modal_overlay","fullscreen_navigation","diegetic"]},focal_region:{type:"string"},responsive_requirement:{type:"string",description:"Whether responsive profile coverage is advisory or required for readiness. Defaults to recommended.",enum:["recommended","required"]},imagery_strategy:{type:"object",description:"Project evidence for required, optional, or intentionally absent imagery.",required:["family","intent","evidence"],properties:{family:{type:"string",enum:["symbol_set","content_thumbnail","identity_visual","illustrative_backdrop","diegetic_surface","no_imagery"]},intent:{type:"string",enum:["required","optional","intentional_none"]},evidence:{type:"array",items:{type:"string"}}}},surface_roles:{type:"array",items:{type:"string",enum:["primary_action","secondary_action","navigation","persistent_status","transient_status","resource_display","contextual_information","identity","spatial_information","slot_action","contextual_action","objective_tracker","decoration"]}},layout_preferences:{type:"array",description:"Optional role-specific layout preferences. Explicit user and project evidence outrank WEPPY fallback values.",items:{type:"object",required:["role"],properties:{role:{type:"string",enum:["primary_action","secondary_action","navigation","persistent_status","transient_status","resource_display","contextual_information","identity","spatial_information","slot_action","contextual_action","objective_tracker","decoration"]},placement_band:{type:"string"},flow_axis:{type:"string",enum:["row","column","radial","single","free"]},surface_mode:{type:"string",enum:["transparent_group","individual_chrome","bounded_group","shared_surface","backdrop"]},avoid_regions:{type:"array",items:{type:"string"}},wrap_policy:{type:"string",enum:["no_wrap","condense","reflow","paginate","collapse"]},decision_source:{type:"string",enum:["explicit_user","project_evidence","existing_ui","weppy_fallback"]},max_edge_gap_px:{type:"number",description:"Optional maximum distance from the declared safe-area edge to painted content.",minimum:0}}}},shape_language:{type:"object",properties:{container_edges:{type:"string"},semantic_shapes:{type:"array",items:{type:"object",required:["role","intent"],properties:{role:{type:"string"},intent:{type:"string"}}}}}},target_profiles:{type:"array",items:{type:"object",required:["id","tier","viewport_class","orientation","input_modes","evidence"],properties:{id:{type:"string"},tier:{type:"string",enum:["primary","secondary","compatibility","excluded"]},viewport_class:{type:"string",enum:["small","medium","large","custom"]},width:{type:"number"},height:{type:"number"},orientation:{type:"string",enum:["portrait","landscape","any"]},input_modes:{type:"array",items:{type:"string",enum:["touch","keyboard_mouse","gamepad","mixed"]}},safe_area_policy:{type:"string"},safe_area_insets_px:{type:"object",required:["top","bottom","left","right"],properties:{top:{type:"number",minimum:0},bottom:{type:"number",minimum:0},left:{type:"number",minimum:0},right:{type:"number",minimum:0}}},evidence:{type:"array",items:{type:"string"}}}}},platform_distribution:{type:"array",items:{type:"object",required:["platform","evidence"],properties:{platform:{type:"string",enum:["computer","phone","tablet","console","vr","unknown"]},share:{type:"number"},evidence:{type:"string"}}}},asset_search_intent:{type:"string",description:"Optional user-approved Creator Store search intent. WEPPY does not synthesize subject queries when omitted."},design_tokens:{type:"object",additionalProperties:!0},approved_assets:{type:"array",items:{type:"object",required:["label","asset_id","review_status"],properties:{label:{type:"string"},asset_id:{type:"string"},asset_type:{type:"string",enum:["image","decal","icon","model","unknown"]},role:{type:"string"},asset_role:{type:"string"},review_status:{type:"string",enum:["approved","reviewed"]},evidence:{type:"string"}}}}}},agentCapabilities:{type:"object",description:"Optional provider-neutral capability declaration from the calling agent after it inspects callable tools and output channels. Do not infer these values from a model or client name. Used by: design_brief.",properties:{image_generation:{type:"string",enum:["available","unavailable","unknown"]},local_image_output:{type:"string",enum:["available","unavailable","unknown"]},image_review:{type:"string",enum:["available","unavailable","unknown"]},evidence:{type:"array",description:"Short non-secret evidence such as callable tool and local output channel names. Never include provider credentials.",items:{type:"string"}}}},briefId:{type:"string",description:"Accepted brief identifier returned by design_brief. Used by: create_tree/update (required), preview/check (optional)."},viewportMode:{type:"string",description:"Viewport review mode. selected_profiles uses profileIds from the accepted Design Contract. Used by: preview, check.",enum:["current","selected_profiles"]},profileIds:{type:"array",description:"Selected Design Contract target profile IDs. Used by: preview, check.",items:{type:"string"}},tree:{type:"object",description:`Declarative UI tree JSON. The root must be ScreenGui.
|
|
150
150
|
Schema: {className: string, name?: string, parent?: string, properties?: {...}, layoutMetadata?: {...}, children?: Tree[]}
|
|
151
151
|
Omit parent to use StarterGui. className is limited to supported Roblox GUI classes: ScreenGui/Frame/TextLabel/TextButton/ImageLabel/ImageButton/ScrollingFrame/TextBox/UIListLayout/UIGridLayout/UIPadding/UICorner/UIStroke/UIAspectRatioConstraint/UIGradient/UITextSizeConstraint/UISizeConstraint/UIScale/UIFlexItem/UIShadow/UIPageLayout/UITableLayout/CanvasGroup/UIDragDetector.
|
|
152
152
|
|
|
@@ -245,7 +245,7 @@ Use a transparent group root for non-modal HUD regions. Opaque paint may remain
|
|
|
245
245
|
|
|
246
246
|
On touch profiles, keep a semantic slot bar between the touch-left and touch-right reserved regions and clear of the top inset. Prefer condense, paginate, collapse, or contextual disclosure over wrapping generic actions into a multi-row bottom-center grid.
|
|
247
247
|
|
|
248
|
-
Each region can preserve \`placement_band\`, \`flow_axis\`, \`surface_mode\`, \`avoid_regions\`, \`wrap_policy\`, and \`
|
|
248
|
+
Each region can preserve \`placement_band\`, \`flow_axis\`, \`surface_mode\`, \`avoid_regions\`, \`wrap_policy\`, \`decision_source\`, and an optional numeric \`max_edge_gap_px\`. These are advisory composition constraints, not exact coordinates or a hard tree preset. When the explicit user or approved project evidence requests a different result, preserve it and report only observed functional risk. An explicit user placement without a numeric maximum does not inherit a WEPPY edge-gap limit.
|
|
249
249
|
|
|
250
250
|
### Design Check coverage gate
|
|
251
251
|
|
|
@@ -271,6 +271,8 @@ Use target-profile recommendations for touch and focus reachability. Treat them
|
|
|
271
271
|
|
|
272
272
|
Use \`ScreenInsets\`, device simulation, and the declared target profile where available. Review critical actions and information against the actual safe area rather than assuming one global inset.
|
|
273
273
|
|
|
274
|
+
For an edge-bound semantic region, compare both the container bounds and the actual painted descendant union with the declared safe boundary. The painted union includes visible background, text, image, and \`UIStroke\` geometry after \`ClipsDescendants\`. A transparent parent can therefore be attached while its visible controls remain detached. Report this as one \`edge_detached\` finding with container, visible, and internal gap evidence. AnchorPoint mismatch alone is diagnostic evidence, not a finding.
|
|
275
|
+
|
|
274
276
|
Evaluate text against the resolved background, including transparency. Contrast and text-size values are accessibility recommendations, not visual-style quotas. If \`TextScaled\` is used, constrain it with \`UITextSizeConstraint\` and verify representative locales.
|
|
275
277
|
|
|
276
278
|
### A.3 Input disclosure and state access
|
|
@@ -831,6 +833,8 @@ evidence_contract:
|
|
|
831
833
|
layout_context:
|
|
832
834
|
presentation_source: contract presentation mode
|
|
833
835
|
reserved_region_source: target-profile reserved interaction regions
|
|
836
|
+
safe_area_source: numeric target-profile insets before named policy
|
|
837
|
+
edge_expectation_source: accepted Layout Plan
|
|
834
838
|
|
|
835
839
|
visual_review_priority_policy:
|
|
836
840
|
functional:
|
|
@@ -866,8 +870,20 @@ rules:
|
|
|
866
870
|
recommendation_source: localization_risk
|
|
867
871
|
safezone:
|
|
868
872
|
dimension: responsive_viewport
|
|
869
|
-
evidence: resolved action bounds and simulated safe area
|
|
873
|
+
evidence: resolved critical action or information painted bounds and simulated safe area
|
|
870
874
|
recommendation_source: target_profile
|
|
875
|
+
edge_detached:
|
|
876
|
+
dimension: responsive_viewport
|
|
877
|
+
evidence: semantic region container bounds and clipped painted descendant union
|
|
878
|
+
recommendation_source: accepted_layout_plan
|
|
879
|
+
one_finding_per_region: true
|
|
880
|
+
metrics:
|
|
881
|
+
- container_edge_gap_px
|
|
882
|
+
- visible_edge_gap_px
|
|
883
|
+
- internal_gap_px
|
|
884
|
+
causes:
|
|
885
|
+
- transparent_parent_gap
|
|
886
|
+
- container_detached
|
|
871
887
|
min_text_size:
|
|
872
888
|
dimension: visual_readability
|
|
873
889
|
evidence: resolved text size
|
|
@@ -894,6 +910,7 @@ non_findings:
|
|
|
894
910
|
- Offset usage without an observed failure
|
|
895
911
|
- sharp, rounded, circular, ring, pill, or mixed semantic shape by itself
|
|
896
912
|
- image presence or absence by itself
|
|
913
|
+
- AnchorPoint difference by itself without an observed edge-gap failure
|
|
897
914
|
`;function gz(){return[{uri:NR,name:"UI Studio Guide",description:"UI Studio authoring and verification guide. Read on entry to manage_ui for the advisory usability and interaction floor, neutral visual vocabulary, and evidence-based review workflow.",mimeType:"text/markdown"},{uri:jR,name:"UI Studio Tokens",description:"Design tokens \u2014 palette families (with mood / pairs_with / avoid_for metadata), spacing densities, elevation, typography families & modular scales, corner languages, motion families (embedded JSON). Referenced by design_brief.color_palette.tokens_ref.",mimeType:"application/json"},{uri:MR,name:"UI Studio Functional Rules",description:"Machine-readable advisory usability and interaction floor with functional evidence fields and non-finding boundaries.",mimeType:"application/yaml"}]}async function hz(t){if(t===NR)return{contents:[{uri:t,mimeType:"text/markdown",text:pz}]};if(t===jR)return{contents:[{uri:t,mimeType:"application/json",text:fz}]};if(t===MR)return{contents:[{uri:t,mimeType:"application/yaml",text:mz}]};throw new Error(`unknown resource URI: ${t}`)}co();var H1=Ft(bo(),1);le();ca();import*as gw from"path";import{fileURLToPath as PPe}from"url";import{randomUUID as kPe}from"crypto";import{createServer as RPe}from"http";le();function zn(t,e,n,r){let i=typeof t=="string"?parseInt(t,10):NaN,a=Number.isFinite(i)?i:e;return n!==void 0&&(a=Math.max(a,n)),r!==void 0&&(a=Math.min(a,r)),a}ca();nr();nr();Ir();import*as Nx from"fs";import*as Js from"path";function Ks(t){let e=Wye(t);return e===null?null:e===".gitignore"||e==="sourcemap.json"||/^place_[^/]+\/sourcemap\.json$/.test(e)?"generated":/(^|\/)(?:\.sync-index|\.sync-meta|\.project-meta|\.sync-config)\.json$/.test(e)||/(^|\/)observability(?:\/|$)/.test(e)||/(^|\/)\.sync-migration-(?:backups|stage)(?:\/|$)/.test(e)?"runtime":/^place_[^/]+\/explorer\/.+\.(?:server|client|module)\.luau$/.test(e)?"user_source":/^place_[^/]+\/explorer\/.+(?:_tree|\.props|\.value)\.json$/.test(e)?"canonical_mirror":null}function Wye(t){let e=t.replaceAll("\\","/").replace(/^\.\/+/,"");return e.length===0||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.split("/").includes("..")?null:e}var L5=5*60*1e3,Hye=2*60*1e3,Zye=-1;function U5(t){let e=[];for(let n of t.split(`
|
|
898
915
|
`)){let r=n.trim();if(!(!r||r.startsWith("#")))try{e.push(JSON.parse(r))}catch{}}return e}function F5(t){for(let e of t.split(`
|
|
899
916
|
`)){let n=e.trim();if(n.startsWith("# SESSION_START "))try{return JSON.parse(n.slice(16))}catch{return null}}return null}function Xr(t){let e=Date.parse(t);return Number.isFinite(e)?e:0}function CA(t,e){return Xr(t)-Xr(e)}function $x(t,e){return Xr(e)-Xr(t)}function Gye(t){return t?Js.normalize(ft(t)):null}function q5(t){return t.trim()}function B5(t){return t?t.endedAt===void 0||t.endedAt===null||t.endedAt==="":!1}function Kye(t,e){return Xr(t.startedAt)<=Xr(e)}function Jye(t){return t.metadata?.status==="active"&&B5(t.metadata)}function Yye(t){return t===void 0||t===""}function Xye(t,e){return t&&t.status==="active"&&B5(t)||!t?.status&&e?.isCurrentHistoryFile===!0&&e?.hasEndTime!==!0?"active":"completed"}function Qye(t,e){if(e.startsWith("property:")){let n=e.slice(9).trim();if(n.length>0)return`${t}.${n}`}return t}function eve(t,e){let n=t.historyManager?.getCurrentHistoryFile(e);if(!n)return null;let r=Js.basename(n);return r.endsWith(".jsonl")?r.slice(0,-6):r}function tve(t,e){return Xye(t.metadata,{isCurrentHistoryFile:e!==null&&t.entryId===e,hasEndTime:!Yye(t.endTime)})}function PA(){return{scriptsModified:0,scriptsCreated:0,instancesCreated:0,instancesDeleted:0,instancesMoved:0,propertiesChanged:0,lightingChanged:!1,terrainChanged:!1,assetsInserted:0}}function nve(t){let e=PA();for(let n of t)switch(n.category){case"script":n.changeType==="create"?e.scriptsCreated++:e.scriptsModified++;break;case"instance":n.changeType==="create"?e.instancesCreated++:n.changeType==="delete"?e.instancesDeleted++:n.changeType==="move"&&e.instancesMoved++;break;case"property":e.propertiesChanged++;break;case"lighting":e.lightingChanged=!0;break;case"terrain":e.terrainChanged=!0;break;case"asset":e.assetsInserted++;break}return e}function z5(t,e,n){return{source:t,sessionKey:e,timestamp:n.timestamp,category:n.category,changeType:n.changeType,target:n.target,summary:n.summary,confidence:n.confidence,before:n.before,details:n.details?{...n.details}:void 0,after:n.after,isSyncBootstrap:n.isSyncBootstrap,contextId:n.contextId,artifactOwnership:n.artifactOwnership,normalizedTarget:q5(n.target),normalizedChangeType:n.changeType}}function rve(t){return{category:t.category,timestamp:t.timestamp,changeType:t.changeType,target:t.target,summary:t.summary,confidence:t.confidence,...t.before!==void 0?{before:t.before}:{},...t.details?{details:t.details}:{},...t.after!==void 0?{after:t.after}:{},...t.isSyncBootstrap?{isSyncBootstrap:!0}:{},...t.contextId?{contextId:t.contextId}:{},...t.artifactOwnership?{artifactOwnership:t.artifactOwnership}:{}}}function vm(t){return[t.category,t.changeType,q5(t.target),t.timestamp,t.isSyncBootstrap===!0?"bootstrap":"normal"].join("|")}function ive(t,e){let n={timestamp:e.timestamp,target:e.target,summary:e.summary,confidence:e.confidence,details:e.details},r={...t.details??{}},i=Array.isArray(r.syncEvidence)?r.syncEvidence:[];r.syncEvidence=[...i,n],t.details=r}function ave(t){let e=[];for(let n of t){if(n.source==="sync"&&!n.isSyncBootstrap){for(let r=e.length-1;r>=0;r--){let i=e[r];if(i.sessionKey===n.sessionKey&&i.source==="tool"&&i.category===n.category&&i.normalizedTarget===n.normalizedTarget&&i.normalizedChangeType===n.normalizedChangeType&&!(Xr(n.timestamp)<Xr(i.timestamp))&&!(Xr(n.timestamp)-Xr(i.timestamp)>Hye)){ive(i,n),n.details=void 0,n.isSyncBootstrap=!1;break}}if(n.details===void 0&&!n.isSyncBootstrap)continue}e.push(n)}return e}function ove(t){return ave(t).sort((e,n)=>CA(e.timestamp,n.timestamp)).map(e=>rve(e))}function sve(t,e,n){return{category:"instance",timestamp:t,changeType:"configure",target:`sync-only:${e}`,summary:"Full sync snapshot applied",confidence:"after-only",details:{placeId:e,writeCount:n,syncOnly:!0},isSyncBootstrap:!0}}function cve(t,e){let n=typeof t.details=="string"?t.details:"",r=t.path.trim();if(t.type==="fullSyncStart"||t.type==="fullSyncComplete"||t.type==="indexRecovery")return null;if(r==="game.Lighting"||r.startsWith("game.Lighting."))return{category:"lighting",timestamp:t.timestamp,changeType:"configure",target:r,summary:`Sync lighting: ${r}`,confidence:"after-only",details:{placeId:e,syncType:t.type,syncDetails:n||void 0},...t.contextId?{contextId:t.contextId}:{}};if(r==="game.Terrain"||r.startsWith("game.Terrain.")||r==="game.Workspace.Terrain"||r.startsWith("game.Workspace.Terrain."))return{category:"terrain",timestamp:t.timestamp,changeType:"configure",target:r,summary:`Sync terrain: ${r}`,confidence:"after-only",details:{placeId:e,syncType:t.type,syncDetails:n||void 0},...t.contextId?{contextId:t.contextId}:{}};if(t.type==="delete")return{category:"instance",timestamp:t.timestamp,changeType:"delete",target:r,summary:`Sync delete instance: ${r}`,confidence:"after-only",details:{placeId:e,syncType:t.type,syncDetails:n||void 0},...t.contextId?{contextId:t.contextId}:{}};if(t.type==="rename"||t.type==="move")return{category:"instance",timestamp:t.timestamp,changeType:"move",target:r,summary:`Sync move instance: ${r}`,confidence:"after-only",details:{placeId:e,syncType:t.type,syncDetails:n||void 0},...t.contextId?{contextId:t.contextId}:{}};if(n.startsWith("script:")){let i=t.diff?.type==="script"?t.diff.scriptMeta:void 0,a=t.diff?.type==="script"?t.diff.scriptDiff:void 0,o=i?`Sync script: ${r} (${i.beforeLines??"new"} \u2192 ${i.afterLines} lines)`:`Sync script: ${r}`;return{category:"script",timestamp:t.timestamp,changeType:"modify",target:r,summary:o,confidence:a?.beforeSource!==void 0?a.beforeSource!==null?"exact":"partial":t.diff?"partial":"after-only",...a?{...a.beforeSource!==null?{before:a.beforeSource}:{},after:a.afterSource}:{after:t.diff??void 0},details:{placeId:e,syncType:t.type,syncDetails:n},...t.contextId?{contextId:t.contextId}:{}}}if(n==="props"||n==="bulk properties"||n.endsWith(".props.json")||n.startsWith("value:")||n.startsWith("property:")){let i=Qye(r,n),a=t.diff?.type==="props"?t.diff.changedProperties:void 0,o=t.diff?.type==="value"?t.diff.valueDiff:void 0,s=a?Object.keys(a):[],c=s.length>0?`Sync property: ${i} [${s.join(", ")}]`:`Sync property: ${i}`,l=o?`Sync value: ${i} (${String(o.before)} \u2192 ${String(o.after)})`:`Sync property: ${i}`,u=t.diff?.type==="value"?l:c;return{category:"property",timestamp:t.timestamp,changeType:"modify",target:i,summary:u,confidence:t.diff?"exact":"after-only",...o?{before:o.before,after:o.after}:{after:t.diff??void 0},details:{placeId:e,syncType:t.type,syncDetails:n||void 0},...t.contextId?{contextId:t.contextId}:{}}}return{category:"instance",timestamp:t.timestamp,changeType:"modify",target:r,summary:`Sync instance: ${r}`,confidence:"after-only",details:{placeId:e,syncType:t.type,syncDetails:n||void 0},...t.contextId?{contextId:t.contextId}:{}}}function V5(t){return t.artifactOwnership??(t.artifactPath?Ks(t.artifactPath):null)}function lve(t,e){let n=V5(t);if(n==="runtime")return null;let r=cve(t,e);return!r||!n?r:{...r,artifactOwnership:n}}function uve(t,e,n){return n<=0?null:sve(e,t,n)}function dve(t,e){let n=[],r=null,i=0,a=()=>{if(!r)return;let o=uve(e,r,i);o&&n.push(o),r=null,i=0};for(let o of t){if(o.type==="indexRecovery"||o.type!=="fullSyncStart"&&o.type!=="fullSyncComplete"&&V5(o)==="runtime")continue;if(o.type==="fullSyncStart"){a(),r=o.timestamp,i=0;continue}if(o.type==="fullSyncComplete"){a();continue}if(r){i++;continue}let s=lve(o,e);s&&n.push(s)}return a(),n}async function kA(t){try{return await Nx.promises.readFile(t,"utf-8")}catch{return null}}async function pve(t){let e=t.syncController?.getDefaultRuntimePlaceId();if(typeof e=="number"&&Number.isFinite(e))return e;let n=[...t.pluginClients.values()].filter(s=>typeof s.placeId=="number"&&Number.isFinite(s.placeId)).sort((s,c)=>c.lastSeen-s.lastSeen)[0];if(n?.placeId!==void 0)return n.placeId;let r=t.historyManager?.getCurrentHistoryFile();if(!r)return null;let i=await kA(r);if(!i)return null;let o=F5(i)?.placeId;return typeof o=="number"&&Number.isFinite(o)?o:null}async function fve(t,e){let n=[];try{n=await Nx.promises.readdir(t)}catch{return[]}let r=n.filter(a=>a.endsWith(".jsonl")).sort().reverse(),i=[];for(let a of r){let o=Js.join(t,a),s=await kA(o);if(!s)continue;let c=F5(s),l=U5(s),u=e(l),d=c?.startedAt??c?.startTime??l[0]?.timestamp??"",p=typeof c?.endedAt=="string"&&c.endedAt.length>0?c.endedAt:void 0,f=typeof c?.placeId=="number"?c.placeId:null;i.push({entryId:a.replace(/\.jsonl$/,""),sessionId:c?.sessionId??a.replace(/\.jsonl$/,""),placeId:f,startedAt:d,endTime:p,metadata:c,entries:l,changes:u})}return i}async function mve(t){let e=Gye(t);if(!e)return[];let n=[],r=[];try{r=await Nx.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let i=r.filter(a=>a.isDirectory()&&/^place_\d+/.test(a.name));for(let a of i){let o=a.name.match(/^place_(\d+)/),s=o?Number.parseInt(o[1],10):NaN;if(!Number.isFinite(s))continue;let c=Js.join(e,a.name,"observability","sync","history.jsonl"),l=await kA(c);if(!l)continue;let u=U5(l);if(u.length===0)continue;let d=`sync-only:${s}`;n.push({entryId:d,sessionId:d,placeId:s,startedAt:u[0].timestamp,status:"completed",entries:u})}return n}function gve(t,e){return e?t.find(n=>n.entryId===e)??null:null}function hve(t,e,n,r){let i=t.filter(o=>o.placeId===r&&Jye(o)).sort((o,s)=>{let c=$x(o.startedAt,s.startedAt);return c!==0?c:o.sessionId.localeCompare(s.sessionId)});if(i.length>0)return i;let a=gve(t,e);return a?n===r&&(a.placeId===r||a.placeId===null)?[a]:n===null&&a.placeId===null?[a]:[]:[]}function yve(t){let e=new Map;for(let n of t){if(n.status!=="active")continue;let r=n.placeId??Zye,i=e.get(r)??[];i.push(n),e.set(r,i)}for(let n of e.values()){n.sort((r,i)=>{let a=$x(r.startedAt,i.startedAt);return a!==0?a:r.sessionId.localeCompare(i.sessionId)});for(let r=1;r<n.length;r++)n[r].status="completed"}}function vve(t,e){let n=Xr(e),r=new Date(Math.floor(n/L5)*L5).toISOString();return`sync-only:${t}:${r}`}function bve(t){let e=new Map;for(let r of t){let i=new Map;for(let a of r.entries){let o=vve(r.placeId,a.timestamp),s=i.get(o)??[];s.push(a),i.set(o,s)}for(let[a,o]of i.entries()){let s=o[0]?.timestamp??r.startedAt,c=e.get(a);if(c){c.entries.push(...o),c.entries.sort((l,u)=>CA(l.timestamp,u.timestamp));continue}e.set(a,{entryId:a,sessionId:a,placeId:r.placeId,startedAt:s,status:"completed",entries:[...o].sort((l,u)=>CA(l.timestamp,u.timestamp))})}}return[...e.values()]}function _ve(t,e,n,r){let i=new Map;for(let s of t){let c={entryId:s.entryId,sessionId:s.sessionId,placeId:s.placeId,startedAt:s.startedAt,endTime:s.endTime,status:tve(s,n),metadata:s.metadata,toolEntries:[...s.entries],syncEntries:[],toolChanges:[...s.changes],changes:[],changeSummary:PA()};i.set(c.entryId,c)}let a=bve(e);for(let s of a){let c=hve(t,n,r,s.placeId),l=[];for(let u of s.entries){let d=c.find(p=>Kye(p,u.timestamp))??null;if(d){let p=i.get(d.entryId);if(p){p.syncEntries.push(u),p.placeId===null&&(p.placeId=s.placeId);continue}}l.push(u)}l.length!==0&&i.set(s.entryId,{entryId:s.entryId,sessionId:s.sessionId,placeId:s.placeId,startedAt:s.startedAt,status:s.status,metadata:{sessionId:s.sessionId,startTime:s.startedAt,totalCommands:l.length,pid:process.pid,version:"sync-only",placeId:s.placeId,startedAt:s.startedAt,status:s.status},toolEntries:[],syncEntries:l,toolChanges:[],changes:[],changeSummary:PA()})}for(let s of i.values()){let c=dve(s.syncEntries,s.placeId??0),l=ove([...s.toolChanges.map(u=>z5("tool",s.entryId,u)),...c.map(u=>z5("sync",s.entryId,u))]);s.changes=l,s.changeSummary=nve(l)}let o=[...i.values()].filter(s=>s.changes.length>0);yve(o);for(let s of o)s.status!=="active"&&(s.endTime=s.endTime??[...s.toolEntries,...s.syncEntries].map(c=>"timestamp"in c?c.timestamp:"").filter(Boolean).sort($x)[0]);return o.sort((s,c)=>{let l=$x(s.startedAt,c.startedAt);return l!==0?l:c.entryId.localeCompare(s.entryId)}),o}async function xve(t,e){if(!t.historyManager)return{sessions:[],currentPlaceId:null};let n=await pve(t),r=qn(t,n),i=await t.historyManager.getHistoryDir(n,r),a=await fve(i,e),o=await mve(t.config.dataDir),s=eve(t,n??void 0);return{sessions:_ve(a,o,s,n),currentPlaceId:n}}async function To(t,e){return xve(t,e)}function Ys(t,e){if(e?.entryId)return t.sessions.find(r=>r.entryId===e.entryId)??null;let n=e?.placeId;if(n!=null){let r=t.sessions.filter(a=>a.placeId===n);if(r.length>0)return r.find(a=>a.status==="active")??r[0]??null;let i=t.sessions.find(a=>a.status==="active");if(i)return i}return t.sessions[0]??null}function Sve(){return{scriptsModified:0,scriptsCreated:0,instancesCreated:0,instancesDeleted:0,instancesMoved:0,propertiesChanged:0,lightingChanged:!1,terrainChanged:!1,assetsInserted:0}}var wve=new Set(["manage_terrain_fill_block","manage_terrain_fill_ball","manage_terrain_fill_cylinder","manage_terrain_fill_wedge","manage_terrain_clear_region","manage_terrain_clear_bounds","manage_terrain_replace_material","manage_terrain_colors_set","manage_terrain_write_voxels","manage_terrain_generate","manage_terrain_smooth"]),Ive=new Set(["execute_luau","manage_selection","manage_sync","manage_logs","manage_camera","system_info"]),Cve=new Set(["manage_terrain_colors_get","manage_terrain_read_voxel","manage_terrain_read_voxels"]);function Pve(t){let e=t.tool,n=t.command;return!e||!n||Ive.has(e)||Cve.has(n)?null:{tool:e,command:n}}function kve(t){return typeof t.contextId=="string"&&t.contextId.length>0?t.contextId:typeof t.parameters?.contextId=="string"&&t.parameters.contextId.length>0?t.parameters.contextId:null}function Rve(t,e){if(!e)return null;let n=kve(t);if(!n)return e;let r=i=>({...i,contextId:n});return Array.isArray(e)?e.map(r):r(e)}function jx(t){return Array.isArray(t)?t.length:0}function Su(t){return t.result??{}}function Mx(t,e){let n=Su(t),r=!1;for(let i of e){if(!Object.prototype.hasOwnProperty.call(n,i))continue;r=!0;let a=n[i];if(typeof a=="number"&&Number.isFinite(a))return a;if(Array.isArray(a))return a.length}return r?0:null}function Eve(t){let e=Mx(t,["successCount","created"]);if(e!==null)return e;let n=t.parameters;return jx(n.instances)}function Tve(t){let e=Mx(t,["successCount","deleted"]);if(e!==null)return e;let n=t.parameters;return jx(n.paths)}function Ave(t){let e=Mx(t,["successCount","duplicated"]);if(e!==null)return e;let n=t.parameters;return jx(n.paths)}function Ove(t){let e=Mx(t,["count","duplicated","successCount"]);if(e!==null)return e;let n=t.parameters;return typeof n.count=="number"?n.count:0}function Dve(t){let e=Su(t);if(Array.isArray(e.results)){let n=0;for(let r of e.results){if(!r||typeof r!="object")continue;let i=r;if(!(i.updated===!0||i.wouldUpdate===!0))continue;let o=i.replacements;typeof o=="number"&&Number.isFinite(o)?n+=o:n+=1}return n}return typeof e.totalReplacements=="number"&&Number.isFinite(e.totalReplacements)?e.totalReplacements:null}function $ve(t){let e=Su(t);if(!Array.isArray(e.results))return null;let n=e.results.filter(r=>{if(!r||typeof r!="object")return!1;let i=r;return Object.prototype.hasOwnProperty.call(i,"updated")?i.updated===!0:Object.prototype.hasOwnProperty.call(i,"wouldUpdate")?i.wouldUpdate===!0:Object.prototype.hasOwnProperty.call(i,"success")?i.success!==!1:!0});return n.length>0?n:null}function W5(t){let e=Su(t);if(Array.isArray(e.updated))return e.updated;if(Array.isArray(e.results))return e.results.filter(r=>{if(!r||typeof r!="object")return!0;let i=r;return Object.prototype.hasOwnProperty.call(i,"success")?i.success!==!1:Object.prototype.hasOwnProperty.call(i,"failed")?!i.failed:!0});let n=t.parameters;return Array.isArray(n.paths)?n.paths:[]}function Nve(t){let e=Su(t);if(typeof e.successCount=="number"&&Number.isFinite(e.successCount))return e.successCount;if(Array.isArray(e.updated))return e.updated.length;if(Array.isArray(e.results))return W5(t).length;let n=t.parameters;return jx(n.paths)}function xu(t,e){let n=[];for(let r=0;r<t;r++)n.push(e(r));return n}function jve(t){let e=Pve(t);if(!e)return null;let{tool:n,command:r}=e,i=r!==n&&r.startsWith(`${n}_`)?r.slice(n.length+1):"",a=`${n}.${i}`,o=t.parameters??{},s=Su(t),c=o.path??"",l=o.lines??o.content??s.lines??s.content??o.newLines,u=s.lines??s.content??s.deletedLines??s.deletedContent??o.lines??o.content;if(a==="manage_scripts.replace"&&o.dryRun===!0)return null;switch(a){case"manage_scripts.set_source":case"manage_scripts.delete":return{category:"script",timestamp:t.timestamp,changeType:a==="manage_scripts.delete"?"delete":"modify",target:c,summary:a==="manage_scripts.delete"?`Delete script: ${c}`:`Modify script source: ${c}`,confidence:a==="manage_scripts.delete"?"intent-only":"exact",before:s.previousSource,after:o.source};case"manage_scripts.edit_replace":case"manage_scripts.replace":if(a==="manage_scripts.replace"){let d=$ve(t);if(d)return xu(d.length,f=>{let m=d[f]??{},g=m.path??c;return{category:"script",timestamp:t.timestamp,changeType:"modify",target:g,summary:`Batch replace in script: ${g}`,confidence:"exact",before:m.replacedLines??s.replacedLines,after:o.replacement,details:{pattern:o.pattern,replacement:o.replacement,batchIndex:f,replacements:m.replacements,result:m}}});if(Dve(t)===0)return null}return{category:"script",timestamp:t.timestamp,changeType:"modify",target:c,summary:a==="manage_scripts.replace"?`Batch replace in script: ${c}`:`Edit script lines: ${c}`,confidence:"exact",before:s.replacedLines,after:a==="manage_scripts.replace"?o.replacement:o.newLines,...a==="manage_scripts.replace"?{details:{pattern:o.pattern,replacement:o.replacement}}:{}};case"manage_scripts.edit_insert":return{category:"script",timestamp:t.timestamp,changeType:"modify",target:c,summary:`Insert script lines: ${c}`,confidence:"exact",after:l};case"manage_scripts.edit_delete":return{category:"script",timestamp:t.timestamp,changeType:"modify",target:c,summary:`Delete script lines: ${c}`,confidence:"exact",before:u};case"manage_scripts.create":return{category:"script",timestamp:t.timestamp,changeType:"create",target:c,summary:`Create script: ${c}`,confidence:"exact",after:o.source};case"mutate_instances.create":return{category:"instance",timestamp:t.timestamp,changeType:"create",target:c,className:o.className,summary:`Create instance: ${o.className??"Instance"} at ${c}`,confidence:"exact"};case"mutate_instances.create_tree":return{category:"instance",timestamp:t.timestamp,changeType:"create",target:c,summary:`Create instance tree: ${c}`,confidence:"exact",details:{tree:o.tree}};case"mutate_instances.mass_create":return xu(Eve(t),d=>{let f=(Array.isArray(s.created)?s.created:Array.isArray(o.instances)?o.instances:[])[d]??{},m=f.parentPath??f.parent??o.parent??c,g=f.name??`item-${d+1}`,y=`${m}.${g}`;return{category:"instance",timestamp:t.timestamp,changeType:"create",target:y,summary:`Mass create instance: ${y}`,confidence:"exact",details:{batchIndex:d,instance:f}}});case"mutate_instances.delete":return{category:"instance",timestamp:t.timestamp,changeType:"delete",target:c,summary:`Delete instance: ${c}`,confidence:"intent-only"};case"mutate_instances.move":case"mutate_instances.rename":case"mutate_instances.pivot":return{category:"instance",timestamp:t.timestamp,changeType:"move",target:c,summary:a==="mutate_instances.rename"?`Rename instance: ${c} \u2192 ${o.newName??""}`:a==="mutate_instances.pivot"?`Pivot instance: ${c}`:`Move instance: ${c} \u2192 ${o.newParent??""}`,confidence:a==="mutate_instances.rename"?"exact":"partial",after:a==="mutate_instances.rename"?o.newName:a==="mutate_instances.pivot"?{position:o.position,cframe:o.cframe,offset:o.offset}:o.newParent};case"mutate_instances.clone":return{category:"instance",timestamp:t.timestamp,changeType:"create",target:c,summary:`Clone instance: ${c}`,confidence:"exact"};case"mutate_instances.mass_delete":return xu(Tve(t),d=>{let p=Array.isArray(s.deleted)?s.deleted:Array.isArray(o.paths)?o.paths:[],f=p[d],m=typeof f=="string"?f:f?.path??f?.newPath??p[d]??c;return{category:"instance",timestamp:t.timestamp,changeType:"delete",target:m,summary:`Mass delete instance: ${m}`,confidence:"intent-only",details:{batchIndex:d}}});case"mutate_instances.mass_duplicate":return xu(Ave(t),d=>{let p=Array.isArray(s.duplicated)?s.duplicated:Array.isArray(o.paths)?o.paths:[],f=p[d],m=typeof f=="string"?f:f?.newPath??f?.path??p[d]??c;return{category:"instance",timestamp:t.timestamp,changeType:"create",target:m,summary:`Mass duplicate instance: ${m}`,confidence:"exact",details:{batchIndex:d}}});case"mutate_instances.smart_duplicate":{let d=Ove(t);return xu(d,p=>({category:"instance",timestamp:t.timestamp,changeType:"create",target:c,summary:`Smart duplicate instance: ${c}`,confidence:"exact",details:{batchIndex:p,count:d}}))}case"manage_properties.set":return{category:"property",timestamp:t.timestamp,changeType:"modify",target:`${c}.${o.property??""}`,summary:`Set property: ${c}.${o.property??""}`,confidence:"exact",before:s.previousValue??s.oldValue,after:o.value};case"manage_properties.mass_set":{let d=W5(t),p=Nve(t);if(p<=0)return null;let f=o.propertyName??s.propertyName??"",m=Object.prototype.hasOwnProperty.call(o,"propertyValue")?o.propertyValue:s.propertyValue,g=Array.isArray(o.paths)?o.paths:[];return xu(p,y=>{let v=d[y],b=typeof v=="string"?v:v?.path??g[y]??c,x=typeof v=="object"&&v&&v.propertyName?v.propertyName:f,I=typeof v=="object"&&v?v.newValue??v.value??v.propertyValue??m:m,w=b&&x?`${b}.${x}`:b||c;return{category:"property",timestamp:t.timestamp,changeType:"modify",target:w,summary:`Mass set property: ${w}`,confidence:"exact",before:typeof v=="object"&&v?v.previousValue??v.oldValue:void 0,after:I,details:{batchIndex:y,propertyName:x,propertyValue:I}}})}case"manage_assets.insert":case"manage_assets.insert_free":case"manage_assets.insert_package":case"manage_assets.search_insert":return{category:"asset",timestamp:t.timestamp,changeType:"create",target:s.path??c,summary:`Insert asset: ${o.assetId??o.query??"unknown"}`,confidence:"exact",details:{assetId:o.assetId,query:o.query}};default:return n==="manage_lighting"?{category:"lighting",timestamp:t.timestamp,changeType:"configure",target:`Lighting.${i}`,summary:`Configure lighting: ${i}`,confidence:"after-only",details:o}:n==="manage_terrain"&&wve.has(r)?{category:"terrain",timestamp:t.timestamp,changeType:"configure",target:`Terrain.${i}`,summary:`Configure terrain: ${i}`,confidence:"after-only",details:o}:null}}function fa(t){let e=[];for(let n of t){let r=Rve(n,jve(n));r&&(Array.isArray(r)?e.push(...r):e.push(r))}return e}function RA(t){let e=Sve();for(let n of t)if(!n.isSyncBootstrap)switch(n.category){case"script":n.changeType==="create"?e.scriptsCreated++:e.scriptsModified++;break;case"instance":n.changeType==="create"?e.instancesCreated++:n.changeType==="delete"?e.instancesDeleted++:n.changeType==="move"&&e.instancesMoved++;break;case"property":e.propertiesChanged++;break;case"lighting":e.lightingChanged=!0;break;case"terrain":e.terrainChanged=!0;break;case"asset":e.assetsInserted++;break}return e}function Mve(t,e,n){if(e.startsWith("sync-only:"))return!1;let r=Yr(t);return e===t.sessionId&&(n===void 0||n===r)}function EA(t,e){let n=new Map;for(let r of e){let i=n.get(r.entryId)??[];i.push(r),n.set(r.entryId,i)}return[...n.entries()].map(([r,i])=>{let a=[...i].sort((c,l)=>c.timestamp.localeCompare(l.timestamp)),o=a.map(c=>c.change),s=Mve(t,a[0]?.sessionId??r,a[0]?.placeId)?"active":"completed";return{entryId:r,sessionId:a[0]?.sessionId??r,...a[0]?.placeId!==void 0?{placeId:a[0]?.placeId}:{},startTime:a[0]?.timestamp??"",endTime:s==="completed"?a[a.length-1]?.timestamp:void 0,status:s,changes:o,changeSummary:RA(o),isBootstrapOnly:o.length>0&&o.every(c=>c.isSyncBootstrap===!0)}}).filter(r=>r.changes.length>0).sort((r,i)=>i.startTime.localeCompare(r.startTime))}function TA(t){return{entryId:t.entryId,sessionId:t.sessionId,...t.placeId!==null?{placeId:t.placeId}:{},startTime:t.startedAt,endTime:t.endTime,status:t.status,changes:t.changes,changeSummary:t.changeSummary,isBootstrapOnly:t.changes.length>0&&t.changes.every(e=>e.isSyncBootstrap===!0)}}function AA(t,e){return e===null?!0:t.placeId===void 0||t.placeId===e}function Lve(t,e){return t.map(TA).filter(n=>AA(n,e))}function Lx(t,e){let n=Ai(e.query?.placeId),r=pa(t,n);return{placeId:r,placeName:qn(t,r)}}function H5(t){return async(e,n)=>{try{let r=zn(e.query.limit,10,void 0,50),i=zn(e.query.offset,0),a=e.query.status,{placeId:o,placeName:s}=Lx(t,e),c=EA(t,await Zs(t,o,s));c.length===0&&t.historyManager&&(c=Lve((await To(t,fa)).sessions,o));let l=a?c.filter(m=>m.status===a):c,u=l.length,d=l.slice(i,i+r),p=i+r<u,f=await Gs(t,o,s);n.json({entries:d.map(m=>({entryId:m.entryId,startTime:m.startTime,...m.endTime?{endTime:m.endTime}:{},status:m.status,changeSummary:m.changeSummary,...Ox(m.changes,f)??{},...m.changes.length>0&&m.changes.every(g=>g.isSyncBootstrap===!0)?{isBootstrapOnly:!0}:{}})),total:u,hasMore:p})}catch(r){h.error("\uCCB4\uC778\uC9C0\uB85C\uADF8 \uBAA9\uB85D \uC870\uD68C \uC2E4\uD328",r),n.status(500).json({error:"Failed to get changelog list"})}}}function Z5(t){return async(e,n)=>{try{let r=e.params.id;if(!r){n.status(404).json({error:"Not found"});return}let{placeId:i,placeName:a}=Lx(t,e),o=EA(t,await Zs(t,i,a)).find(l=>l.entryId===r);if(!o&&t.historyManager){let l=Ys(await To(t,fa),{entryId:r});if(l){let u=TA(l);AA(u,i)&&(o=u)}}if(!o){n.status(404).json({error:"Changelog entry not found"});return}let s=await Gs(t,i,a),c=Ox(o.changes,s);n.json({entryId:r,startTime:o.startTime,...o.endTime?{endTime:o.endTime}:{},status:o.status,entries:[],failures:[],...c??{},metadata:{sessionId:o.sessionId,startTime:o.startTime,totalCommands:o.changes.length,pid:process.pid,version:"changelog-sessions"}})}catch(r){h.error("\uCCB4\uC778\uC9C0\uB85C\uADF8 \uC0C1\uC138 \uC870\uD68C \uC2E4\uD328",r),n.status(500).json({error:"Failed to get changelog detail"})}}}function G5(t){return async(e,n)=>{try{let r=e.params.id;if(!r){n.status(404).json({error:"Not found"});return}let{placeId:i,placeName:a}=Lx(t,e),o=EA(t,await Zs(t,i,a)).find(c=>c.entryId===r);if(!o&&t.historyManager){let c=Ys(await To(t,fa),{entryId:r});if(c){let l=TA(c);AA(l,i)&&(o=l)}}if(!o){n.status(404).json({error:"Changelog entry not found"});return}let s=await Gs(t,i,a);n.json({changes:o.changes.map(c=>Eo(c,s))})}catch(r){h.error("\uCCB4\uC778\uC9C0\uB85C\uADF8 \uBCC0\uACBD \uCD94\uCD9C \uC2E4\uD328",r),n.status(500).json({error:"Failed to extract changes"})}}}function K5(t){return async(e,n)=>{try{let{placeId:r,placeName:i}=Lx(t,e);if(t.projectChangesCleanupScheduler&&typeof r=="number"&&Number.isFinite(r)){let o=await t.projectChangesCleanupScheduler.clearPlace(r);n.json({ok:!0,target:"changelog",placeId:r,clearedCount:o.removedSessionCount,compactedContextCount:o.compactedContextCount,afterUsage:o.afterUsage});return}let a=await IA(t,r,i);n.json({ok:!0,target:"changelog",placeId:r,clearedCount:a})}catch(r){h.error("\uCCB4\uC778\uC9C0\uB85C\uADF8 \uC0AD\uC81C \uC2E4\uD328",r),n.status(500).json({error:"Failed to clear changelog"})}}}import GA from"path";import{promises as KA}from"fs";var wu=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Y5=new Set,OA=typeof process=="object"&&process?process:{},X5=(t,e,n,r)=>{typeof OA.emitWarning=="function"?OA.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},zx=globalThis.AbortController,J5=globalThis.AbortSignal;if(typeof zx>"u"){J5=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,i){this._onabort.push(i)}},zx=class{constructor(){e()}signal=new J5;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let i of this.signal._onabort)i(r);this.signal.onabort?.(r)}}};let t=OA.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,X5("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var zve=t=>!Y5.has(t),Rqe=Symbol("type"),Ao=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Q5=t=>Ao(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Iu:null:null,Iu=class extends Array{constructor(e){super(e),this.fill(0)}},DA=class t{heap;length;static#c=!1;static create(e){let n=Q5(e);if(!n)return[];t.#c=!0;let r=new t(e,n);return t.#c=!1,r}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Cu=class t{#c;#d;#g;#h;#T;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#r;#n;#e;#l;#p;#s;#a;#v;#o;#b;#_;#f;#x;#P;#u;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#f,sizes:e.#b,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#l,prev:e.#p,get head(){return e.#s},get tail(){return e.#a},free:e.#v,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,i,a)=>e.#$(n,r,i,a),moveToTail:n=>e.#E(n),indexes:n=>e.#S(n),rindexes:n=>e.#w(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#d}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#T}get memoMethod(){return this.#A}get dispose(){return this.#g}get disposeAfter(){return this.#h}constructor(e){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:p,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:g,fetchMethod:y,memoMethod:v,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:x,allowStaleOnFetchRejection:I,allowStaleOnFetchAbort:w,ignoreFetchAbort:N}=e;if(n!==0&&!Ao(n))throw new TypeError("max option must be a nonnegative integer");let k=n?Q5(n):Array;if(!k)throw new Error("invalid max value: "+n);if(this.#c=n,this.#d=f,this.maxEntrySize=m||this.#d,this.sizeCalculation=g,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#A=v,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#T=y,this.#P=!!y,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#l=new k(n),this.#p=new k(n),this.#s=0,this.#a=0,this.#v=DA.create(n),this.#i=0,this.#y=0,typeof l=="function"&&(this.#g=l),typeof u=="function"?(this.#h=u,this.#o=[]):(this.#h=void 0,this.#o=void 0),this.#x=!!this.#g,this.#u=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!I,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!N,this.maxEntrySize!==0){if(this.#d!==0&&!Ao(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!Ao(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!x,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=Ao(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!Ao(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#c===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#d){let V="LRU_CACHE_UNBOUNDED";zve(V)&&(Y5.add(V),X5("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",V,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#N(){let e=new Iu(this.#c),n=new Iu(this.#c);this.#f=e,this.#_=n,this.#j=(a,o,s=wu.now())=>{if(n[a]=o!==0?s:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(a)&&this.#I(this.#n[a],"expire")},o+1);c.unref&&c.unref()}},this.#k=a=>{n[a]=e[a]!==0?wu.now():0},this.#C=(a,o)=>{if(e[o]){let s=e[o],c=n[o];if(!s||!c)return;a.ttl=s,a.start=c,a.now=r||i();let l=a.now-c;a.remainingTTL=s-l}};let r=0,i=()=>{let a=wu.now();if(this.ttlResolution>0){r=a;let o=setTimeout(()=>r=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#r.get(a);if(o===void 0)return 0;let s=e[o],c=n[o];if(!s||!c)return 1/0;let l=(r||i())-c;return s-l},this.#m=a=>{let o=n[a],s=e[a];return!!s&&!!o&&(r||i())-o>s}}#k=()=>{};#C=()=>{};#j=()=>{};#m=()=>!1;#F(){let e=new Iu(this.#c);this.#y=0,this.#b=e,this.#R=n=>{this.#y-=e[n],e[n]=0},this.#M=(n,r,i,a)=>{if(this.#t(r))return 0;if(!Ao(i))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(i=a(r,n),!Ao(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#O=(n,r,i)=>{if(e[n]=r,this.#d){let a=this.#d-e[n];for(;this.#y>a;)this.#D(!0)}this.#y+=e[n],i&&(i.entrySize=r,i.totalCalculatedSize=this.#y)}}#R=e=>{};#O=(e,n,r)=>{};#M=(e,n,r,i)=>{if(r||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#a;!(!this.#L(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#p[n]}*#w({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#s;!(!this.#L(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#l[n]}#L(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#w())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#w()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#w())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let i=this.#e[r],a=this.#t(i)?i.__staleWhileFetching:i;if(a!==void 0&&e(a,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let i=this.#e[r],a=this.#t(i)?i.__staleWhileFetching:i;a!==void 0&&e.call(n,a,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#w()){let i=this.#e[r],a=this.#t(i)?i.__staleWhileFetching:i;a!==void 0&&e.call(n,a,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#w({allowStale:!0}))this.#m(n)&&(this.#I(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],i=this.#t(r)?r.__staleWhileFetching:r;if(i===void 0)return;let a={value:i};if(this.#f&&this.#_){let o=this.#f[n],s=this.#_[n];if(o&&s){let c=o-(wu.now()-s);a.ttl=c,a.start=Date.now()}}return this.#b&&(a.size=this.#b[n]),a}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;if(a===void 0||r===void 0)continue;let o={value:a};if(this.#f&&this.#_){o.ttl=this.#f[n];let s=wu.now()-this.#_[n];o.start=Math.floor(Date.now()-s)}this.#b&&(o.size=this.#b[n]),e.unshift([r,o])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let i=Date.now()-r.start;r.start=wu.now()-i}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:c}=r,{noUpdateTTL:l=this.noUpdateTTL}=r,u=this.#M(e,n,r.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#I(e,"set"),this;let d=this.#i===0?void 0:this.#r.get(e);if(d===void 0)d=this.#i===0?this.#a:this.#v.length!==0?this.#v.pop():this.#i===this.#c?this.#D(!1):this.#i,this.#n[d]=e,this.#e[d]=n,this.#r.set(e,d),this.#l[this.#a]=d,this.#p[d]=this.#a,this.#a=d,this.#i++,this.#O(d,u,c),c&&(c.set="add"),l=!1;else{this.#E(d);let p=this.#e[d];if(n!==p){if(this.#P&&this.#t(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#x&&this.#g?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"]))}else o||(this.#x&&this.#g?.(p,e,"set"),this.#u&&this.#o?.push([p,e,"set"]));if(this.#R(d),this.#O(d,u,c),this.#e[d]=n,c){c.set="replace";let f=p&&this.#t(p)?p.__staleWhileFetching:p;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(i!==0&&!this.#f&&this.#N(),this.#f&&(l||this.#j(d,i,a),c&&this.#C(c,d)),!o&&this.#u&&this.#o){let p=this.#o,f;for(;f=p?.shift();)this.#h?.(...f)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#s];if(this.#D(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#o){let e=this.#o,n;for(;n=e?.shift();)this.#h?.(...n)}}}#D(e){let n=this.#s,r=this.#n[n],i=this.#e[n];return this.#P&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#x||this.#u)&&(this.#x&&this.#g?.(i,r,"evict"),this.#u&&this.#o?.push([i,r,"evict"])),this.#R(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#v.push(n)),this.#i===1?(this.#s=this.#a=0,this.#v.length=0):this.#s=this.#l[n],this.#r.delete(r),this.#i--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:i}=n,a=this.#r.get(e);if(a!==void 0){let o=this.#e[a];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#m(a))i&&(i.has="stale",this.#C(i,a));else return r&&this.#k(a),i&&(i.has="hit",this.#C(i,a)),!0}else i&&(i.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,i=this.#r.get(e);if(i===void 0||!r&&this.#m(i))return;let a=this.#e[i];return this.#t(a)?a.__staleWhileFetching:a}#$(e,n,r,i){let a=n===void 0?void 0:this.#e[n];if(this.#t(a))return a;let o=new zx,{signal:s}=r;s?.addEventListener("abort",()=>o.abort(s.reason),{signal:o.signal});let c={signal:o.signal,options:r,context:i},l=(g,y=!1)=>{let{aborted:v}=o.signal,b=r.ignoreFetchAbort&&g!==void 0;if(r.status&&(v&&!y?(r.status.fetchAborted=!0,r.status.fetchError=o.signal.reason,b&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),v&&!b&&!y)return d(o.signal.reason);let x=f;return this.#e[n]===f&&(g===void 0?x.__staleWhileFetching?this.#e[n]=x.__staleWhileFetching:this.#I(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,g,c.options))),g},u=g=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=g),d(g)),d=g=>{let{aborted:y}=o.signal,v=y&&r.allowStaleOnFetchAbort,b=v||r.allowStaleOnFetchRejection,x=b||r.noDeleteOnFetchRejection,I=f;if(this.#e[n]===f&&(!x||I.__staleWhileFetching===void 0?this.#I(e,"fetch"):v||(this.#e[n]=I.__staleWhileFetching)),b)return r.status&&I.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),I.__staleWhileFetching;if(I.__returned===I)throw g},p=(g,y)=>{let v=this.#T?.(e,a,c);v&&v instanceof Promise&&v.then(b=>g(b===void 0?void 0:b),y),o.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(g(void 0),r.allowStaleOnFetchAbort&&(g=b=>l(b,!0)))})};r.status&&(r.status.fetchDispatched=!0);let f=new Promise(p).then(l,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return n===void 0?(this.set(e,m,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=m,m}#t(e){if(!this.#P)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof zx}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:y=!1,status:v,signal:b}=n;if(!this.#P)return v&&(v.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:a,status:v});let x={allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:s,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:v,signal:b},I=this.#r.get(e);if(I===void 0){v&&(v.fetch="miss");let w=this.#$(e,I,x,g);return w.__returned=w}else{let w=this.#e[I];if(this.#t(w)){let ue=r&&w.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",ue&&(v.returnedStale=!0)),ue?w.__staleWhileFetching:w.__returned=w}let N=this.#m(I);if(!y&&!N)return v&&(v.fetch="hit"),this.#E(I),i&&this.#k(I),v&&this.#C(v,I),w;let k=this.#$(e,I,x,g),te=k.__staleWhileFetching!==void 0&&r;return v&&(v.fetch=N?"stale":"refresh",te&&N&&(v.returnedStale=!0)),te?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#A;if(!r)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:a,...o}=n,s=this.get(e,o);if(!a&&s!==void 0)return s;let c=r(e,s,{options:o,context:i});return this.set(e,c,o),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=n,s=this.#r.get(e);if(s!==void 0){let c=this.#e[s],l=this.#t(c);return o&&this.#C(o,s),this.#m(s)?(o&&(o.get="stale"),l?(o&&r&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),r?c.__staleWhileFetching:void 0):(a||this.#I(e,"expire"),o&&r&&(o.returnedStale=!0),r?c:void 0)):(o&&(o.get="hit"),l?c.__staleWhileFetching:(this.#E(s),i&&this.#k(s),c))}else o&&(o.get="miss")}#z(e,n){this.#p[n]=e,this.#l[e]=n}#E(e){e!==this.#a&&(e===this.#s?this.#s=this.#l[e]:this.#z(this.#p[e],this.#l[e]),this.#z(this.#a,e),this.#a=e)}delete(e){return this.#I(e,"delete")}#I(e,n){let r=!1;if(this.#i!==0){let i=this.#r.get(e);if(i!==void 0)if(r=!0,this.#i===1)this.#U(n);else{this.#R(i);let a=this.#e[i];if(this.#t(a)?a.__abortController.abort(new Error("deleted")):(this.#x||this.#u)&&(this.#x&&this.#g?.(a,e,n),this.#u&&this.#o?.push([a,e,n])),this.#r.delete(e),this.#n[i]=void 0,this.#e[i]=void 0,i===this.#a)this.#a=this.#p[i];else if(i===this.#s)this.#s=this.#l[i];else{let o=this.#p[i];this.#l[o]=this.#l[i];let s=this.#l[i];this.#p[s]=this.#p[i]}this.#i--,this.#v.push(i)}}if(this.#u&&this.#o?.length){let i=this.#o,a;for(;a=i?.shift();)this.#h?.(...a)}return r}clear(){return this.#U("delete")}#U(e){for(let n of this.#w({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let i=this.#n[n];this.#x&&this.#g?.(r,i,e),this.#u&&this.#o?.push([r,i,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#f&&this.#_&&(this.#f.fill(0),this.#_.fill(0)),this.#b&&this.#b.fill(0),this.#s=0,this.#a=0,this.#v.length=0,this.#y=0,this.#i=0,this.#u&&this.#o){let n=this.#o,r;for(;r=n?.shift();)this.#h?.(...r)}}};ix();Kr();Io();import D from"path";import{createHash as qve}from"crypto";import{promises as Pu}from"fs";var Uve=/[.\[\]"']/;function e9(t){return t.length===0||Uve.test(t)}function t9(t){let e=t.replace(/\\/g,"\\\\");return e.includes('"')?e.includes("'")?`"${e.replace(/"/g,'\\"')}"`:`'${e}'`:`"${e}"`}function Fve(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="\\"&&n+1<t.length){e+=t[n+1]??"",n++;continue}e+=r}return e}function ma(t){let e=[],n=0,r=t.length;for(;n<r;){let i=t[n];if(!i)break;if(i==="."){n++;continue}if(i==="["){for(n++;n<r&&/\s/.test(t[n]??"");)n++;let s=t[n];if(s==='"'||s==="'"){n++;let u="";for(;n<r;){let d=t[n];if(!d)break;if(d==="\\"&&n+1<r){u+=`${d}${t[n+1]??""}`,n+=2;continue}if(d===s){n++;break}u+=d,n++}for(;n<r&&/\s/.test(t[n]??"");)n++;t[n]==="]"&&n++,e.push(Fve(u));continue}let c="";for(;n<r&&t[n]!=="]";)c+=t[n]??"",n++;t[n]==="]"&&n++;let l=c.trim();l.length>0&&e.push(l);continue}let a=n;for(;n<r;){let s=t[n];if(s==="."||s==="[")break;n++}let o=t.slice(a,n).trim();o.length>0&&e.push(o)}return e}function ln(t){let e=ma(t);return e[0]==="game"?e.slice(1):e}function kt(t){if(t.length===0)return"";let e="";for(let n=0;n<t.length;n++){let r=t[n]??"";if(n===0){e=e9(r)?`[${t9(r)}]`:r;continue}e9(r)?e+=`[${t9(r)}]`:e+=`.${r}`}return e}function St(t){let e=ma(t);return e[e.length-1]??""}function Nt(t){let e=ma(t);return e.length<=1?"":kt(e.slice(0,-1))}function bm(t,e){let n=ma(t);return n.length===0?e:(n[n.length-1]=e,kt(n))}Sr();le();var Bve=/[\u0000-\u001f<>:"/\\|?*[\]]/g,Vve=/[. ]+$/,Wve=/\.\./g,Hve=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i,Zve=/^\s*$/;function Ux(t,e){let n=D.resolve(t),r=D.resolve(e),i=D.relative(n,r);return i===""||!i.startsWith("..")&&!D.isAbsolute(i)}function $A(t){let e=D.basename(t);return e==="_tree.json"||e===".sync-meta.json"||e===".sync-index.json"||e===".project-meta.json"}function n9(t,e){let n=[],r=new Set([...t.keys(),...e.keys()]);for(let a of r){let o=t.get(a),s=e.get(a);if(o&&s){if(o.kind!==s.kind){n.push({relativePath:a,kind:o.kind,changeType:o.kind==="dir"?"unlinkDir":"unlink",previous:o}),n.push({relativePath:a,kind:s.kind,changeType:s.kind==="dir"?"addDir":"add",current:s});continue}s.kind==="file"&&(o.mtimeMs!==s.mtimeMs||o.size!==s.size)&&n.push({relativePath:a,kind:"file",changeType:"change",previous:o,current:s});continue}if(s&&!o){n.push({relativePath:a,kind:s.kind,changeType:s.kind==="dir"?"addDir":"add",current:s});continue}o&&!s&&n.push({relativePath:a,kind:o.kind,changeType:o.kind==="dir"?"unlinkDir":"unlink",previous:o})}let i={unlink:0,unlinkDir:1,add:2,addDir:3,change:4};return n.sort((a,o)=>{let s=a.relativePath.localeCompare(o.relativePath);return s!==0?s:i[a.changeType]-i[o.changeType]}),n}var Oo=class t{explorerRoot;syncRoot;formatVersion;studioHashes=new Map;fileHashes=new Map;nameCounters=new Map;nameMapping=new Map;reverseNameMapping=new Map;pendingRetroactiveRenames=new Map;instanceDirMap=new Map;instanceClassMap=new Map;sessionDebugMappings=new Map;constructor(e,n,r=bt){this.syncRoot=D.resolve(e),this.explorerRoot=D.resolve(n),this.formatVersion=r}setFormatVersion(e){this.formatVersion=e}getInstanceKey(e,n){return`${e}#${Math.max(1,n??1)}`}getSessionDebugKey(e,n){return`${e}\0${n}`}resolveFilePath(e){return this.resolveChildrenDir(e)}resolveChildrenDir(e){let n=ln(e).map(i=>this.sanitizeName(i)),r=D.resolve(this.explorerRoot,...n);return this.validatePathSecurity(r),r}resolvePropsPath(e){let n=ln(e).map(s=>this.sanitizeName(s));if(n.length===0)throw new Error("Cannot resolve props path for empty instance path");let r=this.getOriginalNameForSegments(e,n),i=this.sanitizeName(r),a=D.resolve(this.explorerRoot,...n),o=D.join(a,HT(i));return this.validatePathSecurity(o),o}resolveParentDir(e){let n=ln(e).map(a=>this.sanitizeName(a));if(n.length<=1)return this.explorerRoot;let r=n.slice(0,-1),i=D.resolve(this.explorerRoot,...r);return this.validatePathSecurity(i),i}resolveScriptPath(e,n,r){let i=ln(e).map(c=>this.sanitizeName(c)),a=this.getOriginalNameForSegments(e,i),o=this.sanitizeName(a),s=D.resolve(this.explorerRoot,...i);return D.join(s,zs(o,n))}resolveValuePath(e){let n=ln(e).map(s=>this.sanitizeName(s));if(n.length===0)throw new Error("Cannot resolve value path for empty instance path");let r=this.getOriginalNameForSegments(e,n),i=this.sanitizeName(r),a=D.resolve(this.explorerRoot,...n),o=D.join(a,ZT(i));return this.validatePathSecurity(o),o}sanitizeName(e){if(e===".."||e===".")return"_";let n=e.replace(Bve,"_");return n=n.replace(Wve,"_"),n=n.replace(Vve,"_"),Zve.test(n)?"_unnamed":(Hve.test(n)&&(n=`${n}_`),n)}resolveNameCollision(e,n){let r=this.nameCounters.get(e);r||(r=new Map,this.nameCounters.set(e,r));let i=r.get(n);if(i===void 0)return r.set(n,1),So(n);if(i===1){r.set(n,2);let o=`${e}\0${n}`,s=So(n),c=So(n,1);return this.pendingRetroactiveRenames.set(o,{from:s,to:c}),So(n,2)}let a=i+1;return r.set(n,a),So(n,a)}getOriginalNameForDir(e,n){let r=D.join(e,n),i=this.reverseNameMapping.get(r);return i?St(i.instancePath)||n:Ri(n).name}getOriginalNameForSegments(e,n){if(n.length===0)return"_unnamed";let r=n[n.length-1];if(n.length<=1)return Ri(r).name;let i=n.slice(0,-1),a=D.resolve(this.explorerRoot,...i);return this.getOriginalNameForDir(a,r)}resetNameCounters(){this.nameCounters.clear(),this.nameMapping.clear(),this.reverseNameMapping.clear(),this.pendingRetroactiveRenames.clear(),this.instanceDirMap.clear()}clearAllMaps(){this.resetNameCounters(),this.instanceClassMap.clear(),this.sessionDebugMappings.clear(),this.studioHashes.clear(),this.fileHashes.clear()}registerCollision(e,n,r){let i=St(e)||"_unnamed",a=this.sanitizeName(i),o=this.resolveNameCollision(r,a),s=n??1,c=`${e}#${s}`;this.nameMapping.set(c,o);let l=D.join(r,o);this.instanceDirMap.set(c,l);let u=D.join(r,o);this.reverseNameMapping.set(u,{instancePath:e,siblingIndex:s});let d,p=`${r}\0${a}`,f=this.pendingRetroactiveRenames.get(p);if(f){this.pendingRetroactiveRenames.delete(p);let m=D.join(r,f.from),g=this.reverseNameMapping.get(m);if(g){let y=`${g.instancePath}#${g.siblingIndex}`;this.nameMapping.set(y,f.to),this.instanceDirMap.set(y,D.join(r,f.to)),this.reverseNameMapping.delete(m),this.reverseNameMapping.set(D.join(r,f.to),g),d={from:f.from,to:f.to,instancePath:g.instancePath,siblingIndex:g.siblingIndex}}}return d?{resolved:o,retroactiveRename:d}:{resolved:o}}registerCollisionWithPreferredName(e,n,r,i){let a=St(e)||"_unnamed",o=this.sanitizeName(a);if(i&&D.basename(i)===i){let s=Ri(i),c=this.sanitizeName(s.name)===o,l=D.join(r,i);if(c&&!this.reverseNameMapping.has(l)){let u=Math.max(1,n??1),d=this.getInstanceKey(e,u);this.nameMapping.set(d,i),this.instanceDirMap.set(d,D.join(r,i)),this.reverseNameMapping.set(l,{instancePath:e,siblingIndex:u});let p=this.nameCounters.get(r);p||(p=new Map,this.nameCounters.set(r,p));let f=Math.max(1,s.siblingIndex??1);return p.set(o,Math.max(p.get(o)??0,f)),{resolved:i}}}return this.registerCollision(e,n,r)}planCollisionReindexAfterRemoval(e,n,r){let i=this.planCollisionReindexAfterBatchRemovals(e,[n??1],r),a=i.removed[0];return{baseName:i.baseName,removedSiblingIndex:a?.siblingIndex??n??1,removedResolved:a?.resolved,remainingCount:i.remainingCount,renames:i.renames}}planCollisionReindexAfterBatchRemovals(e,n,r){let i=[...new Set(n.map(d=>Math.max(1,d)))].sort((d,p)=>d-p),a=new Set(i),o=this.sanitizeName(St(e)||"_unnamed"),s=i.map(d=>({siblingIndex:d,resolved:this.nameMapping.get(`${e}#${d}`)})),c=[];for(let[d,p]of this.reverseNameMapping)D.dirname(d)===r&&p.instancePath===e&&(a.has(p.siblingIndex)||c.push({instancePath:p.instancePath,siblingIndex:p.siblingIndex,resolved:D.basename(d)}));c.sort((d,p)=>d.siblingIndex-p.siblingIndex);let l=[],u=c.length;for(let d=0;d<c.length;d++){let p=c[d],f=u<=1?1:d+1,m=u<=1?So(o):So(o,f);(p.siblingIndex!==f||p.resolved!==m)&&l.push({instancePath:p.instancePath,oldSiblingIndex:p.siblingIndex,newSiblingIndex:f,from:p.resolved,to:m})}return{baseName:o,removed:s,remainingCount:u,renames:l}}applyCollisionReindexAfterRemoval(e,n,r){this.applyCollisionReindexAfterBatchRemovals(e,n,{baseName:r.baseName,removed:[{siblingIndex:r.removedSiblingIndex,resolved:r.removedResolved}],remainingCount:r.remainingCount,renames:r.renames})}applyCollisionReindexAfterBatchRemovals(e,n,r){for(let a of r.removed){let o=`${e}#${a.siblingIndex}`;this.nameMapping.delete(o),this.instanceDirMap.delete(o),this.instanceClassMap.delete(o),a.resolved&&this.reverseNameMapping.delete(D.join(n,a.resolved))}let i=this.nameCounters.get(n);r.remainingCount<=0?i&&(i.delete(r.baseName),i.size===0&&this.nameCounters.delete(n)):i&&i.set(r.baseName,r.remainingCount),this.pendingRetroactiveRenames.delete(`${n}\0${r.baseName}`);for(let a of r.renames){let o=`${a.instancePath}#${a.oldSiblingIndex}`,s=`${a.instancePath}#${a.newSiblingIndex}`,c=D.join(n,a.to);o!==s&&(this.nameMapping.delete(o),this.instanceDirMap.delete(o)),this.nameMapping.set(s,a.to),this.instanceDirMap.set(s,c);let l=this.instanceClassMap.get(o);o!==s&&this.instanceClassMap.delete(o),l&&this.instanceClassMap.set(s,l);let u=D.join(n,a.to),d=D.join(n,a.from);d!==u&&this.reverseNameMapping.delete(d),this.reverseNameMapping.set(u,{instancePath:a.instancePath,siblingIndex:a.newSiblingIndex})}}getResolvedName(e,n){return this.nameMapping.get(`${e}#${n}`)}getRegisteredSiblingIndices(e,n){let r=[];for(let[i,a]of this.reverseNameMapping)D.dirname(i)===n&&a.instancePath===e&&r.push(a.siblingIndex);return r.sort((i,a)=>i-a)}getEffectiveDir(e,n){let r=n??1;return this.instanceDirMap.get(`${e}#${r}`)}setClassName(e,n,r){this.instanceClassMap.set(this.getInstanceKey(e,r),n)}getClassName(e,n){return this.instanceClassMap.get(this.getInstanceKey(e,n))}getSessionDebugMapping(e,n){return this.sessionDebugMappings.get(this.getSessionDebugKey(e,n))}setSessionDebugMapping(e){this.sessionDebugMappings.set(this.getSessionDebugKey(e.scope,e.sessionDebugId),e)}updateSessionDebugMappingResolvedName(e,n,r,i){if(e)for(let[a,o]of this.sessionDebugMappings)o.scope===e&&o.instancePath===n&&o.siblingIndex===r&&this.sessionDebugMappings.set(a,{...o,resolvedName:i,updatedAt:new Date().toISOString()})}resolveInstanceInfoFromDirectory(e){let n=D.resolve(e),r=D.relative(this.explorerRoot,n);if(r===""||r.startsWith("..")||D.isAbsolute(r))return null;let i=r.split(D.sep).filter(c=>c.length>0);if(i.length===0)return null;let a=["game"],o=this.explorerRoot,s=1;for(let c of i){let l=this.getOriginalInstance(o,c);if(l)a.push(St(l.instancePath)||Ri(c).name),s=l.siblingIndex;else{let u=Ri(c);a.push(u.name),s=u.siblingIndex??1}o=D.join(o,c)}return{instancePath:kt(a),siblingIndex:s}}getStartingDirectoryForFsPath(e){return D.basename(e)==="_tree.json"?D.dirname(e):this.getFileTypeFromPath(e)!=="unknown"||D.extname(e)!==""?D.dirname(e):e}getClassNameForFsPath(e){let n=D.resolve(e),r=this.getStartingDirectoryForFsPath(n);for(;Ux(this.explorerRoot,r)&&r!==this.explorerRoot&&r!==D.dirname(r);){let i=this.resolveClassNameForDirectory(r);if(i)return i;r=D.dirname(r)}}isPathUnderClass(e,n){let r=D.resolve(e),i=this.getStartingDirectoryForFsPath(r);for(;Ux(this.explorerRoot,i)&&i!==this.explorerRoot&&i!==D.dirname(i);){let a=this.resolveClassNameForDirectory(i);if(a&&n.has(a))return!0;i=D.dirname(i)}return!1}resolveClassNameForDirectory(e){let n=this.resolveInstanceInfoFromDirectory(e);if(!n)return;let r=this.getClassName(n.instancePath,n.siblingIndex);if(r)return r;let i=this.getInstancePath(e);return this.getClassName(i,n.siblingIndex)}resolveEffectiveParentDir(e,n){if(n&&n>=1){let r=Nt(e);if(r){let i=this.instanceDirMap.get(`${r}#${n}`);if(i)return i}}return this.resolveParentDir(e)}getOriginalInstance(e,n){return this.reverseNameMapping.get(D.join(e,n))}resetNameMappings(){this.nameMapping.clear(),this.reverseNameMapping.clear()}mergeNameMappingsFrom(e){let n=e.explorerRoot,r=this.explorerRoot;for(let[i,a]of e.nameMapping)this.nameMapping.set(i,a);for(let[i,a]of e.reverseNameMapping)if(i.startsWith(n)){let o=i.slice(n.length),s=r+o;this.reverseNameMapping.set(s,a)}else this.reverseNameMapping.set(i,a);for(let[i,a]of e.instanceDirMap)if(a.startsWith(n)){let o=a.slice(n.length),s=r+o;this.instanceDirMap.set(i,s)}else this.instanceDirMap.set(i,a);for(let[i,a]of e.instanceClassMap)this.instanceClassMap.set(i,a);for(let[i,a]of e.nameCounters){let o=i.startsWith(n)?r+i.slice(n.length):i,s=new Map;for(let[c,l]of a)s.set(c,l);this.nameCounters.set(o,s)}}mergeSessionDebugMappingsFrom(e){for(let[n,r]of e.sessionDebugMappings)this.sessionDebugMappings.set(n,r)}getNameMappings(){return new Map(this.nameMapping)}getReverseNameMappings(){return new Map(this.reverseNameMapping)}renameReverseNameMappingsUnder(e,n){let r=e.endsWith(D.sep)?"":D.sep,i=e+r,a=n+r,o=[];for(let[s,c]of this.reverseNameMapping)(s.startsWith(i)||s===e)&&o.push([s,c]);for(let[s,c]of o){this.reverseNameMapping.delete(s);let l=s===e?n:a+s.slice(i.length);this.reverseNameMapping.set(l,c)}}renameInstanceDirMappingsUnder(e,n){let r=e.endsWith(D.sep)?"":D.sep,i=e+r,a=n+r,o=[];for(let[s,c]of this.instanceDirMap)if(c.startsWith(i)||c===e){let l=c===e?n:a+c.slice(i.length);o.push([s,l])}for(let[s,c]of o)this.instanceDirMap.set(s,c)}renameNameMappingKeys(e,n){let r=e+".",i=n+".",a=[];for(let[o,s]of this.nameMapping)if(o.startsWith(r)||o.startsWith(e+"#")){let c=o.startsWith(r)?i+o.slice(r.length):n+o.slice(e.length);a.push([o,c,s])}for(let[o,s,c]of a)this.nameMapping.delete(o),this.nameMapping.set(s,c)}renameClassMappingKeys(e,n){let r=e+".",i=n+".",a=[];for(let[o,s]of this.instanceClassMap)if(o.startsWith(r)||o.startsWith(e+"#")){let c=o.startsWith(r)?i+o.slice(r.length):n+o.slice(e.length);a.push([o,c,s])}for(let[o,s,c]of a)this.instanceClassMap.delete(o),this.instanceClassMap.set(s,c)}validatePathSecurity(e){let n=D.resolve(e);if(!Ux(this.explorerRoot,n))throw new Error(`Path traversal detected: resolved path "${n}" is outside explorerRoot "${this.explorerRoot}"`)}computeHash(e){return qve("md5").update(e,"utf-8").digest("hex")}hasChanged(e,n){let r=this.computeHash(n);return this.studioHashes.get(e)!==r}updateHash(e,n){this.studioHashes.set(e,this.computeHash(n))}updateFileHash(e,n){this.fileHashes.set(e,this.computeHash(n))}updateBothHashes(e,n){let r=this.computeHash(n);this.studioHashes.set(e,r),this.fileHashes.set(e,r)}updateHashByValue(e,n){this.studioHashes.set(e,n)}updateFileHashByValue(e,n){this.fileHashes.set(e,n)}removeHash(e){this.studioHashes.delete(e),this.fileHashes.delete(e)}removeHashesUnder(e){let n=e.endsWith(D.sep)?e:e+D.sep;for(let r of this.studioHashes.keys())(r.startsWith(n)||r===e)&&this.studioHashes.delete(r);for(let r of this.fileHashes.keys())(r.startsWith(n)||r===e)&&this.fileHashes.delete(r)}removeClassMappingsUnderInstancePath(e){let n=`${e}#`,r=`${e}.`,i=[];for(let a of this.instanceClassMap.keys())(a.startsWith(n)||a.startsWith(r))&&i.push(a);for(let a of i)this.instanceClassMap.delete(a)}renameHashKey(e,n){let r=this.studioHashes.get(e),i=this.fileHashes.get(e);r!==void 0&&(this.studioHashes.delete(e),this.studioHashes.set(n,r)),i!==void 0&&(this.fileHashes.delete(e),this.fileHashes.set(n,i))}renameHashKeysUnder(e,n){let r=e.endsWith(D.sep)?"":D.sep,i=e+r,a=n+r,o=[];for(let[c,l]of this.studioHashes)c.startsWith(i)&&o.push([c,l]);for(let[c,l]of o)this.studioHashes.delete(c),this.studioHashes.set(a+c.slice(i.length),l);let s=[];for(let[c,l]of this.fileHashes)c.startsWith(i)&&s.push([c,l]);for(let[c,l]of s)this.fileHashes.delete(c),this.fileHashes.set(a+c.slice(i.length),l)}getHash(e){return this.studioHashes.get(e)}getStoredFileHash(e){return this.fileHashes.get(e)}getFileHash(e){return this.getStoredFileHash(e)}getHashPair(e){return{studioHash:this.studioHashes.get(e),fileHash:this.fileHashes.get(e)}}getAllHashes(){return new Map(this.studioHashes)}getAllFileHashes(){return new Map(this.fileHashes)}clearAllHashes(){this.studioHashes.clear(),this.fileHashes.clear()}clearClassMappings(){this.instanceClassMap.clear()}hasEntry(e){return this.studioHashes.has(e)||this.fileHashes.has(e)}hasInstancePath(e){for(let n of this.studioHashes.keys())if(this.resolveInstancePathFromFsPath(n)===e)return!0;return!1}get hashCount(){return this.studioHashes.size}async buildSnapshotSeed(){let e=new Map;return await this.collectSnapshotSeedEntries(this.explorerRoot,e),e}async collectSnapshotSeedEntries(e,n){let r;try{r=await Pu.readdir(e,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of r){let a=D.join(e,i.name),o=D.relative(this.explorerRoot,a),s;try{s=await Pu.stat(a)}catch(c){if(c.code==="ENOENT")continue;throw c}if(i.isDirectory()){n.set(o,{relativePath:o,kind:"dir",mtimeMs:s.mtimeMs,size:null}),await this.collectSnapshotSeedEntries(a,n);continue}i.isFile()&&($A(o)||n.set(o,{relativePath:o,kind:"file",mtimeMs:s.mtimeMs,size:s.size}))}}getFileStatus(e,n){let r=this.studioHashes.get(e),i=this.fileHashes.get(e);if(!r||!i)return"synced";if(n===void 0)return r===i?"synced":"studio-modified";let a=n!==i,o=r!==i;return!a&&!o?"synced":a&&!o?"file-modified":!a&&o?"studio-modified":"conflict"}async scanForFileModifications(){let e=[],n=[],r=[];for(let[i]of this.fileHashes){let a=D.relative(this.syncRoot,i);if(a.endsWith("_tree.json"))continue;let o=this.getFileTypeFromPath(i);if(o!=="script"&&o!=="props"&&o!=="value")continue;let s;try{let d=await Pu.readFile(i,"utf-8");s=this.computeHash(d)}catch(d){if(d.code==="ENOENT"){let p=this.resolveInstancePathFromFsPath(i);p&&r.push({fsPath:i,relPath:a,instancePath:p,fileType:o});continue}h.warn("Failed to read file for scanning",{path:i,error:d instanceof Error?d.message:String(d)});continue}let c=this.getFileStatus(i,s);if(c==="synced"||c==="studio-modified")continue;let l=this.resolveInstancePathFromFsPath(i);if(!l)continue;let u={fsPath:i,relPath:a,instancePath:l,fileType:o};c==="file-modified"?e.push(u):c==="conflict"&&n.push(u)}return{modified:e,conflicts:n,deleted:r}}resolveFile(e,n,r){if(n==="apply-studio"){let i=this.studioHashes.get(e);i&&this.fileHashes.set(e,i)}else n==="apply-file"&&r&&this.fileHashes.set(e,r)}async getModifiedFiles(){let e=[],n=new Set;for(let i of this.fileHashes.keys())n.add(D.resolve(i));for(let i of this.studioHashes.keys())n.add(D.resolve(i));for(let[i]of this.fileHashes){let a=D.resolve(i),o=D.relative(this.syncRoot,a);if(o.endsWith("_tree.json"))continue;let s=this.getFileTypeFromPath(a);if(s!=="script"&&s!=="props"&&s!=="value")continue;let c=this.resolveInstancePathFromFsPath(a);if(!c)continue;let l;try{let d=await Pu.readFile(a,"utf-8");l=this.computeHash(d)}catch(d){if(d.code==="ENOENT"){e.push({fsPath:a,relPath:o,instancePath:c,changeType:"deleted",fileType:s});continue}continue}let u=this.fileHashes.get(a);u&&l!==u&&e.push({fsPath:a,relPath:o,instancePath:c,changeType:"modified",fileType:s})}let r=await this.collectTrackedFiles(this.explorerRoot);for(let i of r){let a=D.resolve(i);if(n.has(a))continue;let o=D.relative(this.syncRoot,a),s=this.getFileTypeFromPath(a);if(s!=="script"&&s!=="props"&&s!=="value")continue;let c=this.resolveInstancePathFromFsPath(a);c&&e.push({fsPath:a,relPath:o,instancePath:c,changeType:"added",fileType:s})}return e}async collectTrackedFiles(e){let n=[],r;try{r=await Pu.readdir(e,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return n;throw i}for(let i of r){let a=D.join(e,i.name);if(i.isDirectory()){let s=await this.collectTrackedFiles(a);n.push(...s);continue}if(!i.isFile())continue;let o=this.getFileTypeFromPath(a);(o==="script"||o==="props"||o==="value")&&n.push(a)}return n}getFileTypeFromPath(e){let n=D.relative(this.explorerRoot,e);if(n.startsWith("..")||D.isAbsolute(n))return"unknown";let r=D.basename(e);if(r==="_tree.json")return"tree";let i=D.dirname(e),a=D.dirname(i),o=D.basename(i);if(!o||i===e)return"unknown";let s=this.getOriginalNameForDir(a,o),c=this.sanitizeName(s);return r===HT(c)?"props":r===ZT(c)?"value":r===zs(c,"Script")||r===zs(c,"LocalScript")||r===zs(c,"ModuleScript")?"script":"unknown"}resolveInstancePathFromFsPath(e){if(D.basename(e)==="_tree.json")return null;let r=D.relative(this.explorerRoot,e);if(r.startsWith(".."))return null;let i=r.split(D.sep).filter(l=>l.length>0);if(i.length<2)return null;let a=this.getFileTypeFromPath(e);if(a!=="props"&&a!=="value"&&a!=="script")return null;let o=i.slice(0,-1),s=["game"],c=this.explorerRoot;for(let l of o){c=D.join(c,l);let u=D.dirname(c),d=this.getOriginalNameForDir(u,l);s.push(d)}return kt(s)}async loadFromDisk(){let e=D.join(this.syncRoot,".sync-index.json");try{let n=await Pu.readFile(e,"utf-8"),r=JSON.parse(n);if(r.version!==this.formatVersion){h.warn("sync-index \uBC84\uC804 \uBD88\uC77C\uCE58, \uBB34\uC2DC\uD558\uACE0 \uC0C8\uB85C \uC0DD\uC131",{found:r.version,expected:this.formatVersion});return}this.replacePersistenceState(r),h.info("Loaded sync index from disk",{entries:Object.keys(r.files).length,nameMappings:this.nameMapping.size,classMappings:this.instanceClassMap.size,sessionDebugMappings:this.sessionDebugMappings.size})}catch(n){if(n.code==="ENOENT"){h.info("No existing .sync-index.json found, starting fresh");return}h.warn("Failed to load .sync-index.json",{error:n instanceof Error?n.message:String(n)})}}rebuildNameCountersFromReverseMappings(){this.nameCounters.clear();for(let[e,n]of this.reverseNameMapping){let r=D.dirname(e),i=this.sanitizeName(St(n.instancePath)||Ri(D.basename(e)).name),a=this.nameCounters.get(r);a||(a=new Map,this.nameCounters.set(r,a));let o=a.get(i)??0;a.set(i,o+1)}}async saveToDisk(){await this.savePersistenceStateToDisk(this.toSyncIndexData()),h.debug("Saved sync index to disk",{entries:this.studioHashes.size})}buildFullSyncPersistenceStateFrom(e){let n=new t(this.syncRoot,this.explorerRoot,this.formatVersion);for(let[r,i]of e.studioHashes)n.updateHashByValue(this.remapFullSyncPath(r,e.explorerRoot),i);for(let[r,i]of e.fileHashes)n.updateFileHashByValue(this.remapFullSyncPath(r,e.explorerRoot),i);return n.mergeNameMappingsFrom(e),n.mergeSessionDebugMappingsFrom(e),n.toSyncIndexData()}async savePersistenceStateToDisk(e){if(e.version!==this.formatVersion)throw new Error(`Sync index persistence version mismatch: ${e.version} !== ${this.formatVersion}`);let n=D.join(this.syncRoot,".sync-index.json");await bn(n,JSON.stringify(e,null,2))}replacePersistenceState(e){if(e.version!==this.formatVersion)throw new Error(`Sync index persistence version mismatch: ${e.version} !== ${this.formatVersion}`);this.clearPersistenceMaps();for(let[n,r]of Object.entries(e.files)){let i=D.resolve(this.syncRoot,n);this.studioHashes.set(i,r.studioHash),this.fileHashes.set(i,r.fileHash)}for(let[n,r]of Object.entries(e.nameMappings??{}))this.nameMapping.set(n,r);for(let[n,r]of Object.entries(e.reverseNameMappings??{})){let i=D.isAbsolute(n)?n:D.resolve(this.explorerRoot,n);this.reverseNameMapping.set(i,r)}for(let[n,r]of Object.entries(e.instanceDirMappings??{}))this.instanceDirMap.set(n,D.resolve(this.explorerRoot,r));for(let[n,r]of Object.entries(e.instanceClassMappings??{}))this.instanceClassMap.set(n,r);for(let n of Object.values(e.sessionDebugMappings??{}))n.scope&&n.sessionDebugId&&this.setSessionDebugMapping(n);this.rebuildNameCountersFromReverseMappings()}clearPersistenceMaps(){this.studioHashes.clear(),this.fileHashes.clear(),this.nameCounters.clear(),this.nameMapping.clear(),this.reverseNameMapping.clear(),this.pendingRetroactiveRenames.clear(),this.instanceDirMap.clear(),this.instanceClassMap.clear(),this.sessionDebugMappings.clear()}remapFullSyncPath(e,n){if(!Ux(n,e))throw new Error(`Full sync index path escapes explorer root: ${e}`);return D.resolve(this.explorerRoot,D.relative(n,e))}toSyncIndexData(){let e=new Date().toISOString(),n={},r=new Set([...this.studioHashes.keys(),...this.fileHashes.keys()]);for(let a of r){let o=D.relative(this.syncRoot,a),s=this.studioHashes.get(a)??"",c=this.fileHashes.get(a)??s,l="synced";s&&c&&s!==c&&(l="studio-modified"),n[o]={studioHash:s,fileHash:c,lastStudioSync:e,status:l}}let i={version:this.formatVersion,files:n};if(this.nameMapping.size>0){let a={};for(let[o,s]of this.nameMapping)a[o]=s;i.nameMappings=a}if(this.reverseNameMapping.size>0){let a={};for(let[o,s]of this.reverseNameMapping){let c=D.relative(this.explorerRoot,o),l=c.startsWith("..")?o:c;a[l]=s}i.reverseNameMappings=a}if(this.instanceDirMap.size>0){let a={};for(let[o,s]of this.instanceDirMap){let c=D.relative(this.explorerRoot,s);c.startsWith("..")||(a[o]=c)}i.instanceDirMappings=a}if(this.instanceClassMap.size>0){let a={};for(let[o,s]of this.instanceClassMap)a[o]=s;i.instanceClassMappings=a}if(this.sessionDebugMappings.size>0){let a={};for(let[o,s]of this.sessionDebugMappings)a[o]=s;i.sessionDebugMappings=a}return i}getInstancePath(e){let r=D.relative(this.explorerRoot,e).split(D.sep).filter(i=>i.length>0);return kt(["game",...r])}getExplorerRoot(){return this.explorerRoot}getSyncRoot(){return this.syncRoot}};Kr();import wt from"path";import{promises as Qe}from"fs";import{randomUUID as Gve}from"crypto";Io();le();var r9=1e3,i9=1e4,a9=50,Kve=1e3,Jve=16e3;function NA(t){return Qe.readFile(t,"utf-8").catch(e=>(e.code!=="ENOENT"&&h.warn("\uD30C\uC77C \uC77D\uAE30 \uC2E4\uD328 (diff \uC0DD\uB7B5)",{filePath:t,error:e}),null))}function MA(t,e){return Object.keys(t.properties).length>0||Object.keys(t.attributes??{}).length>0||(t.tags?.length??0)>0?!1:wr.has(t.className)?!0:e&&sx.has(t.className)}var ku=class{config;index;changeLogBuffer=[];historyBuffer=[];flushTimer=null;onWriteCallback;onHistoryFlushCallback;historyContextIdResolver;placeId;formatVersion;bootstrapMode=!1;get historyEnabled(){return this.onHistoryFlushCallback!==void 0}constructor(e,n,r,i=bt){this.config=e,this.index=n,this.placeId=r,this.formatVersion=i}setFormatVersion(e){this.formatVersion=e}setOnWriteCallback(e){this.onWriteCallback=e}setBootstrapMode(e){this.bootstrapMode=e}setOnHistoryFlushCallback(e){this.onHistoryFlushCallback=e}setHistoryContextIdResolver(e){this.historyContextIdResolver=e}async writeProps(e,n){let r=this.index.resolvePropsPath(e);if(this.formatVersion===Dt){let o=!1;if(sx.has(n.className)&&(o=await Qe.access(this.index.resolveValuePath(e)).then(()=>!0).catch(()=>!1)),MA(n,o))return await this.removeRedundantProps(e,r),!1}let i=this.serializeArtifact(n);if(!this.index.hasChanged(r,i))return!1;let a;if(!this.bootstrapMode&&this.historyEnabled){let o=await NA(r),s=o!==null?JSON.parse(o).properties:null,c=Yve(s,n.properties);Object.keys(c).length>0&&(a={type:"props",changedProperties:c})}try{return await this.ensureDir(wt.dirname(r)),await this.atomicWrite(r,i),await this.updateSyncIndex(r,i),this.appendChangeLog(`WRITE ${this.relativePath(r)}`),this.appendHistory({timestamp:new Date().toISOString(),type:"write",direction:"forward",source:"studio",path:e,details:"props",...a!==void 0?{diff:a}:{}},r),!0}catch(o){this.handleDiskError(o,"writeProps",r)}}async writeScript(e,n,r,i){let a=this.index.resolveScriptPath(e,n,i),o=r;if(!this.index.hasChanged(a,o))return!1;let s;if(!this.bootstrapMode&&this.historyEnabled){let c=await NA(a),l=c!==null?c.split(`
|
|
@@ -919,7 +936,7 @@ ${y9}
|
|
|
919
936
|
`)}
|
|
920
937
|
`,"utf8")>kbe;)n.shift();let r=`${t}.${process.pid}.tmp`;Vn.writeFileSync(r,n.length>0?`${n.join(`
|
|
921
938
|
`)}
|
|
922
|
-
`:"","utf8"),Vn.renameSync(r,t)}function k9(t){try{return Vn.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(".jsonl")).map(e=>{let n=XA.join(t,e.name);return{filePath:n,modifiedAtMs:Vn.statSync(n).mtimeMs}}).sort((e,n)=>e.modifiedAtMs-n.modifiedAtMs)}catch{return[]}}async function R9(t,e=20){return!Number.isInteger(e)||e<=0?[]:k9(QT(t)).slice(-e).map(r=>r.filePath)}function E9(t){let e=QT(t.appDataDir),n=XA.join(e,Abe(t.instanceId));return{filePath:n,record(i,a,o={},s){try{let l={...YA(o),schemaVersion:1,timestamp:Tbe(s),source:i,event:a,pid:t.pid,instanceId:t.instanceId,sessionId:t.sessionId};Vn.mkdirSync(e,{recursive:!0}),Dbe(n,JSON.stringify(l))}catch{}},pruneOldInstanceFiles(){try{let i=k9(e);for(let a of i.slice(0,-20))Vn.rmSync(a.filePath,{force:!0})}catch{}}}}vt();function T9(t,e){let n=$be(),r=n.replace(/-/g,"").substring(0,8).toUpperCase(),i=`${r.substring(0,4)}-${r.substring(4,8)}`,a=E9({appDataDir:t.appDataDir??Ke(),pid:process.pid,instanceId:n,sessionId:i});return{config:t,app:e,instanceId:n,sessionId:i,startTime:Date.now(),runtimeDiagnostics:a,baseUrl:`http://${t.httpHost}:${t.httpPort}`,commandQueue:new Map,pendingCommands:new Map,globalPendingCommands:[],totalCommandsProcessed:0,pluginClients:new Map,pluginCommandSessionsByClientId:new Map,pluginCommandClientIdsByProcessToken:new Map,mcpInstances:new Map,cachedSelectionMap:new Map,studioRoutingMode:"recentPriority",pinnedTargetClientId:null,isClientMode:!1,clientModeHealthTimer:null,clientModeConsecutiveHealthFailures:0,clientModeUpstreamReachable:!0,clientModeUpstreamContextCaptureEnabled:!0,clientModeLastHealthSuccessAt:null,clientModeLastHealthFailureAt:null,clientModeLastHealthError:null,shuttingDown:!1,onUpstreamPermanentlyDown:null,clientModeIdleTimeoutMs:t.clientModeIdleTimeoutMs??36e5,clientModeIdleWatchdogTimer:null,shutdownFn:null,historyManager:null,analyticsManager:null,executionContextManager:null,licenseState:null,syncController:null,internalCommandExecutor:null,dashboardFolderPicker:null,assetLibraryOpenCloudServiceFactory:null,projectChangesCleanupScheduler:null,activeSyncOwnerInstanceId:null,activeProjectRoot:null,pendingDashboardSyncRootPin:null,playtestControlCommand:null,dashboardSyncRootSwitchInFlight:!1,uiStudioRecorders:new Map,uiStudioDesignContracts:P9(),aiClientName:"",pluginVersion:"",syncedSessionToken:null,serverLastCommandAt:null}}var A9=Ft(bo(),1);le();function O9(t){let e=A9.default.json({limit:"5mb"});t.app.use((n,r,i)=>{if(n.path.startsWith("/sync/")){i();return}e(n,r,i)}),t.app.use((n,r,i)=>{r.setHeader("Access-Control-Allow-Origin","http://localhost:3002"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type"),i()}),t.app.use((n,r,i)=>{h.debug(`${n.method} ${n.path}`,{ip:n.ip}),i()})}co();import{randomUUID as $S}from"crypto";co();le();function Nbe(){let t=process.env.WEPPY_ROBLOX_MCP_VERSION?.trim();return t||null}var Ye=Nbe()??"2.14.2";ca();nr();Pm();Ro();fu();co();Ro();var L9="studio-",Mbe=/^studio-[1-9]\d*$/;function nS(t){return Mbe.test(t)}function z9(t,e){let n=new Set;for(let r of t)e!==void 0&&r.clientId===e||r.targetAlias&&nS(r.targetAlias)&&n.add(r.targetAlias);return n}function Lbe(t,e){let n=z9(t,e),r=1;for(;n.has(`${L9}${r}`);)r+=1;return`${L9}${r}`}function rS(t,e){let n=z9(t,e.clientId);return e.targetAlias&&nS(e.targetAlias)&&!n.has(e.targetAlias)||(e.targetAlias=Lbe(t,e.clientId)),e.targetAlias}fu();function iS(t){for(let e of t)rS(t,e)}function aS(t){let e={clientId:t.clientId,targetAlias:t.targetAlias??t.clientId.slice(0,8),lastSeen:t.lastSeen,connectedAt:t.connectedAt,transport:"websocket",connectionState:t.commandSessionState??Be.CONNECTED};return t.placeId!==void 0&&(e.placeId=t.placeId),t.placeName!==void 0&&(e.placeName=t.placeName),t.pluginVersion!==void 0&&(e.pluginVersion=t.pluginVersion),t.studioVersion!==void 0&&(e.studioVersion=t.studioVersion),t.lastRoutedAt!==void 0&&(e.lastRoutedAt=t.lastRoutedAt),t.processToken!==void 0&&(e.processToken=t.processToken),t.inFlightRequestId!==void 0&&(e.inFlightRequestId=t.inFlightRequestId),t.studioState!==void 0&&(e.studioState=t.studioState),t.studioStateSource!==void 0&&(e.studioStateSource=t.studioStateSource),t.studioStateUpdatedAt!==void 0&&(e.studioStateUpdatedAt=t.studioStateUpdatedAt),t.playtestMode!==void 0&&(e.playtestMode=t.playtestMode),e}function aO(t){let e=Un(t);return iS(e),dm(e.map(aS),null)}function oS(t){let e=new Set;t.aiClientName&&e.add(t.aiClientName);for(let n of t.mcpInstances.values())n.aiClientName&&e.add(n.aiClientName);return Array.from(e)}function U9(t){let n=Date.now();for(let[r,i]of t.mcpInstances)i.lastSeen&&n-i.lastSeen>15e3&&(t.mcpInstances.delete(r),i.sessionId&&t.executionContextManager?.endSession(i.sessionId),h.debug("Removed stale MCP instance",{instanceId:r,lastSeen:i.lastSeen}))}function F9(t,e,n){let r=e.query.clientId;if(r&&t.pluginClients.has(r)){let i=t.pluginClients.get(r);i.lastSeen=Date.now()}try{let i=e.body;if(!i||!Array.isArray(i.selection)||typeof i.count!="number"){h.warn("Invalid selection update request",{body:i}),n.status(400).json({error:"Invalid request body"});return}let a=r||"unknown",o=Date.now();t.cachedSelectionMap.set(a,{selection:i.selection,count:i.count,timestamp:o,clientId:a}),h.debug("Selection cache updated",{count:i.count,clientId:a,timestamp:o}),n.json({status:"ok",timestamp:o})}catch(i){h.error("Error handling selection update",i),n.status(500).json({error:"Internal server error"})}}function q9(t,e,n){let r=parseInt(e.query.maxAge)||3e4,i=km(t,r);i?n.json({cached:!0,...i}):n.json({cached:!1,message:"No cached selection available"})}function km(t,e=3e4,n){if(t.cachedSelectionMap.size===0)return null;let r;if(n)r=t.cachedSelectionMap.get(n);else for(let a of t.cachedSelectionMap.values())(!r||a.timestamp>r.timestamp)&&(r=a);if(!r)return null;let i=Date.now()-r.timestamp;return e===0||i<=e?r:null}function oO(t,e){let n=t.pluginClients.get(e.clientId),r=Date.now(),i=[...t.pluginClients.values()].filter(c=>c.clientId===e.clientId||c.commandSessionState!==Be.DISCONNECTED),a=n??{clientId:e.clientId,connectedAt:r,lastSeen:r,commandsProcessed:0,connectionType:"polling"},o=rS(i,a),s={clientId:e.clientId,targetAlias:o,projectName:e.projectName??n?.projectName,placeName:e.placeName??n?.placeName,placeId:e.placeId??n?.placeId,pluginVersion:e.pluginVersion??n?.pluginVersion,studioVersion:e.studioVersion??n?.studioVersion,connectedAt:n?.connectedAt||r,lastSeen:r,commandsProcessed:n?.commandsProcessed||0,connectionType:n?.connectionType||"polling",inFlightRequestId:n?.inFlightRequestId,studioState:n?.studioState,studioStateSource:n?.studioStateSource,studioStateUpdatedAt:n?.studioStateUpdatedAt,playtestMode:n?.playtestMode,...n?.commandSessionState?{commandSessionState:n.commandSessionState}:{},...n?.processToken?{processToken:n.processToken}:{}};return t.pluginClients.set(e.clientId,s),t.syncController&&typeof t.syncController.setCurrentConnectedPlace=="function"&&typeof e.placeId=="number"&&Number.isFinite(e.placeId)&&t.syncController.setCurrentConnectedPlace(e.placeId,e.placeName??null),t.pendingCommands.has(e.clientId)||t.pendingCommands.set(e.clientId,[]),e.pluginVersion&&(t.pluginVersion=e.pluginVersion),typeof s.placeId=="number"&&Number.isFinite(s.placeId)&&Ax(t,s.placeId,s.placeName??null),t.analyticsManager&&(e.pluginVersion&&t.analyticsManager.setPluginVersion(e.pluginVersion),t.analyticsManager.trackPluginConnected()),h.info("Plugin client registered",{clientId:e.clientId,targetAlias:o,projectName:e.projectName,placeName:e.placeName,isReconnect:!!n}),{clientInfo:s,sessionId:t.sessionId,mcpVersion:Ye,mcpInstanceCount:t.mcpInstances.size+1,aiClientNames:oS(t)}}function sO(t,e){let n=t.pluginClients.get(e),r=t.pluginClients.has(e),i=n?.commandSessionState===Be.CONNECTED;if(t.pluginClients.delete(e),t.pendingCommands.delete(e),r&&pu(t,e),r&&t.syncController&&typeof t.syncController.clearCurrentConnectedPlaceIfMatch=="function"&&typeof n?.placeId=="number"&&Number.isFinite(n.placeId)){let a=[...t.pluginClients.values()].filter(o=>typeof o.placeId=="number"&&Number.isFinite(o.placeId)).sort((o,s)=>s.lastSeen-o.lastSeen)[0];a?t.syncController.setCurrentConnectedPlace?.(a.placeId??null,a.placeName??null):t.syncController.clearCurrentConnectedPlaceIfMatch(n.placeId)}return i&&pm(t,e,"disconnected",n),h.info("Plugin client unregistered",{clientId:e,existed:r}),r}function sS(t,e,n){try{let r=e.body;if(!r.clientId){n.status(400).json({error:"Missing clientId"});return}let i=oO(t,{clientId:r.clientId,projectName:r.projectName,placeName:r.placeName,placeId:r.placeId,pluginVersion:r.pluginVersion,studioVersion:r.studioVersion});n.json({status:"ok",clientId:r.clientId,targetAlias:i.clientInfo.targetAlias,serverInstanceId:t.instanceId,sessionId:i.sessionId,mcpVersion:i.mcpVersion,connectedAt:i.clientInfo.connectedAt,aiClientNames:i.aiClientNames,serverStartTime:t.startTime,mcpInstanceCount:i.mcpInstanceCount})}catch(r){h.error("Error registering plugin client",r),n.status(500).json({error:"Internal server error"})}}function cS(t,e,n){let r=e.body?.clientId;if(!r){n.status(400).json({error:"Missing clientId"});return}let i=sO(t,r);n.json({status:"ok",existed:i})}function B9(t,e,n){try{let r=e.body;if(!r.instanceId){n.status(400).json({error:"Missing instanceId"});return}let i=Date.now(),a={instanceId:r.instanceId,...typeof r.sessionId=="string"?{sessionId:r.sessionId}:{},pid:r.pid,connectedAt:i,isServer:!1,lastSeen:i};r.aiClientName&&(a.aiClientName=r.aiClientName),r.cwd&&(a.cwd=r.cwd),"projectRoot"in r&&(a.projectRoot=r.projectRoot),t.mcpInstances.set(r.instanceId,a),pt(t,"mcp_status",{aiClientName:a.aiClientName??"Unknown",instanceId:r.instanceId,status:"registered"}),vu(t,{timestamp:new Date().toISOString(),type:"mcp",status:"registered",instanceId:r.instanceId,message:`MCP registered \u2014 ${a.aiClientName??r.instanceId}`,...a.aiClientName?{aiClientName:a.aiClientName}:{}}),h.info("MCP instance registered (client mode)",{instanceId:r.instanceId,pid:r.pid,cwd:r.cwd}),n.json({status:"ok",instanceId:r.instanceId,serverInstanceId:t.instanceId,sessionId:t.sessionId,mcpVersion:Ye,mcpInstanceCount:t.mcpInstances.size+1})}catch(r){h.error("Error registering MCP instance",r),n.status(500).json({error:"Internal server error"})}}function V9(t,e,n){let r=e.body?.instanceId;if(!r){n.status(400).json({error:"Missing instanceId"});return}let i=t.mcpInstances.get(r),a=!!i;t.mcpInstances.delete(r),i?.sessionId&&t.executionContextManager?.endSession(i.sessionId),a&&(pt(t,"mcp_status",{aiClientName:i?.aiClientName??"Unknown",instanceId:r,status:"unregistered"}),vu(t,{timestamp:new Date().toISOString(),type:"mcp",status:"unregistered",instanceId:r,message:`MCP unregistered \u2014 ${i?.aiClientName??r}`,...i?.aiClientName?{aiClientName:i.aiClientName}:{}})),h.info("MCP instance unregistered",{instanceId:r,existed:a}),n.json({status:"ok",existed:a})}function W9(t,e,n){let{instanceId:r,aiClientName:i}=e.body;if(r&&i){let a=t.mcpInstances.get(r);a&&(a.aiClientName=i)}n.json({status:"ok"})}function H9(t){let e=3e4,n=Date.now(),r=Zr({appDataDir:t.config.appDataDir});for(let[a,o]of t.pluginClients)n-o.lastSeen>e&&(t.pluginClients.delete(a),t.pendingCommands.delete(a),pu(t,a));U9(t);let i=Un(t);return iS(i),{serverInstanceId:t.instanceId,sessionId:t.sessionId,mcpVersion:Ye,uptime:n-t.startTime,serverStartTime:t.startTime,serverExecutable:process.execPath,serverHost:t.config.httpHost,serverPort:t.config.httpPort,serverPid:process.pid,pluginClients:i.map(aS),studioRoutingMode:t.studioRoutingMode,pinnedTargetClientId:t.pinnedTargetClientId,mcpInstances:[{instanceId:t.instanceId,pid:process.pid,connectedAt:t.startTime,isServer:!0,cwd:process.cwd(),projectRoot:r,lastSeen:n,...t.aiClientName?{aiClientName:t.aiClientName}:{}},...Array.from(t.mcpInstances.values())],mcpInstanceCount:t.mcpInstances.size+1}}function lS(t,e){e.json(H9(t))}function uS(t,e,n){let r=e.query.instanceId;r&&t.mcpInstances.has(r)&&(t.mcpInstances.get(r).lastSeen=Date.now()),U9(t);let i=Un(t);iS(i);let s={...{status:"online",connectedClients:i.length,queuedCommands:y5(t),uptime:Date.now()-t.startTime,version:Ye,enableContextCapture:t.executionContextManager?.isEnabled()??t.config.enableContextCapture??!0,isClientMode:t.isClientMode,shuttingDown:t.shuttingDown,pid:process.pid,sessionId:t.sessionId,nodeVersion:process.version,studioRoutingMode:t.studioRoutingMode,pinnedTargetClientId:t.pinnedTargetClientId},instanceId:t.instanceId,mcpInstanceCount:t.mcpInstances.size+1,aiClientNames:oS(t),pluginVersion:t.pluginVersion||void 0,dashboardSseClients:t.dashboardSseClients?.size??0,websocketClients:i.length,pluginClients:i.map(aS),...t.isClientMode?{upstream:{reachable:t.clientModeUpstreamReachable,consecutiveFailures:t.clientModeConsecutiveHealthFailures,lastSuccessAt:t.clientModeLastHealthSuccessAt,lastFailureAt:t.clientModeLastHealthFailureAt,lastError:t.clientModeLastHealthError,baseUrl:t.baseUrl}}:{}};n.json(s)}function Z9(t,e,n,r){let i=e.ip||e.socket.remoteAddress||"";if(!(i==="127.0.0.1"||i==="::1"||i==="::ffff:127.0.0.1"||i==="localhost")){h.warn("Shutdown request rejected from non-localhost",{ip:i}),n.status(403).json({error:"Forbidden: localhost only"});return}h.info("Shutdown request received, initiating graceful shutdown",{requestedBy:i,uptime:Date.now()-t.startTime}),n.json({status:"shutting_down",message:"Server will shutdown gracefully",pid:process.pid}),setTimeout(async()=>{try{await r(),h.info("Graceful shutdown completed"),process.exit(0)}catch(o){h.error("Error during graceful shutdown",o),process.exit(1)}},100)}async function dS(t){if(t.isClientMode)try{let e=await fetch(`${t.baseUrl}/connection-info`);if(e.ok)return await e.json()}catch(e){h.warn("Failed to fetch connection info from server",{error:e})}return H9(t)}Ro();var _t={bridgeRunTest:"manage_studio_run_test_bridge",placeInfo:"system_info_place_info",clearLogs:"manage_logs_clear",createScript:"manage_scripts_create",getLogs:"manage_logs_get",deleteScript:"manage_scripts_delete",canonical:{playStart:"manage_studio_play_start",playStop:"manage_studio_play_stop",playPause:"manage_studio_play_pause",playResume:"manage_studio_play_resume",playStatus:"manage_studio_play_status",runTest:"manage_studio_run_test"}},Ube=new Set([_t.canonical.runTest]),Fbe=new Set([_t.canonical.playStop]),k8e=new Set([_t.canonical.playStart,_t.canonical.playStop,_t.canonical.playPause,_t.canonical.playResume,_t.canonical.playStatus]);function Di(t){return Ube.has(t)}function Rm(t){return Fbe.has(t)}var A8e=_t.canonical.playStop,G9=[5e3,15e3];fu();var qbe=new Set(["manage_assets_export_selection_rbxm","manage_assets_export_path_rbxm","manage_assets_review_model","manage_assets_generate_model","manage_assets_import_rbxm","manage_assets_generate_thumbnail"]),_n=class t extends Error{code;routing;constructor(e,n,r){super(n),this.name="CommandTargetSelectionError",this.code=e,this.routing=r,Object.setPrototypeOf(this,t.prototype)}};function Bbe(t={},e){let n={},r=t.clientId,i=t.targetAlias,a=t.placeId;if(r!==void 0){if(typeof r!="string"||r.trim().length===0)throw new _n("invalid_target_selector","clientId target selector must be a non-empty string",{selectionMode:"clientId",...typeof r=="string"?{requestedClientId:r.trim()}:{}});n.requestedClientId=r.trim()}if(i!==void 0){if(typeof i!="string"||i.trim().length===0)throw new _n("invalid_target_selector","targetAlias target selector must be a non-empty string",{selectionMode:"targetAlias",...typeof i=="string"?{requestedTargetAlias:i.trim()}:{}});n.requestedTargetAlias=i.trim()}if(a!==void 0&&Vbe(e,t)){if(typeof a!="number"||!Number.isFinite(a))throw new _n("invalid_target_selector","placeId target selector must be a finite number",{selectionMode:"placeId"});n.requestedPlaceId=a}return n}function pS(t,e,n={},r){let i=Bbe(n,r),a=V8(e,t.studioRoutingMode==="pinned"?t.pinnedTargetClientId:null);if(i.requestedClientId!==void 0)return Wbe(a,i);if(i.requestedTargetAlias!==void 0)return Hbe(a,i);if(i.requestedPlaceId!==void 0)return Zbe(a,i);if(t.studioRoutingMode==="pinned"&&t.pinnedTargetClientId!==null){let s=a.find(c=>c.clientId===t.pinnedTargetClientId);if(s)return{targetClientId:s.clientId,routing:ni("pinnedTarget",i,s)}}let o=a[0];return o?{targetClientId:o.clientId,routing:ni("recentPriority",i,o)}:{routing:{selectionMode:"globalQueue"}}}function Vbe(t,e){return!t||!qbe.has(t)?!0:e.scope==="shared"}function Wbe(t,e){let n=t.find(r=>r.clientId===e.requestedClientId);if(!n)throw new _n("target_client_not_found",`Target client not found: ${e.requestedClientId}`,ni("clientId",e));if(e.requestedTargetAlias!==void 0&&n.targetAlias!==e.requestedTargetAlias)throw new _n("target_selector_mismatch",`Target client ${n.clientId} does not match targetAlias ${e.requestedTargetAlias}`,ni("clientId",e,n));return K9("clientId",e,n),{targetClientId:n.clientId,routing:ni("clientId",e,n)}}function Hbe(t,e){let n=t.find(r=>r.targetAlias!==void 0&&nS(r.targetAlias)&&r.targetAlias===e.requestedTargetAlias);if(!n)throw new _n("target_alias_not_found",`Target alias not found: ${e.requestedTargetAlias}`,ni("targetAlias",e));return K9("targetAlias",e,n),{targetClientId:n.clientId,routing:ni("targetAlias",e,n)}}function Zbe(t,e){let n=t.filter(i=>i.placeId===e.requestedPlaceId);if(n.length===0)throw new _n("target_place_not_found",`Target place not found: ${e.requestedPlaceId}`,ni("placeId",e));if(n.length>1)throw new _n("target_place_ambiguous",`Target place is ambiguous: ${e.requestedPlaceId}`,ni("placeId",e));let r=n[0];return{targetClientId:r.clientId,routing:ni("placeId",e,r)}}function K9(t,e,n){if(e.requestedPlaceId!==void 0&&n.placeId!==e.requestedPlaceId)throw new _n("target_selector_mismatch",`Target client ${n.clientId} is not connected to placeId ${e.requestedPlaceId}`,ni(t,e,n))}function ni(t,e,n){let r={selectionMode:t};return e.requestedClientId!==void 0&&(r.requestedClientId=e.requestedClientId),e.requestedTargetAlias!==void 0&&(r.requestedTargetAlias=e.requestedTargetAlias),e.requestedPlaceId!==void 0&&(r.requestedPlaceId=e.requestedPlaceId),n!==void 0&&(r.actualClientId=n.clientId,n.targetAlias!==void 0&&(r.actualTargetAlias=n.targetAlias),n.placeId!==void 0&&(r.actualPlaceId=n.placeId),n.placeName!==void 0&&(r.actualPlaceName=n.placeName)),r}rA();le();wm();var nc={query_instances:{discriminator:"action",validActions:new Set(["get","children","find_child","find_descendant","wait_for_child","class_info","search_name","search_class","search_property","search_tag","file_tree","project_structure","descendants","ancestors"]),allowedParams:{query_instances_get:new Set(["path","sessionDebugId","siblingIndex","placeId","clientId","targetAlias"]),query_instances_children:new Set(["path","sessionDebugId","siblingIndex","recursive","maxDepth","placeId","clientId","targetAlias"]),query_instances_find_child:new Set(["path","childName","placeId","clientId","targetAlias"]),query_instances_find_descendant:new Set(["path","descendantName","placeId","clientId","targetAlias"]),query_instances_wait_for_child:new Set(["path","childName","timeout","placeId","clientId","targetAlias"]),query_instances_class_info:new Set(["className","placeId","clientId","targetAlias"]),query_instances_search_name:new Set(["root","query","caseSensitive","maxResults","placeId","clientId","targetAlias"]),query_instances_search_class:new Set(["className","root","includeSubclasses","maxResults","placeId","clientId","targetAlias"]),query_instances_search_property:new Set(["root","propertyName","propertyValue","maxResults","placeId","clientId","targetAlias"]),query_instances_search_tag:new Set(["root","tag","maxResults","placeId","clientId","targetAlias"]),query_instances_file_tree:new Set(["maxDepth","root","includeServices","placeId","clientId","targetAlias"]),query_instances_project_structure:new Set(["root","depth","placeId","clientId","targetAlias"]),query_instances_descendants:new Set(["path","sessionDebugId","siblingIndex","maxResults","placeId","clientId","targetAlias"]),query_instances_ancestors:new Set(["path","sessionDebugId","siblingIndex","placeId","clientId","targetAlias"])},paramAliases:{query_instances_search_name:{query:"pattern"},query_instances_search_property:{root:"rootPath"},query_instances_search_tag:{root:"rootPath"},query_instances_project_structure:{root:"rootPath"}}},mutate_instances:{discriminator:"action",validActions:new Set(["create","create_with_props","delete","clone","move","rename","pivot","create_tree","mass_create","mass_delete","mass_duplicate","smart_duplicate","scatter"]),allowedParams:{mutate_instances_create:new Set(["className","parent","name","properties","placeId","clientId","targetAlias"]),mutate_instances_create_with_props:new Set(["className","parent","name","properties","placeId","clientId","targetAlias"]),mutate_instances_delete:new Set(["path","sessionDebugId","siblingIndex","placeId","clientId","targetAlias"]),mutate_instances_clone:new Set(["path","sourcePath","sessionDebugId","siblingIndex","targetParent","newName","placeId","clientId","targetAlias"]),mutate_instances_move:new Set(["path","sessionDebugId","siblingIndex","newParent","placeId","clientId","targetAlias"]),mutate_instances_rename:new Set(["path","sessionDebugId","siblingIndex","newName","placeId","clientId","targetAlias"]),mutate_instances_pivot:new Set(["path","sessionDebugId","siblingIndex","position","cframe","offset","placeId","clientId","targetAlias"]),mutate_instances_create_tree:new Set(["parent","tree","placeId","clientId","targetAlias"]),mutate_instances_mass_create:new Set(["instances","placeId","clientId","targetAlias"]),mutate_instances_mass_delete:new Set(["paths","placeId","clientId","targetAlias"]),mutate_instances_mass_duplicate:new Set(["targetParent","paths","placeId","clientId","targetAlias"]),mutate_instances_smart_duplicate:new Set(["path","sessionDebugId","siblingIndex","targetParent","offset","count","placeId","clientId","targetAlias"]),mutate_instances_scatter:new Set(["templatePaths","region","count","seed","maxSlope","avoidWater","alignToNormal","scaleJitter","minSpacing","parentName","placeId","clientId","targetAlias"])},paramAliases:{mutate_instances_clone:{path:"sourcePath"},mutate_instances_smart_duplicate:{spacing:"offset"}}},manage_properties:{discriminator:"action",validActions:new Set(["get","set","get_all","set_multiple","get_attr","set_attr","get_all_attrs","delete_attr","add_tag","remove_tag","check_tag","get_tags","get_tagged","set_calculated","set_relative","mass_set","mass_get","modify_children"]),allowedParams:{manage_properties_get:new Set(["path","property","placeId","clientId","targetAlias"]),manage_properties_set:new Set(["path","property","value","placeId","clientId","targetAlias"]),manage_properties_get_all:new Set(["path","includeReadOnly","placeId","clientId","targetAlias"]),manage_properties_set_multiple:new Set(["path","properties","placeId","clientId","targetAlias"]),manage_properties_get_attr:new Set(["path","attribute","placeId","clientId","targetAlias"]),manage_properties_set_attr:new Set(["path","value","attribute","placeId","clientId","targetAlias"]),manage_properties_get_all_attrs:new Set(["path","placeId","clientId","targetAlias"]),manage_properties_delete_attr:new Set(["path","attribute","placeId","clientId","targetAlias"]),manage_properties_add_tag:new Set(["path","tag","placeId","clientId","targetAlias"]),manage_properties_remove_tag:new Set(["path","tag","placeId","clientId","targetAlias"]),manage_properties_check_tag:new Set(["path","tag","placeId","clientId","targetAlias"]),manage_properties_get_tags:new Set(["path","placeId","clientId","targetAlias"]),manage_properties_get_tagged:new Set(["tagName","root","maxResults","placeId","clientId","targetAlias"]),manage_properties_set_calculated:new Set(["path","expression","variables","propertyName","placeId","clientId","targetAlias"]),manage_properties_set_relative:new Set(["path","value","operation","amount","propertyName","placeId","clientId","targetAlias"]),manage_properties_mass_set:new Set(["paths","propertyName","propertyValue","placeId","clientId","targetAlias"]),manage_properties_mass_get:new Set(["paths","propertyName","placeId","clientId","targetAlias"]),manage_properties_modify_children:new Set(["parentPath","modifications","propertyName","propertyValue","filter","recursive","placeId","clientId","targetAlias"])},paramAliases:{manage_properties_get_tagged:{tagName:"tag",root:"rootPath"},manage_properties_set_relative:{amount:"value"}}},manage_scripts:{discriminator:"action",validActions:new Set(["get_source","set_source","create","delete","edit_replace","edit_insert","edit_delete","search","replace","get_dependencies","validate"]),allowedParams:{manage_scripts_get_source:new Set(["path","startLine","endLine","placeId","clientId","targetAlias"]),manage_scripts_set_source:new Set(["path","source","validate","placeId","clientId","targetAlias"]),manage_scripts_create:new Set(["source","scriptType","parent","name","placeId","clientId","targetAlias"]),manage_scripts_delete:new Set(["path","placeId","clientId","targetAlias"]),manage_scripts_edit_replace:new Set(["path","startLine","endLine","newLines","validate","placeId","clientId","targetAlias"]),manage_scripts_edit_insert:new Set(["path","lines","afterLine","content","validate","placeId","clientId","targetAlias"]),manage_scripts_edit_delete:new Set(["path","startLine","endLine","validate","placeId","clientId","targetAlias"]),manage_scripts_search:new Set(["path","pattern","caseSensitive","wholeWord","usePattern","maxResults","placeId","clientId","targetAlias"]),manage_scripts_replace:new Set(["path","pattern","replacement","usePattern","dryRun","placeId","clientId","targetAlias"]),manage_scripts_get_dependencies:new Set(["path","placeId","clientId","targetAlias"]),manage_scripts_validate:new Set(["source","path","placeId","clientId","targetAlias"])},paramAliases:{manage_scripts_edit_replace:{newLines:"newContent"},manage_scripts_edit_insert:{lines:"content"},manage_scripts_replace:{pattern:"searchPattern"}}},manage_ui:{discriminator:"action",validActions:new Set(["design_brief","create_tree","update","delete","preview","check"]),allowedParams:{manage_ui_design_brief:new Set(["brief","projectContext","agentCapabilities","placeId","clientId","targetAlias"]),manage_ui_create_tree:new Set(["briefId","tree","placeId","clientId","targetAlias"]),manage_ui_update:new Set(["targetPath","changes","briefId","placeId","clientId","targetAlias"]),manage_ui_delete:new Set(["targetPath","placeId","clientId","targetAlias"]),manage_ui_preview:new Set(["targetPath","briefId","viewportMode","profileIds","placeId","clientId","targetAlias"]),manage_ui_check:new Set(["targetPath","briefId","visualReview","viewportMode","profileIds","placeId","clientId","targetAlias"])}},manage_lighting:{discriminator:"action",validActions:new Set(["lighting","atmosphere","sky","terrain_props","time","mood"]),allowedParams:{manage_lighting_lighting:new Set(["properties","placeId","clientId","targetAlias"]),manage_lighting_atmosphere:new Set(["properties","createIfMissing","placeId","clientId","targetAlias"]),manage_lighting_sky:new Set(["properties","createIfMissing","placeId","clientId","targetAlias"]),manage_lighting_terrain_props:new Set(["properties","placeId","clientId","targetAlias"]),manage_lighting_time:new Set(["time","clockTime","placeId","clientId","targetAlias"]),manage_lighting_mood:new Set(["preset","overrides","placeId","clientId","targetAlias"])}},manage_selection:{discriminator:"action",validActions:new Set(["get","set","clear","cached","context","details","add","remove","watch"]),allowedParams:{manage_selection_get:new Set(["placeId","clientId","targetAlias"]),manage_selection_set:new Set(["paths","placeId","clientId","targetAlias"]),manage_selection_clear:new Set(["placeId","clientId","targetAlias"]),manage_selection_cached:new Set(["maxAge"]),manage_selection_context:new Set(["includeSource","includeProperties","includeChildren","placeId","clientId","targetAlias"]),manage_selection_details:new Set(["maxDepth","includeAncestors","placeId","clientId","targetAlias"]),manage_selection_add:new Set(["paths","placeId","clientId","targetAlias"]),manage_selection_remove:new Set(["paths","placeId","clientId","targetAlias"]),manage_selection_watch:new Set(["placeId","clientId","targetAlias"])}},manage_camera:{discriminator:"action",validActions:new Set(["info","focus_path","focus_position","suggest","screenshot"]),allowedParams:{manage_camera_info:new Set(["placeId","clientId","targetAlias"]),manage_camera_focus_path:new Set(["path","distance","duration","offset","respectAutoFocusSetting","placeId","clientId","targetAlias"]),manage_camera_focus_position:new Set(["position","distance","duration","offset","lookAt","respectAutoFocusSetting","placeId","clientId","targetAlias"]),manage_camera_suggest:new Set(["path","placeId","clientId","targetAlias"]),manage_camera_screenshot:new Set(["placeId","clientId","targetAlias"])},paramAliases:{manage_camera_suggest:{path:"targetPath"}}},manage_tween:{discriminator:"action",validActions:new Set(["create","play","pause","cancel"]),allowedParams:{manage_tween_create:new Set(["path","tweenInfo","properties","placeId","clientId","targetAlias"]),manage_tween_play:new Set(["tweenId","placeId","clientId","targetAlias"]),manage_tween_pause:new Set(["tweenId","placeId","clientId","targetAlias"]),manage_tween_cancel:new Set(["tweenId","placeId","clientId","targetAlias"])}},manage_audio:{discriminator:"action",validActions:new Set(["play","stop","pause","resume","set_listener"]),allowedParams:{manage_audio_play:new Set(["path","soundId","volume","looped","playbackSpeed","placeId","clientId","targetAlias"]),manage_audio_stop:new Set(["path","placeId","clientId","targetAlias"]),manage_audio_pause:new Set(["path","placeId","clientId","targetAlias"]),manage_audio_resume:new Set(["path","placeId","clientId","targetAlias"]),manage_audio_set_listener:new Set(["listenerType","listenerPath","placeId","clientId","targetAlias"])}},manage_animation:{discriminator:"action",validActions:new Set(["load","play","stop","get_tracks"]),allowedParams:{manage_animation_load:new Set(["path","animationId","placeId","clientId","targetAlias"]),manage_animation_play:new Set(["path","trackId","speed","fadeTime","weight","priority","placeId","clientId","targetAlias"]),manage_animation_stop:new Set(["path","trackId","fadeTime","placeId","clientId","targetAlias"]),manage_animation_get_tracks:new Set(["path","placeId","clientId","targetAlias"])}},manage_physics:{discriminator:"action",validActions:new Set(["register_group","set_collidable","get_groups"]),allowedParams:{manage_physics_register_group:new Set(["groupName","placeId","clientId","targetAlias"]),manage_physics_set_collidable:new Set(["group1","group2","collidable","placeId","clientId","targetAlias"]),manage_physics_get_groups:new Set(["placeId","clientId","targetAlias"])}},manage_effects:{discriminator:"action",validActions:new Set(["emit","clear","toggle"]),allowedParams:{manage_effects_emit:new Set(["path","count","placeId","clientId","targetAlias"]),manage_effects_clear:new Set(["path","placeId","clientId","targetAlias"]),manage_effects_toggle:new Set(["path","enabled","placeId","clientId","targetAlias"])}},manage_terrain:{discriminator:"action",validActions:new Set(["fill_block","fill_ball","fill_cylinder","fill_wedge","clear_region","clear_bounds","replace_material","colors_get","colors_set","read_voxel","read_voxels","write_voxels","generate","smooth"]),allowedParams:{manage_terrain_fill_block:new Set(["cframe","size","placeId","clientId","targetAlias"]),manage_terrain_fill_ball:new Set(["center","radius","placeId","clientId","targetAlias"]),manage_terrain_fill_cylinder:new Set(["cframe","radius","height","placeId","clientId","targetAlias"]),manage_terrain_fill_wedge:new Set(["cframe","size","placeId","clientId","targetAlias"]),manage_terrain_clear_region:new Set(["region","placeId","clientId","targetAlias"]),manage_terrain_clear_bounds:new Set(["min","max","placeId","clientId","targetAlias"]),manage_terrain_replace_material:new Set(["material","region","sourceMaterial","targetMaterial","placeId","clientId","targetAlias"]),manage_terrain_colors_get:new Set(["material","placeId","clientId","targetAlias"]),manage_terrain_colors_set:new Set(["material","color","placeId","clientId","targetAlias"]),manage_terrain_read_voxel:new Set(["position","placeId","clientId","targetAlias"]),manage_terrain_read_voxels:new Set(["region","resolution","placeId","clientId","targetAlias"]),manage_terrain_write_voxels:new Set(["region","resolution","materials","occupancy","placeId","clientId","targetAlias"]),manage_terrain_generate:new Set(["region","preset","seed","baseHeight","amplitude","frequency","octaves","persistence","waterLevel","edgeBlend","materialPalette","layers","placeId","clientId","targetAlias"]),manage_terrain_smooth:new Set(["region","intensity","placeId","clientId","targetAlias"])}},spatial_query:{discriminator:"action",validActions:new Set(["raycast","find_ground","check_placement","multi_raycast","scan_area","find_flat","find_spawn","analyze_walkable","spatial_map","find_space","bounds","snap_grid","collision"]),allowedParams:{spatial_query_raycast:new Set(["origin","direction","filterType","filterList","filterInstances","ignoreWater","placeId","clientId","targetAlias"]),spatial_query_find_ground:new Set(["maxDistance","position","filterList","filterInstances","offset","placeId","clientId","targetAlias"]),spatial_query_check_placement:new Set(["position","size","filterList","filterInstances","rotation","checkGround","placeId","clientId","targetAlias"]),spatial_query_multi_raycast:new Set(["filterType","filterList","filterInstances","ignoreWater","rays","placeId","clientId","targetAlias"]),spatial_query_scan_area:new Set(["size","filterList","filterInstances","center","resolution","maxResults","placeId","clientId","targetAlias"]),spatial_query_find_flat:new Set(["searchArea","minSize","maxSlope","tolerance","maxResults","placeId","clientId","targetAlias"]),spatial_query_find_spawn:new Set(["searchArea","spawnSize","minSpacing","preferOutdoor","count","placeId","clientId","targetAlias"]),spatial_query_analyze_walkable:new Set(["area","maxSlope","resolution","characterHeight","maxStepHeight","placeId","clientId","targetAlias"]),spatial_query_spatial_map:new Set(["path","rootPath","includeModels","maxResults","placeId","clientId","targetAlias"]),spatial_query_find_space:new Set(["size","searchArea","gridSize","gridSnap","padding","placeId","clientId","targetAlias"]),spatial_query_bounds:new Set(["path","paths","placeId","clientId","targetAlias"]),spatial_query_snap_grid:new Set(["gridSize","path","gridSnap","axes","placeId","clientId","targetAlias"]),spatial_query_collision:new Set(["position","path","ignorePaths","placeId","clientId","targetAlias"])},paramAliases:{spatial_query_spatial_map:{path:"rootPath"}}},manage_assets:{discriminator:"action",validActions:new Set(["insert","info","search","search_insert","insert_free","insert_package","export_selection_json","export_selection_rbxm","export_path_rbxm","review_model","generate_model","upload_asset","import_rbxm","generate_thumbnail"]),allowedParams:{manage_assets_insert:new Set(["assetId","parent","name","position","placeId","clientId","targetAlias"]),manage_assets_info:new Set(["assetId","placeId","clientId","targetAlias"]),manage_assets_search:new Set(["query","maxResults","category","sortType","placeId","clientId","targetAlias"]),manage_assets_search_insert:new Set(["parent","name","query","placeId","clientId","targetAlias"]),manage_assets_insert_free:new Set(["assetId","parent","name","position","placeId","clientId","targetAlias"]),manage_assets_insert_package:new Set(["assetId","parent","name","placeId","clientId","targetAlias"]),manage_assets_export_selection_json:new Set(["format","includeProperties","includeChildren","maxDepth","placeId","clientId","targetAlias"]),manage_assets_export_selection_rbxm:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","displayName","description","thumbnailMode","uploadMode","uploadTemporaryAssets","creatorType","creatorId","clientId","targetAlias"]),manage_assets_export_path_rbxm:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","sourcePath","displayName","description","thumbnailMode","uploadMode","uploadTemporaryAssets","creatorType","creatorId","clientId","targetAlias"]),manage_assets_review_model:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","sourcePath","displayName","description","thumbnailMode","uploadMode","uploadTemporaryAssets","creatorType","creatorId","exportToLibrary","expectedUse","expectedGroups","maxDescendants","maxDepth","readiness","clientId","targetAlias"]),manage_assets_generate_model:new Set(["contextId","contextSummary","replayMetadata","placeId","category","prompt","schemaMode","predefinedSchema","schemaGroups","size","maxTriangles","generateTextures","review","targetParent","name","displayName","expectedUse","expectedGroups","maxDescendants","maxDepth","readiness","anchorMode","clientId","targetAlias"]),manage_assets_upload_asset:new Set(["contextId","contextSummary","replayMetadata","placeId","category","assetType","sourcePath","displayName","description","creatorType","creatorId","clientId","targetAlias"]),manage_assets_import_rbxm:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","assetLibraryAssetId","targetParent","name","clientId","targetAlias"]),manage_assets_generate_thumbnail:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","assetLibraryAssetId","clientId","targetAlias"])},paramAliases:{manage_assets_search:{maxResults:"limit"}}},manage_open_cloud_assets:{discriminator:"action",validActions:new Set(["preflight","credential_status","capabilities","upload","link","update","info","operation_status"]),allowedParams:{manage_open_cloud_assets_preflight:new Set(["filePath","category","creatorType","creatorId"]),manage_open_cloud_assets_credential_status:new Set([]),manage_open_cloud_assets_capabilities:new Set([]),manage_open_cloud_assets_upload:new Set(["contextId","contextSummary","replayMetadata","filePath","category","scope","placeId","displayName","description","creatorType","creatorId","expectedPrice","waitForOperation","operationPollTimeoutMs","operationPollIntervalMs"]),manage_open_cloud_assets_link:new Set(["contextId","contextSummary","replayMetadata","assetId","filePath","category","scope","placeId","displayName","description"]),manage_open_cloud_assets_update:new Set(["contextId","contextSummary","replayMetadata","assetId","filePath","category","displayName","description","creatorType","creatorId","expectedPrice","updateMask","waitForOperation","operationPollTimeoutMs","operationPollIntervalMs"]),manage_open_cloud_assets_info:new Set(["assetId","readMask"]),manage_open_cloud_assets_operation_status:new Set(["operationId"])}},manage_sync:{discriminator:"action",validActions:new Set(["status_current_place","history","directions","read_file","write_file","progress"]),allowedParams:{manage_sync_status_current_place:new Set([]),manage_sync_history:new Set(["placeId","query"]),manage_sync_directions:new Set(["placeId"]),manage_sync_read_file:new Set(["placeId","instancePath"]),manage_sync_write_file:new Set(["placeId","instancePath","content"]),manage_sync_progress:new Set([])}},workspace_state:{discriminator:"action",validActions:new Set(["sync","snapshot","changes","viewport","clear_history","metadata","scripts","selection_info","clear_cache"]),allowedParams:{workspace_state_sync:new Set(["includeMetadata","placeId","clientId","targetAlias"]),workspace_state_snapshot:new Set(["placeId","clientId","targetAlias"]),workspace_state_changes:new Set(["limit","placeId","clientId","targetAlias"]),workspace_state_viewport:new Set(["includeCameraInfo","includeSelectionBounds","placeId","clientId","targetAlias"]),workspace_state_clear_history:new Set(["placeId","clientId","targetAlias"]),workspace_state_metadata:new Set(["placeId","clientId","targetAlias"]),workspace_state_scripts:new Set(["placeId","clientId","targetAlias"]),workspace_state_selection_info:new Set(["placeId","clientId","targetAlias"]),workspace_state_clear_cache:new Set(["placeId","clientId","targetAlias"])}},manage_logs:{discriminator:"action",validActions:new Set(["get","clear","errors"]),allowedParams:{manage_logs_get:new Set(["level","limit","pattern","since","sinceSeq","placeId","clientId","targetAlias"]),manage_logs_clear:new Set(["placeId","clientId","targetAlias"]),manage_logs_errors:new Set(["limit","placeId","clientId","targetAlias"])},paramAliases:{manage_logs_get:{level:"type"}}},system_info:{discriminator:"action",validActions:new Set(["ping","connection","usage","place_info","services","preflight"]),allowedParams:{system_info_ping:new Set(["message","placeId","clientId","targetAlias"]),system_info_connection:new Set([]),system_info_usage:new Set(["placeId","clientId","targetAlias"]),system_info_place_info:new Set(["placeId","clientId","targetAlias"]),system_info_services:new Set(["placeId","clientId","targetAlias"]),system_info_preflight:new Set(["placeId","clientId","targetAlias"])}},manage_studio:{discriminator:"action",validActions:new Set(["toggle_ui_preview","test_profile_get","test_profile_set","test_profile_reset","experience_language_get","experience_language_set","play_start","play_stop","play_pause","play_resume","play_status","run_test"]),allowedParams:{manage_studio_toggle_ui_preview:new Set(["enabled","placeId","clientId","targetAlias"]),manage_studio_test_profile_get:new Set(["placeId","clientId","targetAlias"]),manage_studio_test_profile_set:new Set(["testProfile","placeId","clientId","targetAlias"]),manage_studio_test_profile_reset:new Set(["placeId","clientId","targetAlias"]),manage_studio_experience_language_get:new Set(["placeId","clientId","targetAlias"]),manage_studio_experience_language_set:new Set(["locale","placeId","clientId","targetAlias"]),manage_studio_play_start:new Set(["mode","testProfile","restoreAfterTest","placeId","clientId","targetAlias"]),manage_studio_play_stop:new Set(["placeId","clientId","targetAlias"]),manage_studio_play_pause:new Set(["placeId","clientId","targetAlias"]),manage_studio_play_resume:new Set(["placeId","clientId","targetAlias"]),manage_studio_play_status:new Set(["placeId","clientId","targetAlias"]),manage_studio_run_test:new Set(["mode","script","test_name","timeout","testProfile","restoreAfterTest","placeId","clientId","targetAlias","contextId","contextSummary","replayMetadata"])}}};var Gbe={manage_scripts_validate:"internal",manage_selection_cached:"internal",manage_open_cloud_assets_preflight:"internal",manage_open_cloud_assets_credential_status:"internal",manage_open_cloud_assets_capabilities:"internal",manage_open_cloud_assets_upload:"internal",manage_open_cloud_assets_link:"internal",manage_open_cloud_assets_update:"internal",manage_open_cloud_assets_info:"internal",manage_open_cloud_assets_operation_status:"internal",manage_sync_status_current_place:"internal",manage_sync_history:"internal",manage_sync_directions:"internal",manage_sync_read_file:"internal",manage_sync_write_file:"internal",manage_sync_progress:"internal",system_info_connection:"internal",system_info_preflight:"internal",manage_studio_experience_language_set:"internal",manage_studio_run_test:"internal"};function fS(t){return Gbe[t]||"plugin"}var J9=new Set(["batch_execute","execute_luau","extended_call_method","extended_call_methods","extended_get_properties","extended_get_property","extended_set_properties","extended_set_property","manage_animation_get_tracks","manage_animation_load","manage_animation_play","manage_animation_stop","manage_assets_export_path_rbxm","manage_assets_export_selection_json","manage_assets_export_selection_rbxm","manage_assets_generate_model","manage_assets_generate_thumbnail","manage_assets_import_rbxm","manage_assets_info","manage_assets_insert","manage_assets_insert_free","manage_assets_insert_package","manage_assets_review_model","manage_assets_search","manage_assets_search_insert","manage_assets_upload_asset","manage_audio_pause","manage_audio_play","manage_audio_resume","manage_audio_set_listener","manage_audio_stop","manage_camera_screenshot","manage_effects_clear","manage_effects_emit","manage_effects_toggle","manage_lighting_atmosphere","manage_lighting_lighting","manage_lighting_mood","manage_lighting_sky","manage_lighting_terrain_props","manage_lighting_time","manage_open_cloud_assets_capabilities","manage_open_cloud_assets_credential_status","manage_open_cloud_assets_info","manage_open_cloud_assets_link","manage_open_cloud_assets_operation_status","manage_open_cloud_assets_preflight","manage_open_cloud_assets_update","manage_open_cloud_assets_upload","manage_physics_get_groups","manage_physics_register_group","manage_physics_set_collidable","manage_properties_mass_get","manage_properties_mass_set","manage_properties_modify_children","manage_properties_set_calculated","manage_properties_set_relative","manage_scripts_replace","manage_selection_add","manage_selection_context","manage_selection_details","manage_selection_remove","manage_selection_watch","manage_studio_experience_language_get","manage_studio_experience_language_set","manage_studio_play_pause","manage_studio_play_resume","manage_studio_play_start","manage_studio_play_status","manage_studio_play_stop","manage_studio_run_test","manage_studio_test_profile_get","manage_studio_test_profile_reset","manage_studio_test_profile_set","manage_studio_toggle_ui_preview","manage_sync_directions","manage_sync_history","manage_sync_progress","manage_sync_read_file","manage_sync_status_current_place","manage_sync_write_file","manage_terrain_clear_bounds","manage_terrain_clear_region","manage_terrain_colors_get","manage_terrain_colors_set","manage_terrain_fill_ball","manage_terrain_fill_block","manage_terrain_fill_cylinder","manage_terrain_fill_wedge","manage_terrain_generate","manage_terrain_read_voxel","manage_terrain_read_voxels","manage_terrain_replace_material","manage_terrain_smooth","manage_terrain_write_voxels","manage_tween_cancel","manage_tween_create","manage_tween_pause","manage_tween_play","manage_ui_check","manage_ui_create_tree","manage_ui_delete","manage_ui_design_brief","manage_ui_preview","manage_ui_update","mutate_instances_create_tree","mutate_instances_mass_create","mutate_instances_mass_delete","mutate_instances_mass_duplicate","mutate_instances_scatter","mutate_instances_smart_duplicate","query_instances_ancestors","query_instances_descendants","query_instances_file_tree","query_instances_project_structure","query_instances_search_property","query_instances_search_tag","spatial_query_analyze_walkable","spatial_query_bounds","spatial_query_check_placement","spatial_query_collision","spatial_query_find_flat","spatial_query_find_ground","spatial_query_find_space","spatial_query_find_spawn","spatial_query_multi_raycast","spatial_query_raycast","spatial_query_scan_area","spatial_query_snap_grid","spatial_query_spatial_map","system_info_place_info","system_info_services","workspace_state_changes","workspace_state_clear_cache","workspace_state_clear_history","workspace_state_metadata","workspace_state_scripts","workspace_state_selection_info","workspace_state_snapshot","workspace_state_sync","workspace_state_viewport"]),cO=new Set(["system_info_connection","system_info_ping","system_info_preflight","system_info_usage"]);function ar(t){return J9.has(t)?"pro":"basic"}Ir();mS();import{readFile as h_e}from"node:fs/promises";import y_e from"node:path";import{createHash as l_e,randomUUID as fO}from"node:crypto";import{mkdir as $m,readFile as iV,readdir as aV,rename as oV,rm as u_e,stat as d_e,writeFile as xS}from"node:fs/promises";import Mt from"node:path";import{extname as Xbe}from"node:path";import{constants as Qbe}from"node:fs";import{access as e_e,stat as t_e}from"node:fs/promises";var Tm=20*1024*1024,vS=[{category:"image",assetType:"Image",folder:"images",extensions:[".png",".jpeg",".jpg",".bmp",".tga"],supportsContentUpdate:!1,contentTypes:{".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".bmp":"image/bmp",".tga":"image/tga"}},{category:"decal",assetType:"Decal",folder:"decals",extensions:[".png",".jpeg",".jpg",".bmp",".tga"],supportsContentUpdate:!1,contentTypes:{".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".bmp":"image/bmp",".tga":"image/tga"}},{category:"audio",assetType:"Audio",folder:"audio",extensions:[".mp3",".ogg",".wav",".flac"],supportsContentUpdate:!1,contentTypes:{".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".flac":"audio/flac"}},{category:"mesh",assetType:"Mesh",folder:"meshes",extensions:[".mesh"],supportsContentUpdate:!1,contentTypes:{".mesh":"application/octet-stream"}},{category:"model",assetType:"Model",folder:"models",extensions:[".fbx",".gltf",".glb",".rbxm",".rbxmx"],supportsContentUpdate:!0,contentTypes:{".fbx":"model/fbx",".gltf":"model/gltf+json",".glb":"model/gltf-binary",".rbxm":"model/x-rbxm",".rbxmx":"model/x-rbxm"}},{category:"video",assetType:"Video",folder:"videos",extensions:[".mp4",".mov"],supportsContentUpdate:!1,contentTypes:{".mp4":"video/mp4",".mov":"video/quicktime"}},{category:"animation",assetType:"Animation",folder:"animations",extensions:[".rbxm",".rbxmx"],supportsContentUpdate:!0,contentTypes:{".rbxm":"model/x-rbxm",".rbxmx":"model/x-rbxm"}}],n_e=new Map(vS.map(t=>[t.category,t]));function hS(t){if(!t)throw new Error("Open Cloud asset upload is disabled in WEPPY Dashboard settings.")}function gS(t,e){return t.split(e.apiKey).join("[redacted]")}function yS(t){let e=n_e.get(t);if(!e)throw new Error(`Unsupported asset category: ${t}`);return e}function $u(t){return yS(t)}async function uO(t,e,n=Tm){let r=yS(t),i=Xbe(e).toLowerCase(),a=r.contentTypes[i]??null,o=await t_e(e),s=!0;try{await e_e(e,Qbe.R_OK)}catch{s=!1}return{category:t,extension:i,contentType:a,formatValid:a!==null,sizeBytes:o.size,sizeValid:o.size<=n,maxFileSizeBytes:n,regularFile:o.isFile(),readable:s}}function Q9(t,e){let n=t.creatorType??e.creatorType,r=t.creatorId??e.creatorId;if(!n||!r)throw new Error("creatorType and creatorId are required for Roblox Open Cloud asset upload/update.");return{...t,creatorType:n,creatorId:r}}async function eV(t,e,n){let r=await uO(t.category,e,n);if(!r.formatValid||!r.contentType)throw new Error(`Unsupported file extension ${r.extension||"(none)"} for ${t.category}.`);if(!r.regularFile)throw new Error("Asset path must reference a regular file.");if(!r.readable)throw new Error("Asset file is not readable.");if(!r.sizeValid)throw new Error(`Asset file is too large. Maximum size is ${n} bytes.`);return r.contentType}function tV(t){return typeof t.path=="string"&&t.path.startsWith("operations/")?t.path:null}function nV(t,e,n,r){let i={apiKey:t.apiKey,operationId:e};return n!==void 0&&(i.intervalMs=n),r!==void 0&&(i.timeoutMs=r),i}var Du=class{client;credentialStore;isOpenCloudUploadEnabled;maxFileSizeBytes;constructor(e){this.client=e.client,this.credentialStore=e.credentialStore,this.isOpenCloudUploadEnabled=e.isOpenCloudUploadEnabled,this.maxFileSizeBytes=e.maxFileSizeBytes??Tm}getCapabilities(){return vS.map(({contentTypes:e,...n})=>n)}async uploadAsset(e){hS(this.isOpenCloudUploadEnabled());let n=await this.getRequiredCredential(),r=Q9(e,n),i=yS(r.category),a=await eV(i,r.filePath,this.maxFileSizeBytes);try{let o={apiKey:n.apiKey,assetType:i.assetType,displayName:r.displayName,description:r.description??"",creatorType:r.creatorType,creatorId:r.creatorId,filePath:r.filePath,contentType:a};r.expectedPrice!==void 0&&(o.expectedPrice=r.expectedPrice);let s=await this.client.createAsset(o);if(r.waitForOperation){let c=tV(s);return c?await this.client.pollOperation(nV(n,c,r.operationPollIntervalMs,r.operationPollTimeoutMs)):s}return s}catch(o){throw new Error(gS(o instanceof Error?o.message:String(o),n))}}async updateAsset(e){hS(this.isOpenCloudUploadEnabled());let n=await this.getRequiredCredential(),r=Q9(e,n),i=yS(r.category),a;if(r.filePath){if(!i.supportsContentUpdate)throw new Error(`${i.category} assets do not support content updates.`);a=await eV(i,r.filePath,this.maxFileSizeBytes)}try{let o={apiKey:n.apiKey,assetId:r.assetId,assetType:i.assetType,creatorType:r.creatorType,creatorId:r.creatorId};r.filePath&&(o.filePath=r.filePath),a!==void 0&&(o.contentType=a),r.displayName!==void 0&&(o.displayName=r.displayName),r.description!==void 0&&(o.description=r.description),r.updateMask!==void 0&&(o.updateMask=r.updateMask),r.expectedPrice!==void 0&&(o.expectedPrice=r.expectedPrice);let s=await this.client.updateAsset(o);if(r.waitForOperation){let c=tV(s);return c?await this.client.pollOperation(nV(n,c,r.operationPollIntervalMs,r.operationPollTimeoutMs)):s}return s}catch(o){throw new Error(gS(o instanceof Error?o.message:String(o),n))}}async getAsset(e){let n=await this.getRequiredCredential();try{let r={apiKey:n.apiKey,assetId:e.assetId};return e.readMask!==void 0&&(r.readMask=e.readMask),await this.client.getAsset(r)}catch(r){throw new Error(gS(r instanceof Error?r.message:String(r),n))}}async getOperation(e){let n=await this.getRequiredCredential();try{return await this.client.getOperation({apiKey:n.apiKey,operationId:e.operationId})}catch(r){throw new Error(gS(r instanceof Error?r.message:String(r),n))}}async getRequiredCredential(){let e=await this.credentialStore.getCredentialForUse();if(!e)throw new Error("Configure a Roblox Open Cloud API key in WEPPY Dashboard before using Open Cloud asset upload.");return e}};import rV from"node:fs";import un from"node:path";ix();var r_e=/^asset_(image|decal|audio|mesh|model|video|animation)_\d+_[a-z0-9]+$/;function i_e(t){if(!Number.isInteger(t)||t<0)throw new Error(`Invalid place ID: ${t}`)}function a_e(t,e){try{return rV.statSync(un.join(t,e,".sync-meta.json")).isFile()}catch{return!1}}function o_e(t,e){i_e(e.placeId);let n=`place_${e.placeId}`,r=e.placeName?lu(e.placeName):"",i=r?`${n}_${r}`:n,a=[];try{let o=new RegExp(`^place_${e.placeId}(?:_.*)?$`);a=rV.readdirSync(t,{withFileTypes:!0}).filter(s=>s.isDirectory()&&o.test(s.name)).map(s=>s.name).sort()}catch{return i}return r&&a.includes(i)?i:a.find(o=>a_e(t,o))??(a.includes(i)?i:null)??a[0]??i}function dO(t){let e=un.resolve(t.projectSyncRoot),n=$u(t.category).folder,r=t.scope.kind==="place"?un.join(e,o_e(e,t.scope),"assets",n):un.join(e,"shared-assets",n);return{root:r,inbox:un.join(r,"inbox"),index:un.join(r,".asset-library-index.json")}}function s_e(t){let e=r_e.exec(t);return e?.[1]?e[1]:null}function Am(t,e){let n=s_e(t);return n?e?n===e:!0:!1}function bS(t,e){if(!Am(t,e))throw new Error(`Invalid asset ID: ${t}`)}function $i(t,e){let n=un.relative(un.resolve(t),un.resolve(e));return n===""||!n.startsWith("..")&&!un.isAbsolute(n)}function c_e(t){bS(t.assetId,t.category);let e=dO(t),n=un.resolve(e.root,t.assetId);if(!$i(e.root,n))throw new Error(`Invalid asset path for ${t.assetId}`);return n}function _S(t){let e=c_e(t),n=un.resolve(e,t.relativeFileName);if(!$i(e,n))throw new Error(`Invalid asset file path for ${t.assetId}`);return n}function Om(t,e){return un.relative(un.resolve(t),un.resolve(e)).split(un.sep).join("/")}var sV=20*1024*1024,p_e=200,pO=8,f_e=512,m_e=120;function cV(t,e){return t.kind!==e.kind?!1:t.kind==="shared"&&e.kind==="shared"?!0:t.kind==="place"&&e.kind==="place"&&t.placeId===e.placeId}function lV(t,e){let n=Mt.extname(t).toLowerCase(),r=$u(e);if(!r.extensions.includes(n))return null;let i=r.contentTypes[n];return i?{canonicalExt:n,mimeType:i}:null}function mO(t,e,n){if(e!=="image"&&e!=="decal")return!0;let r=Mt.extname(t).toLowerCase();return r===".png"?n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10:r===".jpg"||r===".jpeg"?n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255:r===".bmp"?n.length>=2&&n[0]===66&&n[1]===77:r===".tga"?n.length>0:!1}function uV(t){return l_e("sha256").update(t).digest("hex")}function gO(t){if(t===void 0||t==="")return"";if(t.length>f_e||t.includes("\0")||t.includes("\\")||Mt.isAbsolute(t))throw new Error(`Invalid Asset Library folder path: ${t}`);let e=t.split("/");if(e.length>pO||e.some(n=>n.length===0||n.length>m_e||n==="."||n===".."))throw new Error(`Invalid Asset Library folder path: ${t}`);return e.join("/")}function SS(t){return t.now?.()??Date.now()}function g_e(t){return(t.randomId?.()??fO().replace(/-/g,"").slice(0,6)).toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,12)||"asset"}function dV(t,e){let n=Math.floor(SS(t)/1e3);for(let r=0;r<20;r++){let i=g_e(t),a=r===0?`asset_${t.category}_${n}_${i}`:`asset_${t.category}_${n}_${i}${r}`;if(!e.has(a))return a}return`asset_${t.category}_${n}_${fO().replace(/-/g,"").slice(0,10)}`}function pV(t){let e=Mt.parse(t).name.trim();return e.length>0?e:t}function fV(t){if(t.mimeType!=="image/png")throw new Error("Asset Library preview must be an image/png thumbnail");if(Mt.basename(t.fileName).toLowerCase()!=="thumbnail.png")throw new Error("Asset Library preview file must be thumbnail.png");if(!mO("thumbnail.png","image",t.content))throw new Error("Asset Library preview is not a valid PNG file");return{fileName:"thumbnail.png",content:t.content}}async function hO(t,e){let n=`${t}.tmp.${fO().slice(0,8)}`;await xS(n,JSON.stringify(e,null,2),"utf8"),await oV(n,t)}async function mV(t,e){try{let n=await iV(Mt.join(e,"asset.json"),"utf8"),r=JSON.parse(n);return!Am(r.id,t.category)||r.category!==t.category||!cV(r.scope,t.scope)?null:(gO(r.folderPath),r)}catch{return null}}async function Dm(t,e){let n;try{n=await aV(e.root,{withFileTypes:!0})}catch(i){if(i?.code==="ENOENT")return[];throw i}let r=[];for(let i of n.sort((a,o)=>a.name.localeCompare(o.name))){if(!i.isDirectory()||!Am(i.name,t.category))continue;let a=Mt.join(e.root,i.name),o=await mV(t,a);o&&r.push(o)}return r.sort((i,a)=>a.createdAt.localeCompare(i.createdAt)||a.id.localeCompare(i.id))}async function Nu(t,e,n){if(bS(n.id,t.category),n.category!==t.category||!cV(n.scope,t.scope))throw new Error(`Asset metadata does not match library scope/category: ${n.id}`);gO(n.folderPath);let r=Mt.join(e.root,n.id);if(!$i(e.root,r))throw new Error(`Invalid asset path for ${n.id}`);await $m(r,{recursive:!0}),await hO(Mt.join(r,"asset.json"),n)}async function gV(t,e){await $m(t.root,{recursive:!0});let n={version:1,generatedAt:new Date().toISOString(),assets:e.map(r=>r.id)};await hO(t.index,n)}function ri(t,e,n){return{fileName:t,reason:e,message:n}}async function hV(t,e=t,n=[]){let r;try{r=await aV(e,{withFileTypes:!0})}catch(a){if(a?.code==="ENOENT")return[];throw a}let i=[];for(let a of r.sort((o,s)=>o.name.localeCompare(s.name))){let o=[...n,a.name],s=Mt.join(e,a.name);if(a.isDirectory()&&!a.isSymbolicLink()&&!a.name.startsWith(".")){let c=o.join("/");if(o.length>pO){i.push({entry:a,sourcePath:s,relativePath:c,folderPath:n.join("/"),skipReason:"maxDepth",skipMessage:`folder depth exceeds ${pO}`});continue}try{gO(c)}catch{i.push({entry:a,sourcePath:s,relativePath:c,folderPath:n.join("/"),skipReason:"unsupportedType",skipMessage:"invalid Asset Library folder path"});continue}i.push(...await hV(t,s,o));continue}i.push({entry:a,sourcePath:s,relativePath:o.join("/"),folderPath:n.join("/")})}return i}async function Ni(t){let e=dO(t);return await $m(e.inbox,{recursive:!0}),e}async function wS(t){let e=await Ni(t),n=await Dm(t,e);return await gV(e,n),n}async function Xt(t,e){bS(e,t.category);let n=await Ni(t),r=Mt.join(n.root,e);if(!$i(n.root,r))throw new Error(`Invalid asset path for ${e}`);let i=await mV(t,r);if(!i)throw new Error(`Asset not found: ${e}`);return i}async function ju(t){let e=await Ni(t),n=await Dm(t,e),r={version:1,generatedAt:new Date().toISOString(),assets:n.map(i=>i.id)};return await hO(e.index,r),r}async function yV(t){let e=await Ni(t),n=await Dm(t,e),r=new Set(n.map(p=>p.id)),i=new Set(n.map(p=>p.file.sha256)),a=[],o=[],s=t.maxFileSizeBytes??sV,c=t.maxFilesPerRescan??p_e,l=await hV(e.inbox),u=0;for(let p of l){let{entry:f,sourcePath:m}=p;if(p.skipReason){o.push(ri(p.relativePath,p.skipReason,p.skipMessage??"inbox entry skipped"));continue}if(f.name.startsWith(".")&&!f.isFile()){o.push(ri(p.relativePath,"hidden","hidden or system file"));continue}if(f.isSymbolicLink()){o.push(ri(p.relativePath,"symlink","symlink files are not followed"));continue}if(f.isDirectory()){o.push(ri(p.relativePath,"nestedDirectory","nested directories are not scanned"));continue}if(!f.isFile()){o.push(ri(p.relativePath,"unsupportedType","unsupported inbox entry type"));continue}if(u+=1,u>c){o.push(ri(p.relativePath,"maxFileCount","rescan file count limit exceeded"));continue}if(f.name.startsWith(".")){o.push(ri(p.relativePath,"hidden","hidden or system file"));continue}let g=lV(f.name,t.category);if(!g){o.push(ri(f.name,"unsupportedType",`unsupported ${t.category} extension`));continue}let y=await d_e(m);if(y.size>s){o.push(ri(f.name,"oversized","asset file is larger than the configured limit"));continue}let v=await iV(m);if(!mO(f.name,t.category,v)){o.push(ri(f.name,"invalidSignature","file signature does not match the extension"));continue}let b=uV(v);if(i.has(b)){o.push(ri(f.name,"duplicate","asset content already exists in Asset Library"));continue}let x=dV(t,r);r.add(x),i.add(b);let I=Mt.join(e.root,x),w=`original${g.canonicalExt}`;await $m(I,{recursive:!0}),await oV(m,Mt.join(I,w));let N=new Date(SS(t)).toISOString(),k={version:1,id:x,category:t.category,scope:t.scope,...p.folderPath?{folderPath:p.folderPath}:{},status:"localOnly",displayName:pV(f.name),description:"",source:{kind:"generated",originalPath:Om(t.projectSyncRoot,m)},file:{original:w,preview:null,mimeType:g.mimeType,sha256:b,sizeBytes:y.size,width:null,height:null,durationMs:null},roblox:{uploaded:!1},usage:{lastScannedAt:null,scanSource:null,references:[]},createdAt:N,updatedAt:N};await Nu(t,e,k),a.push(k)}let d=await Dm(t,e);return await gV(e,d),{assets:d,adopted:a,skipped:o,adoptedCount:a.length,skippedCount:o.length}}async function Nm(t){let e=await Ni(t),n=lV(t.originalFileName,t.category);if(!n)throw new Error(`Unsupported ${t.category} extension for Asset Library export`);let r=t.maxFileSizeBytes??sV;if(t.content.length>r)throw new Error("asset file is larger than the configured limit");if(!mO(t.originalFileName,t.category,t.content))throw new Error("file signature does not match the extension");let i=await Dm(t,e),a=uV(t.content),o=i.find(y=>y.file.sha256===a);if(o)return{asset:o,deduplicated:!0};let s=new Set(i.map(y=>y.id)),c=dV(t,s),l=Mt.join(e.root,c);if(!$i(e.root,l))throw new Error(`Invalid asset path for ${c}`);let u=`original${n.canonicalExt}`;await $m(l,{recursive:!0}),await xS(Mt.join(l,u),t.content);let d=null;if(t.preview){let y=fV(t.preview);d=y.fileName,await xS(Mt.join(l,y.fileName),y.content)}let p=new Date(SS(t)).toISOString(),f=t.roblox??{uploaded:!1},m=f.uploaded&&f.assetId?"uploaded":"localOnly",g={version:1,id:c,category:t.category,scope:t.scope,status:m,displayName:t.displayName?.trim()||pV(t.originalFileName),description:t.description??"",source:{...t.source,originalPath:Om(t.projectSyncRoot,Mt.join(l,u))},file:{original:u,preview:d,mimeType:n.mimeType,sha256:a,sizeBytes:t.content.length,width:null,height:null,durationMs:null},roblox:f,usage:{lastScannedAt:null,scanSource:null,references:[]},...t.rbxm?{rbxm:t.rbxm}:{},createdAt:p,updatedAt:p};return await Nu(t,e,g),await ju(t),{asset:g,deduplicated:!1}}async function vV(t){let e=await Ni(t),n=await Xt(t,t.assetId),r=fV(t.preview),i=_S({...t,relativeFileName:r.fileName});await xS(i,r.content);let a={...n,file:{...n.file,preview:r.fileName},...n.rbxm&&t.rbxmThumbnail?{rbxm:{...n.rbxm,thumbnail:t.rbxmThumbnail}}:{},updatedAt:new Date(SS(t)).toISOString()};return await Nu(t,e,a),await ju(t),{asset:a}}async function bV(t,e,n){let r=await Ni(t),i=await Xt(t,e),a={...i,displayName:typeof n.displayName=="string"?n.displayName:i.displayName,description:typeof n.description=="string"?n.description:i.description,source:{...i.source,...n.source?.agent!==void 0?{agent:n.source.agent}:{},...n.source?.contextId!==void 0?{contextId:n.source.contextId}:{},...n.source?.prompt!==void 0?{prompt:n.source.prompt}:{}},updatedAt:new Date().toISOString()};return await Nu(t,r,a),await ju(t),a}async function _V(t,e,n){let r=await Ni(t),a={...await Xt(t,e),usage:n,updatedAt:new Date().toISOString()};return await Nu(t,r,a),await ju(t),a}async function xV(t,e){let n=await Ni(t);await Xt(t,e);let r=Mt.join(n.root,e);if(!$i(n.root,r))throw new Error(`Invalid asset path for ${e}`);return await u_e(r,{recursive:!0}),await ju(t),{assetId:e,removed:1}}async function ji(t){let e=await Ni(t);return await Nu(t,e,t.asset),await ju(t),t.asset}async function Mu(t){let e=await Xt(t,t.assetId);return _S({...t,relativeFileName:e.file.original})}async function SV(t){let e=await Xt(t,t.assetId);return _S({...t,relativeFileName:e.file.preview??e.file.original})}var v_e="https://create.roblox.com/dashboard/creations/store",b_e="manage_assets_import_rbxm",vO="manage_assets_generate_thumbnail",__e="manage_assets_review_model";var bO=new Set([b_e,vO]),_O=new Set(["manage_assets_export_selection_rbxm","manage_assets_export_path_rbxm",__e]),x_e=new Set(["model","animation"]);function st(t){return t&&typeof t=="object"?t:null}function S_e(t){if(typeof t!="string"||!x_e.has(t))throw new Error(`Unsupported Asset Library .rbxm round-trip category: ${String(t??"(missing)")}`);return t}function w_e(t){if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return t;if(typeof t=="string"&&t.trim().length>0){let e=Number.parseInt(t,10);if(Number.isInteger(e)&&e>=0)return e}return null}function wV(t,e){for(let n of t.pluginClients.values())if(!(typeof n.placeId!="number"||!Number.isFinite(n.placeId))&&!(e!==void 0&&n.placeId!==e))return{placeId:n.placeId,...n.placeName?{placeName:n.placeName}:{}};return null}function xO(t,e){let n=ft(t.config.dataDir),r=S_e(e.category),i=typeof e.scope=="string"?e.scope:"place",a=typeof e.assetLibraryAssetId=="string"&&e.assetLibraryAssetId.length>0?e.assetLibraryAssetId:void 0;if(i==="shared")return{projectSyncRoot:n,scope:{kind:"shared"},category:r,...a?{assetId:a}:{}};if(i!=="place")throw new Error(`Invalid Asset Library scope: ${i}`);let o=w_e(e.placeId),s=t.syncController?.getDefaultRuntimePlaceId()??null,c=o??s??wV(t)?.placeId??null;if(c===null)throw new Error("No placeId is available for Asset Library .rbxm round-trip.");let l=wV(t,c);return{projectSyncRoot:n,scope:{kind:"place",placeId:c,...l?.placeName?{placeName:l.placeName}:{}},category:r,...a?{assetId:a}:{}}}function I_e(t){if(y_e.extname(t.file.original).toLowerCase()!==".rbxm")throw new Error(`Asset Library Studio round-trip supports original.rbxm only. Unsupported original file: ${t.file.original}`)}function C_e(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} is missing`);return Buffer.from(t,"base64")}function P_e(t,e){let n=st(e),i={kind:n?.kind==="generation"||typeof t.prompt=="string"?"generated":"studioExport",originalPath:"studio:selection"};if(n){let a=typeof n.path=="string"?n.path:typeof n.kind=="string"?n.kind:void 0;a&&(i.originalPath=`studio:${a}`);let o=ye(n.prompt,1e3);o&&(i.prompt=o)}if(!i.prompt){let a=ye(t.prompt,1e3);a&&(i.prompt=a)}return typeof t.contextId=="string"&&(i.contextId=t.contextId),i}function kV(t){let e=st(t);if(!e)return;let n={};typeof e.width=="number"&&(n.width=e.width),typeof e.height=="number"&&(n.height=e.height),typeof e.source=="string"&&(n.source=e.source),typeof e.error=="string"&&(n.error=e.error);let r=jm(e.attempts);return r.length>0&&(n.attempts=r),Object.keys(n).length>0?n:void 0}function ye(t,e){return typeof t!="string"?null:t.slice(0,e)}function k_e(t){if(typeof t!="string")return null;let e=t.trim();return/^\d+$/.test(e)?e:null}function IV(t){return`rbxassetid://${t}`}function CV(t){return`${v_e}/${t}/configure`}function PV(t){return`assets/${t}`}function Pr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function RV(t){return Array.isArray(t)?t.slice(0,100).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.name,256),i=ye(n.className,128),a=ye(n.path,512);return r===null||i===null||a===null?[]:[{name:r,className:i,path:a}]}):[]}function R_e(t){let e=st(t);if(!e)return{};let n={};for(let[r,i]of Object.entries(e).slice(0,100))typeof i!="number"||!Number.isFinite(i)||i<0||(n[r.slice(0,128)]=Math.floor(i));return n}function E_e(t){return Array.isArray(t)?t.slice(0,200).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.path,512),i=ye(n.property,128),a=ye(n.value,1024);if(r===null||i===null||a===null)return[];let o=ye(n.assetId,64);return[{path:r,property:i,value:a,...o?{assetId:o}:{}}]}):[]}function jm(t){return Array.isArray(t)?t.slice(0,8).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.method,80),i=n.status==="success"||n.status==="failed"||n.status==="skipped"?n.status:null;if(r===null||i===null)return[];let a=ye(n.message,512);return[{method:r,status:i,...a?{message:a}:{}}]}):[]}function T_e(t,e){let n=t.thumbnailMode==="auto"?"auto":"none";if(n==="none")return{mode:n,status:"skipped",message:"Thumbnail generation disabled"};let r=kV(e),i=st(e),a=typeof i?.pngBase64=="string"&&i.pngBase64.length>0,o=typeof i?.base64Rgba=="string"&&i.base64Rgba.length>0&&i.format==="rgba8"&&typeof i.width=="number"&&typeof i.height=="number";if(r&&(a||o)){let s=Pr(r.width),c=Pr(r.height),l=jm(i?.attempts);return{mode:n,status:"generated",...s!==void 0?{width:s}:{},...c!==void 0?{height:c}:{},...typeof r.source=="string"?{source:r.source.slice(0,128)}:{},...l.length>0?{attempts:l}:{}}}if(r&&typeof r.error=="string"){let s=jm(st(e)?.attempts);return{mode:n,status:"failed",message:r.error.slice(0,512),...s.length>0?{attempts:s}:{}}}return{mode:n,status:"skipped",message:"Thumbnail was not returned"}}function A_e(t,e){let n=st(t);if(!n)return e;let r=n.mode==="auto"||n.mode==="none"?n.mode:e.mode,i=n.status==="generated"||n.status==="skipped"||n.status==="failed"?n.status:e.status,a=ye(n.message,512),o=Pr(n.width),s=Pr(n.height),c=ye(n.source,128),l=jm(n.attempts);return{mode:r,status:i,...a?{message:a}:{},...o!==void 0?{width:o}:{},...s!==void 0?{height:s}:{},...c?{source:c}:{},...l.length>0?{attempts:l}:{}}}function yO(t,e=0){if(e>3)return;if(typeof t=="string")return t.slice(0,512);if(typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return t.slice(0,50).flatMap(i=>{let a=yO(i,e+1);return a===void 0?[]:[a]});let n=st(t);if(!n)return;let r={};for(let[i,a]of Object.entries(n).slice(0,50)){let o=yO(a,e+1);o!==void 0&&(r[i.slice(0,128)]=o)}return r}function O_e(t){let e=st(t),n=Pr(e?.x),r=Pr(e?.y),i=Pr(e?.z);if(!(n===void 0||r===void 0||i===void 0))return{x:n,y:r,z:i}}function D_e(t){return Array.isArray(t)?t.slice(0,100).flatMap(e=>{let n=st(e);if(!n)return[];let r=n.severity==="info"||n.severity==="warning"||n.severity==="error"?n.severity:null,i=ye(n.category,80),a=ye(n.code,120),o=ye(n.path,512),s=ye(n.message,512);if(!r||i===null||a===null||o===null||s===null)return[];let c=ye(n.suggestion,512);return[{severity:r,category:i,code:a,path:o,message:s,...c?{suggestion:c}:{}}]}):[]}function $_e(t){let e=st(t);if(!e)return;let n=e.readiness==="ready"||e.readiness==="review"||e.readiness==="blocked"?e.readiness:null;if(!n)return;let r=yO(e.summary),i=ye(e.reviewedAt,64),a=RV(e.roots);return{readiness:n,...i?{reviewedAt:i}:{},...a.length>0?{roots:a}:{},summary:st(r)??{},findings:D_e(e.findings)}}function N_e(t){let e=st(t);if(!e)return;let n={};for(let[r,i]of Object.entries(e).slice(0,16))typeof i=="string"&&(n[r.slice(0,128)]=i.slice(0,256)),typeof i=="number"&&Number.isFinite(i)&&(n[r.slice(0,128)]=i),typeof i=="boolean"&&(n[r.slice(0,128)]=i);return Object.keys(n).length>0?n:void 0}function j_e(t){let e=st(t);if(!e)return;let n=ye(e.provider,120);if(!n)return;let r=ye(e.generatedAt,64),i=ye(e.prompt,1e3),a=e.schemaMode==="predefined"||e.schemaMode==="custom"?e.schemaMode:void 0,o=e.predefinedSchema==="Body1"||e.predefinedSchema==="Car5"?e.predefinedSchema:void 0,s=Array.isArray(e.schemaGroups)?e.schemaGroups.slice(0,50).flatMap(f=>{let m=ye(f,120);return m?[m]:[]}):void 0,c=O_e(e.requestedSize),l=Pr(e.maxTriangles),u=ye(e.targetParent,512),d=ye(e.path,512),p=N_e(e.metadata);return{provider:n,...r?{generatedAt:r}:{},...i?{prompt:i}:{},...a?{schemaMode:a}:{},...o?{predefinedSchema:o}:{},...s&&s.length>0?{schemaGroups:s}:{},...c?{requestedSize:c}:{},...l!==void 0?{maxTriangles:Math.floor(l)}:{},...typeof e.generateTextures=="boolean"?{generateTextures:e.generateTextures}:{},...u?{targetParent:u}:{},...d?{path:d}:{},...p?{metadata:p}:{}}}function M_e(t){return Array.isArray(t)?t.slice(0,100).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.path,512),i=n.assetType==="Mesh"||n.assetType==="Image"||n.assetType==="Model"?n.assetType:null,a=n.status==="uploaded"||n.status==="failed"?n.status:null;if(r===null||i===null||a===null)return[];let o=ye(n.assetId,64),s=ye(n.assetUri,128),c=n.creatorType==="user"||n.creatorType==="group"?n.creatorType:void 0,l=ye(n.creatorId,64),u=ye(n.sourceProperty,128),d=ye(n.uploadedAt,64),p=ye(n.message,512);return[{path:r,assetType:i,status:a,...o?{assetId:o}:{},...s?{assetUri:s}:{},...c?{creatorType:c}:{},...l?{creatorId:l}:{},...u?{sourceProperty:u}:{},...d?{uploadedAt:d}:{},...p?{message:p}:{}}]}):[]}function L_e(t){let e=st(t);if(!e||e.uploaded!==!0)return;let n=k_e(e.assetId);if(!n)return;let r=ye(e.uploadedAt,64)??new Date().toISOString(),i=e.creatorType==="user"||e.creatorType==="group"?e.creatorType:void 0,a=ye(e.creatorId,64);return{uploaded:!0,assetId:n,assetUri:IV(n),assetWebUrl:CV(n),remotePath:PV(n),uploadedAt:r,uploadAttempts:[{startedAt:r,finishedAt:r,status:"uploaded",assetRole:"primary",...i?{creatorType:i}:{},...a?{creatorId:a}:{},assetId:n,assetUri:IV(n),assetWebUrl:CV(n),remotePath:PV(n)}]}}function z_e(t){let e=st(t.value),n=RV(e?.roots),r=R_e(e?.classCounts),i=E_e(e?.resourceReferences),a=$_e(e?.review),o=j_e(e?.generation),s=M_e(e?.studioUploads),c=Pr(e?.exportedCount)??Pr(t.exportedCount)??n.length;return{exportedCount:Math.max(0,Math.floor(c)),roots:n,classCounts:r,resourceReferences:i,thumbnail:A_e(e?.thumbnail,t.fallbackThumbnail),...a?{review:a}:{},...o?{generation:o}:{},...s.length>0?{studioUploads:s}:{}}}function U_e(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10}function EV(t){let e=st(t);if(!e)return;let n=null;if(typeof e.pngBase64=="string"&&e.pngBase64.length>0?n=Buffer.from(e.pngBase64,"base64"):typeof e.base64Rgba=="string"&&e.base64Rgba.length>0&&e.format==="rgba8"&&typeof e.width=="number"&&typeof e.height=="number"&&(n=Buffer.from(X9(e.base64Rgba,e.width,e.height),"base64")),!!n){if(!U_e(n))throw new Error("Thumbnail payload is not a valid PNG image.");return{fileName:"thumbnail.png",content:n,mimeType:"image/png"}}}function F_e(t,e){let n=e instanceof Error?e.message:String(e);return t.thumbnail.status!=="generated"?t:{...t,thumbnail:{...t.thumbnail,status:"failed",message:`Thumbnail payload could not be stored: ${n}`.slice(0,512)}}}async function TV(t){if(!bO.has(t.command))return t.params;let e=xO(t.ctx,t.params);if(!e.assetId)throw new Error("assetLibraryAssetId is required for Asset Library .rbxm round-trip.");let n=await Xt(e,e.assetId);I_e(n);let r=await Mu({...e,assetId:n.id}),i=await h_e(r);return{...t.params,__assetLibraryRbxmBase64:i.toString("base64"),__assetLibraryOriginalFile:n.file.original}}async function AV(t){if(!_O.has(t.command)||!t.result.success)return t.result;let e=st(t.result.data);if(!e||typeof e.rbxmBase64!="string"||e.rbxmBase64.trim().length===0)return t.result;let n=xO(t.ctx,t.params),r=C_e(e.rbxmBase64,"Asset Library .rbxm export payload"),i=typeof t.params.displayName=="string"?t.params.displayName:void 0,a=typeof t.params.description=="string"?t.params.description:void 0,o=`${i?.trim()||"studio-export"}.rbxm`,s,c=null;try{s=EV(e.thumbnail)}catch(f){c=f,s=void 0}let l=z_e({value:e.rbxm,exportedCount:e.exportedCount,fallbackThumbnail:T_e(t.params,e.thumbnail)});c&&(l=F_e(l,c));let u=L_e(e.roblox),d=await Nm({projectSyncRoot:n.projectSyncRoot,scope:n.scope,category:n.category,originalFileName:o,content:r,...i!==void 0?{displayName:i}:{},...a!==void 0?{description:a}:{},source:P_e(t.params,e.source),...s?{preview:s}:{},rbxm:l,...u?{roblox:u}:{}}),p=kV(e.thumbnail);return{...t.result,data:{asset:d.asset,deduplicated:d.deduplicated,...typeof e.byteLength=="number"?{byteLength:e.byteLength}:{},...typeof e.exportedCount=="number"?{exportedCount:e.exportedCount}:{},...e.source!==void 0?{source:e.source}:{},...p?{thumbnail:p}:{}}}}async function OV(t){if(!t.result.success)return t.result;let e=st(t.result.data),n=st(e?.thumbnail),r;try{r=EV(n)}catch(d){return{...t.result,success:!1,error:d instanceof Error?d.message:String(d)}}if(!n||!r)return{...t.result,success:!1,error:typeof n?.error=="string"?n.error:"Thumbnail payload is missing from Asset Library thumbnail generation result."};let i=Pr(n.width),a=Pr(n.height),o=ye(n.source,128),s=jm(n.attempts),c={mode:"auto",status:"generated",...i!==void 0?{width:i}:{},...a!==void 0?{height:a}:{},...o?{source:o}:{},...s.length>0?{attempts:s}:{}},l=xO(t.ctx,t.params);if(!l.assetId)throw new Error("assetLibraryAssetId is required for Asset Library thumbnail generation.");let u=await vV({projectSyncRoot:l.projectSyncRoot,scope:l.scope,category:l.category,assetId:l.assetId,preview:r,rbxmThumbnail:c});return{...t.result,data:{asset:u.asset,...i!==void 0?{width:i}:{},...a!==void 0?{height:a}:{},...o?{source:o}:{}}}}function q_e(t){if(t===null||typeof t!="object")return;let e=t.proFallback;if(e===null||typeof e!="object")return;let n=e;if(typeof n.executedCommand!="string")return;let r=Array.isArray(n.alternatives)?n.alternatives.filter(i=>typeof i=="string"):void 0;return{executedCommand:n.executedCommand,...typeof n.requestedCommand=="string"?{requestedCommand:n.requestedCommand}:{},...r?{alternatives:r}:{}}}var B_e=/^Pro action '[^']+' is blocked in Basic mode\. Basic fallback '([^']+)' failed: (.*)$/s,V_e=/^Pro action '[^']+' is blocked in Basic mode\.(?! Basic fallback ')/,W_e=/instance not found|not found in|parent not found/,H_e=/is required|missing required/,Z_e=/unknown action|unknown command/,G_e=/must be|invalid|cannot/;function K_e(t){let e=B_e.exec(t);return e?{fallbackCommand:e[1],reason:e[2]}:null}function J_e(t){return V_e.test(t)}function Y_e(t){let e=t.toLowerCase();return W_e.test(e)?"not_found":H_e.test(e)?"missing_param":Z_e.test(e)?"unknown_action":G_e.test(e)?"validation":"other"}function SO(t){return t.errorType==="bridge_error"||t.errorType==="command_timeout"||t.errorType==="plugin_runtime"||t.errorType==="exception"||t.errorType==="device_blocked"||t.failureOrigin==="bridge"||t.failureOrigin==="plugin_runtime"||t.failureOrigin==="server_exception"||t.failureOrigin==="product_bug"||t.failureOrigin==="unknown"||t.recoverability==="retry"||t.recoverability==="wait_connection"||t.recoverability==="unknown"?"error":"warning"}function Lu(t){if(t.resultSuccess){let e=q_e(t.resultData);return e?{kind:"success_fallback",fallbackCommand:e.executedCommand,...e.alternatives?{alternatives:e.alternatives}:{}}:{kind:"success_ok"}}if(!t.resultError)return{kind:"error"};if(t.tier==="pro"){let e=K_e(t.resultError);if(e)return{kind:"blocked_fallback_failed",fallbackCommand:e.fallbackCommand,blockedDetail:Y_e(e.reason)};if(J_e(t.resultError))return{kind:"blocked_unsupported"}}return t.failureClassification?{kind:SO(t.failureClassification)}:{kind:"error"}}function Se(t,e,n,r,i={}){return{errorType:t,errorDetail:e,failureOrigin:n,recoverability:r,...i}}function X_e(t){let e=t.toLowerCase();return/^\s*compilation error:/.test(e)?Se("execution_failed","compile_error","agent_request","code_fix",{validationStage:"plugin_handler"}):/^\s*result too large:/.test(e)?Se("execution_failed","result_too_large","agent_request","code_fix",{validationStage:"plugin_handler"}):/^\s*execution timed out after/.test(e)?Se("execution_failed","execution_timeout","agent_request","code_fix",{validationStage:"plugin_handler"}):/potentially dangerous infinite loop|blocked in sandbox|access to .* is blocked|forbidden|not allowed|cannot access/.test(e)?Se("execution_failed","blocked_source","roblox_policy","code_fix",{validationStage:"plugin_handler"}):null}function Q_e(t){let e=t.toLowerCase();return/startline and endline must be provided together/.test(e)||/startline must be a positive integer/.test(e)||/endline must be a positive integer/.test(e)||/endline must be >= startline/.test(e)?Se("execution_failed","validation","agent_request","fix_params",{validationStage:"schema"}):null}function DV(t){let e=t.toLowerCase();return/upstream_server_down/.test(e)?Se("bridge_error","upstream_down","bridge","wait_connection"):/^http [45]\d\d/.test(e)?Se("bridge_error","http_error","bridge","retry"):/duplicate request\s*id/.test(e)?Se("bridge_error","duplicate_request_id","bridge","code_fix"):/timeout/.test(e)?Se("command_timeout","timeout","bridge","retry"):/econnrefused|socket hang up|econnreset|epipe|network/.test(e)?Se("bridge_error","connection","bridge","wait_connection"):/abort/.test(e)?Se("command_timeout","aborted","bridge","retry"):/runtime error|traceback|attempt to/.test(e)?Se("plugin_runtime","runtime_error","plugin_runtime","code_fix"):/created instance, but failed to set \d+ propert/.test(e)?Se("execution_failed","property_apply_failed","agent_request","fix_params",{validationStage:"plugin_handler",partialSuccess:"true"}):/failed to set property/.test(e)?Se("execution_failed","property_apply_failed","agent_request","fix_params",{validationStage:"plugin_handler"}):/parent(?: instance)? not found/.test(e)?Se("execution_failed","parent_not_found","agent_request","fix_params",{validationStage:"plugin_handler"}):/(?:instance|path|root|source instance|ancestor instance) not found|target\s+(?:path\s+)?(?:['"`][^'"`]+['"`]\s+)?not found|not found in|no synced file found for instance/.test(e)?Se("execution_failed","not_found","user_project_state","fix_params",{validationStage:"plugin_handler"}):/is required|missing required/.test(e)?Se("execution_failed","missing_param","agent_request","fix_params",{validationStage:"schema"}):/invalid classname|invalid class/.test(e)?Se("execution_failed","invalid_class","agent_request","fix_params",{validationStage:"plugin_handler"}):/unknown action|unknown command/.test(e)?Se("execution_failed","unknown_action","agent_request","fix_params",{validationStage:"dispatcher"}):/failed to insert asset/.test(e)?Se("execution_failed","asset_error","roblox_policy","fix_params",{validationStage:"roblox_api"}):/failed to read property|property access denied/.test(e)?Se("execution_failed","property_error","agent_request","fix_params",{validationStage:"plugin_handler"}):/forbidden (?:path|parent path)|exceeds (?:total lines|max(?:imum)?(?: length)?)|is not (?:a|an) /.test(e)?Se("execution_failed","validation","agent_request","fix_params",{validationStage:"plugin_handler"}):/sync controller not available|project sync is not initialized|no active sync place|not found in sync cache/.test(e)?Se("execution_failed","sync_not_ready","user_project_state","wait_connection",{validationStage:"preflight"}):/cannot capture edit-mode screenshot while a playtest is active|play-mode screenshot capture is not supported/.test(e)?Se("execution_failed","unsupported_context","roblox_policy","no_retry",{validationStage:"preflight"}):/editableimage api is not enabled|allow mesh \/ image apis|allow http requests/.test(e)?Se("execution_failed","feature_disabled","roblox_policy","no_retry",{validationStage:"preflight"}):/must be|invalid|cannot/.test(e)?Se("execution_failed","validation","agent_request","fix_params",{validationStage:"plugin_handler"}):Se("execution_failed","other","unknown","unknown")}function zu(t,e){if(t==="manage_scripts_get_source"){let r=Q_e(e);if(r)return r}if(t==="execute_luau"){let r=X_e(e);if(r)return r}let n=DV(e);return t==="execute_luau"&&n.errorDetail==="runtime_error"&&/^\s*runtime error:/i.test(e)?Se("execution_failed","runtime_error","agent_request","code_fix"):n}function $V(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return/timeout/.test(n)?Se("command_timeout","timeout","bridge","retry"):/econnrefused|socket hang up|network|econnreset|epipe/.test(n)?Se("bridge_error","connection","bridge","wait_connection"):/eaddrinuse/.test(n)?Se("bridge_error","port_in_use","bridge","no_retry"):Se("exception","unexpected","server_exception","code_fix")}kS();Fu();import{randomBytes as xxe}from"node:crypto";var Sxe=["manage_ui_create_tree","manage_ui_update","manage_ui_delete"],ZV=["manage_ui_preview","manage_ui_check"],wxe=["ui_role","style_family","layout_family","device_policy","safe_area_policy","existing_ui_strategy"],Ixe=["screen_job","primary_action","visual_thesis","signature_motif","layout_family","imagery_family","ornamentation_family","composition_family","motion_family","device_policy","quality_priority","primary_view_profile_id","responsive_requirement"];function TS(t){return t&&typeof t=="object"?t:void 0}function OO(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ES(t){let e=TS(t);if(!e)return;let n={};for(let r of wxe){let i=e[r];typeof i=="string"&&i.trim().length>0&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}function DO(t){let e=ES(t.qualityPlanSummary);if(e)return e;let n=TS(t.contextSummary),r=ES(n?.qualityPlanSummary);if(r)return r;let i=ES(n?.qualityPlan);if(i)return i;let a=ES(n?.quality_plan);if(a)return a}function GV(t){let e=TS(t);if(!e)return;let n={};for(let r of Ixe){let i=e[r];typeof i=="string"&&i.trim().length>0&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}function KV(t,e){return e?{...t??{},...e}:t}function Cxe(t){return typeof t=="string"?{snapshotId:t}:t&&typeof t=="object"?{snapshotId:typeof t.snapshotId=="string"?t.snapshotId:null,...t.designCheckSummary!==void 0&&{designCheckSummary:t.designCheckSummary},...t.capturedAt!==void 0&&{capturedAt:t.capturedAt},...t.error!==void 0&&{error:t.error}}:{snapshotId:null,error:"preview unavailable"}}function JV(t,e,n,r,i){if(!e)return;let a=OO(e.priority_high),o=OO(e.priority_medium),s=OO(e.priority_low),c=typeof e.total=="number"&&Number.isFinite(e.total)?e.total:a+o+s,l=n??(typeof e.target=="string"?e.target:void 0),u={source:t,...l!==void 0&&{targetPath:l},...typeof r=="string"&&{snapshotId:r},...i!==void 0&&{capturedAt:i},priority_high:a,priority_medium:o,priority_low:s,total:c,deterministic_status:e.deterministic_status==="failed"?"failed":"completed",visual_status:e.visual_status==="completed"||e.visual_status==="skipped"||e.visual_status==="failed"?e.visual_status:"not_requested",coverage:e.coverage==="structural_and_visual"?"structural_and_visual":"structural_only",skipped_reasons:Array.isArray(e.skipped_reasons)?e.skipped_reasons.filter(d=>typeof d=="string"):[],interaction_status:e.interaction_status,primary_view_context_status:e.primary_view_context_status,responsive_status:e.responsive_status,responsive_profiles_reviewed:e.responsive_profiles_reviewed,viewport_profiles_tested:e.viewport_profiles_tested,primary_visual_status:e.primary_visual_status??"not_requested",primary_visual_verdict:e.primary_visual_verdict,critic_summary:typeof e.critic_summary=="string"?e.critic_summary.trim():void 0,responsive_requirement:e.responsive_requirement};return{...u,...rc(u)}}function YV(t,e){if(!e)return t;if(!t)return e;let n=t.targetPath===e.targetPath?t.targetPath:void 0,r=t.snapshotId===e.snapshotId?t.snapshotId:void 0,i={source:e.source,...n!==void 0&&{targetPath:n},...r!==void 0&&{snapshotId:r},...e.capturedAt!==void 0&&{capturedAt:e.capturedAt},priority_high:t.priority_high+e.priority_high,priority_medium:t.priority_medium+e.priority_medium,priority_low:t.priority_low+e.priority_low,total:t.total+e.total,deterministic_status:t.deterministic_status==="failed"||e.deterministic_status==="failed"?"failed":"completed",visual_status:e.visual_status,coverage:t.coverage==="structural_and_visual"||e.coverage==="structural_and_visual"?"structural_and_visual":"structural_only",skipped_reasons:Array.from(new Set([...t.skipped_reasons,...e.skipped_reasons])),interaction_status:e.coverage_dimensions.interaction.status,primary_view_context_status:e.coverage_dimensions.primary_view_context.status,responsive_status:e.coverage_dimensions.responsive_viewport.status,viewport_profiles_tested:Array.from(new Set([...t.viewport_profiles_tested,...e.viewport_profiles_tested])),primary_visual_status:e.primary_visual_status,primary_visual_verdict:e.primary_visual_verdict??t.primary_visual_verdict,critic_summary:e.critic_summary??t.critic_summary,responsive_requirement:e.responsive_requirement??t.responsive_requirement};return{...i,...rc(i)}}function Pxe(t){let e=TS(t);if(e)for(let n of["userMessage","intent","expectedBehavior"]){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r.trim().slice(0,80)}}function kxe(){let t={source:"unavailable",priority_high:0,priority_medium:0,priority_low:0,total:0,deterministic_status:"failed",visual_status:"not_requested",coverage:"structural_only",skipped_reasons:["design_check_unavailable"],primary_visual_status:"not_requested"};return{...t,...rc(t)}}function XV(t){let e=t.now??Date.now,n=null,r=null,i=u=>`${u}_${e()}_${xxe(3).toString("hex")}`,a=()=>{r&&(clearTimeout(r),r=null)},o=()=>{a(),r=setTimeout(()=>{c("idle_timeout")},t.idleMs)},s=async u=>{try{return Cxe(await t.capturePreview(u))}catch(d){return{snapshotId:null,error:d instanceof Error?d.message:String(d)}}},c=async u=>{if(!n)return;a();let d=n;n=null;let p={},f;for(let b of d.affectedPaths)if(d.afterSnapshotsPathPolicy[b]==="skip")p[b]=null;else{let x=await s(b);p[b]=x.snapshotId,x.snapshotId===null&&d.unavailableEvidence.push({phase:"after",targetPath:b,reason:x.error??"preview unavailable"}),f=YV(f,JV("after_snapshot",x.designCheckSummary,b,x.snapshotId,x.capturedAt))}let m=d.latestVisualReview&&d.latestDesignCheckSummary?d.latestDesignCheckSummary:f??d.latestDesignCheckSummary??kxe(),g={...m,responsive_requirement:d.designContractSummary?.responsive_requirement??m.responsive_requirement},y={...g,...rc(g)},v={requestId:d.requestId,...d.contextId!==void 0&&{contextId:d.contextId},...d.label!==void 0&&{label:d.label},startedAt:d.startedAtIso,closedAt:new Date(e()).toISOString(),closeReason:u,ok:d.ok,affectedPaths:Array.from(d.affectedPaths).sort(),mutationCount:d.mutationCount,beforeSnapshots:d.beforeSnapshots,afterSnapshots:p,childMutationIds:d.childMutationIds,...d.qualityPlanSummary!==void 0&&{qualityPlanSummary:d.qualityPlanSummary},...d.designContractSummary!==void 0&&{designContractSummary:d.designContractSummary},postChangeDesignCheckSummary:y,...d.latestVisualReview!==void 0&&{latestVisualReview:d.latestVisualReview},coverageDimensions:y.coverage_dimensions,viewportProfilesTested:y.viewport_profiles_tested,readiness:y.readiness,...d.unavailableEvidence.length>0&&{unavailableEvidence:d.unavailableEvidence}};await LV(t.placeDir,v)},l=u=>({requestId:i("req"),contextId:u.contextId,label:Pxe(u.contextSummary),startedAtIso:new Date(e()).toISOString(),startedAtMs:e(),affectedPaths:new Set,beforeSnapshots:{},afterSnapshotsPathPolicy:{},childMutationIds:[],mutationCount:0,ok:!0,qualityPlanSummary:DO(u),designContractSummary:GV(u.designContractSummary),latestDesignCheckSummary:void 0,latestVisualReview:void 0,unavailableEvidence:[],pendingMutation:void 0});return{async beforeMutation(u){if(ZV.includes(u.command)){if(n){let p=i("mut");n.qualityPlanSummary=KV(n.qualityPlanSummary,DO(u)),n.pendingMutation={mutationId:p,startedMs:e(),args:u}}return}if(!Sxe.includes(u.command))return;if(n&&n.contextId!==u.contextId?await c("context_change"):n&&a(),n||(n=l(u)),n.qualityPlanSummary=KV(n.qualityPlanSummary,DO(u)),n.designContractSummary={...n.designContractSummary??{},...GV(u.designContractSummary)??{}},u.targetPath&&!(u.targetPath in n.beforeSnapshots)){if(n.affectedPaths.add(u.targetPath),u.command==="manage_ui_create_tree")n.beforeSnapshots[u.targetPath]=null;else{let p=await s(u.targetPath);n.beforeSnapshots[u.targetPath]=p.snapshotId,p.snapshotId===null&&n.unavailableEvidence.push({phase:"before",targetPath:u.targetPath,reason:p.error??"preview unavailable"})}u.command==="manage_ui_delete"?n.afterSnapshotsPathPolicy[u.targetPath]="skip":u.targetPath in n.afterSnapshotsPathPolicy||(n.afterSnapshotsPathPolicy[u.targetPath]="capture")}let d=i("mut");n.pendingMutation={mutationId:d,startedMs:e(),args:u}},async afterMutation(u){if(!n?.pendingMutation)return;let{mutationId:d,args:p}=n.pendingMutation,f={mutationId:d,requestId:n.requestId,ts:new Date(e()).toISOString(),command:p.command,origin:p.origin,...p.targetPath!==void 0&&{targetPath:p.targetPath},...p.briefId!==void 0&&{briefId:p.briefId},...u.diffSummary!==void 0&&{diffSummary:u.diffSummary},...u.changeDetails!==void 0&&{changeDetails:u.changeDetails},ok:u.ok,...u.error!==void 0&&{error:u.error},durationMs:u.durationMs};if(await zV(t.placeDir,f),n.pendingMutation=void 0,ZV.includes(p.command)){let m=JV("check_results",u.designCheckSummary,p.targetPath,u.snapshotId,u.capturedAt);n.latestDesignCheckSummary=YV(n.latestDesignCheckSummary,m),m?.snapshotId&&m.primary_visual_verdict&&m.critic_summary&&(n.latestVisualReview={snapshotId:m.snapshotId,verdict:m.primary_visual_verdict,summary:m.critic_summary});return}if(n.mutationCount++,n.childMutationIds.push(d),u.ok||(n.ok=!1),!n.contextId){await c("legacy_single");return}o()},async flushNow(){n&&await c("explicit")}}}var Rxe=new Set(["available","unavailable","unknown"]),Exe=Object.freeze({status:"recommended",blocking:!1,can_accept:!0,can_edit:!0,can_skip:!0,allows_custom_answer:!0});function Wn(t){if(!(typeof t!="object"||t===null||Array.isArray(t)))return t}function $O(t){return typeof t=="string"&&Rxe.has(t)?t:"unknown"}function Txe(t){let e=Wn(t);return{imageGeneration:$O(e?.image_generation),localImageOutput:$O(e?.local_image_output),imageReview:$O(e?.image_review)}}function Axe(t){let e=Wn(t.design_contract),n=Wn(e?.imagery_strategy);if(typeof n?.family=="string")return n.family;if(typeof e?.imagery_family=="string")return e.imagery_family;let r=Wn(t.quality_plan);if(typeof r?.imagery_family=="string")return r.imagery_family;if(Array.isArray(t.candidate_briefs)){let i=Wn(t.candidate_briefs[0]),a=Wn(i?.design_contract);if(typeof a?.imagery_family=="string")return a.imagery_family}return"pictogram_set"}function Oxe(t){let e=Wn(t.design_contract);if(Wn(e?.imagery_strategy)?.intent==="required")return!0;if(Array.isArray(t.candidate_briefs)){let r=Wn(t.candidate_briefs[0]),i=Wn(r?.design_contract);return Wn(i?.imagery_strategy)?.intent==="required"}return!1}function Dxe(t){return t==="item_thumbnail"?"item_thumbnail":t==="character_portrait"?"character_portrait":t==="decorative_illustration"?"decorative_illustration":t==="diegetic_surface"?"diegetic_surface":"pictogram"}function $xe(t){let e=Array.isArray(t.asset_recommendations)?t.asset_recommendations:[];for(let r of e){let i=Wn(r);if(!(!i||typeof i.source!="string")){if(i.source==="user_reference")return{mode:"user_reference",reason:"Use the user-provided image reference before generating another asset.",hasConcreteAsset:!0};if(i.source==="project_asset")return{mode:"project_asset",reason:"Use the reviewed project asset before generating another asset.",hasConcreteAsset:!0};if(i.source==="existing_ui")return{mode:"project_asset",reason:"The existing UI image remains a fallback until the user accepts it for this role.",hasConcreteAsset:!1};if(i.source==="creator_store_search")return{mode:"creator_store",reason:"The Creator Store candidate remains a fallback until the user accepts it.",hasConcreteAsset:!1}}}let n=Wn(t.brief);return Array.isArray(n?.reference_assets)&&n.reference_assets.length>0?{mode:"user_reference",reason:"Use the reference asset already accepted in the brief.",hasConcreteAsset:!0}:{mode:"assetless",reason:"Continue with a coherent primitive pictogram or intentional no-imagery treatment.",hasConcreteAsset:!1}}function Nxe(t,e){let n=Axe(t),r=Dxe(n),i=$xe(t),a=n==="no_imagery",o=Oxe(t)&&!a,s={need:a?"optional":o?"required":"helpful",intended_use:r,fallback_mode:i.mode,fallback_reason:i.reason,resolution_status:a||i.hasConcreteAsset?"resolved":o?"unresolved":"optional",primary_visual_approval_eligible:!o||i.hasConcreteAsset};return a?{...s,status:"not_needed",reason:"The recommended direction intentionally uses no imagery.",requires_generation_approval:!1,requires_upload_approval:!1}:i.hasConcreteAsset?{...s,status:"not_needed",reason:"A concrete asset candidate already exists for the recommended direction.",requires_generation_approval:!1,requires_upload_approval:!1}:e.imageGeneration==="available"&&e.localImageOutput==="available"?{...s,status:"recommended",reason:"The calling agent can generate an image and materialize it as a local file.",question:`Generate a bounded local ${r} image set for this recommended UI direction?`,requires_generation_approval:!0,requires_upload_approval:!0}:e.imageGeneration==="unavailable"||e.localImageOutput==="unavailable"?{...s,status:"unavailable",reason:"This agent environment cannot complete the local generated-image path.",requires_generation_approval:!1,requires_upload_approval:!1}:{...s,status:"unknown",reason:"The calling agent should inspect its callable image tools and local output channel once, then use the fallback if support remains unknown.",requires_generation_approval:!1,requires_upload_approval:!1}}function QV(t,e){let n=Wn(t)??{},r=Txe(e);return{...n,recommendation_policy:Exe,asset_generation_proposal:Nxe(n,r)}}var f3=100,tSe=12e4,nSe=15e3,m3=new Set(["manage_ui_create_tree","manage_ui_update","manage_ui_delete"]);function rSe(t,e){return`License required for internal command ${t}. ${e??"Activate Pro license to use this feature."}`}var iSe={Text:{category:"text",label:"\uD14D\uC2A4\uD2B8"},PlaceholderText:{category:"text",label:"\uD50C\uB808\uC774\uC2A4\uD640\uB354"},TextColor3:{category:"color",label:"\uAE00\uC790\uC0C9"},BackgroundColor3:{category:"color",label:"\uBC30\uACBD\uC0C9"},BorderColor3:{category:"color",label:"\uD14C\uB450\uB9AC\uC0C9"},ImageColor3:{category:"color",label:"\uC774\uBBF8\uC9C0\uC0C9"},Size:{category:"size",label:"\uC0AC\uC774\uC988"},TextSize:{category:"size",label:"\uAE00\uC790 \uD06C\uAE30"},Position:{category:"layout",label:"\uC704\uCE58"},AnchorPoint:{category:"layout",label:"\uC575\uCEE4"},Rotation:{category:"layout",label:"\uD68C\uC804"},LayoutOrder:{category:"layout",label:"\uB808\uC774\uC544\uC6C3 \uC21C\uC11C"},Visible:{category:"state",label:"\uD45C\uC2DC \uC0C1\uD0DC"},Active:{category:"state",label:"\uD65C\uC131 \uC0C1\uD0DC"},Interactable:{category:"state",label:"\uC0C1\uD638\uC791\uC6A9 \uC0C1\uD0DC"},Selectable:{category:"state",label:"\uC120\uD0DD \uAC00\uB2A5"},Enabled:{category:"state",label:"\uD65C\uC131\uD654"},Image:{category:"asset",label:"\uC774\uBBF8\uC9C0"},Texture:{category:"asset",label:"\uD14D\uC2A4\uCC98"},SoundId:{category:"asset",label:"\uC0AC\uC6B4\uB4DC"}},aSe={text:"\uD14D\uC2A4\uD2B8",color:"\uCEEC\uB7EC",size:"\uC0AC\uC774\uC988",layout:"\uB808\uC774\uC544\uC6C3",state:"\uC0C1\uD0DC",asset:"\uC5D0\uC14B",property:"\uC18D\uC131"},oSe=Object.entries(nc).reduce((t,[e,n])=>{for(let r of n.validActions)t[`${e}_${r}`]=e;return t},{});function s3(t){return{toolName:oSe[t]||t,commandName:t}}function c3(t,e){if(typeof t.contextId=="string"||!e||typeof e!="object")return t;let n=e.contextId;return typeof n=="string"?{...t,contextId:n}:t}function AS(t,e){if(t!=="manage_sync_status_current_place")return e;let{placeId:n,...r}=e;return r}function sSe(t,e){let n=e.routing;return{requestId:t,success:!1,error:e.message,errorCode:e.code,routing:n,data:{routing:n}}}async function g3(t,e){let n=t.syncController;if(!n)return null;try{let r=e.placeId,i=n.getDefaultRuntimePlaceId(),a=null;if(typeof r=="number"&&Number.isFinite(r))a=r;else if(typeof r=="string"&&r.trim().length>0){let s=Number.parseInt(r,10);Number.isFinite(s)&&(a=s)}if(a===null&&(a=i),a===null||!Number.isFinite(a))return null;let o=a===i?n.getDefaultRuntimePlaceName():null;return typeof o=="string"&&o.length>0?await n.config.resolvePlaceRoot(a,o):n.config.getPlaceRoot(a)}catch{return null}}function cSe(t){let e=t.tree;if(!e||typeof e!="object")return;let n=e,r=typeof n.name=="string"&&n.name.length>0?n.name:void 0;return r?`${typeof n.parent=="string"&&n.parent.length>0?n.parent:"StarterGui"}.${r}`:void 0}function lSe(t,e){let n=e.targetPath;if(typeof n=="string"&&n.length>0)return n;if(t==="manage_ui_create_tree")return cSe(e)}function uSe(t){let e=iSe[t];if(e)return e;let n=t.toLowerCase();return n.includes("color")?{category:"color",label:"\uC0C9\uC0C1"}:t==="Size"||n.endsWith("size")||n.includes("scale")?{category:"size",label:"\uC0AC\uC774\uC988"}:n.includes("position")||n.includes("anchor")||n.includes("rotation")||n.includes("layout")?{category:"layout",label:"\uB808\uC774\uC544\uC6C3"}:n.includes("visible")||n.includes("active")||n.includes("enabled")||n.includes("selectable")||n.includes("interactable")?{category:"state",label:"\uC0C1\uD0DC"}:n.includes("image")||n.includes("texture")||n.includes("sound")||n.includes("asset")?{category:"asset",label:"\uC5D0\uC14B"}:n.includes("text")||n.includes("placeholder")?{category:"text",label:"\uD14D\uC2A4\uD2B8"}:{category:"property",label:t}}function l3(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function dSe(t){if(!t||typeof t!="object")return new Map;let e=t,n=e.changed_properties??e.changedProperties;if(!Array.isArray(n))return new Map;let r=new Map;for(let i of n){if(!i||typeof i!="object")continue;let a=i,o=a.property;if(typeof o!="string"||o.length===0)continue;let s=l3(a,"before"),c=l3(a,"after");r.set(o,{...s&&{before:a.before},...c&&{after:a.after},hasBefore:s,hasAfter:c})}return r}function h3(t,e){let r=t.changes?.properties;if(!r||typeof r!="object")return;let i=dSe(e),a=Object.entries(r).map(([o,s])=>{let c=uSe(o),l=i.get(o),u={property:o,category:c.category,label:c.label,after:l?.hasAfter?l.after:s};return l?.hasBefore&&(u.before=l.before),u});return a.length>0?a:void 0}function y3(t){if(!t||t.length===0)return;let e=new Map;for(let i of t)e.set(i.category,(e.get(i.category)??0)+1);let r=["text","color","size","layout","state","asset","property"].map(i=>{let a=e.get(i)??0;return a>0?`${aSe[i]} ${a}\uAC1C`:null}).filter(i=>i!==null);return r.length>0?`${r.join(", ")} \uBCC0\uACBD`:void 0}function u3(t,e){if(t==="manage_ui_update"){let n=e.changes,r=y3(h3(e));if(r)return r;let i=n?.properties?Object.keys(n.properties).length:0,a=Array.isArray(n?.addChildren)?n.addChildren.length:0,o=Array.isArray(n?.removeChildren)?n.removeChildren.length:0;return`${i} props, +${a}, -${o}`}if(t==="manage_ui_create_tree")return"tree \uC0DD\uC131";if(t==="manage_ui_delete")return"\uC81C\uAC70\uB428"}function Hm(t){return t&&typeof t=="object"?t:void 0}function OS(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function v3(t){let e=Hm(t),n=Hm(e?.design_check_summary);if(n)return{priority_high:OS(n,"priority_high"),priority_medium:OS(n,"priority_medium"),priority_low:OS(n,"priority_low"),total:OS(n,"total"),...typeof n.scope=="string"&&{scope:n.scope},...typeof n.target=="string"&&{target:n.target},...n.deterministic_status==="completed"||n.deterministic_status==="failed"?{deterministic_status:n.deterministic_status}:{},...n.visual_status==="not_requested"||n.visual_status==="completed"||n.visual_status==="skipped"||n.visual_status==="failed"?{visual_status:n.visual_status}:{},...n.coverage==="structural_only"||n.coverage==="structural_and_visual"?{coverage:n.coverage}:{},...Array.isArray(n.skipped_reasons)?{skipped_reasons:n.skipped_reasons.filter(r=>typeof r=="string")}:{}}}function b3(t){let n=Hm(t)?.snapshot_id;return typeof n=="string"?n:null}function d3(t){if(typeof t=="string"&&t.trim().length>0)return t;if(typeof t=="number"&&Number.isFinite(t)){let e=t<1e10?t*1e3:t;return new Date(e).toISOString()}}function _3(t){let e=Hm(t),n=Hm(e?.meta);return d3(n?.captured_at)??d3(n?.evaluated_at)}function pSe(t,e){let n=t.uiStudioRecorders.get(e);if(n)return n;let r=XV({placeDir:e,idleMs:nSe,capturePreview:async i=>{try{let a=await Rr(t,"manage_ui_preview",{targetPath:i},$S());if(!a.success||!a.data||typeof a.data!="object")return null;let o=v3(a.data),s=_3(a.data);return{snapshotId:b3(a.data),...o!==void 0&&{designCheckSummary:o},...s!==void 0&&{capturedAt:s}}}catch{return null}}});return t.uiStudioRecorders.set(e,r),r}async function fSe(t,e,n){if(!m3.has(e))return null;let r=await g3(t,n);if(!r)return null;let i=pSe(t,r),a=e,o=typeof n.contextId=="string"?n.contextId:void 0,s=n.contextSummary,c=s!==void 0&&typeof s=="object"?s:void 0,l=lSe(a,n),u=typeof n.briefId=="string"?n.briefId:void 0,d=u!==void 0?t.uiStudioDesignContracts.get(r,u):void 0,p={command:a,...o!==void 0&&{contextId:o},...c!==void 0&&{contextSummary:c},...l!==void 0&&{targetPath:l},...u!==void 0&&{briefId:u},...d!==void 0&&{designContractSummary:d},origin:n.__origin==="dashboard"?"dashboard":"ai"};try{return await i.beforeMutation(p),{recorder:i,command:a,params:n,startedAt:Date.now()}}catch(f){return h.debug("UI Studio recorder beforeMutation \uC2E4\uD328 (\uBB34\uC2DC)",{error:f}),null}}async function p3(t,e){if(t)try{let n=t.command==="manage_ui_update"?h3(t.params,e.data):void 0,r=t.command==="manage_ui_update"?y3(n)??u3(t.command,t.params):u3(t.command,t.params),i=v3(e.data),a=b3(e.data),o=_3(e.data);await t.recorder.afterMutation({ok:e.success,durationMs:Date.now()-t.startedAt,...r!==void 0&&{diffSummary:r},...n!==void 0&&{changeDetails:n},...e.error!==void 0&&{error:e.error},...i!==void 0&&{designCheckSummary:i},...a!==null&&{snapshotId:a},...o!==void 0&&{capturedAt:o}})}catch(n){h.debug("UI Studio recorder afterMutation \uC2E4\uD328 (\uBB34\uC2DC)",{error:n})}}async function DS(t,e,n,r,i,a){if(!t.historyManager)return;let o=!i.success&&i.error?zu(n,i.error):void 0,s=Lu({resultSuccess:i.success,resultData:i.data,resultError:i.error,tier:ar(n),...o?{failureClassification:o}:{}});if(i.success){let u=s.kind==="success_fallback"&&i.data&&typeof i.data=="object"?{...i.data,outcomeStatus:"fallback",requestedCommand:n,executedCommand:s.fallbackCommand,...s.alternatives?{alternatives:s.alternatives}:{}}:i.data,d=AS(n,r);i.routing?await t.historyManager.recordSuccess(e,d,u,a,n,void 0,i.routing):await t.historyManager.recordSuccess(e,d,u,a,n);return}if(s.kind==="blocked_unsupported"){await t.historyManager.recordBlockedOutcome(e,AS(n,r),i.error||"Pro action blocked in Basic mode","blocked_unsupported",{executionTimeMs:a,command:n,...i.routing?{routing:i.routing}:{}});return}if(s.kind==="blocked_fallback_failed"){await t.historyManager.recordBlockedOutcome(e,AS(n,r),i.error||"Pro action blocked in Basic mode","blocked_fallback_failed",{executionTimeMs:a,command:n,...s.fallbackCommand?{fallbackCommand:s.fallbackCommand}:{},...s.blockedDetail?{blockedDetail:s.blockedDetail}:{},...i.routing?{routing:i.routing}:{}});return}let c=s.kind==="warning"?t.historyManager.recordWarning.bind(t.historyManager):t.historyManager.recordFailure.bind(t.historyManager),l=AS(n,r);i.routing?await c(e,l,i.error||"Unknown error",a,i.errorCode??o?.errorType.toUpperCase(),n,void 0,i.routing):await c(e,l,i.error||"Unknown error",a,i.errorCode??o?.errorType.toUpperCase(),n)}function MO(t,e,n){let r=t.pendingCommands.get(e)||[];r.length>=f3&&r.shift(),r.push(n),t.pendingCommands.set(e,r)}function mSe(t,e){t.globalPendingCommands.length>=f3&&t.globalPendingCommands.shift(),t.globalPendingCommands.push(e)}function x3(t,e,n){let r=$S(),i={requestId:r,command:e.command,params:e.params,timestamp:Date.now(),queueTimeoutMs:e.queueTimeoutMs,ackedTimeoutMs:e.ackedTimeoutMs,state:$n.QUEUED,targetClientId:n,resolve:()=>{},reject:a=>{h.debug("Auxiliary playtest stop command ended without awaited response",{requestId:r,targetClientId:n,error:a.message})},timeoutId:null};return t.commandQueue.set(r,i),i.timeoutId=setTimeout(()=>{Sx(t,i,i.queueTimeoutMs)},i.queueTimeoutMs),{event:"command",id:r,data:{command:i.command,requestId:r,params:i.params}}}function gSe(t,e,n,r){if(!Rm(e.data.command))return;let i=t.commandQueue.get(e.data.requestId);if(!i)return;S3(t,i);let a=n.filter(o=>o.clientId!==r);for(let o of a){let s=x3(t,i,o.clientId);MO(t,o.clientId,s)}a.length>0&&h.info("Fan-out playtest stop command to active plugin clients",{requestId:e.data.requestId,primaryClientId:r,auxiliaryClientIds:a.map(o=>o.clientId)})}function S3(t,e,n){for(let r of G9)setTimeout(()=>{let a=n?[...new Set(n)]:[...new Set(Un(t).map(o=>o.clientId))];for(let o of a){if(!t.pluginClients.get(o))continue;let c=x3(t,e,o);MO(t,o,c)}h.info("Retry playtest stop command to active plugin clients",{sourceRequestId:e.requestId,delayMs:r,targetClientIds:a}),hu(t)},r).unref?.()}function w3(t){return t==="clientId"||t==="targetAlias"||t==="placeId"}function hSe(t,e,n){if(!n||!Rm(e.data.command))return!1;let r=t.commandQueue.get(e.data.requestId)?.routing?.selectionMode;return!w3(r)}function ySe(t,e,n){h.debug("Broadcasting command",{command:e.data.command,requestId:e.data.requestId,targetClientId:n||"all",activeWebsocketClients:Un(t).length});let r=n;if(n){MO(t,n,e);let i=t.commandQueue.get(e.data.requestId),a=i?.routing?.selectionMode;if(i&&Rm(e.data.command)&&w3(a))S3(t,i,[n]);else if(hSe(t,e,n)){let o=Un(t).sort((s,c)=>c.lastSeen-s.lastSeen);gSe(t,e,o,n),r=void 0}}else mSe(t,e);hu(t,r)}async function I3(t,e,n){let r=Date.now(),i="",a={};try{let o=e.body;i=o.command??"",a=o.params||{};let s=o.requestId;if(o.instanceId||(t.serverLastCommandAt=Date.now()),o.instanceId){let m=t.mcpInstances.get(o.instanceId);m&&(m.lastCommandAt=Date.now(),m.lastSeen=m.lastCommandAt)}let c=s3(i),l=typeof o.timeout=="number"&&Number.isFinite(o.timeout)&&o.timeout>0?{timeout:o.timeout}:void 0,u=o.instanceId?t.mcpInstances.get(o.instanceId)?.sessionId??t.sessionId:t.sessionId;if(!i){n.status(400).json({error:"Missing command"});return}if(h.debug("Received execute request",{command:i,requestId:s}),i==="manage_camera_play_screenshot"){let m="manage_camera.play_screenshot is not supported. Screenshot capture is available only in Edit mode via manage_camera.screenshot.",g=Date.now()-r;t.historyManager&&await t.historyManager.recordFailure("manage_camera",a,m,g,"UNSUPPORTED_COMMAND",i),n.json({requestId:s,success:!1,error:m});return}if(i==="get_cached_selection"){let m=a.maxAge,g=km(t,m!==void 0?m:3e4),y=Date.now()-r;if(!g){let x={requestId:s,success:!0,data:{cached:!1,message:"No cached selection data available. The plugin may not be connected or no selection changes have occurred yet."}};t.historyManager&&await t.historyManager.recordSuccess(c.toolName,a,x.data,y,c.commandName),n.json(x);return}let v=Date.now()-g.timestamp,b={cached:!0,selection:g.selection,count:g.count,timestamp:g.timestamp,age:v};t.historyManager&&await t.historyManager.recordSuccess(c.toolName,a,b,y,c.commandName),n.json({requestId:s,success:!0,data:b});return}if(i==="get_connection_info"){let m=await dS(t),g=Date.now()-r;t.historyManager&&await t.historyManager.recordSuccess(c.toolName,a,m,g,c.commandName),n.json({requestId:s,success:!0,data:m});return}if(fS(i)==="internal"){if(!t.internalCommandExecutor){n.status(503).json({requestId:s,success:!1,error:`Internal command executor is not initialized for command: ${i}`});return}if(ar(i)==="pro"){if(!t.licenseState){n.status(503).json({requestId:s,success:!1,error:`License state manager is not initialized for internal command: ${i}`});return}let b=await t.licenseState.evaluateProAccess();if(!b.allowed){let x=rSe(i,b.reason),I=Date.now()-r;t.historyManager&&await DS(t,c.toolName,c.commandName,a,{success:!1,error:x},I),n.json({requestId:s,success:!1,error:x});return}}let m={...a,__sessionId:u},g=await t.internalCommandExecutor(i,m),y=Date.now()-r,v=c3(m,g.data);t.historyManager&&await DS(t,c.toolName,c.commandName,v,{success:g.success,data:g.data,error:g.error||"Internal command failed",...g.errorCode?{errorCode:g.errorCode}:{},...g.routing?{routing:g.routing}:{}},y),n.json({requestId:s,...g});return}let d=await Rr(t,i,a,s,l),p=Date.now()-r,f={...c3(a,d.data),__sessionId:u};t.historyManager&&await DS(t,c.toolName,c.commandName,f,d,p),n.json(d)}catch(o){let s=Date.now()-r,c=ir(o);if(t.historyManager&&i){let l=s3(i);await t.historyManager.recordFailure(l.toolName,a,c,s,"EXCEPTION",l.commandName)}h.error("Execute request failed",o),n.status(500).json({success:!1,error:c})}}async function C3(t,e,n){let r=Date.now(),i=e.body,a=i.action;if(!a||typeof a!="string"){n.status(400).json({success:!1,error:"Missing required field: action"});return}if(!new Set(["get","set","get_all","set_multiple","get_attr","set_attr","get_all_attrs","delete_attr","add_tag","remove_tag","check_tag","get_tags","get_tagged"]).has(a)){n.status(400).json({success:!1,error:`Unsupported action: ${a}`});return}let s=`manage_properties_${a}`,c=$S(),{action:l,...u}=i;try{t.serverLastCommandAt=Date.now();let d=await Rr(t,s,u,c),p=Date.now()-r;t.historyManager&&await DS(t,"manage_properties",s,u,d,p),n.json(d)}catch(d){let p=Date.now()-r,f=ir(d);t.historyManager&&await t.historyManager.recordFailure("manage_properties",u,f,p,"EXCEPTION",s),h.error("/api/properties \uC694\uCCAD \uCC98\uB9AC \uC2E4\uD328",d),n.status(500).json({success:!1,error:f})}}async function Rr(t,e,n,r,i){if(h.debug("Executing command locally",{command:e,requestId:r}),s5(t,r)){let d=`Duplicate requestId '${r}' for command '${e}'. Generate a unique requestId for each command.`;return h.warn("Duplicate execute request rejected",{command:e,requestId:r}),{requestId:r,success:!1,error:d}}let a;try{a=pS(t,Un(t),n,e)}catch(d){if(d instanceof _n)return h.warn("Command target selection failed",{command:e,requestId:r,errorCode:d.code,routing:d.routing}),sSe(r,d);throw d}let o=m3.has(e)?await fSe(t,e,n):null,s=t.config.requestTimeout,c=i?.timeout??Math.max(t.config.requestTimeout,tSe),l=bO.has(e)?await TV({ctx:t,command:e,params:n}):n,u=new Promise((d,p)=>{let f=Date.now(),m={requestId:r,command:e,params:l,timestamp:f,queueTimeoutMs:s,ackedTimeoutMs:c,state:$n.QUEUED,...a.targetClientId?{targetClientId:a.targetClientId}:{},routing:a.routing,resolve:d,reject:p,timeoutId:null};t.commandQueue.set(r,m),vx(t,a.targetClientId,f),m.timeoutId=setTimeout(()=>{Sx(t,m,s)},s)});return ySe(t,{event:"command",id:$S(),data:{command:e,requestId:r,params:l}},a.targetClientId),u.then(async d=>{let p=d;if(e==="manage_ui_design_brief"&&d.success&&d.data){let f=QV(d.data,n.agentCapabilities);p={...d,data:f};try{let m=await g3(t,n);m&&t.uiStudioDesignContracts.remember(m,f)}catch(m){h.debug("UI Studio Design Contract cache failed",{error:m instanceof Error?m.message:String(m)})}}if(e==="manage_ui_preview"&&d.success&&d.data)try{let{processPreviewResult:f,resolvePreviewPlaceDirFromCtx:m}=await Promise.resolve().then(()=>(jO(),NO)),g=await m(t,n),y=await f("manage_ui_preview",d.data,g);p={...d,data:y.data,...y.mcpContent?{mcpContent:y.mcpContent}:{}}}catch(f){h.warn("preview post-processing failed",{error:f instanceof Error?f.message:String(f)})}if(e==="manage_ui_check"&&d.success&&d.data&&n.visualReview!==void 0)try{let{resolvePreviewPlaceDirFromCtx:f}=await Promise.resolve().then(()=>(jO(),NO)),{processCheckResult:m}=await Promise.resolve().then(()=>(o3(),a3)),g=await f(t,n),y=await m("manage_ui_check",d.data,g,n);p={...p,data:y.data}}catch(f){h.warn("check visual post-processing failed",{error:f instanceof Error?f.message:String(f)})}return _O.has(e)?p=await AV({ctx:t,command:e,params:n,result:p}):e===vO&&(p=await OV({ctx:t,params:n,result:p})),p}).then(async d=>(await p3(o,{success:d.success,...d.data!==void 0&&{data:d.data},...d.error!==void 0&&{error:d.error}}),d),async d=>{throw await p3(o,{success:!1,error:ir(d)}),d})}le();ca();function NS(t,e){let n={};e.provider!==void 0&&(n.provider=e.provider),e.tier!==void 0&&(n.tier=e.tier),e.status!==void 0&&(n.status=e.status),e.canUsePro!==void 0&&(n.canUsePro=e.canUsePro),e.cleared===!0&&(n.cleared=!0),pt(t,"license",n)}function Mi(t,e,n,r){t.status(e).json({success:!1,error:{code:n,message:r}})}function vSe(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e.length>0?e:void 0}function jS(t,e){if(e==="plugin")return t;let n={...t};return delete n.sessionToken,n}function Zm(t,e,n,r){let i=vSe(r??e.query.provider)??"auto";return t.licenseState?.supportsProvider(i)===!1?(Mi(n,400,"LICENSE_PROVIDER_UNSUPPORTED",`provider "${i}" is not supported`),null):i}function Gm(t,e){return t.licenseState?!0:(Mi(e,503,"LICENSE_NOT_INITIALIZED","License system is not initialized"),!1)}function bSe(t){if(!t||typeof t!="object")return!1;let e=t;return(e.canUsePro===!0||e.canUsePro===!1)&&typeof e.status=="string"&&typeof e.checkedAt=="number"}function Km(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=e.body,a=typeof i?.licenseKey=="string"?i.licenseKey:"";if(!a.trim()){Mi(n,400,"LICENSE_KEY_REQUIRED","licenseKey is required");return}let o=Zm(t,e,n,i?.provider);if(!o)return;let s=typeof i?.pluginClientId=="string"?i.pluginClientId:typeof e.query.clientId=="string"?e.query.clientId:void 0,c=typeof i?.deviceId=="string"?i.deviceId:void 0,l={licenseKey:a,provider:o,clientType:r};s&&(l.pluginClientId=s),c&&(l.deviceId=c),t.licenseState.activateGateway(l).then(u=>{t.analyticsManager?.setTier(u.canUsePro?"pro":"basic"),NS(t,{provider:u.provider,tier:u.canUsePro?"pro":"basic",status:u.status,canUsePro:u.canUsePro}),n.json(jS(u,r))}).catch(u=>{h.warn("License activate failed",{error:u instanceof Error?u.message:"unknown_error"}),Mi(n,502,"LICENSE_ACTIVATE_FAILED",u instanceof Error?u.message:"License activation failed")})}function Jm(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=Zm(t,e,n);if(i)try{let a=t.licenseState.getStatus(i);t.analyticsManager?.setTier(a.canUsePro?"pro":"basic"),n.json(jS(a,r))}catch(a){h.warn("License status check failed",{error:a instanceof Error?a.message:"unknown_error"}),Mi(n,502,"LICENSE_STATUS_FAILED",a instanceof Error?a.message:"License status check failed")}}function Ym(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=e.body,a=Zm(t,e,n,i?.provider);if(!a)return;let o={provider:a,clientType:r};r==="plugin"&&typeof i?.sessionToken=="string"&&i.sessionToken.trim()&&(o.sessionToken=i.sessionToken.trim()),typeof i?.pluginClientId=="string"&&(o.pluginClientId=i.pluginClientId),typeof i?.deviceId=="string"&&(o.deviceId=i.deviceId),t.licenseState.refreshGateway(o).then(s=>{t.analyticsManager?.setTier(s.canUsePro?"pro":"basic"),NS(t,{provider:s.provider,tier:s.canUsePro?"pro":"basic",status:s.status,canUsePro:s.canUsePro}),n.json(jS(s,r))}).catch(s=>{h.warn("License refresh failed",{error:s instanceof Error?s.message:"unknown_error"}),Mi(n,502,"LICENSE_REFRESH_FAILED",s instanceof Error?s.message:"License refresh failed")})}function Xm(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=e.body,a=Zm(t,e,n,i?.provider);a&&t.licenseState.resetGateway({provider:a,clientType:r}).then(o=>{t.analyticsManager?.setTier("basic"),NS(t,{provider:o.provider,tier:"basic",status:o.status,canUsePro:o.canUsePro,cleared:!0}),n.json(jS(o,r))}).catch(o=>{h.warn("License reset failed",{error:o instanceof Error?o.message:"unknown_error"}),Mi(n,502,"LICENSE_RESET_FAILED",o instanceof Error?o.message:"License reset failed")})}function LO(t,e,n){if(!Gm(t,n))return;let r=e.body,i=Zm(t,e,n,r?.provider);if(!i)return;if(r?.clientType!=="plugin"){Mi(n,400,"LICENSE_CLIENT_TYPE_INVALID","clientType must be plugin");return}let a=typeof r?.sessionToken=="string"&&r.sessionToken.trim()?r.sessionToken.trim():void 0,o=bSe(r?.snapshot)?r.snapshot:void 0;if(!o&&!a){Mi(n,400,"LICENSE_BOOTSTRAP_REQUIRED","snapshot or sessionToken is required");return}let s={provider:i,clientType:"plugin"};o&&(s.snapshot=o),a&&(s.sessionToken=a),t.licenseState.bootstrap(s).then(c=>{t.analyticsManager?.setTier(c.canUsePro?"pro":"basic"),NS(t,{provider:c.provider,tier:c.canUsePro?"pro":"basic",status:c.status,canUsePro:c.canUsePro}),n.json({ok:!0})}).catch(c=>{h.warn("License bootstrap failed",{error:c instanceof Error?c.message:"unknown_error"}),Mi(n,502,"LICENSE_BOOTSTRAP_FAILED",c instanceof Error?c.message:"License bootstrap failed")})}function P3(t){t.app.post("/license/bootstrap",(e,n)=>LO(t,e,n)),t.app.post("/license/activate",(e,n)=>Km(t,e,n,"plugin")),t.app.post("/license/refresh",(e,n)=>Ym(t,e,n,"plugin")),t.app.post("/license/reset",(e,n)=>Xm(t,e,n,"plugin")),t.app.get("/license/status",(e,n)=>Jm(t,e,n,"plugin"))}vt();le();import{promises as MS}from"fs";import zO from"path";function _Se(t){let e=t.config.appDataDir??Ke();return zO.join(e,"observability","logs")}async function Vu(t,e,n){let r=e.query.clientId;if(r&&t.pluginClients.has(r)){let i=t.pluginClients.get(r);i.lastSeen=Date.now()}try{let i=e.body;if(!i||!Array.isArray(i.logs)){h.warn("Invalid logs request",{body:i}),n.status(400).json({error:"Invalid request body"});return}let a=_Se(t);await MS.mkdir(a,{recursive:!0});let c=`plugin-${new Date().toISOString().split("T")[0]}.log`,l=zO.join(a,c),u=zO.join(a,"current.log"),d=i.logs.map(p=>`[${new Date(p.timestamp*1e3).toISOString().replace("T"," ").substring(0,19)}] [${p.level}] ${p.message}`).join(`
|
|
939
|
+
`:"","utf8"),Vn.renameSync(r,t)}function k9(t){try{return Vn.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(".jsonl")).map(e=>{let n=XA.join(t,e.name);return{filePath:n,modifiedAtMs:Vn.statSync(n).mtimeMs}}).sort((e,n)=>e.modifiedAtMs-n.modifiedAtMs)}catch{return[]}}async function R9(t,e=20){return!Number.isInteger(e)||e<=0?[]:k9(QT(t)).slice(-e).map(r=>r.filePath)}function E9(t){let e=QT(t.appDataDir),n=XA.join(e,Abe(t.instanceId));return{filePath:n,record(i,a,o={},s){try{let l={...YA(o),schemaVersion:1,timestamp:Tbe(s),source:i,event:a,pid:t.pid,instanceId:t.instanceId,sessionId:t.sessionId};Vn.mkdirSync(e,{recursive:!0}),Dbe(n,JSON.stringify(l))}catch{}},pruneOldInstanceFiles(){try{let i=k9(e);for(let a of i.slice(0,-20))Vn.rmSync(a.filePath,{force:!0})}catch{}}}}vt();function T9(t,e){let n=$be(),r=n.replace(/-/g,"").substring(0,8).toUpperCase(),i=`${r.substring(0,4)}-${r.substring(4,8)}`,a=E9({appDataDir:t.appDataDir??Ke(),pid:process.pid,instanceId:n,sessionId:i});return{config:t,app:e,instanceId:n,sessionId:i,startTime:Date.now(),runtimeDiagnostics:a,baseUrl:`http://${t.httpHost}:${t.httpPort}`,commandQueue:new Map,pendingCommands:new Map,globalPendingCommands:[],totalCommandsProcessed:0,pluginClients:new Map,pluginCommandSessionsByClientId:new Map,pluginCommandClientIdsByProcessToken:new Map,mcpInstances:new Map,cachedSelectionMap:new Map,studioRoutingMode:"recentPriority",pinnedTargetClientId:null,isClientMode:!1,clientModeHealthTimer:null,clientModeConsecutiveHealthFailures:0,clientModeUpstreamReachable:!0,clientModeUpstreamContextCaptureEnabled:!0,clientModeLastHealthSuccessAt:null,clientModeLastHealthFailureAt:null,clientModeLastHealthError:null,shuttingDown:!1,onUpstreamPermanentlyDown:null,clientModeIdleTimeoutMs:t.clientModeIdleTimeoutMs??36e5,clientModeIdleWatchdogTimer:null,shutdownFn:null,historyManager:null,analyticsManager:null,executionContextManager:null,licenseState:null,syncController:null,internalCommandExecutor:null,dashboardFolderPicker:null,assetLibraryOpenCloudServiceFactory:null,projectChangesCleanupScheduler:null,activeSyncOwnerInstanceId:null,activeProjectRoot:null,pendingDashboardSyncRootPin:null,playtestControlCommand:null,dashboardSyncRootSwitchInFlight:!1,uiStudioRecorders:new Map,uiStudioDesignContracts:P9(),aiClientName:"",pluginVersion:"",syncedSessionToken:null,serverLastCommandAt:null}}var A9=Ft(bo(),1);le();function O9(t){let e=A9.default.json({limit:"5mb"});t.app.use((n,r,i)=>{if(n.path.startsWith("/sync/")){i();return}e(n,r,i)}),t.app.use((n,r,i)=>{r.setHeader("Access-Control-Allow-Origin","http://localhost:3002"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type"),i()}),t.app.use((n,r,i)=>{h.debug(`${n.method} ${n.path}`,{ip:n.ip}),i()})}co();import{randomUUID as $S}from"crypto";co();le();function Nbe(){let t=process.env.WEPPY_ROBLOX_MCP_VERSION?.trim();return t||null}var Ye=Nbe()??"2.14.3";ca();nr();Pm();Ro();fu();co();Ro();var L9="studio-",Mbe=/^studio-[1-9]\d*$/;function nS(t){return Mbe.test(t)}function z9(t,e){let n=new Set;for(let r of t)e!==void 0&&r.clientId===e||r.targetAlias&&nS(r.targetAlias)&&n.add(r.targetAlias);return n}function Lbe(t,e){let n=z9(t,e),r=1;for(;n.has(`${L9}${r}`);)r+=1;return`${L9}${r}`}function rS(t,e){let n=z9(t,e.clientId);return e.targetAlias&&nS(e.targetAlias)&&!n.has(e.targetAlias)||(e.targetAlias=Lbe(t,e.clientId)),e.targetAlias}fu();function iS(t){for(let e of t)rS(t,e)}function aS(t){let e={clientId:t.clientId,targetAlias:t.targetAlias??t.clientId.slice(0,8),lastSeen:t.lastSeen,connectedAt:t.connectedAt,transport:"websocket",connectionState:t.commandSessionState??Be.CONNECTED};return t.placeId!==void 0&&(e.placeId=t.placeId),t.placeName!==void 0&&(e.placeName=t.placeName),t.pluginVersion!==void 0&&(e.pluginVersion=t.pluginVersion),t.studioVersion!==void 0&&(e.studioVersion=t.studioVersion),t.lastRoutedAt!==void 0&&(e.lastRoutedAt=t.lastRoutedAt),t.processToken!==void 0&&(e.processToken=t.processToken),t.inFlightRequestId!==void 0&&(e.inFlightRequestId=t.inFlightRequestId),t.studioState!==void 0&&(e.studioState=t.studioState),t.studioStateSource!==void 0&&(e.studioStateSource=t.studioStateSource),t.studioStateUpdatedAt!==void 0&&(e.studioStateUpdatedAt=t.studioStateUpdatedAt),t.playtestMode!==void 0&&(e.playtestMode=t.playtestMode),e}function aO(t){let e=Un(t);return iS(e),dm(e.map(aS),null)}function oS(t){let e=new Set;t.aiClientName&&e.add(t.aiClientName);for(let n of t.mcpInstances.values())n.aiClientName&&e.add(n.aiClientName);return Array.from(e)}function U9(t){let n=Date.now();for(let[r,i]of t.mcpInstances)i.lastSeen&&n-i.lastSeen>15e3&&(t.mcpInstances.delete(r),i.sessionId&&t.executionContextManager?.endSession(i.sessionId),h.debug("Removed stale MCP instance",{instanceId:r,lastSeen:i.lastSeen}))}function F9(t,e,n){let r=e.query.clientId;if(r&&t.pluginClients.has(r)){let i=t.pluginClients.get(r);i.lastSeen=Date.now()}try{let i=e.body;if(!i||!Array.isArray(i.selection)||typeof i.count!="number"){h.warn("Invalid selection update request",{body:i}),n.status(400).json({error:"Invalid request body"});return}let a=r||"unknown",o=Date.now();t.cachedSelectionMap.set(a,{selection:i.selection,count:i.count,timestamp:o,clientId:a}),h.debug("Selection cache updated",{count:i.count,clientId:a,timestamp:o}),n.json({status:"ok",timestamp:o})}catch(i){h.error("Error handling selection update",i),n.status(500).json({error:"Internal server error"})}}function q9(t,e,n){let r=parseInt(e.query.maxAge)||3e4,i=km(t,r);i?n.json({cached:!0,...i}):n.json({cached:!1,message:"No cached selection available"})}function km(t,e=3e4,n){if(t.cachedSelectionMap.size===0)return null;let r;if(n)r=t.cachedSelectionMap.get(n);else for(let a of t.cachedSelectionMap.values())(!r||a.timestamp>r.timestamp)&&(r=a);if(!r)return null;let i=Date.now()-r.timestamp;return e===0||i<=e?r:null}function oO(t,e){let n=t.pluginClients.get(e.clientId),r=Date.now(),i=[...t.pluginClients.values()].filter(c=>c.clientId===e.clientId||c.commandSessionState!==Be.DISCONNECTED),a=n??{clientId:e.clientId,connectedAt:r,lastSeen:r,commandsProcessed:0,connectionType:"polling"},o=rS(i,a),s={clientId:e.clientId,targetAlias:o,projectName:e.projectName??n?.projectName,placeName:e.placeName??n?.placeName,placeId:e.placeId??n?.placeId,pluginVersion:e.pluginVersion??n?.pluginVersion,studioVersion:e.studioVersion??n?.studioVersion,connectedAt:n?.connectedAt||r,lastSeen:r,commandsProcessed:n?.commandsProcessed||0,connectionType:n?.connectionType||"polling",inFlightRequestId:n?.inFlightRequestId,studioState:n?.studioState,studioStateSource:n?.studioStateSource,studioStateUpdatedAt:n?.studioStateUpdatedAt,playtestMode:n?.playtestMode,...n?.commandSessionState?{commandSessionState:n.commandSessionState}:{},...n?.processToken?{processToken:n.processToken}:{}};return t.pluginClients.set(e.clientId,s),t.syncController&&typeof t.syncController.setCurrentConnectedPlace=="function"&&typeof e.placeId=="number"&&Number.isFinite(e.placeId)&&t.syncController.setCurrentConnectedPlace(e.placeId,e.placeName??null),t.pendingCommands.has(e.clientId)||t.pendingCommands.set(e.clientId,[]),e.pluginVersion&&(t.pluginVersion=e.pluginVersion),typeof s.placeId=="number"&&Number.isFinite(s.placeId)&&Ax(t,s.placeId,s.placeName??null),t.analyticsManager&&(e.pluginVersion&&t.analyticsManager.setPluginVersion(e.pluginVersion),t.analyticsManager.trackPluginConnected()),h.info("Plugin client registered",{clientId:e.clientId,targetAlias:o,projectName:e.projectName,placeName:e.placeName,isReconnect:!!n}),{clientInfo:s,sessionId:t.sessionId,mcpVersion:Ye,mcpInstanceCount:t.mcpInstances.size+1,aiClientNames:oS(t)}}function sO(t,e){let n=t.pluginClients.get(e),r=t.pluginClients.has(e),i=n?.commandSessionState===Be.CONNECTED;if(t.pluginClients.delete(e),t.pendingCommands.delete(e),r&&pu(t,e),r&&t.syncController&&typeof t.syncController.clearCurrentConnectedPlaceIfMatch=="function"&&typeof n?.placeId=="number"&&Number.isFinite(n.placeId)){let a=[...t.pluginClients.values()].filter(o=>typeof o.placeId=="number"&&Number.isFinite(o.placeId)).sort((o,s)=>s.lastSeen-o.lastSeen)[0];a?t.syncController.setCurrentConnectedPlace?.(a.placeId??null,a.placeName??null):t.syncController.clearCurrentConnectedPlaceIfMatch(n.placeId)}return i&&pm(t,e,"disconnected",n),h.info("Plugin client unregistered",{clientId:e,existed:r}),r}function sS(t,e,n){try{let r=e.body;if(!r.clientId){n.status(400).json({error:"Missing clientId"});return}let i=oO(t,{clientId:r.clientId,projectName:r.projectName,placeName:r.placeName,placeId:r.placeId,pluginVersion:r.pluginVersion,studioVersion:r.studioVersion});n.json({status:"ok",clientId:r.clientId,targetAlias:i.clientInfo.targetAlias,serverInstanceId:t.instanceId,sessionId:i.sessionId,mcpVersion:i.mcpVersion,connectedAt:i.clientInfo.connectedAt,aiClientNames:i.aiClientNames,serverStartTime:t.startTime,mcpInstanceCount:i.mcpInstanceCount})}catch(r){h.error("Error registering plugin client",r),n.status(500).json({error:"Internal server error"})}}function cS(t,e,n){let r=e.body?.clientId;if(!r){n.status(400).json({error:"Missing clientId"});return}let i=sO(t,r);n.json({status:"ok",existed:i})}function B9(t,e,n){try{let r=e.body;if(!r.instanceId){n.status(400).json({error:"Missing instanceId"});return}let i=Date.now(),a={instanceId:r.instanceId,...typeof r.sessionId=="string"?{sessionId:r.sessionId}:{},pid:r.pid,connectedAt:i,isServer:!1,lastSeen:i};r.aiClientName&&(a.aiClientName=r.aiClientName),r.cwd&&(a.cwd=r.cwd),"projectRoot"in r&&(a.projectRoot=r.projectRoot),t.mcpInstances.set(r.instanceId,a),pt(t,"mcp_status",{aiClientName:a.aiClientName??"Unknown",instanceId:r.instanceId,status:"registered"}),vu(t,{timestamp:new Date().toISOString(),type:"mcp",status:"registered",instanceId:r.instanceId,message:`MCP registered \u2014 ${a.aiClientName??r.instanceId}`,...a.aiClientName?{aiClientName:a.aiClientName}:{}}),h.info("MCP instance registered (client mode)",{instanceId:r.instanceId,pid:r.pid,cwd:r.cwd}),n.json({status:"ok",instanceId:r.instanceId,serverInstanceId:t.instanceId,sessionId:t.sessionId,mcpVersion:Ye,mcpInstanceCount:t.mcpInstances.size+1})}catch(r){h.error("Error registering MCP instance",r),n.status(500).json({error:"Internal server error"})}}function V9(t,e,n){let r=e.body?.instanceId;if(!r){n.status(400).json({error:"Missing instanceId"});return}let i=t.mcpInstances.get(r),a=!!i;t.mcpInstances.delete(r),i?.sessionId&&t.executionContextManager?.endSession(i.sessionId),a&&(pt(t,"mcp_status",{aiClientName:i?.aiClientName??"Unknown",instanceId:r,status:"unregistered"}),vu(t,{timestamp:new Date().toISOString(),type:"mcp",status:"unregistered",instanceId:r,message:`MCP unregistered \u2014 ${i?.aiClientName??r}`,...i?.aiClientName?{aiClientName:i.aiClientName}:{}})),h.info("MCP instance unregistered",{instanceId:r,existed:a}),n.json({status:"ok",existed:a})}function W9(t,e,n){let{instanceId:r,aiClientName:i}=e.body;if(r&&i){let a=t.mcpInstances.get(r);a&&(a.aiClientName=i)}n.json({status:"ok"})}function H9(t){let e=3e4,n=Date.now(),r=Zr({appDataDir:t.config.appDataDir});for(let[a,o]of t.pluginClients)n-o.lastSeen>e&&(t.pluginClients.delete(a),t.pendingCommands.delete(a),pu(t,a));U9(t);let i=Un(t);return iS(i),{serverInstanceId:t.instanceId,sessionId:t.sessionId,mcpVersion:Ye,uptime:n-t.startTime,serverStartTime:t.startTime,serverExecutable:process.execPath,serverHost:t.config.httpHost,serverPort:t.config.httpPort,serverPid:process.pid,pluginClients:i.map(aS),studioRoutingMode:t.studioRoutingMode,pinnedTargetClientId:t.pinnedTargetClientId,mcpInstances:[{instanceId:t.instanceId,pid:process.pid,connectedAt:t.startTime,isServer:!0,cwd:process.cwd(),projectRoot:r,lastSeen:n,...t.aiClientName?{aiClientName:t.aiClientName}:{}},...Array.from(t.mcpInstances.values())],mcpInstanceCount:t.mcpInstances.size+1}}function lS(t,e){e.json(H9(t))}function uS(t,e,n){let r=e.query.instanceId;r&&t.mcpInstances.has(r)&&(t.mcpInstances.get(r).lastSeen=Date.now()),U9(t);let i=Un(t);iS(i);let s={...{status:"online",connectedClients:i.length,queuedCommands:y5(t),uptime:Date.now()-t.startTime,version:Ye,enableContextCapture:t.executionContextManager?.isEnabled()??t.config.enableContextCapture??!0,isClientMode:t.isClientMode,shuttingDown:t.shuttingDown,pid:process.pid,sessionId:t.sessionId,nodeVersion:process.version,studioRoutingMode:t.studioRoutingMode,pinnedTargetClientId:t.pinnedTargetClientId},instanceId:t.instanceId,mcpInstanceCount:t.mcpInstances.size+1,aiClientNames:oS(t),pluginVersion:t.pluginVersion||void 0,dashboardSseClients:t.dashboardSseClients?.size??0,websocketClients:i.length,pluginClients:i.map(aS),...t.isClientMode?{upstream:{reachable:t.clientModeUpstreamReachable,consecutiveFailures:t.clientModeConsecutiveHealthFailures,lastSuccessAt:t.clientModeLastHealthSuccessAt,lastFailureAt:t.clientModeLastHealthFailureAt,lastError:t.clientModeLastHealthError,baseUrl:t.baseUrl}}:{}};n.json(s)}function Z9(t,e,n,r){let i=e.ip||e.socket.remoteAddress||"";if(!(i==="127.0.0.1"||i==="::1"||i==="::ffff:127.0.0.1"||i==="localhost")){h.warn("Shutdown request rejected from non-localhost",{ip:i}),n.status(403).json({error:"Forbidden: localhost only"});return}h.info("Shutdown request received, initiating graceful shutdown",{requestedBy:i,uptime:Date.now()-t.startTime}),n.json({status:"shutting_down",message:"Server will shutdown gracefully",pid:process.pid}),setTimeout(async()=>{try{await r(),h.info("Graceful shutdown completed"),process.exit(0)}catch(o){h.error("Error during graceful shutdown",o),process.exit(1)}},100)}async function dS(t){if(t.isClientMode)try{let e=await fetch(`${t.baseUrl}/connection-info`);if(e.ok)return await e.json()}catch(e){h.warn("Failed to fetch connection info from server",{error:e})}return H9(t)}Ro();var _t={bridgeRunTest:"manage_studio_run_test_bridge",placeInfo:"system_info_place_info",clearLogs:"manage_logs_clear",createScript:"manage_scripts_create",getLogs:"manage_logs_get",deleteScript:"manage_scripts_delete",canonical:{playStart:"manage_studio_play_start",playStop:"manage_studio_play_stop",playPause:"manage_studio_play_pause",playResume:"manage_studio_play_resume",playStatus:"manage_studio_play_status",runTest:"manage_studio_run_test"}},Ube=new Set([_t.canonical.runTest]),Fbe=new Set([_t.canonical.playStop]),k8e=new Set([_t.canonical.playStart,_t.canonical.playStop,_t.canonical.playPause,_t.canonical.playResume,_t.canonical.playStatus]);function Di(t){return Ube.has(t)}function Rm(t){return Fbe.has(t)}var A8e=_t.canonical.playStop,G9=[5e3,15e3];fu();var qbe=new Set(["manage_assets_export_selection_rbxm","manage_assets_export_path_rbxm","manage_assets_review_model","manage_assets_generate_model","manage_assets_import_rbxm","manage_assets_generate_thumbnail"]),_n=class t extends Error{code;routing;constructor(e,n,r){super(n),this.name="CommandTargetSelectionError",this.code=e,this.routing=r,Object.setPrototypeOf(this,t.prototype)}};function Bbe(t={},e){let n={},r=t.clientId,i=t.targetAlias,a=t.placeId;if(r!==void 0){if(typeof r!="string"||r.trim().length===0)throw new _n("invalid_target_selector","clientId target selector must be a non-empty string",{selectionMode:"clientId",...typeof r=="string"?{requestedClientId:r.trim()}:{}});n.requestedClientId=r.trim()}if(i!==void 0){if(typeof i!="string"||i.trim().length===0)throw new _n("invalid_target_selector","targetAlias target selector must be a non-empty string",{selectionMode:"targetAlias",...typeof i=="string"?{requestedTargetAlias:i.trim()}:{}});n.requestedTargetAlias=i.trim()}if(a!==void 0&&Vbe(e,t)){if(typeof a!="number"||!Number.isFinite(a))throw new _n("invalid_target_selector","placeId target selector must be a finite number",{selectionMode:"placeId"});n.requestedPlaceId=a}return n}function pS(t,e,n={},r){let i=Bbe(n,r),a=V8(e,t.studioRoutingMode==="pinned"?t.pinnedTargetClientId:null);if(i.requestedClientId!==void 0)return Wbe(a,i);if(i.requestedTargetAlias!==void 0)return Hbe(a,i);if(i.requestedPlaceId!==void 0)return Zbe(a,i);if(t.studioRoutingMode==="pinned"&&t.pinnedTargetClientId!==null){let s=a.find(c=>c.clientId===t.pinnedTargetClientId);if(s)return{targetClientId:s.clientId,routing:ni("pinnedTarget",i,s)}}let o=a[0];return o?{targetClientId:o.clientId,routing:ni("recentPriority",i,o)}:{routing:{selectionMode:"globalQueue"}}}function Vbe(t,e){return!t||!qbe.has(t)?!0:e.scope==="shared"}function Wbe(t,e){let n=t.find(r=>r.clientId===e.requestedClientId);if(!n)throw new _n("target_client_not_found",`Target client not found: ${e.requestedClientId}`,ni("clientId",e));if(e.requestedTargetAlias!==void 0&&n.targetAlias!==e.requestedTargetAlias)throw new _n("target_selector_mismatch",`Target client ${n.clientId} does not match targetAlias ${e.requestedTargetAlias}`,ni("clientId",e,n));return K9("clientId",e,n),{targetClientId:n.clientId,routing:ni("clientId",e,n)}}function Hbe(t,e){let n=t.find(r=>r.targetAlias!==void 0&&nS(r.targetAlias)&&r.targetAlias===e.requestedTargetAlias);if(!n)throw new _n("target_alias_not_found",`Target alias not found: ${e.requestedTargetAlias}`,ni("targetAlias",e));return K9("targetAlias",e,n),{targetClientId:n.clientId,routing:ni("targetAlias",e,n)}}function Zbe(t,e){let n=t.filter(i=>i.placeId===e.requestedPlaceId);if(n.length===0)throw new _n("target_place_not_found",`Target place not found: ${e.requestedPlaceId}`,ni("placeId",e));if(n.length>1)throw new _n("target_place_ambiguous",`Target place is ambiguous: ${e.requestedPlaceId}`,ni("placeId",e));let r=n[0];return{targetClientId:r.clientId,routing:ni("placeId",e,r)}}function K9(t,e,n){if(e.requestedPlaceId!==void 0&&n.placeId!==e.requestedPlaceId)throw new _n("target_selector_mismatch",`Target client ${n.clientId} is not connected to placeId ${e.requestedPlaceId}`,ni(t,e,n))}function ni(t,e,n){let r={selectionMode:t};return e.requestedClientId!==void 0&&(r.requestedClientId=e.requestedClientId),e.requestedTargetAlias!==void 0&&(r.requestedTargetAlias=e.requestedTargetAlias),e.requestedPlaceId!==void 0&&(r.requestedPlaceId=e.requestedPlaceId),n!==void 0&&(r.actualClientId=n.clientId,n.targetAlias!==void 0&&(r.actualTargetAlias=n.targetAlias),n.placeId!==void 0&&(r.actualPlaceId=n.placeId),n.placeName!==void 0&&(r.actualPlaceName=n.placeName)),r}rA();le();wm();var nc={query_instances:{discriminator:"action",validActions:new Set(["get","children","find_child","find_descendant","wait_for_child","class_info","search_name","search_class","search_property","search_tag","file_tree","project_structure","descendants","ancestors"]),allowedParams:{query_instances_get:new Set(["path","sessionDebugId","siblingIndex","placeId","clientId","targetAlias"]),query_instances_children:new Set(["path","sessionDebugId","siblingIndex","recursive","maxDepth","placeId","clientId","targetAlias"]),query_instances_find_child:new Set(["path","childName","placeId","clientId","targetAlias"]),query_instances_find_descendant:new Set(["path","descendantName","placeId","clientId","targetAlias"]),query_instances_wait_for_child:new Set(["path","childName","timeout","placeId","clientId","targetAlias"]),query_instances_class_info:new Set(["className","placeId","clientId","targetAlias"]),query_instances_search_name:new Set(["root","query","caseSensitive","maxResults","placeId","clientId","targetAlias"]),query_instances_search_class:new Set(["className","root","includeSubclasses","maxResults","placeId","clientId","targetAlias"]),query_instances_search_property:new Set(["root","propertyName","propertyValue","maxResults","placeId","clientId","targetAlias"]),query_instances_search_tag:new Set(["root","tag","maxResults","placeId","clientId","targetAlias"]),query_instances_file_tree:new Set(["maxDepth","root","includeServices","placeId","clientId","targetAlias"]),query_instances_project_structure:new Set(["root","depth","placeId","clientId","targetAlias"]),query_instances_descendants:new Set(["path","sessionDebugId","siblingIndex","maxResults","placeId","clientId","targetAlias"]),query_instances_ancestors:new Set(["path","sessionDebugId","siblingIndex","placeId","clientId","targetAlias"])},paramAliases:{query_instances_search_name:{query:"pattern"},query_instances_search_property:{root:"rootPath"},query_instances_search_tag:{root:"rootPath"},query_instances_project_structure:{root:"rootPath"}}},mutate_instances:{discriminator:"action",validActions:new Set(["create","create_with_props","delete","clone","move","rename","pivot","create_tree","mass_create","mass_delete","mass_duplicate","smart_duplicate","scatter"]),allowedParams:{mutate_instances_create:new Set(["className","parent","name","properties","placeId","clientId","targetAlias"]),mutate_instances_create_with_props:new Set(["className","parent","name","properties","placeId","clientId","targetAlias"]),mutate_instances_delete:new Set(["path","sessionDebugId","siblingIndex","placeId","clientId","targetAlias"]),mutate_instances_clone:new Set(["path","sourcePath","sessionDebugId","siblingIndex","targetParent","newName","placeId","clientId","targetAlias"]),mutate_instances_move:new Set(["path","sessionDebugId","siblingIndex","newParent","placeId","clientId","targetAlias"]),mutate_instances_rename:new Set(["path","sessionDebugId","siblingIndex","newName","placeId","clientId","targetAlias"]),mutate_instances_pivot:new Set(["path","sessionDebugId","siblingIndex","position","cframe","offset","placeId","clientId","targetAlias"]),mutate_instances_create_tree:new Set(["parent","tree","placeId","clientId","targetAlias"]),mutate_instances_mass_create:new Set(["instances","placeId","clientId","targetAlias"]),mutate_instances_mass_delete:new Set(["paths","placeId","clientId","targetAlias"]),mutate_instances_mass_duplicate:new Set(["targetParent","paths","placeId","clientId","targetAlias"]),mutate_instances_smart_duplicate:new Set(["path","sessionDebugId","siblingIndex","targetParent","offset","count","placeId","clientId","targetAlias"]),mutate_instances_scatter:new Set(["templatePaths","region","count","seed","maxSlope","avoidWater","alignToNormal","scaleJitter","minSpacing","parentName","placeId","clientId","targetAlias"])},paramAliases:{mutate_instances_clone:{path:"sourcePath"},mutate_instances_smart_duplicate:{spacing:"offset"}}},manage_properties:{discriminator:"action",validActions:new Set(["get","set","get_all","set_multiple","get_attr","set_attr","get_all_attrs","delete_attr","add_tag","remove_tag","check_tag","get_tags","get_tagged","set_calculated","set_relative","mass_set","mass_get","modify_children"]),allowedParams:{manage_properties_get:new Set(["path","property","placeId","clientId","targetAlias"]),manage_properties_set:new Set(["path","property","value","placeId","clientId","targetAlias"]),manage_properties_get_all:new Set(["path","includeReadOnly","placeId","clientId","targetAlias"]),manage_properties_set_multiple:new Set(["path","properties","placeId","clientId","targetAlias"]),manage_properties_get_attr:new Set(["path","attribute","placeId","clientId","targetAlias"]),manage_properties_set_attr:new Set(["path","value","attribute","placeId","clientId","targetAlias"]),manage_properties_get_all_attrs:new Set(["path","placeId","clientId","targetAlias"]),manage_properties_delete_attr:new Set(["path","attribute","placeId","clientId","targetAlias"]),manage_properties_add_tag:new Set(["path","tag","placeId","clientId","targetAlias"]),manage_properties_remove_tag:new Set(["path","tag","placeId","clientId","targetAlias"]),manage_properties_check_tag:new Set(["path","tag","placeId","clientId","targetAlias"]),manage_properties_get_tags:new Set(["path","placeId","clientId","targetAlias"]),manage_properties_get_tagged:new Set(["tagName","root","maxResults","placeId","clientId","targetAlias"]),manage_properties_set_calculated:new Set(["path","expression","variables","propertyName","placeId","clientId","targetAlias"]),manage_properties_set_relative:new Set(["path","value","operation","amount","propertyName","placeId","clientId","targetAlias"]),manage_properties_mass_set:new Set(["paths","propertyName","propertyValue","placeId","clientId","targetAlias"]),manage_properties_mass_get:new Set(["paths","propertyName","placeId","clientId","targetAlias"]),manage_properties_modify_children:new Set(["parentPath","modifications","propertyName","propertyValue","filter","recursive","placeId","clientId","targetAlias"])},paramAliases:{manage_properties_get_tagged:{tagName:"tag",root:"rootPath"},manage_properties_set_relative:{amount:"value"}}},manage_scripts:{discriminator:"action",validActions:new Set(["get_source","set_source","create","delete","edit_replace","edit_insert","edit_delete","search","replace","get_dependencies","validate"]),allowedParams:{manage_scripts_get_source:new Set(["path","startLine","endLine","placeId","clientId","targetAlias"]),manage_scripts_set_source:new Set(["path","source","validate","placeId","clientId","targetAlias"]),manage_scripts_create:new Set(["source","scriptType","parent","name","placeId","clientId","targetAlias"]),manage_scripts_delete:new Set(["path","placeId","clientId","targetAlias"]),manage_scripts_edit_replace:new Set(["path","startLine","endLine","newLines","validate","placeId","clientId","targetAlias"]),manage_scripts_edit_insert:new Set(["path","lines","afterLine","content","validate","placeId","clientId","targetAlias"]),manage_scripts_edit_delete:new Set(["path","startLine","endLine","validate","placeId","clientId","targetAlias"]),manage_scripts_search:new Set(["path","pattern","caseSensitive","wholeWord","usePattern","maxResults","placeId","clientId","targetAlias"]),manage_scripts_replace:new Set(["path","pattern","replacement","usePattern","dryRun","placeId","clientId","targetAlias"]),manage_scripts_get_dependencies:new Set(["path","placeId","clientId","targetAlias"]),manage_scripts_validate:new Set(["source","path","placeId","clientId","targetAlias"])},paramAliases:{manage_scripts_edit_replace:{newLines:"newContent"},manage_scripts_edit_insert:{lines:"content"},manage_scripts_replace:{pattern:"searchPattern"}}},manage_ui:{discriminator:"action",validActions:new Set(["design_brief","create_tree","update","delete","preview","check"]),allowedParams:{manage_ui_design_brief:new Set(["brief","projectContext","agentCapabilities","placeId","clientId","targetAlias"]),manage_ui_create_tree:new Set(["briefId","tree","placeId","clientId","targetAlias"]),manage_ui_update:new Set(["targetPath","changes","briefId","placeId","clientId","targetAlias"]),manage_ui_delete:new Set(["targetPath","placeId","clientId","targetAlias"]),manage_ui_preview:new Set(["targetPath","briefId","viewportMode","profileIds","placeId","clientId","targetAlias"]),manage_ui_check:new Set(["targetPath","briefId","visualReview","viewportMode","profileIds","placeId","clientId","targetAlias"])}},manage_lighting:{discriminator:"action",validActions:new Set(["lighting","atmosphere","sky","terrain_props","time","mood"]),allowedParams:{manage_lighting_lighting:new Set(["properties","placeId","clientId","targetAlias"]),manage_lighting_atmosphere:new Set(["properties","createIfMissing","placeId","clientId","targetAlias"]),manage_lighting_sky:new Set(["properties","createIfMissing","placeId","clientId","targetAlias"]),manage_lighting_terrain_props:new Set(["properties","placeId","clientId","targetAlias"]),manage_lighting_time:new Set(["time","clockTime","placeId","clientId","targetAlias"]),manage_lighting_mood:new Set(["preset","overrides","placeId","clientId","targetAlias"])}},manage_selection:{discriminator:"action",validActions:new Set(["get","set","clear","cached","context","details","add","remove","watch"]),allowedParams:{manage_selection_get:new Set(["placeId","clientId","targetAlias"]),manage_selection_set:new Set(["paths","placeId","clientId","targetAlias"]),manage_selection_clear:new Set(["placeId","clientId","targetAlias"]),manage_selection_cached:new Set(["maxAge"]),manage_selection_context:new Set(["includeSource","includeProperties","includeChildren","placeId","clientId","targetAlias"]),manage_selection_details:new Set(["maxDepth","includeAncestors","placeId","clientId","targetAlias"]),manage_selection_add:new Set(["paths","placeId","clientId","targetAlias"]),manage_selection_remove:new Set(["paths","placeId","clientId","targetAlias"]),manage_selection_watch:new Set(["placeId","clientId","targetAlias"])}},manage_camera:{discriminator:"action",validActions:new Set(["info","focus_path","focus_position","suggest","screenshot"]),allowedParams:{manage_camera_info:new Set(["placeId","clientId","targetAlias"]),manage_camera_focus_path:new Set(["path","distance","duration","offset","respectAutoFocusSetting","placeId","clientId","targetAlias"]),manage_camera_focus_position:new Set(["position","distance","duration","offset","lookAt","respectAutoFocusSetting","placeId","clientId","targetAlias"]),manage_camera_suggest:new Set(["path","placeId","clientId","targetAlias"]),manage_camera_screenshot:new Set(["placeId","clientId","targetAlias"])},paramAliases:{manage_camera_suggest:{path:"targetPath"}}},manage_tween:{discriminator:"action",validActions:new Set(["create","play","pause","cancel"]),allowedParams:{manage_tween_create:new Set(["path","tweenInfo","properties","placeId","clientId","targetAlias"]),manage_tween_play:new Set(["tweenId","placeId","clientId","targetAlias"]),manage_tween_pause:new Set(["tweenId","placeId","clientId","targetAlias"]),manage_tween_cancel:new Set(["tweenId","placeId","clientId","targetAlias"])}},manage_audio:{discriminator:"action",validActions:new Set(["play","stop","pause","resume","set_listener"]),allowedParams:{manage_audio_play:new Set(["path","soundId","volume","looped","playbackSpeed","placeId","clientId","targetAlias"]),manage_audio_stop:new Set(["path","placeId","clientId","targetAlias"]),manage_audio_pause:new Set(["path","placeId","clientId","targetAlias"]),manage_audio_resume:new Set(["path","placeId","clientId","targetAlias"]),manage_audio_set_listener:new Set(["listenerType","listenerPath","placeId","clientId","targetAlias"])}},manage_animation:{discriminator:"action",validActions:new Set(["load","play","stop","get_tracks"]),allowedParams:{manage_animation_load:new Set(["path","animationId","placeId","clientId","targetAlias"]),manage_animation_play:new Set(["path","trackId","speed","fadeTime","weight","priority","placeId","clientId","targetAlias"]),manage_animation_stop:new Set(["path","trackId","fadeTime","placeId","clientId","targetAlias"]),manage_animation_get_tracks:new Set(["path","placeId","clientId","targetAlias"])}},manage_physics:{discriminator:"action",validActions:new Set(["register_group","set_collidable","get_groups"]),allowedParams:{manage_physics_register_group:new Set(["groupName","placeId","clientId","targetAlias"]),manage_physics_set_collidable:new Set(["group1","group2","collidable","placeId","clientId","targetAlias"]),manage_physics_get_groups:new Set(["placeId","clientId","targetAlias"])}},manage_effects:{discriminator:"action",validActions:new Set(["emit","clear","toggle"]),allowedParams:{manage_effects_emit:new Set(["path","count","placeId","clientId","targetAlias"]),manage_effects_clear:new Set(["path","placeId","clientId","targetAlias"]),manage_effects_toggle:new Set(["path","enabled","placeId","clientId","targetAlias"])}},manage_terrain:{discriminator:"action",validActions:new Set(["fill_block","fill_ball","fill_cylinder","fill_wedge","clear_region","clear_bounds","replace_material","colors_get","colors_set","read_voxel","read_voxels","write_voxels","generate","smooth"]),allowedParams:{manage_terrain_fill_block:new Set(["cframe","size","placeId","clientId","targetAlias"]),manage_terrain_fill_ball:new Set(["center","radius","placeId","clientId","targetAlias"]),manage_terrain_fill_cylinder:new Set(["cframe","radius","height","placeId","clientId","targetAlias"]),manage_terrain_fill_wedge:new Set(["cframe","size","placeId","clientId","targetAlias"]),manage_terrain_clear_region:new Set(["region","placeId","clientId","targetAlias"]),manage_terrain_clear_bounds:new Set(["min","max","placeId","clientId","targetAlias"]),manage_terrain_replace_material:new Set(["material","region","sourceMaterial","targetMaterial","placeId","clientId","targetAlias"]),manage_terrain_colors_get:new Set(["material","placeId","clientId","targetAlias"]),manage_terrain_colors_set:new Set(["material","color","placeId","clientId","targetAlias"]),manage_terrain_read_voxel:new Set(["position","placeId","clientId","targetAlias"]),manage_terrain_read_voxels:new Set(["region","resolution","placeId","clientId","targetAlias"]),manage_terrain_write_voxels:new Set(["region","resolution","materials","occupancy","placeId","clientId","targetAlias"]),manage_terrain_generate:new Set(["region","preset","seed","baseHeight","amplitude","frequency","octaves","persistence","waterLevel","edgeBlend","materialPalette","layers","placeId","clientId","targetAlias"]),manage_terrain_smooth:new Set(["region","intensity","placeId","clientId","targetAlias"])}},spatial_query:{discriminator:"action",validActions:new Set(["raycast","find_ground","check_placement","multi_raycast","scan_area","find_flat","find_spawn","analyze_walkable","spatial_map","find_space","bounds","snap_grid","collision"]),allowedParams:{spatial_query_raycast:new Set(["origin","direction","filterType","filterList","filterInstances","ignoreWater","placeId","clientId","targetAlias"]),spatial_query_find_ground:new Set(["maxDistance","position","filterList","filterInstances","offset","placeId","clientId","targetAlias"]),spatial_query_check_placement:new Set(["position","size","filterList","filterInstances","rotation","checkGround","placeId","clientId","targetAlias"]),spatial_query_multi_raycast:new Set(["filterType","filterList","filterInstances","ignoreWater","rays","placeId","clientId","targetAlias"]),spatial_query_scan_area:new Set(["size","filterList","filterInstances","center","resolution","maxResults","placeId","clientId","targetAlias"]),spatial_query_find_flat:new Set(["searchArea","minSize","maxSlope","tolerance","maxResults","placeId","clientId","targetAlias"]),spatial_query_find_spawn:new Set(["searchArea","spawnSize","minSpacing","preferOutdoor","count","placeId","clientId","targetAlias"]),spatial_query_analyze_walkable:new Set(["area","maxSlope","resolution","characterHeight","maxStepHeight","placeId","clientId","targetAlias"]),spatial_query_spatial_map:new Set(["path","rootPath","includeModels","maxResults","placeId","clientId","targetAlias"]),spatial_query_find_space:new Set(["size","searchArea","gridSize","gridSnap","padding","placeId","clientId","targetAlias"]),spatial_query_bounds:new Set(["path","paths","placeId","clientId","targetAlias"]),spatial_query_snap_grid:new Set(["gridSize","path","gridSnap","axes","placeId","clientId","targetAlias"]),spatial_query_collision:new Set(["position","path","ignorePaths","placeId","clientId","targetAlias"])},paramAliases:{spatial_query_spatial_map:{path:"rootPath"}}},manage_assets:{discriminator:"action",validActions:new Set(["insert","info","search","search_insert","insert_free","insert_package","export_selection_json","export_selection_rbxm","export_path_rbxm","review_model","generate_model","upload_asset","import_rbxm","generate_thumbnail"]),allowedParams:{manage_assets_insert:new Set(["assetId","parent","name","position","placeId","clientId","targetAlias"]),manage_assets_info:new Set(["assetId","placeId","clientId","targetAlias"]),manage_assets_search:new Set(["query","maxResults","category","sortType","placeId","clientId","targetAlias"]),manage_assets_search_insert:new Set(["parent","name","query","placeId","clientId","targetAlias"]),manage_assets_insert_free:new Set(["assetId","parent","name","position","placeId","clientId","targetAlias"]),manage_assets_insert_package:new Set(["assetId","parent","name","placeId","clientId","targetAlias"]),manage_assets_export_selection_json:new Set(["format","includeProperties","includeChildren","maxDepth","placeId","clientId","targetAlias"]),manage_assets_export_selection_rbxm:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","displayName","description","thumbnailMode","uploadMode","uploadTemporaryAssets","creatorType","creatorId","clientId","targetAlias"]),manage_assets_export_path_rbxm:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","sourcePath","displayName","description","thumbnailMode","uploadMode","uploadTemporaryAssets","creatorType","creatorId","clientId","targetAlias"]),manage_assets_review_model:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","sourcePath","displayName","description","thumbnailMode","uploadMode","uploadTemporaryAssets","creatorType","creatorId","exportToLibrary","expectedUse","expectedGroups","maxDescendants","maxDepth","readiness","clientId","targetAlias"]),manage_assets_generate_model:new Set(["contextId","contextSummary","replayMetadata","placeId","category","prompt","schemaMode","predefinedSchema","schemaGroups","size","maxTriangles","generateTextures","review","targetParent","name","displayName","expectedUse","expectedGroups","maxDescendants","maxDepth","readiness","anchorMode","clientId","targetAlias"]),manage_assets_upload_asset:new Set(["contextId","contextSummary","replayMetadata","placeId","category","assetType","sourcePath","displayName","description","creatorType","creatorId","clientId","targetAlias"]),manage_assets_import_rbxm:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","assetLibraryAssetId","targetParent","name","clientId","targetAlias"]),manage_assets_generate_thumbnail:new Set(["contextId","contextSummary","replayMetadata","scope","placeId","category","assetLibraryAssetId","clientId","targetAlias"])},paramAliases:{manage_assets_search:{maxResults:"limit"}}},manage_open_cloud_assets:{discriminator:"action",validActions:new Set(["preflight","credential_status","capabilities","upload","link","update","info","operation_status"]),allowedParams:{manage_open_cloud_assets_preflight:new Set(["filePath","category","creatorType","creatorId"]),manage_open_cloud_assets_credential_status:new Set([]),manage_open_cloud_assets_capabilities:new Set([]),manage_open_cloud_assets_upload:new Set(["contextId","contextSummary","replayMetadata","filePath","category","scope","placeId","displayName","description","creatorType","creatorId","expectedPrice","waitForOperation","operationPollTimeoutMs","operationPollIntervalMs"]),manage_open_cloud_assets_link:new Set(["contextId","contextSummary","replayMetadata","assetId","filePath","category","scope","placeId","displayName","description"]),manage_open_cloud_assets_update:new Set(["contextId","contextSummary","replayMetadata","assetId","filePath","category","displayName","description","creatorType","creatorId","expectedPrice","updateMask","waitForOperation","operationPollTimeoutMs","operationPollIntervalMs"]),manage_open_cloud_assets_info:new Set(["assetId","readMask"]),manage_open_cloud_assets_operation_status:new Set(["operationId"])}},manage_sync:{discriminator:"action",validActions:new Set(["status_current_place","history","directions","read_file","write_file","progress"]),allowedParams:{manage_sync_status_current_place:new Set([]),manage_sync_history:new Set(["placeId","query"]),manage_sync_directions:new Set(["placeId"]),manage_sync_read_file:new Set(["placeId","instancePath"]),manage_sync_write_file:new Set(["placeId","instancePath","content"]),manage_sync_progress:new Set([])}},workspace_state:{discriminator:"action",validActions:new Set(["sync","snapshot","changes","viewport","clear_history","metadata","scripts","selection_info","clear_cache"]),allowedParams:{workspace_state_sync:new Set(["includeMetadata","placeId","clientId","targetAlias"]),workspace_state_snapshot:new Set(["placeId","clientId","targetAlias"]),workspace_state_changes:new Set(["limit","placeId","clientId","targetAlias"]),workspace_state_viewport:new Set(["includeCameraInfo","includeSelectionBounds","placeId","clientId","targetAlias"]),workspace_state_clear_history:new Set(["placeId","clientId","targetAlias"]),workspace_state_metadata:new Set(["placeId","clientId","targetAlias"]),workspace_state_scripts:new Set(["placeId","clientId","targetAlias"]),workspace_state_selection_info:new Set(["placeId","clientId","targetAlias"]),workspace_state_clear_cache:new Set(["placeId","clientId","targetAlias"])}},manage_logs:{discriminator:"action",validActions:new Set(["get","clear","errors"]),allowedParams:{manage_logs_get:new Set(["level","limit","pattern","since","sinceSeq","placeId","clientId","targetAlias"]),manage_logs_clear:new Set(["placeId","clientId","targetAlias"]),manage_logs_errors:new Set(["limit","placeId","clientId","targetAlias"])},paramAliases:{manage_logs_get:{level:"type"}}},system_info:{discriminator:"action",validActions:new Set(["ping","connection","usage","place_info","services","preflight"]),allowedParams:{system_info_ping:new Set(["message","placeId","clientId","targetAlias"]),system_info_connection:new Set([]),system_info_usage:new Set(["placeId","clientId","targetAlias"]),system_info_place_info:new Set(["placeId","clientId","targetAlias"]),system_info_services:new Set(["placeId","clientId","targetAlias"]),system_info_preflight:new Set(["placeId","clientId","targetAlias"])}},manage_studio:{discriminator:"action",validActions:new Set(["toggle_ui_preview","test_profile_get","test_profile_set","test_profile_reset","experience_language_get","experience_language_set","play_start","play_stop","play_pause","play_resume","play_status","run_test"]),allowedParams:{manage_studio_toggle_ui_preview:new Set(["enabled","placeId","clientId","targetAlias"]),manage_studio_test_profile_get:new Set(["placeId","clientId","targetAlias"]),manage_studio_test_profile_set:new Set(["testProfile","placeId","clientId","targetAlias"]),manage_studio_test_profile_reset:new Set(["placeId","clientId","targetAlias"]),manage_studio_experience_language_get:new Set(["placeId","clientId","targetAlias"]),manage_studio_experience_language_set:new Set(["locale","placeId","clientId","targetAlias"]),manage_studio_play_start:new Set(["mode","testProfile","restoreAfterTest","placeId","clientId","targetAlias"]),manage_studio_play_stop:new Set(["placeId","clientId","targetAlias"]),manage_studio_play_pause:new Set(["placeId","clientId","targetAlias"]),manage_studio_play_resume:new Set(["placeId","clientId","targetAlias"]),manage_studio_play_status:new Set(["placeId","clientId","targetAlias"]),manage_studio_run_test:new Set(["mode","script","test_name","timeout","testProfile","restoreAfterTest","placeId","clientId","targetAlias","contextId","contextSummary","replayMetadata"])}}};var Gbe={manage_scripts_validate:"internal",manage_selection_cached:"internal",manage_open_cloud_assets_preflight:"internal",manage_open_cloud_assets_credential_status:"internal",manage_open_cloud_assets_capabilities:"internal",manage_open_cloud_assets_upload:"internal",manage_open_cloud_assets_link:"internal",manage_open_cloud_assets_update:"internal",manage_open_cloud_assets_info:"internal",manage_open_cloud_assets_operation_status:"internal",manage_sync_status_current_place:"internal",manage_sync_history:"internal",manage_sync_directions:"internal",manage_sync_read_file:"internal",manage_sync_write_file:"internal",manage_sync_progress:"internal",system_info_connection:"internal",system_info_preflight:"internal",manage_studio_experience_language_set:"internal",manage_studio_run_test:"internal"};function fS(t){return Gbe[t]||"plugin"}var J9=new Set(["batch_execute","execute_luau","extended_call_method","extended_call_methods","extended_get_properties","extended_get_property","extended_set_properties","extended_set_property","manage_animation_get_tracks","manage_animation_load","manage_animation_play","manage_animation_stop","manage_assets_export_path_rbxm","manage_assets_export_selection_json","manage_assets_export_selection_rbxm","manage_assets_generate_model","manage_assets_generate_thumbnail","manage_assets_import_rbxm","manage_assets_info","manage_assets_insert","manage_assets_insert_free","manage_assets_insert_package","manage_assets_review_model","manage_assets_search","manage_assets_search_insert","manage_assets_upload_asset","manage_audio_pause","manage_audio_play","manage_audio_resume","manage_audio_set_listener","manage_audio_stop","manage_camera_screenshot","manage_effects_clear","manage_effects_emit","manage_effects_toggle","manage_lighting_atmosphere","manage_lighting_lighting","manage_lighting_mood","manage_lighting_sky","manage_lighting_terrain_props","manage_lighting_time","manage_open_cloud_assets_capabilities","manage_open_cloud_assets_credential_status","manage_open_cloud_assets_info","manage_open_cloud_assets_link","manage_open_cloud_assets_operation_status","manage_open_cloud_assets_preflight","manage_open_cloud_assets_update","manage_open_cloud_assets_upload","manage_physics_get_groups","manage_physics_register_group","manage_physics_set_collidable","manage_properties_mass_get","manage_properties_mass_set","manage_properties_modify_children","manage_properties_set_calculated","manage_properties_set_relative","manage_scripts_replace","manage_selection_add","manage_selection_context","manage_selection_details","manage_selection_remove","manage_selection_watch","manage_studio_experience_language_get","manage_studio_experience_language_set","manage_studio_play_pause","manage_studio_play_resume","manage_studio_play_start","manage_studio_play_status","manage_studio_play_stop","manage_studio_run_test","manage_studio_test_profile_get","manage_studio_test_profile_reset","manage_studio_test_profile_set","manage_studio_toggle_ui_preview","manage_sync_directions","manage_sync_history","manage_sync_progress","manage_sync_read_file","manage_sync_status_current_place","manage_sync_write_file","manage_terrain_clear_bounds","manage_terrain_clear_region","manage_terrain_colors_get","manage_terrain_colors_set","manage_terrain_fill_ball","manage_terrain_fill_block","manage_terrain_fill_cylinder","manage_terrain_fill_wedge","manage_terrain_generate","manage_terrain_read_voxel","manage_terrain_read_voxels","manage_terrain_replace_material","manage_terrain_smooth","manage_terrain_write_voxels","manage_tween_cancel","manage_tween_create","manage_tween_pause","manage_tween_play","manage_ui_check","manage_ui_create_tree","manage_ui_delete","manage_ui_design_brief","manage_ui_preview","manage_ui_update","mutate_instances_create_tree","mutate_instances_mass_create","mutate_instances_mass_delete","mutate_instances_mass_duplicate","mutate_instances_scatter","mutate_instances_smart_duplicate","query_instances_ancestors","query_instances_descendants","query_instances_file_tree","query_instances_project_structure","query_instances_search_property","query_instances_search_tag","spatial_query_analyze_walkable","spatial_query_bounds","spatial_query_check_placement","spatial_query_collision","spatial_query_find_flat","spatial_query_find_ground","spatial_query_find_space","spatial_query_find_spawn","spatial_query_multi_raycast","spatial_query_raycast","spatial_query_scan_area","spatial_query_snap_grid","spatial_query_spatial_map","system_info_place_info","system_info_services","workspace_state_changes","workspace_state_clear_cache","workspace_state_clear_history","workspace_state_metadata","workspace_state_scripts","workspace_state_selection_info","workspace_state_snapshot","workspace_state_sync","workspace_state_viewport"]),cO=new Set(["system_info_connection","system_info_ping","system_info_preflight","system_info_usage"]);function ar(t){return J9.has(t)?"pro":"basic"}Ir();mS();import{readFile as h_e}from"node:fs/promises";import y_e from"node:path";import{createHash as l_e,randomUUID as fO}from"node:crypto";import{mkdir as $m,readFile as iV,readdir as aV,rename as oV,rm as u_e,stat as d_e,writeFile as xS}from"node:fs/promises";import Mt from"node:path";import{extname as Xbe}from"node:path";import{constants as Qbe}from"node:fs";import{access as e_e,stat as t_e}from"node:fs/promises";var Tm=20*1024*1024,vS=[{category:"image",assetType:"Image",folder:"images",extensions:[".png",".jpeg",".jpg",".bmp",".tga"],supportsContentUpdate:!1,contentTypes:{".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".bmp":"image/bmp",".tga":"image/tga"}},{category:"decal",assetType:"Decal",folder:"decals",extensions:[".png",".jpeg",".jpg",".bmp",".tga"],supportsContentUpdate:!1,contentTypes:{".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".bmp":"image/bmp",".tga":"image/tga"}},{category:"audio",assetType:"Audio",folder:"audio",extensions:[".mp3",".ogg",".wav",".flac"],supportsContentUpdate:!1,contentTypes:{".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".flac":"audio/flac"}},{category:"mesh",assetType:"Mesh",folder:"meshes",extensions:[".mesh"],supportsContentUpdate:!1,contentTypes:{".mesh":"application/octet-stream"}},{category:"model",assetType:"Model",folder:"models",extensions:[".fbx",".gltf",".glb",".rbxm",".rbxmx"],supportsContentUpdate:!0,contentTypes:{".fbx":"model/fbx",".gltf":"model/gltf+json",".glb":"model/gltf-binary",".rbxm":"model/x-rbxm",".rbxmx":"model/x-rbxm"}},{category:"video",assetType:"Video",folder:"videos",extensions:[".mp4",".mov"],supportsContentUpdate:!1,contentTypes:{".mp4":"video/mp4",".mov":"video/quicktime"}},{category:"animation",assetType:"Animation",folder:"animations",extensions:[".rbxm",".rbxmx"],supportsContentUpdate:!0,contentTypes:{".rbxm":"model/x-rbxm",".rbxmx":"model/x-rbxm"}}],n_e=new Map(vS.map(t=>[t.category,t]));function hS(t){if(!t)throw new Error("Open Cloud asset upload is disabled in WEPPY Dashboard settings.")}function gS(t,e){return t.split(e.apiKey).join("[redacted]")}function yS(t){let e=n_e.get(t);if(!e)throw new Error(`Unsupported asset category: ${t}`);return e}function $u(t){return yS(t)}async function uO(t,e,n=Tm){let r=yS(t),i=Xbe(e).toLowerCase(),a=r.contentTypes[i]??null,o=await t_e(e),s=!0;try{await e_e(e,Qbe.R_OK)}catch{s=!1}return{category:t,extension:i,contentType:a,formatValid:a!==null,sizeBytes:o.size,sizeValid:o.size<=n,maxFileSizeBytes:n,regularFile:o.isFile(),readable:s}}function Q9(t,e){let n=t.creatorType??e.creatorType,r=t.creatorId??e.creatorId;if(!n||!r)throw new Error("creatorType and creatorId are required for Roblox Open Cloud asset upload/update.");return{...t,creatorType:n,creatorId:r}}async function eV(t,e,n){let r=await uO(t.category,e,n);if(!r.formatValid||!r.contentType)throw new Error(`Unsupported file extension ${r.extension||"(none)"} for ${t.category}.`);if(!r.regularFile)throw new Error("Asset path must reference a regular file.");if(!r.readable)throw new Error("Asset file is not readable.");if(!r.sizeValid)throw new Error(`Asset file is too large. Maximum size is ${n} bytes.`);return r.contentType}function tV(t){return typeof t.path=="string"&&t.path.startsWith("operations/")?t.path:null}function nV(t,e,n,r){let i={apiKey:t.apiKey,operationId:e};return n!==void 0&&(i.intervalMs=n),r!==void 0&&(i.timeoutMs=r),i}var Du=class{client;credentialStore;isOpenCloudUploadEnabled;maxFileSizeBytes;constructor(e){this.client=e.client,this.credentialStore=e.credentialStore,this.isOpenCloudUploadEnabled=e.isOpenCloudUploadEnabled,this.maxFileSizeBytes=e.maxFileSizeBytes??Tm}getCapabilities(){return vS.map(({contentTypes:e,...n})=>n)}async uploadAsset(e){hS(this.isOpenCloudUploadEnabled());let n=await this.getRequiredCredential(),r=Q9(e,n),i=yS(r.category),a=await eV(i,r.filePath,this.maxFileSizeBytes);try{let o={apiKey:n.apiKey,assetType:i.assetType,displayName:r.displayName,description:r.description??"",creatorType:r.creatorType,creatorId:r.creatorId,filePath:r.filePath,contentType:a};r.expectedPrice!==void 0&&(o.expectedPrice=r.expectedPrice);let s=await this.client.createAsset(o);if(r.waitForOperation){let c=tV(s);return c?await this.client.pollOperation(nV(n,c,r.operationPollIntervalMs,r.operationPollTimeoutMs)):s}return s}catch(o){throw new Error(gS(o instanceof Error?o.message:String(o),n))}}async updateAsset(e){hS(this.isOpenCloudUploadEnabled());let n=await this.getRequiredCredential(),r=Q9(e,n),i=yS(r.category),a;if(r.filePath){if(!i.supportsContentUpdate)throw new Error(`${i.category} assets do not support content updates.`);a=await eV(i,r.filePath,this.maxFileSizeBytes)}try{let o={apiKey:n.apiKey,assetId:r.assetId,assetType:i.assetType,creatorType:r.creatorType,creatorId:r.creatorId};r.filePath&&(o.filePath=r.filePath),a!==void 0&&(o.contentType=a),r.displayName!==void 0&&(o.displayName=r.displayName),r.description!==void 0&&(o.description=r.description),r.updateMask!==void 0&&(o.updateMask=r.updateMask),r.expectedPrice!==void 0&&(o.expectedPrice=r.expectedPrice);let s=await this.client.updateAsset(o);if(r.waitForOperation){let c=tV(s);return c?await this.client.pollOperation(nV(n,c,r.operationPollIntervalMs,r.operationPollTimeoutMs)):s}return s}catch(o){throw new Error(gS(o instanceof Error?o.message:String(o),n))}}async getAsset(e){let n=await this.getRequiredCredential();try{let r={apiKey:n.apiKey,assetId:e.assetId};return e.readMask!==void 0&&(r.readMask=e.readMask),await this.client.getAsset(r)}catch(r){throw new Error(gS(r instanceof Error?r.message:String(r),n))}}async getOperation(e){let n=await this.getRequiredCredential();try{return await this.client.getOperation({apiKey:n.apiKey,operationId:e.operationId})}catch(r){throw new Error(gS(r instanceof Error?r.message:String(r),n))}}async getRequiredCredential(){let e=await this.credentialStore.getCredentialForUse();if(!e)throw new Error("Configure a Roblox Open Cloud API key in WEPPY Dashboard before using Open Cloud asset upload.");return e}};import rV from"node:fs";import un from"node:path";ix();var r_e=/^asset_(image|decal|audio|mesh|model|video|animation)_\d+_[a-z0-9]+$/;function i_e(t){if(!Number.isInteger(t)||t<0)throw new Error(`Invalid place ID: ${t}`)}function a_e(t,e){try{return rV.statSync(un.join(t,e,".sync-meta.json")).isFile()}catch{return!1}}function o_e(t,e){i_e(e.placeId);let n=`place_${e.placeId}`,r=e.placeName?lu(e.placeName):"",i=r?`${n}_${r}`:n,a=[];try{let o=new RegExp(`^place_${e.placeId}(?:_.*)?$`);a=rV.readdirSync(t,{withFileTypes:!0}).filter(s=>s.isDirectory()&&o.test(s.name)).map(s=>s.name).sort()}catch{return i}return r&&a.includes(i)?i:a.find(o=>a_e(t,o))??(a.includes(i)?i:null)??a[0]??i}function dO(t){let e=un.resolve(t.projectSyncRoot),n=$u(t.category).folder,r=t.scope.kind==="place"?un.join(e,o_e(e,t.scope),"assets",n):un.join(e,"shared-assets",n);return{root:r,inbox:un.join(r,"inbox"),index:un.join(r,".asset-library-index.json")}}function s_e(t){let e=r_e.exec(t);return e?.[1]?e[1]:null}function Am(t,e){let n=s_e(t);return n?e?n===e:!0:!1}function bS(t,e){if(!Am(t,e))throw new Error(`Invalid asset ID: ${t}`)}function $i(t,e){let n=un.relative(un.resolve(t),un.resolve(e));return n===""||!n.startsWith("..")&&!un.isAbsolute(n)}function c_e(t){bS(t.assetId,t.category);let e=dO(t),n=un.resolve(e.root,t.assetId);if(!$i(e.root,n))throw new Error(`Invalid asset path for ${t.assetId}`);return n}function _S(t){let e=c_e(t),n=un.resolve(e,t.relativeFileName);if(!$i(e,n))throw new Error(`Invalid asset file path for ${t.assetId}`);return n}function Om(t,e){return un.relative(un.resolve(t),un.resolve(e)).split(un.sep).join("/")}var sV=20*1024*1024,p_e=200,pO=8,f_e=512,m_e=120;function cV(t,e){return t.kind!==e.kind?!1:t.kind==="shared"&&e.kind==="shared"?!0:t.kind==="place"&&e.kind==="place"&&t.placeId===e.placeId}function lV(t,e){let n=Mt.extname(t).toLowerCase(),r=$u(e);if(!r.extensions.includes(n))return null;let i=r.contentTypes[n];return i?{canonicalExt:n,mimeType:i}:null}function mO(t,e,n){if(e!=="image"&&e!=="decal")return!0;let r=Mt.extname(t).toLowerCase();return r===".png"?n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10:r===".jpg"||r===".jpeg"?n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255:r===".bmp"?n.length>=2&&n[0]===66&&n[1]===77:r===".tga"?n.length>0:!1}function uV(t){return l_e("sha256").update(t).digest("hex")}function gO(t){if(t===void 0||t==="")return"";if(t.length>f_e||t.includes("\0")||t.includes("\\")||Mt.isAbsolute(t))throw new Error(`Invalid Asset Library folder path: ${t}`);let e=t.split("/");if(e.length>pO||e.some(n=>n.length===0||n.length>m_e||n==="."||n===".."))throw new Error(`Invalid Asset Library folder path: ${t}`);return e.join("/")}function SS(t){return t.now?.()??Date.now()}function g_e(t){return(t.randomId?.()??fO().replace(/-/g,"").slice(0,6)).toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,12)||"asset"}function dV(t,e){let n=Math.floor(SS(t)/1e3);for(let r=0;r<20;r++){let i=g_e(t),a=r===0?`asset_${t.category}_${n}_${i}`:`asset_${t.category}_${n}_${i}${r}`;if(!e.has(a))return a}return`asset_${t.category}_${n}_${fO().replace(/-/g,"").slice(0,10)}`}function pV(t){let e=Mt.parse(t).name.trim();return e.length>0?e:t}function fV(t){if(t.mimeType!=="image/png")throw new Error("Asset Library preview must be an image/png thumbnail");if(Mt.basename(t.fileName).toLowerCase()!=="thumbnail.png")throw new Error("Asset Library preview file must be thumbnail.png");if(!mO("thumbnail.png","image",t.content))throw new Error("Asset Library preview is not a valid PNG file");return{fileName:"thumbnail.png",content:t.content}}async function hO(t,e){let n=`${t}.tmp.${fO().slice(0,8)}`;await xS(n,JSON.stringify(e,null,2),"utf8"),await oV(n,t)}async function mV(t,e){try{let n=await iV(Mt.join(e,"asset.json"),"utf8"),r=JSON.parse(n);return!Am(r.id,t.category)||r.category!==t.category||!cV(r.scope,t.scope)?null:(gO(r.folderPath),r)}catch{return null}}async function Dm(t,e){let n;try{n=await aV(e.root,{withFileTypes:!0})}catch(i){if(i?.code==="ENOENT")return[];throw i}let r=[];for(let i of n.sort((a,o)=>a.name.localeCompare(o.name))){if(!i.isDirectory()||!Am(i.name,t.category))continue;let a=Mt.join(e.root,i.name),o=await mV(t,a);o&&r.push(o)}return r.sort((i,a)=>a.createdAt.localeCompare(i.createdAt)||a.id.localeCompare(i.id))}async function Nu(t,e,n){if(bS(n.id,t.category),n.category!==t.category||!cV(n.scope,t.scope))throw new Error(`Asset metadata does not match library scope/category: ${n.id}`);gO(n.folderPath);let r=Mt.join(e.root,n.id);if(!$i(e.root,r))throw new Error(`Invalid asset path for ${n.id}`);await $m(r,{recursive:!0}),await hO(Mt.join(r,"asset.json"),n)}async function gV(t,e){await $m(t.root,{recursive:!0});let n={version:1,generatedAt:new Date().toISOString(),assets:e.map(r=>r.id)};await hO(t.index,n)}function ri(t,e,n){return{fileName:t,reason:e,message:n}}async function hV(t,e=t,n=[]){let r;try{r=await aV(e,{withFileTypes:!0})}catch(a){if(a?.code==="ENOENT")return[];throw a}let i=[];for(let a of r.sort((o,s)=>o.name.localeCompare(s.name))){let o=[...n,a.name],s=Mt.join(e,a.name);if(a.isDirectory()&&!a.isSymbolicLink()&&!a.name.startsWith(".")){let c=o.join("/");if(o.length>pO){i.push({entry:a,sourcePath:s,relativePath:c,folderPath:n.join("/"),skipReason:"maxDepth",skipMessage:`folder depth exceeds ${pO}`});continue}try{gO(c)}catch{i.push({entry:a,sourcePath:s,relativePath:c,folderPath:n.join("/"),skipReason:"unsupportedType",skipMessage:"invalid Asset Library folder path"});continue}i.push(...await hV(t,s,o));continue}i.push({entry:a,sourcePath:s,relativePath:o.join("/"),folderPath:n.join("/")})}return i}async function Ni(t){let e=dO(t);return await $m(e.inbox,{recursive:!0}),e}async function wS(t){let e=await Ni(t),n=await Dm(t,e);return await gV(e,n),n}async function Xt(t,e){bS(e,t.category);let n=await Ni(t),r=Mt.join(n.root,e);if(!$i(n.root,r))throw new Error(`Invalid asset path for ${e}`);let i=await mV(t,r);if(!i)throw new Error(`Asset not found: ${e}`);return i}async function ju(t){let e=await Ni(t),n=await Dm(t,e),r={version:1,generatedAt:new Date().toISOString(),assets:n.map(i=>i.id)};return await hO(e.index,r),r}async function yV(t){let e=await Ni(t),n=await Dm(t,e),r=new Set(n.map(p=>p.id)),i=new Set(n.map(p=>p.file.sha256)),a=[],o=[],s=t.maxFileSizeBytes??sV,c=t.maxFilesPerRescan??p_e,l=await hV(e.inbox),u=0;for(let p of l){let{entry:f,sourcePath:m}=p;if(p.skipReason){o.push(ri(p.relativePath,p.skipReason,p.skipMessage??"inbox entry skipped"));continue}if(f.name.startsWith(".")&&!f.isFile()){o.push(ri(p.relativePath,"hidden","hidden or system file"));continue}if(f.isSymbolicLink()){o.push(ri(p.relativePath,"symlink","symlink files are not followed"));continue}if(f.isDirectory()){o.push(ri(p.relativePath,"nestedDirectory","nested directories are not scanned"));continue}if(!f.isFile()){o.push(ri(p.relativePath,"unsupportedType","unsupported inbox entry type"));continue}if(u+=1,u>c){o.push(ri(p.relativePath,"maxFileCount","rescan file count limit exceeded"));continue}if(f.name.startsWith(".")){o.push(ri(p.relativePath,"hidden","hidden or system file"));continue}let g=lV(f.name,t.category);if(!g){o.push(ri(f.name,"unsupportedType",`unsupported ${t.category} extension`));continue}let y=await d_e(m);if(y.size>s){o.push(ri(f.name,"oversized","asset file is larger than the configured limit"));continue}let v=await iV(m);if(!mO(f.name,t.category,v)){o.push(ri(f.name,"invalidSignature","file signature does not match the extension"));continue}let b=uV(v);if(i.has(b)){o.push(ri(f.name,"duplicate","asset content already exists in Asset Library"));continue}let x=dV(t,r);r.add(x),i.add(b);let I=Mt.join(e.root,x),w=`original${g.canonicalExt}`;await $m(I,{recursive:!0}),await oV(m,Mt.join(I,w));let N=new Date(SS(t)).toISOString(),k={version:1,id:x,category:t.category,scope:t.scope,...p.folderPath?{folderPath:p.folderPath}:{},status:"localOnly",displayName:pV(f.name),description:"",source:{kind:"generated",originalPath:Om(t.projectSyncRoot,m)},file:{original:w,preview:null,mimeType:g.mimeType,sha256:b,sizeBytes:y.size,width:null,height:null,durationMs:null},roblox:{uploaded:!1},usage:{lastScannedAt:null,scanSource:null,references:[]},createdAt:N,updatedAt:N};await Nu(t,e,k),a.push(k)}let d=await Dm(t,e);return await gV(e,d),{assets:d,adopted:a,skipped:o,adoptedCount:a.length,skippedCount:o.length}}async function Nm(t){let e=await Ni(t),n=lV(t.originalFileName,t.category);if(!n)throw new Error(`Unsupported ${t.category} extension for Asset Library export`);let r=t.maxFileSizeBytes??sV;if(t.content.length>r)throw new Error("asset file is larger than the configured limit");if(!mO(t.originalFileName,t.category,t.content))throw new Error("file signature does not match the extension");let i=await Dm(t,e),a=uV(t.content),o=i.find(y=>y.file.sha256===a);if(o)return{asset:o,deduplicated:!0};let s=new Set(i.map(y=>y.id)),c=dV(t,s),l=Mt.join(e.root,c);if(!$i(e.root,l))throw new Error(`Invalid asset path for ${c}`);let u=`original${n.canonicalExt}`;await $m(l,{recursive:!0}),await xS(Mt.join(l,u),t.content);let d=null;if(t.preview){let y=fV(t.preview);d=y.fileName,await xS(Mt.join(l,y.fileName),y.content)}let p=new Date(SS(t)).toISOString(),f=t.roblox??{uploaded:!1},m=f.uploaded&&f.assetId?"uploaded":"localOnly",g={version:1,id:c,category:t.category,scope:t.scope,status:m,displayName:t.displayName?.trim()||pV(t.originalFileName),description:t.description??"",source:{...t.source,originalPath:Om(t.projectSyncRoot,Mt.join(l,u))},file:{original:u,preview:d,mimeType:n.mimeType,sha256:a,sizeBytes:t.content.length,width:null,height:null,durationMs:null},roblox:f,usage:{lastScannedAt:null,scanSource:null,references:[]},...t.rbxm?{rbxm:t.rbxm}:{},createdAt:p,updatedAt:p};return await Nu(t,e,g),await ju(t),{asset:g,deduplicated:!1}}async function vV(t){let e=await Ni(t),n=await Xt(t,t.assetId),r=fV(t.preview),i=_S({...t,relativeFileName:r.fileName});await xS(i,r.content);let a={...n,file:{...n.file,preview:r.fileName},...n.rbxm&&t.rbxmThumbnail?{rbxm:{...n.rbxm,thumbnail:t.rbxmThumbnail}}:{},updatedAt:new Date(SS(t)).toISOString()};return await Nu(t,e,a),await ju(t),{asset:a}}async function bV(t,e,n){let r=await Ni(t),i=await Xt(t,e),a={...i,displayName:typeof n.displayName=="string"?n.displayName:i.displayName,description:typeof n.description=="string"?n.description:i.description,source:{...i.source,...n.source?.agent!==void 0?{agent:n.source.agent}:{},...n.source?.contextId!==void 0?{contextId:n.source.contextId}:{},...n.source?.prompt!==void 0?{prompt:n.source.prompt}:{}},updatedAt:new Date().toISOString()};return await Nu(t,r,a),await ju(t),a}async function _V(t,e,n){let r=await Ni(t),a={...await Xt(t,e),usage:n,updatedAt:new Date().toISOString()};return await Nu(t,r,a),await ju(t),a}async function xV(t,e){let n=await Ni(t);await Xt(t,e);let r=Mt.join(n.root,e);if(!$i(n.root,r))throw new Error(`Invalid asset path for ${e}`);return await u_e(r,{recursive:!0}),await ju(t),{assetId:e,removed:1}}async function ji(t){let e=await Ni(t);return await Nu(t,e,t.asset),await ju(t),t.asset}async function Mu(t){let e=await Xt(t,t.assetId);return _S({...t,relativeFileName:e.file.original})}async function SV(t){let e=await Xt(t,t.assetId);return _S({...t,relativeFileName:e.file.preview??e.file.original})}var v_e="https://create.roblox.com/dashboard/creations/store",b_e="manage_assets_import_rbxm",vO="manage_assets_generate_thumbnail",__e="manage_assets_review_model";var bO=new Set([b_e,vO]),_O=new Set(["manage_assets_export_selection_rbxm","manage_assets_export_path_rbxm",__e]),x_e=new Set(["model","animation"]);function st(t){return t&&typeof t=="object"?t:null}function S_e(t){if(typeof t!="string"||!x_e.has(t))throw new Error(`Unsupported Asset Library .rbxm round-trip category: ${String(t??"(missing)")}`);return t}function w_e(t){if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return t;if(typeof t=="string"&&t.trim().length>0){let e=Number.parseInt(t,10);if(Number.isInteger(e)&&e>=0)return e}return null}function wV(t,e){for(let n of t.pluginClients.values())if(!(typeof n.placeId!="number"||!Number.isFinite(n.placeId))&&!(e!==void 0&&n.placeId!==e))return{placeId:n.placeId,...n.placeName?{placeName:n.placeName}:{}};return null}function xO(t,e){let n=ft(t.config.dataDir),r=S_e(e.category),i=typeof e.scope=="string"?e.scope:"place",a=typeof e.assetLibraryAssetId=="string"&&e.assetLibraryAssetId.length>0?e.assetLibraryAssetId:void 0;if(i==="shared")return{projectSyncRoot:n,scope:{kind:"shared"},category:r,...a?{assetId:a}:{}};if(i!=="place")throw new Error(`Invalid Asset Library scope: ${i}`);let o=w_e(e.placeId),s=t.syncController?.getDefaultRuntimePlaceId()??null,c=o??s??wV(t)?.placeId??null;if(c===null)throw new Error("No placeId is available for Asset Library .rbxm round-trip.");let l=wV(t,c);return{projectSyncRoot:n,scope:{kind:"place",placeId:c,...l?.placeName?{placeName:l.placeName}:{}},category:r,...a?{assetId:a}:{}}}function I_e(t){if(y_e.extname(t.file.original).toLowerCase()!==".rbxm")throw new Error(`Asset Library Studio round-trip supports original.rbxm only. Unsupported original file: ${t.file.original}`)}function C_e(t,e){if(typeof t!="string"||t.trim().length===0)throw new Error(`${e} is missing`);return Buffer.from(t,"base64")}function P_e(t,e){let n=st(e),i={kind:n?.kind==="generation"||typeof t.prompt=="string"?"generated":"studioExport",originalPath:"studio:selection"};if(n){let a=typeof n.path=="string"?n.path:typeof n.kind=="string"?n.kind:void 0;a&&(i.originalPath=`studio:${a}`);let o=ye(n.prompt,1e3);o&&(i.prompt=o)}if(!i.prompt){let a=ye(t.prompt,1e3);a&&(i.prompt=a)}return typeof t.contextId=="string"&&(i.contextId=t.contextId),i}function kV(t){let e=st(t);if(!e)return;let n={};typeof e.width=="number"&&(n.width=e.width),typeof e.height=="number"&&(n.height=e.height),typeof e.source=="string"&&(n.source=e.source),typeof e.error=="string"&&(n.error=e.error);let r=jm(e.attempts);return r.length>0&&(n.attempts=r),Object.keys(n).length>0?n:void 0}function ye(t,e){return typeof t!="string"?null:t.slice(0,e)}function k_e(t){if(typeof t!="string")return null;let e=t.trim();return/^\d+$/.test(e)?e:null}function IV(t){return`rbxassetid://${t}`}function CV(t){return`${v_e}/${t}/configure`}function PV(t){return`assets/${t}`}function Pr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function RV(t){return Array.isArray(t)?t.slice(0,100).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.name,256),i=ye(n.className,128),a=ye(n.path,512);return r===null||i===null||a===null?[]:[{name:r,className:i,path:a}]}):[]}function R_e(t){let e=st(t);if(!e)return{};let n={};for(let[r,i]of Object.entries(e).slice(0,100))typeof i!="number"||!Number.isFinite(i)||i<0||(n[r.slice(0,128)]=Math.floor(i));return n}function E_e(t){return Array.isArray(t)?t.slice(0,200).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.path,512),i=ye(n.property,128),a=ye(n.value,1024);if(r===null||i===null||a===null)return[];let o=ye(n.assetId,64);return[{path:r,property:i,value:a,...o?{assetId:o}:{}}]}):[]}function jm(t){return Array.isArray(t)?t.slice(0,8).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.method,80),i=n.status==="success"||n.status==="failed"||n.status==="skipped"?n.status:null;if(r===null||i===null)return[];let a=ye(n.message,512);return[{method:r,status:i,...a?{message:a}:{}}]}):[]}function T_e(t,e){let n=t.thumbnailMode==="auto"?"auto":"none";if(n==="none")return{mode:n,status:"skipped",message:"Thumbnail generation disabled"};let r=kV(e),i=st(e),a=typeof i?.pngBase64=="string"&&i.pngBase64.length>0,o=typeof i?.base64Rgba=="string"&&i.base64Rgba.length>0&&i.format==="rgba8"&&typeof i.width=="number"&&typeof i.height=="number";if(r&&(a||o)){let s=Pr(r.width),c=Pr(r.height),l=jm(i?.attempts);return{mode:n,status:"generated",...s!==void 0?{width:s}:{},...c!==void 0?{height:c}:{},...typeof r.source=="string"?{source:r.source.slice(0,128)}:{},...l.length>0?{attempts:l}:{}}}if(r&&typeof r.error=="string"){let s=jm(st(e)?.attempts);return{mode:n,status:"failed",message:r.error.slice(0,512),...s.length>0?{attempts:s}:{}}}return{mode:n,status:"skipped",message:"Thumbnail was not returned"}}function A_e(t,e){let n=st(t);if(!n)return e;let r=n.mode==="auto"||n.mode==="none"?n.mode:e.mode,i=n.status==="generated"||n.status==="skipped"||n.status==="failed"?n.status:e.status,a=ye(n.message,512),o=Pr(n.width),s=Pr(n.height),c=ye(n.source,128),l=jm(n.attempts);return{mode:r,status:i,...a?{message:a}:{},...o!==void 0?{width:o}:{},...s!==void 0?{height:s}:{},...c?{source:c}:{},...l.length>0?{attempts:l}:{}}}function yO(t,e=0){if(e>3)return;if(typeof t=="string")return t.slice(0,512);if(typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return t.slice(0,50).flatMap(i=>{let a=yO(i,e+1);return a===void 0?[]:[a]});let n=st(t);if(!n)return;let r={};for(let[i,a]of Object.entries(n).slice(0,50)){let o=yO(a,e+1);o!==void 0&&(r[i.slice(0,128)]=o)}return r}function O_e(t){let e=st(t),n=Pr(e?.x),r=Pr(e?.y),i=Pr(e?.z);if(!(n===void 0||r===void 0||i===void 0))return{x:n,y:r,z:i}}function D_e(t){return Array.isArray(t)?t.slice(0,100).flatMap(e=>{let n=st(e);if(!n)return[];let r=n.severity==="info"||n.severity==="warning"||n.severity==="error"?n.severity:null,i=ye(n.category,80),a=ye(n.code,120),o=ye(n.path,512),s=ye(n.message,512);if(!r||i===null||a===null||o===null||s===null)return[];let c=ye(n.suggestion,512);return[{severity:r,category:i,code:a,path:o,message:s,...c?{suggestion:c}:{}}]}):[]}function $_e(t){let e=st(t);if(!e)return;let n=e.readiness==="ready"||e.readiness==="review"||e.readiness==="blocked"?e.readiness:null;if(!n)return;let r=yO(e.summary),i=ye(e.reviewedAt,64),a=RV(e.roots);return{readiness:n,...i?{reviewedAt:i}:{},...a.length>0?{roots:a}:{},summary:st(r)??{},findings:D_e(e.findings)}}function N_e(t){let e=st(t);if(!e)return;let n={};for(let[r,i]of Object.entries(e).slice(0,16))typeof i=="string"&&(n[r.slice(0,128)]=i.slice(0,256)),typeof i=="number"&&Number.isFinite(i)&&(n[r.slice(0,128)]=i),typeof i=="boolean"&&(n[r.slice(0,128)]=i);return Object.keys(n).length>0?n:void 0}function j_e(t){let e=st(t);if(!e)return;let n=ye(e.provider,120);if(!n)return;let r=ye(e.generatedAt,64),i=ye(e.prompt,1e3),a=e.schemaMode==="predefined"||e.schemaMode==="custom"?e.schemaMode:void 0,o=e.predefinedSchema==="Body1"||e.predefinedSchema==="Car5"?e.predefinedSchema:void 0,s=Array.isArray(e.schemaGroups)?e.schemaGroups.slice(0,50).flatMap(f=>{let m=ye(f,120);return m?[m]:[]}):void 0,c=O_e(e.requestedSize),l=Pr(e.maxTriangles),u=ye(e.targetParent,512),d=ye(e.path,512),p=N_e(e.metadata);return{provider:n,...r?{generatedAt:r}:{},...i?{prompt:i}:{},...a?{schemaMode:a}:{},...o?{predefinedSchema:o}:{},...s&&s.length>0?{schemaGroups:s}:{},...c?{requestedSize:c}:{},...l!==void 0?{maxTriangles:Math.floor(l)}:{},...typeof e.generateTextures=="boolean"?{generateTextures:e.generateTextures}:{},...u?{targetParent:u}:{},...d?{path:d}:{},...p?{metadata:p}:{}}}function M_e(t){return Array.isArray(t)?t.slice(0,100).flatMap(e=>{let n=st(e);if(!n)return[];let r=ye(n.path,512),i=n.assetType==="Mesh"||n.assetType==="Image"||n.assetType==="Model"?n.assetType:null,a=n.status==="uploaded"||n.status==="failed"?n.status:null;if(r===null||i===null||a===null)return[];let o=ye(n.assetId,64),s=ye(n.assetUri,128),c=n.creatorType==="user"||n.creatorType==="group"?n.creatorType:void 0,l=ye(n.creatorId,64),u=ye(n.sourceProperty,128),d=ye(n.uploadedAt,64),p=ye(n.message,512);return[{path:r,assetType:i,status:a,...o?{assetId:o}:{},...s?{assetUri:s}:{},...c?{creatorType:c}:{},...l?{creatorId:l}:{},...u?{sourceProperty:u}:{},...d?{uploadedAt:d}:{},...p?{message:p}:{}}]}):[]}function L_e(t){let e=st(t);if(!e||e.uploaded!==!0)return;let n=k_e(e.assetId);if(!n)return;let r=ye(e.uploadedAt,64)??new Date().toISOString(),i=e.creatorType==="user"||e.creatorType==="group"?e.creatorType:void 0,a=ye(e.creatorId,64);return{uploaded:!0,assetId:n,assetUri:IV(n),assetWebUrl:CV(n),remotePath:PV(n),uploadedAt:r,uploadAttempts:[{startedAt:r,finishedAt:r,status:"uploaded",assetRole:"primary",...i?{creatorType:i}:{},...a?{creatorId:a}:{},assetId:n,assetUri:IV(n),assetWebUrl:CV(n),remotePath:PV(n)}]}}function z_e(t){let e=st(t.value),n=RV(e?.roots),r=R_e(e?.classCounts),i=E_e(e?.resourceReferences),a=$_e(e?.review),o=j_e(e?.generation),s=M_e(e?.studioUploads),c=Pr(e?.exportedCount)??Pr(t.exportedCount)??n.length;return{exportedCount:Math.max(0,Math.floor(c)),roots:n,classCounts:r,resourceReferences:i,thumbnail:A_e(e?.thumbnail,t.fallbackThumbnail),...a?{review:a}:{},...o?{generation:o}:{},...s.length>0?{studioUploads:s}:{}}}function U_e(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10}function EV(t){let e=st(t);if(!e)return;let n=null;if(typeof e.pngBase64=="string"&&e.pngBase64.length>0?n=Buffer.from(e.pngBase64,"base64"):typeof e.base64Rgba=="string"&&e.base64Rgba.length>0&&e.format==="rgba8"&&typeof e.width=="number"&&typeof e.height=="number"&&(n=Buffer.from(X9(e.base64Rgba,e.width,e.height),"base64")),!!n){if(!U_e(n))throw new Error("Thumbnail payload is not a valid PNG image.");return{fileName:"thumbnail.png",content:n,mimeType:"image/png"}}}function F_e(t,e){let n=e instanceof Error?e.message:String(e);return t.thumbnail.status!=="generated"?t:{...t,thumbnail:{...t.thumbnail,status:"failed",message:`Thumbnail payload could not be stored: ${n}`.slice(0,512)}}}async function TV(t){if(!bO.has(t.command))return t.params;let e=xO(t.ctx,t.params);if(!e.assetId)throw new Error("assetLibraryAssetId is required for Asset Library .rbxm round-trip.");let n=await Xt(e,e.assetId);I_e(n);let r=await Mu({...e,assetId:n.id}),i=await h_e(r);return{...t.params,__assetLibraryRbxmBase64:i.toString("base64"),__assetLibraryOriginalFile:n.file.original}}async function AV(t){if(!_O.has(t.command)||!t.result.success)return t.result;let e=st(t.result.data);if(!e||typeof e.rbxmBase64!="string"||e.rbxmBase64.trim().length===0)return t.result;let n=xO(t.ctx,t.params),r=C_e(e.rbxmBase64,"Asset Library .rbxm export payload"),i=typeof t.params.displayName=="string"?t.params.displayName:void 0,a=typeof t.params.description=="string"?t.params.description:void 0,o=`${i?.trim()||"studio-export"}.rbxm`,s,c=null;try{s=EV(e.thumbnail)}catch(f){c=f,s=void 0}let l=z_e({value:e.rbxm,exportedCount:e.exportedCount,fallbackThumbnail:T_e(t.params,e.thumbnail)});c&&(l=F_e(l,c));let u=L_e(e.roblox),d=await Nm({projectSyncRoot:n.projectSyncRoot,scope:n.scope,category:n.category,originalFileName:o,content:r,...i!==void 0?{displayName:i}:{},...a!==void 0?{description:a}:{},source:P_e(t.params,e.source),...s?{preview:s}:{},rbxm:l,...u?{roblox:u}:{}}),p=kV(e.thumbnail);return{...t.result,data:{asset:d.asset,deduplicated:d.deduplicated,...typeof e.byteLength=="number"?{byteLength:e.byteLength}:{},...typeof e.exportedCount=="number"?{exportedCount:e.exportedCount}:{},...e.source!==void 0?{source:e.source}:{},...p?{thumbnail:p}:{}}}}async function OV(t){if(!t.result.success)return t.result;let e=st(t.result.data),n=st(e?.thumbnail),r;try{r=EV(n)}catch(d){return{...t.result,success:!1,error:d instanceof Error?d.message:String(d)}}if(!n||!r)return{...t.result,success:!1,error:typeof n?.error=="string"?n.error:"Thumbnail payload is missing from Asset Library thumbnail generation result."};let i=Pr(n.width),a=Pr(n.height),o=ye(n.source,128),s=jm(n.attempts),c={mode:"auto",status:"generated",...i!==void 0?{width:i}:{},...a!==void 0?{height:a}:{},...o?{source:o}:{},...s.length>0?{attempts:s}:{}},l=xO(t.ctx,t.params);if(!l.assetId)throw new Error("assetLibraryAssetId is required for Asset Library thumbnail generation.");let u=await vV({projectSyncRoot:l.projectSyncRoot,scope:l.scope,category:l.category,assetId:l.assetId,preview:r,rbxmThumbnail:c});return{...t.result,data:{asset:u.asset,...i!==void 0?{width:i}:{},...a!==void 0?{height:a}:{},...o?{source:o}:{}}}}function q_e(t){if(t===null||typeof t!="object")return;let e=t.proFallback;if(e===null||typeof e!="object")return;let n=e;if(typeof n.executedCommand!="string")return;let r=Array.isArray(n.alternatives)?n.alternatives.filter(i=>typeof i=="string"):void 0;return{executedCommand:n.executedCommand,...typeof n.requestedCommand=="string"?{requestedCommand:n.requestedCommand}:{},...r?{alternatives:r}:{}}}var B_e=/^Pro action '[^']+' is blocked in Basic mode\. Basic fallback '([^']+)' failed: (.*)$/s,V_e=/^Pro action '[^']+' is blocked in Basic mode\.(?! Basic fallback ')/,W_e=/instance not found|not found in|parent not found/,H_e=/is required|missing required/,Z_e=/unknown action|unknown command/,G_e=/must be|invalid|cannot/;function K_e(t){let e=B_e.exec(t);return e?{fallbackCommand:e[1],reason:e[2]}:null}function J_e(t){return V_e.test(t)}function Y_e(t){let e=t.toLowerCase();return W_e.test(e)?"not_found":H_e.test(e)?"missing_param":Z_e.test(e)?"unknown_action":G_e.test(e)?"validation":"other"}function SO(t){return t.errorType==="bridge_error"||t.errorType==="command_timeout"||t.errorType==="plugin_runtime"||t.errorType==="exception"||t.errorType==="device_blocked"||t.failureOrigin==="bridge"||t.failureOrigin==="plugin_runtime"||t.failureOrigin==="server_exception"||t.failureOrigin==="product_bug"||t.failureOrigin==="unknown"||t.recoverability==="retry"||t.recoverability==="wait_connection"||t.recoverability==="unknown"?"error":"warning"}function Lu(t){if(t.resultSuccess){let e=q_e(t.resultData);return e?{kind:"success_fallback",fallbackCommand:e.executedCommand,...e.alternatives?{alternatives:e.alternatives}:{}}:{kind:"success_ok"}}if(!t.resultError)return{kind:"error"};if(t.tier==="pro"){let e=K_e(t.resultError);if(e)return{kind:"blocked_fallback_failed",fallbackCommand:e.fallbackCommand,blockedDetail:Y_e(e.reason)};if(J_e(t.resultError))return{kind:"blocked_unsupported"}}return t.failureClassification?{kind:SO(t.failureClassification)}:{kind:"error"}}function Se(t,e,n,r,i={}){return{errorType:t,errorDetail:e,failureOrigin:n,recoverability:r,...i}}function X_e(t){let e=t.toLowerCase();return/^\s*compilation error:/.test(e)?Se("execution_failed","compile_error","agent_request","code_fix",{validationStage:"plugin_handler"}):/^\s*result too large:/.test(e)?Se("execution_failed","result_too_large","agent_request","code_fix",{validationStage:"plugin_handler"}):/^\s*execution timed out after/.test(e)?Se("execution_failed","execution_timeout","agent_request","code_fix",{validationStage:"plugin_handler"}):/potentially dangerous infinite loop|blocked in sandbox|access to .* is blocked|forbidden|not allowed|cannot access/.test(e)?Se("execution_failed","blocked_source","roblox_policy","code_fix",{validationStage:"plugin_handler"}):null}function Q_e(t){let e=t.toLowerCase();return/startline and endline must be provided together/.test(e)||/startline must be a positive integer/.test(e)||/endline must be a positive integer/.test(e)||/endline must be >= startline/.test(e)?Se("execution_failed","validation","agent_request","fix_params",{validationStage:"schema"}):null}function DV(t){let e=t.toLowerCase();return/upstream_server_down/.test(e)?Se("bridge_error","upstream_down","bridge","wait_connection"):/^http [45]\d\d/.test(e)?Se("bridge_error","http_error","bridge","retry"):/duplicate request\s*id/.test(e)?Se("bridge_error","duplicate_request_id","bridge","code_fix"):/timeout/.test(e)?Se("command_timeout","timeout","bridge","retry"):/econnrefused|socket hang up|econnreset|epipe|network/.test(e)?Se("bridge_error","connection","bridge","wait_connection"):/abort/.test(e)?Se("command_timeout","aborted","bridge","retry"):/runtime error|traceback|attempt to/.test(e)?Se("plugin_runtime","runtime_error","plugin_runtime","code_fix"):/created instance, but failed to set \d+ propert/.test(e)?Se("execution_failed","property_apply_failed","agent_request","fix_params",{validationStage:"plugin_handler",partialSuccess:"true"}):/failed to set property/.test(e)?Se("execution_failed","property_apply_failed","agent_request","fix_params",{validationStage:"plugin_handler"}):/parent(?: instance)? not found/.test(e)?Se("execution_failed","parent_not_found","agent_request","fix_params",{validationStage:"plugin_handler"}):/(?:instance|path|root|source instance|ancestor instance) not found|target\s+(?:path\s+)?(?:['"`][^'"`]+['"`]\s+)?not found|not found in|no synced file found for instance/.test(e)?Se("execution_failed","not_found","user_project_state","fix_params",{validationStage:"plugin_handler"}):/is required|missing required/.test(e)?Se("execution_failed","missing_param","agent_request","fix_params",{validationStage:"schema"}):/invalid classname|invalid class/.test(e)?Se("execution_failed","invalid_class","agent_request","fix_params",{validationStage:"plugin_handler"}):/unknown action|unknown command/.test(e)?Se("execution_failed","unknown_action","agent_request","fix_params",{validationStage:"dispatcher"}):/failed to insert asset/.test(e)?Se("execution_failed","asset_error","roblox_policy","fix_params",{validationStage:"roblox_api"}):/failed to read property|property access denied/.test(e)?Se("execution_failed","property_error","agent_request","fix_params",{validationStage:"plugin_handler"}):/forbidden (?:path|parent path)|exceeds (?:total lines|max(?:imum)?(?: length)?)|is not (?:a|an) /.test(e)?Se("execution_failed","validation","agent_request","fix_params",{validationStage:"plugin_handler"}):/sync controller not available|project sync is not initialized|no active sync place|not found in sync cache/.test(e)?Se("execution_failed","sync_not_ready","user_project_state","wait_connection",{validationStage:"preflight"}):/cannot capture edit-mode screenshot while a playtest is active|play-mode screenshot capture is not supported/.test(e)?Se("execution_failed","unsupported_context","roblox_policy","no_retry",{validationStage:"preflight"}):/editableimage api is not enabled|allow mesh \/ image apis|allow http requests/.test(e)?Se("execution_failed","feature_disabled","roblox_policy","no_retry",{validationStage:"preflight"}):/must be|invalid|cannot/.test(e)?Se("execution_failed","validation","agent_request","fix_params",{validationStage:"plugin_handler"}):Se("execution_failed","other","unknown","unknown")}function zu(t,e){if(t==="manage_scripts_get_source"){let r=Q_e(e);if(r)return r}if(t==="execute_luau"){let r=X_e(e);if(r)return r}let n=DV(e);return t==="execute_luau"&&n.errorDetail==="runtime_error"&&/^\s*runtime error:/i.test(e)?Se("execution_failed","runtime_error","agent_request","code_fix"):n}function $V(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return/timeout/.test(n)?Se("command_timeout","timeout","bridge","retry"):/econnrefused|socket hang up|network|econnreset|epipe/.test(n)?Se("bridge_error","connection","bridge","wait_connection"):/eaddrinuse/.test(n)?Se("bridge_error","port_in_use","bridge","no_retry"):Se("exception","unexpected","server_exception","code_fix")}kS();Fu();import{randomBytes as xxe}from"node:crypto";var Sxe=["manage_ui_create_tree","manage_ui_update","manage_ui_delete"],ZV=["manage_ui_preview","manage_ui_check"],wxe=["ui_role","style_family","layout_family","device_policy","safe_area_policy","existing_ui_strategy"],Ixe=["screen_job","primary_action","visual_thesis","signature_motif","layout_family","imagery_family","ornamentation_family","composition_family","motion_family","device_policy","quality_priority","primary_view_profile_id","responsive_requirement"];function TS(t){return t&&typeof t=="object"?t:void 0}function OO(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ES(t){let e=TS(t);if(!e)return;let n={};for(let r of wxe){let i=e[r];typeof i=="string"&&i.trim().length>0&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}function DO(t){let e=ES(t.qualityPlanSummary);if(e)return e;let n=TS(t.contextSummary),r=ES(n?.qualityPlanSummary);if(r)return r;let i=ES(n?.qualityPlan);if(i)return i;let a=ES(n?.quality_plan);if(a)return a}function GV(t){let e=TS(t);if(!e)return;let n={};for(let r of Ixe){let i=e[r];typeof i=="string"&&i.trim().length>0&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}function KV(t,e){return e?{...t??{},...e}:t}function Cxe(t){return typeof t=="string"?{snapshotId:t}:t&&typeof t=="object"?{snapshotId:typeof t.snapshotId=="string"?t.snapshotId:null,...t.designCheckSummary!==void 0&&{designCheckSummary:t.designCheckSummary},...t.capturedAt!==void 0&&{capturedAt:t.capturedAt},...t.error!==void 0&&{error:t.error}}:{snapshotId:null,error:"preview unavailable"}}function JV(t,e,n,r,i){if(!e)return;let a=OO(e.priority_high),o=OO(e.priority_medium),s=OO(e.priority_low),c=typeof e.total=="number"&&Number.isFinite(e.total)?e.total:a+o+s,l=n??(typeof e.target=="string"?e.target:void 0),u={source:t,...l!==void 0&&{targetPath:l},...typeof r=="string"&&{snapshotId:r},...i!==void 0&&{capturedAt:i},priority_high:a,priority_medium:o,priority_low:s,total:c,deterministic_status:e.deterministic_status==="failed"?"failed":"completed",visual_status:e.visual_status==="completed"||e.visual_status==="skipped"||e.visual_status==="failed"?e.visual_status:"not_requested",coverage:e.coverage==="structural_and_visual"?"structural_and_visual":"structural_only",skipped_reasons:Array.isArray(e.skipped_reasons)?e.skipped_reasons.filter(d=>typeof d=="string"):[],interaction_status:e.interaction_status,primary_view_context_status:e.primary_view_context_status,responsive_status:e.responsive_status,responsive_profiles_reviewed:e.responsive_profiles_reviewed,viewport_profiles_tested:e.viewport_profiles_tested,primary_visual_status:e.primary_visual_status??"not_requested",primary_visual_verdict:e.primary_visual_verdict,critic_summary:typeof e.critic_summary=="string"?e.critic_summary.trim():void 0,responsive_requirement:e.responsive_requirement};return{...u,...rc(u)}}function YV(t,e){if(!e)return t;if(!t)return e;let n=t.targetPath===e.targetPath?t.targetPath:void 0,r=t.snapshotId===e.snapshotId?t.snapshotId:void 0,i={source:e.source,...n!==void 0&&{targetPath:n},...r!==void 0&&{snapshotId:r},...e.capturedAt!==void 0&&{capturedAt:e.capturedAt},priority_high:t.priority_high+e.priority_high,priority_medium:t.priority_medium+e.priority_medium,priority_low:t.priority_low+e.priority_low,total:t.total+e.total,deterministic_status:t.deterministic_status==="failed"||e.deterministic_status==="failed"?"failed":"completed",visual_status:e.visual_status,coverage:t.coverage==="structural_and_visual"||e.coverage==="structural_and_visual"?"structural_and_visual":"structural_only",skipped_reasons:Array.from(new Set([...t.skipped_reasons,...e.skipped_reasons])),interaction_status:e.coverage_dimensions.interaction.status,primary_view_context_status:e.coverage_dimensions.primary_view_context.status,responsive_status:e.coverage_dimensions.responsive_viewport.status,viewport_profiles_tested:Array.from(new Set([...t.viewport_profiles_tested,...e.viewport_profiles_tested])),primary_visual_status:e.primary_visual_status,primary_visual_verdict:e.primary_visual_verdict??t.primary_visual_verdict,critic_summary:e.critic_summary??t.critic_summary,responsive_requirement:e.responsive_requirement??t.responsive_requirement};return{...i,...rc(i)}}function Pxe(t){let e=TS(t);if(e)for(let n of["userMessage","intent","expectedBehavior"]){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r.trim().slice(0,80)}}function kxe(){let t={source:"unavailable",priority_high:0,priority_medium:0,priority_low:0,total:0,deterministic_status:"failed",visual_status:"not_requested",coverage:"structural_only",skipped_reasons:["design_check_unavailable"],primary_visual_status:"not_requested"};return{...t,...rc(t)}}function XV(t){let e=t.now??Date.now,n=null,r=null,i=u=>`${u}_${e()}_${xxe(3).toString("hex")}`,a=()=>{r&&(clearTimeout(r),r=null)},o=()=>{a(),r=setTimeout(()=>{c("idle_timeout")},t.idleMs)},s=async u=>{try{return Cxe(await t.capturePreview(u))}catch(d){return{snapshotId:null,error:d instanceof Error?d.message:String(d)}}},c=async u=>{if(!n)return;a();let d=n;n=null;let p={},f;for(let b of d.affectedPaths)if(d.afterSnapshotsPathPolicy[b]==="skip")p[b]=null;else{let x=await s(b);p[b]=x.snapshotId,x.snapshotId===null&&d.unavailableEvidence.push({phase:"after",targetPath:b,reason:x.error??"preview unavailable"}),f=YV(f,JV("after_snapshot",x.designCheckSummary,b,x.snapshotId,x.capturedAt))}let m=d.latestVisualReview&&d.latestDesignCheckSummary?d.latestDesignCheckSummary:f??d.latestDesignCheckSummary??kxe(),g={...m,responsive_requirement:d.designContractSummary?.responsive_requirement??m.responsive_requirement},y={...g,...rc(g)},v={requestId:d.requestId,...d.contextId!==void 0&&{contextId:d.contextId},...d.label!==void 0&&{label:d.label},startedAt:d.startedAtIso,closedAt:new Date(e()).toISOString(),closeReason:u,ok:d.ok,affectedPaths:Array.from(d.affectedPaths).sort(),mutationCount:d.mutationCount,beforeSnapshots:d.beforeSnapshots,afterSnapshots:p,childMutationIds:d.childMutationIds,...d.qualityPlanSummary!==void 0&&{qualityPlanSummary:d.qualityPlanSummary},...d.designContractSummary!==void 0&&{designContractSummary:d.designContractSummary},postChangeDesignCheckSummary:y,...d.latestVisualReview!==void 0&&{latestVisualReview:d.latestVisualReview},coverageDimensions:y.coverage_dimensions,viewportProfilesTested:y.viewport_profiles_tested,readiness:y.readiness,...d.unavailableEvidence.length>0&&{unavailableEvidence:d.unavailableEvidence}};await LV(t.placeDir,v)},l=u=>({requestId:i("req"),contextId:u.contextId,label:Pxe(u.contextSummary),startedAtIso:new Date(e()).toISOString(),startedAtMs:e(),affectedPaths:new Set,beforeSnapshots:{},afterSnapshotsPathPolicy:{},childMutationIds:[],mutationCount:0,ok:!0,qualityPlanSummary:DO(u),designContractSummary:GV(u.designContractSummary),latestDesignCheckSummary:void 0,latestVisualReview:void 0,unavailableEvidence:[],pendingMutation:void 0});return{async beforeMutation(u){if(ZV.includes(u.command)){if(n){let p=i("mut");n.qualityPlanSummary=KV(n.qualityPlanSummary,DO(u)),n.pendingMutation={mutationId:p,startedMs:e(),args:u}}return}if(!Sxe.includes(u.command))return;if(n&&n.contextId!==u.contextId?await c("context_change"):n&&a(),n||(n=l(u)),n.qualityPlanSummary=KV(n.qualityPlanSummary,DO(u)),n.designContractSummary={...n.designContractSummary??{},...GV(u.designContractSummary)??{}},u.targetPath&&!(u.targetPath in n.beforeSnapshots)){if(n.affectedPaths.add(u.targetPath),u.command==="manage_ui_create_tree")n.beforeSnapshots[u.targetPath]=null;else{let p=await s(u.targetPath);n.beforeSnapshots[u.targetPath]=p.snapshotId,p.snapshotId===null&&n.unavailableEvidence.push({phase:"before",targetPath:u.targetPath,reason:p.error??"preview unavailable"})}u.command==="manage_ui_delete"?n.afterSnapshotsPathPolicy[u.targetPath]="skip":u.targetPath in n.afterSnapshotsPathPolicy||(n.afterSnapshotsPathPolicy[u.targetPath]="capture")}let d=i("mut");n.pendingMutation={mutationId:d,startedMs:e(),args:u}},async afterMutation(u){if(!n?.pendingMutation)return;let{mutationId:d,args:p}=n.pendingMutation,f={mutationId:d,requestId:n.requestId,ts:new Date(e()).toISOString(),command:p.command,origin:p.origin,...p.targetPath!==void 0&&{targetPath:p.targetPath},...p.briefId!==void 0&&{briefId:p.briefId},...u.diffSummary!==void 0&&{diffSummary:u.diffSummary},...u.changeDetails!==void 0&&{changeDetails:u.changeDetails},ok:u.ok,...u.error!==void 0&&{error:u.error},durationMs:u.durationMs};if(await zV(t.placeDir,f),n.pendingMutation=void 0,ZV.includes(p.command)){let m=JV("check_results",u.designCheckSummary,p.targetPath,u.snapshotId,u.capturedAt);n.latestDesignCheckSummary=YV(n.latestDesignCheckSummary,m),m?.snapshotId&&m.primary_visual_verdict&&m.critic_summary&&(n.latestVisualReview={snapshotId:m.snapshotId,verdict:m.primary_visual_verdict,summary:m.critic_summary});return}if(n.mutationCount++,n.childMutationIds.push(d),u.ok||(n.ok=!1),!n.contextId){await c("legacy_single");return}o()},async flushNow(){n&&await c("explicit")}}}var Rxe=new Set(["available","unavailable","unknown"]),Exe=Object.freeze({status:"recommended",blocking:!1,can_accept:!0,can_edit:!0,can_skip:!0,allows_custom_answer:!0});function Wn(t){if(!(typeof t!="object"||t===null||Array.isArray(t)))return t}function $O(t){return typeof t=="string"&&Rxe.has(t)?t:"unknown"}function Txe(t){let e=Wn(t);return{imageGeneration:$O(e?.image_generation),localImageOutput:$O(e?.local_image_output),imageReview:$O(e?.image_review)}}function Axe(t){let e=Wn(t.design_contract),n=Wn(e?.imagery_strategy);if(typeof n?.family=="string")return n.family;if(typeof e?.imagery_family=="string")return e.imagery_family;let r=Wn(t.quality_plan);if(typeof r?.imagery_family=="string")return r.imagery_family;if(Array.isArray(t.candidate_briefs)){let i=Wn(t.candidate_briefs[0]),a=Wn(i?.design_contract);if(typeof a?.imagery_family=="string")return a.imagery_family}return"pictogram_set"}function Oxe(t){let e=Wn(t.design_contract);if(Wn(e?.imagery_strategy)?.intent==="required")return!0;if(Array.isArray(t.candidate_briefs)){let r=Wn(t.candidate_briefs[0]),i=Wn(r?.design_contract);return Wn(i?.imagery_strategy)?.intent==="required"}return!1}function Dxe(t){return t==="item_thumbnail"?"item_thumbnail":t==="character_portrait"?"character_portrait":t==="decorative_illustration"?"decorative_illustration":t==="diegetic_surface"?"diegetic_surface":"pictogram"}function $xe(t){let e=Array.isArray(t.asset_recommendations)?t.asset_recommendations:[];for(let r of e){let i=Wn(r);if(!(!i||typeof i.source!="string")){if(i.source==="user_reference")return{mode:"user_reference",reason:"Use the user-provided image reference before generating another asset.",hasConcreteAsset:!0};if(i.source==="project_asset")return{mode:"project_asset",reason:"Use the reviewed project asset before generating another asset.",hasConcreteAsset:!0};if(i.source==="existing_ui")return{mode:"project_asset",reason:"The existing UI image remains a fallback until the user accepts it for this role.",hasConcreteAsset:!1};if(i.source==="creator_store_search")return{mode:"creator_store",reason:"The Creator Store candidate remains a fallback until the user accepts it.",hasConcreteAsset:!1}}}let n=Wn(t.brief);return Array.isArray(n?.reference_assets)&&n.reference_assets.length>0?{mode:"user_reference",reason:"Use the reference asset already accepted in the brief.",hasConcreteAsset:!0}:{mode:"assetless",reason:"Continue with a coherent primitive pictogram or intentional no-imagery treatment.",hasConcreteAsset:!1}}function Nxe(t,e){let n=Axe(t),r=Dxe(n),i=$xe(t),a=n==="no_imagery",o=Oxe(t)&&!a,s={need:a?"optional":o?"required":"helpful",intended_use:r,fallback_mode:i.mode,fallback_reason:i.reason,resolution_status:a||i.hasConcreteAsset?"resolved":o?"unresolved":"optional",primary_visual_approval_eligible:!o||i.hasConcreteAsset};return a?{...s,status:"not_needed",reason:"The recommended direction intentionally uses no imagery.",requires_generation_approval:!1,requires_upload_approval:!1}:i.hasConcreteAsset?{...s,status:"not_needed",reason:"A concrete asset candidate already exists for the recommended direction.",requires_generation_approval:!1,requires_upload_approval:!1}:e.imageGeneration==="available"&&e.localImageOutput==="available"?{...s,status:"recommended",reason:"The calling agent can generate an image and materialize it as a local file.",question:`Generate a bounded local ${r} image set for this recommended UI direction?`,requires_generation_approval:!0,requires_upload_approval:!0}:e.imageGeneration==="unavailable"||e.localImageOutput==="unavailable"?{...s,status:"unavailable",reason:"This agent environment cannot complete the local generated-image path.",requires_generation_approval:!1,requires_upload_approval:!1}:{...s,status:"unknown",reason:"The calling agent should inspect its callable image tools and local output channel once, then use the fallback if support remains unknown.",requires_generation_approval:!1,requires_upload_approval:!1}}function QV(t,e){let n=Wn(t)??{},r=Txe(e);return{...n,recommendation_policy:Exe,asset_generation_proposal:Nxe(n,r)}}var f3=100,tSe=12e4,nSe=15e3,m3=new Set(["manage_ui_create_tree","manage_ui_update","manage_ui_delete"]);function rSe(t,e){return`License required for internal command ${t}. ${e??"Activate Pro license to use this feature."}`}var iSe={Text:{category:"text",label:"\uD14D\uC2A4\uD2B8"},PlaceholderText:{category:"text",label:"\uD50C\uB808\uC774\uC2A4\uD640\uB354"},TextColor3:{category:"color",label:"\uAE00\uC790\uC0C9"},BackgroundColor3:{category:"color",label:"\uBC30\uACBD\uC0C9"},BorderColor3:{category:"color",label:"\uD14C\uB450\uB9AC\uC0C9"},ImageColor3:{category:"color",label:"\uC774\uBBF8\uC9C0\uC0C9"},Size:{category:"size",label:"\uC0AC\uC774\uC988"},TextSize:{category:"size",label:"\uAE00\uC790 \uD06C\uAE30"},Position:{category:"layout",label:"\uC704\uCE58"},AnchorPoint:{category:"layout",label:"\uC575\uCEE4"},Rotation:{category:"layout",label:"\uD68C\uC804"},LayoutOrder:{category:"layout",label:"\uB808\uC774\uC544\uC6C3 \uC21C\uC11C"},Visible:{category:"state",label:"\uD45C\uC2DC \uC0C1\uD0DC"},Active:{category:"state",label:"\uD65C\uC131 \uC0C1\uD0DC"},Interactable:{category:"state",label:"\uC0C1\uD638\uC791\uC6A9 \uC0C1\uD0DC"},Selectable:{category:"state",label:"\uC120\uD0DD \uAC00\uB2A5"},Enabled:{category:"state",label:"\uD65C\uC131\uD654"},Image:{category:"asset",label:"\uC774\uBBF8\uC9C0"},Texture:{category:"asset",label:"\uD14D\uC2A4\uCC98"},SoundId:{category:"asset",label:"\uC0AC\uC6B4\uB4DC"}},aSe={text:"\uD14D\uC2A4\uD2B8",color:"\uCEEC\uB7EC",size:"\uC0AC\uC774\uC988",layout:"\uB808\uC774\uC544\uC6C3",state:"\uC0C1\uD0DC",asset:"\uC5D0\uC14B",property:"\uC18D\uC131"},oSe=Object.entries(nc).reduce((t,[e,n])=>{for(let r of n.validActions)t[`${e}_${r}`]=e;return t},{});function s3(t){return{toolName:oSe[t]||t,commandName:t}}function c3(t,e){if(typeof t.contextId=="string"||!e||typeof e!="object")return t;let n=e.contextId;return typeof n=="string"?{...t,contextId:n}:t}function AS(t,e){if(t!=="manage_sync_status_current_place")return e;let{placeId:n,...r}=e;return r}function sSe(t,e){let n=e.routing;return{requestId:t,success:!1,error:e.message,errorCode:e.code,routing:n,data:{routing:n}}}async function g3(t,e){let n=t.syncController;if(!n)return null;try{let r=e.placeId,i=n.getDefaultRuntimePlaceId(),a=null;if(typeof r=="number"&&Number.isFinite(r))a=r;else if(typeof r=="string"&&r.trim().length>0){let s=Number.parseInt(r,10);Number.isFinite(s)&&(a=s)}if(a===null&&(a=i),a===null||!Number.isFinite(a))return null;let o=a===i?n.getDefaultRuntimePlaceName():null;return typeof o=="string"&&o.length>0?await n.config.resolvePlaceRoot(a,o):n.config.getPlaceRoot(a)}catch{return null}}function cSe(t){let e=t.tree;if(!e||typeof e!="object")return;let n=e,r=typeof n.name=="string"&&n.name.length>0?n.name:void 0;return r?`${typeof n.parent=="string"&&n.parent.length>0?n.parent:"StarterGui"}.${r}`:void 0}function lSe(t,e){let n=e.targetPath;if(typeof n=="string"&&n.length>0)return n;if(t==="manage_ui_create_tree")return cSe(e)}function uSe(t){let e=iSe[t];if(e)return e;let n=t.toLowerCase();return n.includes("color")?{category:"color",label:"\uC0C9\uC0C1"}:t==="Size"||n.endsWith("size")||n.includes("scale")?{category:"size",label:"\uC0AC\uC774\uC988"}:n.includes("position")||n.includes("anchor")||n.includes("rotation")||n.includes("layout")?{category:"layout",label:"\uB808\uC774\uC544\uC6C3"}:n.includes("visible")||n.includes("active")||n.includes("enabled")||n.includes("selectable")||n.includes("interactable")?{category:"state",label:"\uC0C1\uD0DC"}:n.includes("image")||n.includes("texture")||n.includes("sound")||n.includes("asset")?{category:"asset",label:"\uC5D0\uC14B"}:n.includes("text")||n.includes("placeholder")?{category:"text",label:"\uD14D\uC2A4\uD2B8"}:{category:"property",label:t}}function l3(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function dSe(t){if(!t||typeof t!="object")return new Map;let e=t,n=e.changed_properties??e.changedProperties;if(!Array.isArray(n))return new Map;let r=new Map;for(let i of n){if(!i||typeof i!="object")continue;let a=i,o=a.property;if(typeof o!="string"||o.length===0)continue;let s=l3(a,"before"),c=l3(a,"after");r.set(o,{...s&&{before:a.before},...c&&{after:a.after},hasBefore:s,hasAfter:c})}return r}function h3(t,e){let r=t.changes?.properties;if(!r||typeof r!="object")return;let i=dSe(e),a=Object.entries(r).map(([o,s])=>{let c=uSe(o),l=i.get(o),u={property:o,category:c.category,label:c.label,after:l?.hasAfter?l.after:s};return l?.hasBefore&&(u.before=l.before),u});return a.length>0?a:void 0}function y3(t){if(!t||t.length===0)return;let e=new Map;for(let i of t)e.set(i.category,(e.get(i.category)??0)+1);let r=["text","color","size","layout","state","asset","property"].map(i=>{let a=e.get(i)??0;return a>0?`${aSe[i]} ${a}\uAC1C`:null}).filter(i=>i!==null);return r.length>0?`${r.join(", ")} \uBCC0\uACBD`:void 0}function u3(t,e){if(t==="manage_ui_update"){let n=e.changes,r=y3(h3(e));if(r)return r;let i=n?.properties?Object.keys(n.properties).length:0,a=Array.isArray(n?.addChildren)?n.addChildren.length:0,o=Array.isArray(n?.removeChildren)?n.removeChildren.length:0;return`${i} props, +${a}, -${o}`}if(t==="manage_ui_create_tree")return"tree \uC0DD\uC131";if(t==="manage_ui_delete")return"\uC81C\uAC70\uB428"}function Hm(t){return t&&typeof t=="object"?t:void 0}function OS(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function v3(t){let e=Hm(t),n=Hm(e?.design_check_summary);if(n)return{priority_high:OS(n,"priority_high"),priority_medium:OS(n,"priority_medium"),priority_low:OS(n,"priority_low"),total:OS(n,"total"),...typeof n.scope=="string"&&{scope:n.scope},...typeof n.target=="string"&&{target:n.target},...n.deterministic_status==="completed"||n.deterministic_status==="failed"?{deterministic_status:n.deterministic_status}:{},...n.visual_status==="not_requested"||n.visual_status==="completed"||n.visual_status==="skipped"||n.visual_status==="failed"?{visual_status:n.visual_status}:{},...n.coverage==="structural_only"||n.coverage==="structural_and_visual"?{coverage:n.coverage}:{},...Array.isArray(n.skipped_reasons)?{skipped_reasons:n.skipped_reasons.filter(r=>typeof r=="string")}:{}}}function b3(t){let n=Hm(t)?.snapshot_id;return typeof n=="string"?n:null}function d3(t){if(typeof t=="string"&&t.trim().length>0)return t;if(typeof t=="number"&&Number.isFinite(t)){let e=t<1e10?t*1e3:t;return new Date(e).toISOString()}}function _3(t){let e=Hm(t),n=Hm(e?.meta);return d3(n?.captured_at)??d3(n?.evaluated_at)}function pSe(t,e){let n=t.uiStudioRecorders.get(e);if(n)return n;let r=XV({placeDir:e,idleMs:nSe,capturePreview:async i=>{try{let a=await Rr(t,"manage_ui_preview",{targetPath:i},$S());if(!a.success||!a.data||typeof a.data!="object")return null;let o=v3(a.data),s=_3(a.data);return{snapshotId:b3(a.data),...o!==void 0&&{designCheckSummary:o},...s!==void 0&&{capturedAt:s}}}catch{return null}}});return t.uiStudioRecorders.set(e,r),r}async function fSe(t,e,n){if(!m3.has(e))return null;let r=await g3(t,n);if(!r)return null;let i=pSe(t,r),a=e,o=typeof n.contextId=="string"?n.contextId:void 0,s=n.contextSummary,c=s!==void 0&&typeof s=="object"?s:void 0,l=lSe(a,n),u=typeof n.briefId=="string"?n.briefId:void 0,d=u!==void 0?t.uiStudioDesignContracts.get(r,u):void 0,p={command:a,...o!==void 0&&{contextId:o},...c!==void 0&&{contextSummary:c},...l!==void 0&&{targetPath:l},...u!==void 0&&{briefId:u},...d!==void 0&&{designContractSummary:d},origin:n.__origin==="dashboard"?"dashboard":"ai"};try{return await i.beforeMutation(p),{recorder:i,command:a,params:n,startedAt:Date.now()}}catch(f){return h.debug("UI Studio recorder beforeMutation \uC2E4\uD328 (\uBB34\uC2DC)",{error:f}),null}}async function p3(t,e){if(t)try{let n=t.command==="manage_ui_update"?h3(t.params,e.data):void 0,r=t.command==="manage_ui_update"?y3(n)??u3(t.command,t.params):u3(t.command,t.params),i=v3(e.data),a=b3(e.data),o=_3(e.data);await t.recorder.afterMutation({ok:e.success,durationMs:Date.now()-t.startedAt,...r!==void 0&&{diffSummary:r},...n!==void 0&&{changeDetails:n},...e.error!==void 0&&{error:e.error},...i!==void 0&&{designCheckSummary:i},...a!==null&&{snapshotId:a},...o!==void 0&&{capturedAt:o}})}catch(n){h.debug("UI Studio recorder afterMutation \uC2E4\uD328 (\uBB34\uC2DC)",{error:n})}}async function DS(t,e,n,r,i,a){if(!t.historyManager)return;let o=!i.success&&i.error?zu(n,i.error):void 0,s=Lu({resultSuccess:i.success,resultData:i.data,resultError:i.error,tier:ar(n),...o?{failureClassification:o}:{}});if(i.success){let u=s.kind==="success_fallback"&&i.data&&typeof i.data=="object"?{...i.data,outcomeStatus:"fallback",requestedCommand:n,executedCommand:s.fallbackCommand,...s.alternatives?{alternatives:s.alternatives}:{}}:i.data,d=AS(n,r);i.routing?await t.historyManager.recordSuccess(e,d,u,a,n,void 0,i.routing):await t.historyManager.recordSuccess(e,d,u,a,n);return}if(s.kind==="blocked_unsupported"){await t.historyManager.recordBlockedOutcome(e,AS(n,r),i.error||"Pro action blocked in Basic mode","blocked_unsupported",{executionTimeMs:a,command:n,...i.routing?{routing:i.routing}:{}});return}if(s.kind==="blocked_fallback_failed"){await t.historyManager.recordBlockedOutcome(e,AS(n,r),i.error||"Pro action blocked in Basic mode","blocked_fallback_failed",{executionTimeMs:a,command:n,...s.fallbackCommand?{fallbackCommand:s.fallbackCommand}:{},...s.blockedDetail?{blockedDetail:s.blockedDetail}:{},...i.routing?{routing:i.routing}:{}});return}let c=s.kind==="warning"?t.historyManager.recordWarning.bind(t.historyManager):t.historyManager.recordFailure.bind(t.historyManager),l=AS(n,r);i.routing?await c(e,l,i.error||"Unknown error",a,i.errorCode??o?.errorType.toUpperCase(),n,void 0,i.routing):await c(e,l,i.error||"Unknown error",a,i.errorCode??o?.errorType.toUpperCase(),n)}function MO(t,e,n){let r=t.pendingCommands.get(e)||[];r.length>=f3&&r.shift(),r.push(n),t.pendingCommands.set(e,r)}function mSe(t,e){t.globalPendingCommands.length>=f3&&t.globalPendingCommands.shift(),t.globalPendingCommands.push(e)}function x3(t,e,n){let r=$S(),i={requestId:r,command:e.command,params:e.params,timestamp:Date.now(),queueTimeoutMs:e.queueTimeoutMs,ackedTimeoutMs:e.ackedTimeoutMs,state:$n.QUEUED,targetClientId:n,resolve:()=>{},reject:a=>{h.debug("Auxiliary playtest stop command ended without awaited response",{requestId:r,targetClientId:n,error:a.message})},timeoutId:null};return t.commandQueue.set(r,i),i.timeoutId=setTimeout(()=>{Sx(t,i,i.queueTimeoutMs)},i.queueTimeoutMs),{event:"command",id:r,data:{command:i.command,requestId:r,params:i.params}}}function gSe(t,e,n,r){if(!Rm(e.data.command))return;let i=t.commandQueue.get(e.data.requestId);if(!i)return;S3(t,i);let a=n.filter(o=>o.clientId!==r);for(let o of a){let s=x3(t,i,o.clientId);MO(t,o.clientId,s)}a.length>0&&h.info("Fan-out playtest stop command to active plugin clients",{requestId:e.data.requestId,primaryClientId:r,auxiliaryClientIds:a.map(o=>o.clientId)})}function S3(t,e,n){for(let r of G9)setTimeout(()=>{let a=n?[...new Set(n)]:[...new Set(Un(t).map(o=>o.clientId))];for(let o of a){if(!t.pluginClients.get(o))continue;let c=x3(t,e,o);MO(t,o,c)}h.info("Retry playtest stop command to active plugin clients",{sourceRequestId:e.requestId,delayMs:r,targetClientIds:a}),hu(t)},r).unref?.()}function w3(t){return t==="clientId"||t==="targetAlias"||t==="placeId"}function hSe(t,e,n){if(!n||!Rm(e.data.command))return!1;let r=t.commandQueue.get(e.data.requestId)?.routing?.selectionMode;return!w3(r)}function ySe(t,e,n){h.debug("Broadcasting command",{command:e.data.command,requestId:e.data.requestId,targetClientId:n||"all",activeWebsocketClients:Un(t).length});let r=n;if(n){MO(t,n,e);let i=t.commandQueue.get(e.data.requestId),a=i?.routing?.selectionMode;if(i&&Rm(e.data.command)&&w3(a))S3(t,i,[n]);else if(hSe(t,e,n)){let o=Un(t).sort((s,c)=>c.lastSeen-s.lastSeen);gSe(t,e,o,n),r=void 0}}else mSe(t,e);hu(t,r)}async function I3(t,e,n){let r=Date.now(),i="",a={};try{let o=e.body;i=o.command??"",a=o.params||{};let s=o.requestId;if(o.instanceId||(t.serverLastCommandAt=Date.now()),o.instanceId){let m=t.mcpInstances.get(o.instanceId);m&&(m.lastCommandAt=Date.now(),m.lastSeen=m.lastCommandAt)}let c=s3(i),l=typeof o.timeout=="number"&&Number.isFinite(o.timeout)&&o.timeout>0?{timeout:o.timeout}:void 0,u=o.instanceId?t.mcpInstances.get(o.instanceId)?.sessionId??t.sessionId:t.sessionId;if(!i){n.status(400).json({error:"Missing command"});return}if(h.debug("Received execute request",{command:i,requestId:s}),i==="manage_camera_play_screenshot"){let m="manage_camera.play_screenshot is not supported. Screenshot capture is available only in Edit mode via manage_camera.screenshot.",g=Date.now()-r;t.historyManager&&await t.historyManager.recordFailure("manage_camera",a,m,g,"UNSUPPORTED_COMMAND",i),n.json({requestId:s,success:!1,error:m});return}if(i==="get_cached_selection"){let m=a.maxAge,g=km(t,m!==void 0?m:3e4),y=Date.now()-r;if(!g){let x={requestId:s,success:!0,data:{cached:!1,message:"No cached selection data available. The plugin may not be connected or no selection changes have occurred yet."}};t.historyManager&&await t.historyManager.recordSuccess(c.toolName,a,x.data,y,c.commandName),n.json(x);return}let v=Date.now()-g.timestamp,b={cached:!0,selection:g.selection,count:g.count,timestamp:g.timestamp,age:v};t.historyManager&&await t.historyManager.recordSuccess(c.toolName,a,b,y,c.commandName),n.json({requestId:s,success:!0,data:b});return}if(i==="get_connection_info"){let m=await dS(t),g=Date.now()-r;t.historyManager&&await t.historyManager.recordSuccess(c.toolName,a,m,g,c.commandName),n.json({requestId:s,success:!0,data:m});return}if(fS(i)==="internal"){if(!t.internalCommandExecutor){n.status(503).json({requestId:s,success:!1,error:`Internal command executor is not initialized for command: ${i}`});return}if(ar(i)==="pro"){if(!t.licenseState){n.status(503).json({requestId:s,success:!1,error:`License state manager is not initialized for internal command: ${i}`});return}let b=await t.licenseState.evaluateProAccess();if(!b.allowed){let x=rSe(i,b.reason),I=Date.now()-r;t.historyManager&&await DS(t,c.toolName,c.commandName,a,{success:!1,error:x},I),n.json({requestId:s,success:!1,error:x});return}}let m={...a,__sessionId:u},g=await t.internalCommandExecutor(i,m),y=Date.now()-r,v=c3(m,g.data);t.historyManager&&await DS(t,c.toolName,c.commandName,v,{success:g.success,data:g.data,error:g.error||"Internal command failed",...g.errorCode?{errorCode:g.errorCode}:{},...g.routing?{routing:g.routing}:{}},y),n.json({requestId:s,...g});return}let d=await Rr(t,i,a,s,l),p=Date.now()-r,f={...c3(a,d.data),__sessionId:u};t.historyManager&&await DS(t,c.toolName,c.commandName,f,d,p),n.json(d)}catch(o){let s=Date.now()-r,c=ir(o);if(t.historyManager&&i){let l=s3(i);await t.historyManager.recordFailure(l.toolName,a,c,s,"EXCEPTION",l.commandName)}h.error("Execute request failed",o),n.status(500).json({success:!1,error:c})}}async function C3(t,e,n){let r=Date.now(),i=e.body,a=i.action;if(!a||typeof a!="string"){n.status(400).json({success:!1,error:"Missing required field: action"});return}if(!new Set(["get","set","get_all","set_multiple","get_attr","set_attr","get_all_attrs","delete_attr","add_tag","remove_tag","check_tag","get_tags","get_tagged"]).has(a)){n.status(400).json({success:!1,error:`Unsupported action: ${a}`});return}let s=`manage_properties_${a}`,c=$S(),{action:l,...u}=i;try{t.serverLastCommandAt=Date.now();let d=await Rr(t,s,u,c),p=Date.now()-r;t.historyManager&&await DS(t,"manage_properties",s,u,d,p),n.json(d)}catch(d){let p=Date.now()-r,f=ir(d);t.historyManager&&await t.historyManager.recordFailure("manage_properties",u,f,p,"EXCEPTION",s),h.error("/api/properties \uC694\uCCAD \uCC98\uB9AC \uC2E4\uD328",d),n.status(500).json({success:!1,error:f})}}async function Rr(t,e,n,r,i){if(h.debug("Executing command locally",{command:e,requestId:r}),s5(t,r)){let d=`Duplicate requestId '${r}' for command '${e}'. Generate a unique requestId for each command.`;return h.warn("Duplicate execute request rejected",{command:e,requestId:r}),{requestId:r,success:!1,error:d}}let a;try{a=pS(t,Un(t),n,e)}catch(d){if(d instanceof _n)return h.warn("Command target selection failed",{command:e,requestId:r,errorCode:d.code,routing:d.routing}),sSe(r,d);throw d}let o=m3.has(e)?await fSe(t,e,n):null,s=t.config.requestTimeout,c=i?.timeout??Math.max(t.config.requestTimeout,tSe),l=bO.has(e)?await TV({ctx:t,command:e,params:n}):n,u=new Promise((d,p)=>{let f=Date.now(),m={requestId:r,command:e,params:l,timestamp:f,queueTimeoutMs:s,ackedTimeoutMs:c,state:$n.QUEUED,...a.targetClientId?{targetClientId:a.targetClientId}:{},routing:a.routing,resolve:d,reject:p,timeoutId:null};t.commandQueue.set(r,m),vx(t,a.targetClientId,f),m.timeoutId=setTimeout(()=>{Sx(t,m,s)},s)});return ySe(t,{event:"command",id:$S(),data:{command:e,requestId:r,params:l}},a.targetClientId),u.then(async d=>{let p=d;if(e==="manage_ui_design_brief"&&d.success&&d.data){let f=QV(d.data,n.agentCapabilities);p={...d,data:f};try{let m=await g3(t,n);m&&t.uiStudioDesignContracts.remember(m,f)}catch(m){h.debug("UI Studio Design Contract cache failed",{error:m instanceof Error?m.message:String(m)})}}if(e==="manage_ui_preview"&&d.success&&d.data)try{let{processPreviewResult:f,resolvePreviewPlaceDirFromCtx:m}=await Promise.resolve().then(()=>(jO(),NO)),g=await m(t,n),y=await f("manage_ui_preview",d.data,g);p={...d,data:y.data,...y.mcpContent?{mcpContent:y.mcpContent}:{}}}catch(f){h.warn("preview post-processing failed",{error:f instanceof Error?f.message:String(f)})}if(e==="manage_ui_check"&&d.success&&d.data&&n.visualReview!==void 0)try{let{resolvePreviewPlaceDirFromCtx:f}=await Promise.resolve().then(()=>(jO(),NO)),{processCheckResult:m}=await Promise.resolve().then(()=>(o3(),a3)),g=await f(t,n),y=await m("manage_ui_check",d.data,g,n);p={...p,data:y.data}}catch(f){h.warn("check visual post-processing failed",{error:f instanceof Error?f.message:String(f)})}return _O.has(e)?p=await AV({ctx:t,command:e,params:n,result:p}):e===vO&&(p=await OV({ctx:t,params:n,result:p})),p}).then(async d=>(await p3(o,{success:d.success,...d.data!==void 0&&{data:d.data},...d.error!==void 0&&{error:d.error}}),d),async d=>{throw await p3(o,{success:!1,error:ir(d)}),d})}le();ca();function NS(t,e){let n={};e.provider!==void 0&&(n.provider=e.provider),e.tier!==void 0&&(n.tier=e.tier),e.status!==void 0&&(n.status=e.status),e.canUsePro!==void 0&&(n.canUsePro=e.canUsePro),e.cleared===!0&&(n.cleared=!0),pt(t,"license",n)}function Mi(t,e,n,r){t.status(e).json({success:!1,error:{code:n,message:r}})}function vSe(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e.length>0?e:void 0}function jS(t,e){if(e==="plugin")return t;let n={...t};return delete n.sessionToken,n}function Zm(t,e,n,r){let i=vSe(r??e.query.provider)??"auto";return t.licenseState?.supportsProvider(i)===!1?(Mi(n,400,"LICENSE_PROVIDER_UNSUPPORTED",`provider "${i}" is not supported`),null):i}function Gm(t,e){return t.licenseState?!0:(Mi(e,503,"LICENSE_NOT_INITIALIZED","License system is not initialized"),!1)}function bSe(t){if(!t||typeof t!="object")return!1;let e=t;return(e.canUsePro===!0||e.canUsePro===!1)&&typeof e.status=="string"&&typeof e.checkedAt=="number"}function Km(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=e.body,a=typeof i?.licenseKey=="string"?i.licenseKey:"";if(!a.trim()){Mi(n,400,"LICENSE_KEY_REQUIRED","licenseKey is required");return}let o=Zm(t,e,n,i?.provider);if(!o)return;let s=typeof i?.pluginClientId=="string"?i.pluginClientId:typeof e.query.clientId=="string"?e.query.clientId:void 0,c=typeof i?.deviceId=="string"?i.deviceId:void 0,l={licenseKey:a,provider:o,clientType:r};s&&(l.pluginClientId=s),c&&(l.deviceId=c),t.licenseState.activateGateway(l).then(u=>{t.analyticsManager?.setTier(u.canUsePro?"pro":"basic"),NS(t,{provider:u.provider,tier:u.canUsePro?"pro":"basic",status:u.status,canUsePro:u.canUsePro}),n.json(jS(u,r))}).catch(u=>{h.warn("License activate failed",{error:u instanceof Error?u.message:"unknown_error"}),Mi(n,502,"LICENSE_ACTIVATE_FAILED",u instanceof Error?u.message:"License activation failed")})}function Jm(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=Zm(t,e,n);if(i)try{let a=t.licenseState.getStatus(i);t.analyticsManager?.setTier(a.canUsePro?"pro":"basic"),n.json(jS(a,r))}catch(a){h.warn("License status check failed",{error:a instanceof Error?a.message:"unknown_error"}),Mi(n,502,"LICENSE_STATUS_FAILED",a instanceof Error?a.message:"License status check failed")}}function Ym(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=e.body,a=Zm(t,e,n,i?.provider);if(!a)return;let o={provider:a,clientType:r};r==="plugin"&&typeof i?.sessionToken=="string"&&i.sessionToken.trim()&&(o.sessionToken=i.sessionToken.trim()),typeof i?.pluginClientId=="string"&&(o.pluginClientId=i.pluginClientId),typeof i?.deviceId=="string"&&(o.deviceId=i.deviceId),t.licenseState.refreshGateway(o).then(s=>{t.analyticsManager?.setTier(s.canUsePro?"pro":"basic"),NS(t,{provider:s.provider,tier:s.canUsePro?"pro":"basic",status:s.status,canUsePro:s.canUsePro}),n.json(jS(s,r))}).catch(s=>{h.warn("License refresh failed",{error:s instanceof Error?s.message:"unknown_error"}),Mi(n,502,"LICENSE_REFRESH_FAILED",s instanceof Error?s.message:"License refresh failed")})}function Xm(t,e,n,r="plugin"){if(!Gm(t,n))return;let i=e.body,a=Zm(t,e,n,i?.provider);a&&t.licenseState.resetGateway({provider:a,clientType:r}).then(o=>{t.analyticsManager?.setTier("basic"),NS(t,{provider:o.provider,tier:"basic",status:o.status,canUsePro:o.canUsePro,cleared:!0}),n.json(jS(o,r))}).catch(o=>{h.warn("License reset failed",{error:o instanceof Error?o.message:"unknown_error"}),Mi(n,502,"LICENSE_RESET_FAILED",o instanceof Error?o.message:"License reset failed")})}function LO(t,e,n){if(!Gm(t,n))return;let r=e.body,i=Zm(t,e,n,r?.provider);if(!i)return;if(r?.clientType!=="plugin"){Mi(n,400,"LICENSE_CLIENT_TYPE_INVALID","clientType must be plugin");return}let a=typeof r?.sessionToken=="string"&&r.sessionToken.trim()?r.sessionToken.trim():void 0,o=bSe(r?.snapshot)?r.snapshot:void 0;if(!o&&!a){Mi(n,400,"LICENSE_BOOTSTRAP_REQUIRED","snapshot or sessionToken is required");return}let s={provider:i,clientType:"plugin"};o&&(s.snapshot=o),a&&(s.sessionToken=a),t.licenseState.bootstrap(s).then(c=>{t.analyticsManager?.setTier(c.canUsePro?"pro":"basic"),NS(t,{provider:c.provider,tier:c.canUsePro?"pro":"basic",status:c.status,canUsePro:c.canUsePro}),n.json({ok:!0})}).catch(c=>{h.warn("License bootstrap failed",{error:c instanceof Error?c.message:"unknown_error"}),Mi(n,502,"LICENSE_BOOTSTRAP_FAILED",c instanceof Error?c.message:"License bootstrap failed")})}function P3(t){t.app.post("/license/bootstrap",(e,n)=>LO(t,e,n)),t.app.post("/license/activate",(e,n)=>Km(t,e,n,"plugin")),t.app.post("/license/refresh",(e,n)=>Ym(t,e,n,"plugin")),t.app.post("/license/reset",(e,n)=>Xm(t,e,n,"plugin")),t.app.get("/license/status",(e,n)=>Jm(t,e,n,"plugin"))}vt();le();import{promises as MS}from"fs";import zO from"path";function _Se(t){let e=t.config.appDataDir??Ke();return zO.join(e,"observability","logs")}async function Vu(t,e,n){let r=e.query.clientId;if(r&&t.pluginClients.has(r)){let i=t.pluginClients.get(r);i.lastSeen=Date.now()}try{let i=e.body;if(!i||!Array.isArray(i.logs)){h.warn("Invalid logs request",{body:i}),n.status(400).json({error:"Invalid request body"});return}let a=_Se(t);await MS.mkdir(a,{recursive:!0});let c=`plugin-${new Date().toISOString().split("T")[0]}.log`,l=zO.join(a,c),u=zO.join(a,"current.log"),d=i.logs.map(p=>`[${new Date(p.timestamp*1e3).toISOString().replace("T"," ").substring(0,19)}] [${p.level}] ${p.message}`).join(`
|
|
923
940
|
`)+`
|
|
924
941
|
`;await MS.appendFile(l,d,"utf-8");try{let p="";try{p=await MS.readFile(u,"utf-8")}catch{}let m=(p+d).split(`
|
|
925
942
|
`).slice(-500).join(`
|