@weppy/roblox-mcp 1.2.1 → 1.2.2
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/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +15 -0
- package/docs/en/tools/overview.md +0 -1
- package/docs/es/tools/overview.md +0 -1
- package/docs/id/tools/overview.md +0 -1
- package/docs/ja/tools/overview.md +0 -1
- package/docs/ko/tools/overview.md +0 -1
- package/docs/pt-br/tools/overview.md +0 -1
- package/package.json +1 -1
- package/plugins/weppy-roblox-mcp/.claude-plugin/plugin.json +1 -1
- package/plugins/weppy-roblox-mcp/dist/index.js +3 -3
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
},
|
|
7
7
|
"metadata": {
|
|
8
8
|
"description": "Roblox MCP server and tools for AI-powered game development",
|
|
9
|
-
"version": "1.2.
|
|
9
|
+
"version": "1.2.2"
|
|
10
10
|
},
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "weppy-roblox-mcp",
|
|
14
14
|
"source": "./plugins/weppy-roblox-mcp",
|
|
15
15
|
"description": "MCP server for Roblox Studio integration - AI-powered game development with specialized agents and skills",
|
|
16
|
-
"version": "1.2.
|
|
16
|
+
"version": "1.2.2",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "hope1026"
|
|
19
19
|
},
|
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,21 @@ All notable changes to this project will be documented in this file.
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
|
|
14
|
+
## [1.2.2] - 2026-03-01
|
|
15
|
+
|
|
16
|
+
### Features
|
|
17
|
+
|
|
18
|
+
- improve sync conflict UI and tier defaults
|
|
19
|
+
- update icon paths to use PNG format and enhance file visibility handling
|
|
20
|
+
- add IconResolver for managing icons based on Roblox class names
|
|
21
|
+
- Add ManualChangesDialog and ManualSyncPopup for handling manual sync changes
|
|
22
|
+
|
|
23
|
+
### Bug Fixes
|
|
24
|
+
|
|
25
|
+
- remove dead run_command action from system_info tool
|
|
26
|
+
|
|
27
|
+
|
|
13
28
|
## [1.2.1] - 2026-02-28
|
|
14
29
|
|
|
15
30
|
### Other Changes
|
|
@@ -248,7 +248,6 @@ Sync policy:
|
|
|
248
248
|
| `place_info` | Get place ID, name, creator | Pro |
|
|
249
249
|
| `services` | List all Roblox services | Pro |
|
|
250
250
|
| `studio_settings` | Get Studio preferences | Pro |
|
|
251
|
-
| `run_command` | Execute Studio command | Pro |
|
|
252
251
|
|
|
253
252
|
## Batch Execute (Pro)
|
|
254
253
|
|
|
@@ -248,7 +248,6 @@ Politica de Sync:
|
|
|
248
248
|
| `place_info` | Obtener Place ID, nombre, creador | Pro |
|
|
249
249
|
| `services` | Listar todos los servicios de Roblox | Pro |
|
|
250
250
|
| `studio_settings` | Obtener preferencias de Studio | Pro |
|
|
251
|
-
| `run_command` | Ejecutar comando de Studio | Pro |
|
|
252
251
|
|
|
253
252
|
## Batch Execute (Pro)
|
|
254
253
|
|
|
@@ -248,7 +248,6 @@ Kebijakan Sync:
|
|
|
248
248
|
| `place_info` | Mendapatkan Place ID, nama, kreator | Pro |
|
|
249
249
|
| `services` | Mendaftar semua layanan Roblox | Pro |
|
|
250
250
|
| `studio_settings` | Mendapatkan preferensi Studio | Pro |
|
|
251
|
-
| `run_command` | Menjalankan perintah Studio | Pro |
|
|
252
251
|
|
|
253
252
|
## Batch Execute (Pro)
|
|
254
253
|
|
|
@@ -248,7 +248,6 @@ Politica de Sync:
|
|
|
248
248
|
| `place_info` | Obter Place ID, nome, criador | Pro |
|
|
249
249
|
| `services` | Listar todos os servicos Roblox | Pro |
|
|
250
250
|
| `studio_settings` | Obter preferencias do Studio | Pro |
|
|
251
|
-
| `run_command` | Executar comando do Studio | Pro |
|
|
252
251
|
|
|
253
252
|
## Batch Execute (Pro)
|
|
254
253
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weppy/roblox-mcp",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"description": "MCP (Model Context Protocol) server for Roblox Studio integration - enables AI coding agents to interact with Roblox Studio in real-time",
|
|
5
5
|
"main": "plugins/weppy-roblox-mcp/dist/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -97,7 +97,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
|
|
|
97
97
|
|
|
98
98
|
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 rl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=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){n(u);let d=t.seen.get(u),f=d.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 h in c)h==="$ref"||h==="allOf"||h in l||delete c[h];if(f.$ref&&d.def)for(let h in c)h==="$ref"||h==="allOf"||h in d.def&&JSON.stringify(c[h])===JSON.stringify(d.def[h])&&delete c[h]}let p=o._zod.parent;if(p&&p!==u){n(p);let d=t.seen.get(p);if(d?.schema.$ref&&(c.$ref=d.schema.$ref,d.def))for(let f in c)f==="$ref"||f==="allOf"||f in d.def&&JSON.stringify(c[f])===JSON.stringify(d.def[f])&&delete c[f]}t.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(let o of[...t.seen.entries()].reverse())n(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,r.def??r.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:zo(e,"input",t.processors),output:zo(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ft(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ft(n.element,r);if(n.type==="set")return ft(n.valueType,r);if(n.type==="lazy")return ft(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ft(n.innerType,r);if(n.type==="intersection")return ft(n.left,r)||ft(n.right,r);if(n.type==="record"||n.type==="map")return ft(n.keyType,r)||ft(n.valueType,r);if(n.type==="pipe")return ft(n.in,r)||ft(n.out,r);if(n.type==="object"){for(let i in n.shape)if(ft(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(ft(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(ft(i,r))return!0;return!!(n.rest&&ft(n.rest,r))}return!1}var o0=(t,e={})=>r=>{let n=el({...r,processors:e});return Ie(t,n),tl(n,t),rl(n,t)},zo=(t,e,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=el({...i??{},target:a,io:e,processors:r});return Ie(t,o),tl(o,t),rl(o,t)};var AR={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s0=(t,e,r,n)=>{let i=r;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=AR[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(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},c0=(t,e,r,n)=>{let i=r,{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)},l0=(t,e,r,n)=>{r.type="boolean"},u0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},p0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},d0=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},f0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},m0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},h0=(t,e,r,n)=>{r.not={}},g0=(t,e,r,n)=>{},v0=(t,e,r,n)=>{},y0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},x0=(t,e,r,n)=>{let i=t._zod.def,a=Xa(i.entries);a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),r.enum=a},b0=(t,e,r,n)=>{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];r.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[o]:r.const=o}else a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),a.every(o=>typeof o=="boolean")&&(r.type="boolean"),a.every(o=>o===null)&&(r.type="null"),r.enum=a},_0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},w0=(t,e,r,n)=>{let i=r,a=t._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},S0=(t,e,r,n)=>{let i=r,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)},k0=(t,e,r,n)=>{r.type="boolean"},$0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},I0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},P0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},E0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},T0=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},z0=(t,e,r,n)=>{let i=r,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=Ie(a.element,e,{...n,path:[...n.path,"items"]})},C0=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object",i.properties={};let o=a.shape;for(let l in o)i.properties[l]=Ie(o[l],e,{...n,path:[...n.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=Ie(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},yh=(t,e,r,n)=>{let i=t._zod.def,a=i.inclusive===!1,o=i.options.map((s,c)=>Ie(s,e,{...n,path:[...n.path,a?"oneOf":"anyOf",c]}));a?r.oneOf=o:r.anyOf=o},j0=(t,e,r,n)=>{let i=t._zod.def,a=Ie(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=Ie(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];r.allOf=c},R0=(t,e,r,n)=>{let i=r,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((d,f)=>Ie(d,e,{...n,path:[...n.path,o,f]})),l=a.rest?Ie(a.rest,e,{...n,path:[...n.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:p}=t._zod.bag;typeof u=="number"&&(i.minItems=u),typeof p=="number"&&(i.maxItems=p)},O0=(t,e,r,n)=>{let i=r,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=Ie(a.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let p of c)i.patternProperties[p.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Ie(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Ie(a.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let l=o._zod.values;if(l){let u=[...l].filter(p=>typeof p=="string"||typeof p=="number");u.length>0&&(i.required=u)}},D0=(t,e,r,n)=>{let i=t._zod.def,a=Ie(i.innerType,e,n),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},A0=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},N0=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},M0=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},U0=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);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")}r.default=o},q0=(t,e,r,n)=>{let i=t._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Ie(a,e,n);let o=e.seen.get(t);o.ref=a},F0=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.readOnly=!0},L0=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},xh=(t,e,r,n)=>{let i=t._zod.def;Ie(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},Z0=(t,e,r,n)=>{let i=t._zod.innerType;Ie(i,e,n);let a=e.seen.get(t);a.ref=i};function Oi(t){return!!t._zod}function sn(t,e){return Oi(t)?Ti(t,e):t.safeParse(e)}function nl(t){if(!t)return;let e;if(Oi(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function B0(t){if(Oi(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 r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Co={};Na(Co,{ZodAny:()=>uw,ZodArray:()=>mw,ZodBase64:()=>Zh,ZodBase64URL:()=>Hh,ZodBigInt:()=>dl,ZodBigIntFormat:()=>Wh,ZodBoolean:()=>pl,ZodCIDRv4:()=>Fh,ZodCIDRv6:()=>Lh,ZodCUID:()=>Oh,ZodCUID2:()=>Dh,ZodCatch:()=>Ow,ZodCodec:()=>eg,ZodCustom:()=>vl,ZodCustomStringFormat:()=>Ro,ZodDate:()=>Gh,ZodDefault:()=>Ew,ZodDiscriminatedUnion:()=>gw,ZodE164:()=>Vh,ZodEmail:()=>Ch,ZodEmoji:()=>jh,ZodEnum:()=>jo,ZodExactOptional:()=>$w,ZodFile:()=>Sw,ZodFunction:()=>Zw,ZodGUID:()=>al,ZodIPv4:()=>Uh,ZodIPv6:()=>qh,ZodIntersection:()=>vw,ZodJWT:()=>Bh,ZodKSUID:()=>Mh,ZodLazy:()=>qw,ZodLiteral:()=>ww,ZodMAC:()=>ow,ZodMap:()=>bw,ZodNaN:()=>Aw,ZodNanoID:()=>Rh,ZodNever:()=>dw,ZodNonOptional:()=>Yh,ZodNull:()=>lw,ZodNullable:()=>Pw,ZodNumber:()=>ul,ZodNumberFormat:()=>Di,ZodObject:()=>fl,ZodOptional:()=>Xh,ZodPipe:()=>Qh,ZodPrefault:()=>zw,ZodPromise:()=>Lw,ZodReadonly:()=>Nw,ZodRecord:()=>gl,ZodSet:()=>_w,ZodString:()=>cl,ZodStringFormat:()=>we,ZodSuccess:()=>Rw,ZodSymbol:()=>sw,ZodTemplateLiteral:()=>Uw,ZodTransform:()=>kw,ZodTuple:()=>yw,ZodType:()=>W,ZodULID:()=>Ah,ZodURL:()=>ll,ZodUUID:()=>Fr,ZodUndefined:()=>cw,ZodUnion:()=>ml,ZodUnknown:()=>pw,ZodVoid:()=>fw,ZodXID:()=>Nh,ZodXor:()=>hw,_ZodString:()=>zh,_default:()=>Tw,_function:()=>YO,any:()=>OO,array:()=>ee,base64:()=>vO,base64url:()=>yO,bigint:()=>TO,boolean:()=>qe,catch:()=>Dw,check:()=>QO,cidrv4:()=>hO,cidrv6:()=>gO,codec:()=>GO,cuid:()=>sO,cuid2:()=>cO,custom:()=>tg,date:()=>AO,describe:()=>e6,discriminatedUnion:()=>hl,e164:()=>xO,email:()=>XR,emoji:()=>aO,enum:()=>it,exactOptional:()=>Iw,file:()=>VO,float32:()=>$O,float64:()=>IO,function:()=>YO,guid:()=>YR,hash:()=>kO,hex:()=>SO,hostname:()=>wO,httpUrl:()=>iO,instanceof:()=>r6,int:()=>Th,int32:()=>PO,int64:()=>zO,intersection:()=>Do,ipv4:()=>dO,ipv6:()=>mO,json:()=>i6,jwt:()=>bO,keyof:()=>NO,ksuid:()=>pO,lazy:()=>Fw,literal:()=>R,looseObject:()=>nt,looseRecord:()=>FO,mac:()=>fO,map:()=>LO,meta:()=>t6,nan:()=>JO,nanoid:()=>oO,nativeEnum:()=>HO,never:()=>Jh,nonoptional:()=>jw,null:()=>Oo,nullable:()=>ol,nullish:()=>BO,number:()=>de,object:()=>C,optional:()=>Te,partialRecord:()=>qO,pipe:()=>sl,prefault:()=>Cw,preprocess:()=>yl,promise:()=>XO,readonly:()=>Mw,record:()=>Pe,refine:()=>Hw,set:()=>ZO,strictObject:()=>MO,string:()=>w,stringFormat:()=>_O,stringbool:()=>n6,success:()=>WO,superRefine:()=>Vw,symbol:()=>jO,templateLiteral:()=>KO,transform:()=>Kh,tuple:()=>xw,uint32:()=>EO,uint64:()=>CO,ulid:()=>lO,undefined:()=>RO,union:()=>ye,unknown:()=>Se,url:()=>nO,uuid:()=>QR,uuidv4:()=>eO,uuidv6:()=>tO,uuidv7:()=>rO,void:()=>DO,xid:()=>uO,xor:()=>UO});var il={};Na(il,{endsWith:()=>ko,gt:()=>Ur,gte:()=>dt,includes:()=>wo,length:()=>ji,lowercase:()=>bo,lt:()=>Mr,lte:()=>jt,maxLength:()=>Ci,maxSize:()=>Nn,mime:()=>$o,minLength:()=>on,minSize:()=>qr,multipleOf:()=>An,negative:()=>sh,nonnegative:()=>lh,nonpositive:()=>ch,normalize:()=>Io,overwrite:()=>mr,positive:()=>oh,property:()=>uh,regex:()=>xo,size:()=>zi,slugify:()=>Qc,startsWith:()=>So,toLowerCase:()=>Eo,toUpperCase:()=>To,trim:()=>Po,uppercase:()=>_o});var Mn={};Na(Mn,{ZodISODate:()=>Sh,ZodISODateTime:()=>_h,ZodISODuration:()=>Ph,ZodISOTime:()=>$h,date:()=>kh,datetime:()=>wh,duration:()=>Eh,time:()=>Ih});var _h=b("ZodISODateTime",(t,e)=>{Df.init(t,e),we.init(t,e)});function wh(t){return Nm(_h,t)}var Sh=b("ZodISODate",(t,e)=>{Af.init(t,e),we.init(t,e)});function kh(t){return Mm(Sh,t)}var $h=b("ZodISOTime",(t,e)=>{Nf.init(t,e),we.init(t,e)});function Ih(t){return Um($h,t)}var Ph=b("ZodISODuration",(t,e)=>{Mf.init(t,e),we.init(t,e)});function Eh(t){return qm(Ph,t)}var W0=(t,e)=>{yc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bc(t,r)},flatten:{value:r=>xc(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Ii,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Ii,2)}},isEmpty:{get(){return t.issues.length===0}}})},IY=b("ZodError",W0),Rt=b("ZodError",W0,{Parent:Error});var J0=no(Rt),G0=ao(Rt),K0=so(Rt),X0=co(Rt),Y0=s_(Rt),Q0=c_(Rt),ew=l_(Rt),tw=u_(Rt),rw=p_(Rt),nw=d_(Rt),iw=f_(Rt),aw=m_(Rt);var W=b("ZodType",(t,e)=>(H.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:zo(t,"input"),output:zo(t,"output")}}),t.toJSONSchema=o0(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(P.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>ut(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>J0(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>K0(t,r,n),t.parseAsync=async(r,n)=>G0(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>X0(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>Y0(t,r,n),t.decode=(r,n)=>Q0(t,r,n),t.encodeAsync=async(r,n)=>ew(t,r,n),t.decodeAsync=async(r,n)=>tw(t,r,n),t.safeEncode=(r,n)=>rw(t,r,n),t.safeDecode=(r,n)=>nw(t,r,n),t.safeEncodeAsync=async(r,n)=>iw(t,r,n),t.safeDecodeAsync=async(r,n)=>aw(t,r,n),t.refine=(r,n)=>t.check(Hw(r,n)),t.superRefine=r=>t.check(Vw(r)),t.overwrite=r=>t.check(mr(r)),t.optional=()=>Te(t),t.exactOptional=()=>Iw(t),t.nullable=()=>ol(t),t.nullish=()=>Te(ol(t)),t.nonoptional=r=>jw(t,r),t.array=()=>ee(t),t.or=r=>ye([t,r]),t.and=r=>Do(t,r),t.transform=r=>sl(t,Kh(r)),t.default=r=>Tw(t,r),t.prefault=r=>Cw(t,r),t.catch=r=>Dw(t,r),t.pipe=r=>sl(t,r),t.readonly=()=>Mw(t),t.describe=r=>{let n=t.clone();return pt.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return pt.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return pt.get(t);let n=t.clone();return pt.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),zh=b("_ZodString",(t,e)=>{Dn.init(t,e),W.init(t,e),t._zod.processJSONSchema=(n,i,a)=>s0(t,n,i,a);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(xo(...n)),t.includes=(...n)=>t.check(wo(...n)),t.startsWith=(...n)=>t.check(So(...n)),t.endsWith=(...n)=>t.check(ko(...n)),t.min=(...n)=>t.check(on(...n)),t.max=(...n)=>t.check(Ci(...n)),t.length=(...n)=>t.check(ji(...n)),t.nonempty=(...n)=>t.check(on(1,...n)),t.lowercase=n=>t.check(bo(n)),t.uppercase=n=>t.check(_o(n)),t.trim=()=>t.check(Po()),t.normalize=(...n)=>t.check(Io(...n)),t.toLowerCase=()=>t.check(Eo()),t.toUpperCase=()=>t.check(To()),t.slugify=()=>t.check(Qc())}),cl=b("ZodString",(t,e)=>{Dn.init(t,e),zh.init(t,e),t.email=r=>t.check(Rc(Ch,r)),t.url=r=>t.check(yo(ll,r)),t.jwt=r=>t.check(Yc(Bh,r)),t.emoji=r=>t.check(Mc(jh,r)),t.guid=r=>t.check(vo(al,r)),t.uuid=r=>t.check(Oc(Fr,r)),t.uuidv4=r=>t.check(Dc(Fr,r)),t.uuidv6=r=>t.check(Ac(Fr,r)),t.uuidv7=r=>t.check(Nc(Fr,r)),t.nanoid=r=>t.check(Uc(Rh,r)),t.guid=r=>t.check(vo(al,r)),t.cuid=r=>t.check(qc(Oh,r)),t.cuid2=r=>t.check(Fc(Dh,r)),t.ulid=r=>t.check(Lc(Ah,r)),t.base64=r=>t.check(Gc(Zh,r)),t.base64url=r=>t.check(Kc(Hh,r)),t.xid=r=>t.check(Zc(Nh,r)),t.ksuid=r=>t.check(Hc(Mh,r)),t.ipv4=r=>t.check(Vc(Uh,r)),t.ipv6=r=>t.check(Bc(qh,r)),t.cidrv4=r=>t.check(Wc(Fh,r)),t.cidrv6=r=>t.check(Jc(Lh,r)),t.e164=r=>t.check(Xc(Vh,r)),t.datetime=r=>t.check(wh(r)),t.date=r=>t.check(kh(r)),t.time=r=>t.check(Ih(r)),t.duration=r=>t.check(Eh(r))});function w(t){return Dm(cl,t)}var we=b("ZodStringFormat",(t,e)=>{ve.init(t,e),zh.init(t,e)}),Ch=b("ZodEmail",(t,e)=>{If.init(t,e),we.init(t,e)});function XR(t){return Rc(Ch,t)}var al=b("ZodGUID",(t,e)=>{kf.init(t,e),we.init(t,e)});function YR(t){return vo(al,t)}var Fr=b("ZodUUID",(t,e)=>{$f.init(t,e),we.init(t,e)});function QR(t){return Oc(Fr,t)}function eO(t){return Dc(Fr,t)}function tO(t){return Ac(Fr,t)}function rO(t){return Nc(Fr,t)}var ll=b("ZodURL",(t,e)=>{Pf.init(t,e),we.init(t,e)});function nO(t){return yo(ll,t)}function iO(t){return yo(ll,{protocol:/^https?$/,hostname:Ut.domain,...P.normalizeParams(t)})}var jh=b("ZodEmoji",(t,e)=>{Ef.init(t,e),we.init(t,e)});function aO(t){return Mc(jh,t)}var Rh=b("ZodNanoID",(t,e)=>{Tf.init(t,e),we.init(t,e)});function oO(t){return Uc(Rh,t)}var Oh=b("ZodCUID",(t,e)=>{zf.init(t,e),we.init(t,e)});function sO(t){return qc(Oh,t)}var Dh=b("ZodCUID2",(t,e)=>{Cf.init(t,e),we.init(t,e)});function cO(t){return Fc(Dh,t)}var Ah=b("ZodULID",(t,e)=>{jf.init(t,e),we.init(t,e)});function lO(t){return Lc(Ah,t)}var Nh=b("ZodXID",(t,e)=>{Rf.init(t,e),we.init(t,e)});function uO(t){return Zc(Nh,t)}var Mh=b("ZodKSUID",(t,e)=>{Of.init(t,e),we.init(t,e)});function pO(t){return Hc(Mh,t)}var Uh=b("ZodIPv4",(t,e)=>{Uf.init(t,e),we.init(t,e)});function dO(t){return Vc(Uh,t)}var ow=b("ZodMAC",(t,e)=>{Ff.init(t,e),we.init(t,e)});function fO(t){return Am(ow,t)}var qh=b("ZodIPv6",(t,e)=>{qf.init(t,e),we.init(t,e)});function mO(t){return Bc(qh,t)}var Fh=b("ZodCIDRv4",(t,e)=>{Lf.init(t,e),we.init(t,e)});function hO(t){return Wc(Fh,t)}var Lh=b("ZodCIDRv6",(t,e)=>{Zf.init(t,e),we.init(t,e)});function gO(t){return Jc(Lh,t)}var Zh=b("ZodBase64",(t,e)=>{Hf.init(t,e),we.init(t,e)});function vO(t){return Gc(Zh,t)}var Hh=b("ZodBase64URL",(t,e)=>{Vf.init(t,e),we.init(t,e)});function yO(t){return Kc(Hh,t)}var Vh=b("ZodE164",(t,e)=>{Bf.init(t,e),we.init(t,e)});function xO(t){return Xc(Vh,t)}var Bh=b("ZodJWT",(t,e)=>{Wf.init(t,e),we.init(t,e)});function bO(t){return Yc(Bh,t)}var Ro=b("ZodCustomStringFormat",(t,e)=>{Jf.init(t,e),we.init(t,e)});function _O(t,e,r={}){return Ri(Ro,t,e,r)}function wO(t){return Ri(Ro,"hostname",Ut.hostname,t)}function SO(t){return Ri(Ro,"hex",Ut.hex,t)}function kO(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=Ut[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return Ri(Ro,n,i,e)}var ul=b("ZodNumber",(t,e)=>{Tc.init(t,e),W.init(t,e),t._zod.processJSONSchema=(n,i,a)=>c0(t,n,i,a),t.gt=(n,i)=>t.check(Ur(n,i)),t.gte=(n,i)=>t.check(dt(n,i)),t.min=(n,i)=>t.check(dt(n,i)),t.lt=(n,i)=>t.check(Mr(n,i)),t.lte=(n,i)=>t.check(jt(n,i)),t.max=(n,i)=>t.check(jt(n,i)),t.int=n=>t.check(Th(n)),t.safe=n=>t.check(Th(n)),t.positive=n=>t.check(Ur(0,n)),t.nonnegative=n=>t.check(dt(0,n)),t.negative=n=>t.check(Mr(0,n)),t.nonpositive=n=>t.check(jt(0,n)),t.multipleOf=(n,i)=>t.check(An(n,i)),t.step=(n,i)=>t.check(An(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function de(t){return Fm(ul,t)}var Di=b("ZodNumberFormat",(t,e)=>{Gf.init(t,e),ul.init(t,e)});function Th(t){return Lm(Di,t)}function $O(t){return Zm(Di,t)}function IO(t){return Hm(Di,t)}function PO(t){return Vm(Di,t)}function EO(t){return Bm(Di,t)}var pl=b("ZodBoolean",(t,e)=>{mo.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>l0(t,r,n,i)});function qe(t){return Wm(pl,t)}var dl=b("ZodBigInt",(t,e)=>{zc.init(t,e),W.init(t,e),t._zod.processJSONSchema=(n,i,a)=>u0(t,n,i,a),t.gte=(n,i)=>t.check(dt(n,i)),t.min=(n,i)=>t.check(dt(n,i)),t.gt=(n,i)=>t.check(Ur(n,i)),t.gte=(n,i)=>t.check(dt(n,i)),t.min=(n,i)=>t.check(dt(n,i)),t.lt=(n,i)=>t.check(Mr(n,i)),t.lte=(n,i)=>t.check(jt(n,i)),t.max=(n,i)=>t.check(jt(n,i)),t.positive=n=>t.check(Ur(BigInt(0),n)),t.negative=n=>t.check(Mr(BigInt(0),n)),t.nonpositive=n=>t.check(jt(BigInt(0),n)),t.nonnegative=n=>t.check(dt(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(An(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function TO(t){return Jm(dl,t)}var Wh=b("ZodBigIntFormat",(t,e)=>{Kf.init(t,e),dl.init(t,e)});function zO(t){return Gm(Wh,t)}function CO(t){return Km(Wh,t)}var sw=b("ZodSymbol",(t,e)=>{Xf.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>p0(t,r,n,i)});function jO(t){return Xm(sw,t)}var cw=b("ZodUndefined",(t,e)=>{Yf.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>f0(t,r,n,i)});function RO(t){return Ym(cw,t)}var lw=b("ZodNull",(t,e)=>{Qf.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>d0(t,r,n,i)});function Oo(t){return Qm(lw,t)}var uw=b("ZodAny",(t,e)=>{em.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>g0(t,r,n,i)});function OO(){return eh(uw)}var pw=b("ZodUnknown",(t,e)=>{tm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>v0(t,r,n,i)});function Se(){return th(pw)}var dw=b("ZodNever",(t,e)=>{rm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>h0(t,r,n,i)});function Jh(t){return rh(dw,t)}var fw=b("ZodVoid",(t,e)=>{nm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>m0(t,r,n,i)});function DO(t){return nh(fw,t)}var Gh=b("ZodDate",(t,e)=>{im.init(t,e),W.init(t,e),t._zod.processJSONSchema=(n,i,a)=>y0(t,n,i,a),t.min=(n,i)=>t.check(dt(n,i)),t.max=(n,i)=>t.check(jt(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function AO(t){return ih(Gh,t)}var mw=b("ZodArray",(t,e)=>{am.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>z0(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(on(r,n)),t.nonempty=r=>t.check(on(1,r)),t.max=(r,n)=>t.check(Ci(r,n)),t.length=(r,n)=>t.check(ji(r,n)),t.unwrap=()=>t.element});function ee(t,e){return a0(mw,t,e)}function NO(t){let e=t._zod.def.shape;return it(Object.keys(e))}var fl=b("ZodObject",(t,e)=>{t0.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>C0(t,r,n,i),P.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>it(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Se()}),t.loose=()=>t.clone({...t._zod.def,catchall:Se()}),t.strict=()=>t.clone({...t._zod.def,catchall:Jh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>P.extend(t,r),t.safeExtend=r=>P.safeExtend(t,r),t.merge=r=>P.merge(t,r),t.pick=r=>P.pick(t,r),t.omit=r=>P.omit(t,r),t.partial=(...r)=>P.partial(Xh,t,r[0]),t.required=(...r)=>P.required(Yh,t,r[0])});function C(t,e){let r={type:"object",shape:t??{},...P.normalizeParams(e)};return new fl(r)}function MO(t,e){return new fl({type:"object",shape:t,catchall:Jh(),...P.normalizeParams(e)})}function nt(t,e){return new fl({type:"object",shape:t,catchall:Se(),...P.normalizeParams(e)})}var ml=b("ZodUnion",(t,e)=>{ho.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yh(t,r,n,i),t.options=e.options});function ye(t,e){return new ml({type:"union",options:t,...P.normalizeParams(e)})}var hw=b("ZodXor",(t,e)=>{ml.init(t,e),om.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yh(t,r,n,i),t.options=e.options});function UO(t,e){return new hw({type:"union",options:t,inclusive:!1,...P.normalizeParams(e)})}var gw=b("ZodDiscriminatedUnion",(t,e)=>{ml.init(t,e),sm.init(t,e)});function hl(t,e,r){return new gw({type:"union",options:e,discriminator:t,...P.normalizeParams(r)})}var vw=b("ZodIntersection",(t,e)=>{cm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>j0(t,r,n,i)});function Do(t,e){return new vw({type:"intersection",left:t,right:e})}var yw=b("ZodTuple",(t,e)=>{Cc.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>R0(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function xw(t,e,r){let n=e instanceof H,i=n?r:e,a=n?e:null;return new yw({type:"tuple",items:t,rest:a,...P.normalizeParams(i)})}var gl=b("ZodRecord",(t,e)=>{lm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>O0(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Pe(t,e,r){return new gl({type:"record",keyType:t,valueType:e,...P.normalizeParams(r)})}function qO(t,e,r){let n=ut(t);return n._zod.values=void 0,new gl({type:"record",keyType:n,valueType:e,...P.normalizeParams(r)})}function FO(t,e,r){return new gl({type:"record",keyType:t,valueType:e,mode:"loose",...P.normalizeParams(r)})}var bw=b("ZodMap",(t,e)=>{um.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>E0(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(qr(...r)),t.nonempty=r=>t.check(qr(1,r)),t.max=(...r)=>t.check(Nn(...r)),t.size=(...r)=>t.check(zi(...r))});function LO(t,e,r){return new bw({type:"map",keyType:t,valueType:e,...P.normalizeParams(r)})}var _w=b("ZodSet",(t,e)=>{pm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>T0(t,r,n,i),t.min=(...r)=>t.check(qr(...r)),t.nonempty=r=>t.check(qr(1,r)),t.max=(...r)=>t.check(Nn(...r)),t.size=(...r)=>t.check(zi(...r))});function ZO(t,e){return new _w({type:"set",valueType:t,...P.normalizeParams(e)})}var jo=b("ZodEnum",(t,e)=>{dm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(n,i,a)=>x0(t,n,i,a),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let a={};for(let o of n)if(r.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new jo({...e,checks:[],...P.normalizeParams(i),entries:a})},t.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new jo({...e,checks:[],...P.normalizeParams(i),entries:a})}});function it(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new jo({type:"enum",entries:r,...P.normalizeParams(e)})}function HO(t,e){return new jo({type:"enum",entries:t,...P.normalizeParams(e)})}var ww=b("ZodLiteral",(t,e)=>{fm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>b0(t,r,n,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 R(t,e){return new ww({type:"literal",values:Array.isArray(t)?t:[t],...P.normalizeParams(e)})}var Sw=b("ZodFile",(t,e)=>{mm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>S0(t,r,n,i),t.min=(r,n)=>t.check(qr(r,n)),t.max=(r,n)=>t.check(Nn(r,n)),t.mime=(r,n)=>t.check($o(Array.isArray(r)?r:[r],n))});function VO(t){return ph(Sw,t)}var kw=b("ZodTransform",(t,e)=>{hm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>P0(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new jn(t.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(P.issue(a,r.value,e));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),r.issues.push(P.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function Kh(t){return new kw({type:"transform",transform:t})}var Xh=b("ZodOptional",(t,e)=>{jc.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xh(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Te(t){return new Xh({type:"optional",innerType:t})}var $w=b("ZodExactOptional",(t,e)=>{gm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xh(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Iw(t){return new $w({type:"optional",innerType:t})}var Pw=b("ZodNullable",(t,e)=>{vm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>D0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function ol(t){return new Pw({type:"nullable",innerType:t})}function BO(t){return Te(ol(t))}var Ew=b("ZodDefault",(t,e)=>{ym.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>N0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Tw(t,e){return new Ew({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():P.shallowClone(e)}})}var zw=b("ZodPrefault",(t,e)=>{xm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Cw(t,e){return new zw({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():P.shallowClone(e)}})}var Yh=b("ZodNonOptional",(t,e)=>{bm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function jw(t,e){return new Yh({type:"nonoptional",innerType:t,...P.normalizeParams(e)})}var Rw=b("ZodSuccess",(t,e)=>{_m.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>k0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function WO(t){return new Rw({type:"success",innerType:t})}var Ow=b("ZodCatch",(t,e)=>{wm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>U0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Dw(t,e){return new Ow({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Aw=b("ZodNaN",(t,e)=>{Sm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_0(t,r,n,i)});function JO(t){return ah(Aw,t)}var Qh=b("ZodPipe",(t,e)=>{km.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>q0(t,r,n,i),t.in=e.in,t.out=e.out});function sl(t,e){return new Qh({type:"pipe",in:t,out:e})}var eg=b("ZodCodec",(t,e)=>{Qh.init(t,e),go.init(t,e)});function GO(t,e,r){return new eg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var Nw=b("ZodReadonly",(t,e)=>{$m.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>F0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Mw(t){return new Nw({type:"readonly",innerType:t})}var Uw=b("ZodTemplateLiteral",(t,e)=>{Im.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>w0(t,r,n,i)});function KO(t,e){return new Uw({type:"template_literal",parts:t,...P.normalizeParams(e)})}var qw=b("ZodLazy",(t,e)=>{Tm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Z0(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function Fw(t){return new qw({type:"lazy",getter:t})}var Lw=b("ZodPromise",(t,e)=>{Em.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>L0(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function XO(t){return new Lw({type:"promise",innerType:t})}var Zw=b("ZodFunction",(t,e)=>{Pm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>I0(t,r,n,i)});function YO(t){return new Zw({type:"function",input:Array.isArray(t?.input)?xw(t?.input):t?.input??ee(Se()),output:t?.output??Se()})}var vl=b("ZodCustom",(t,e)=>{zm.init(t,e),W.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$0(t,r,n,i)});function QO(t){let e=new _e({check:"custom"});return e._zod.check=t,e}function tg(t,e){return dh(vl,t??(()=>!0),e)}function Hw(t,e={}){return fh(vl,t,e)}function Vw(t){return mh(t)}var e6=hh,t6=gh;function r6(t,e={}){let r=new vl({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...P.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var n6=(...t)=>vh({Codec:eg,Boolean:pl,String:cl},...t);function i6(t){let e=Fw(()=>ye([w(t),de(),qe(),Oo(),ee(e),Pe(w(),e)]));return e}function yl(t,e){return sl(Kh(t),e)}var Bw;Bw||(Bw={});var OY={...Co,...il,iso:Mn};He(Cm());var ng="2025-11-25";var Ww=[ng,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],cn="io.modelcontextprotocol/related-task",bl="2.0",Ke=tg(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Jw=ye([w(),de().int()]),Gw=w(),QY=nt({ttl:ye([de(),Oo()]).optional(),pollInterval:de().optional()}),c6=C({ttl:de().optional()}),l6=C({taskId:w()}),ig=nt({progressToken:Jw.optional(),[cn]:l6.optional()}),Ot=C({_meta:ig.optional()}),Ao=Ot.extend({task:c6.optional()}),Kw=t=>Ao.safeParse(t).success,Xe=C({method:w(),params:Ot.loose().optional()}),qt=C({_meta:ig.optional()}),Ft=C({method:w(),params:qt.loose().optional()}),Ye=nt({_meta:ig.optional()}),_l=ye([w(),de().int()]),Xw=C({jsonrpc:R(bl),id:_l,...Xe.shape}).strict(),ag=t=>Xw.safeParse(t).success,Yw=C({jsonrpc:R(bl),...Ft.shape}).strict(),Qw=t=>Yw.safeParse(t).success,og=C({jsonrpc:R(bl),id:_l,result:Ye}).strict(),No=t=>og.safeParse(t).success;var oe;(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"})(oe||(oe={}));var sg=C({jsonrpc:R(bl),id:_l.optional(),error:C({code:de().int(),message:w(),data:Se().optional()})}).strict();var eS=t=>sg.safeParse(t).success;var tS=ye([Xw,Yw,og,sg]),eQ=ye([og,sg]),wl=Ye.strict(),u6=qt.extend({requestId:_l.optional(),reason:w().optional()}),Sl=Ft.extend({method:R("notifications/cancelled"),params:u6}),p6=C({src:w(),mimeType:w().optional(),sizes:ee(w()).optional(),theme:it(["light","dark"]).optional()}),Mo=C({icons:ee(p6).optional()}),Ai=C({name:w(),title:w().optional()}),rS=Ai.extend({...Ai.shape,...Mo.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),d6=Do(C({applyDefaults:qe().optional()}),Pe(w(),Se())),f6=yl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Do(C({form:d6.optional(),url:Ke.optional()}),Pe(w(),Se()).optional())),m6=nt({list:Ke.optional(),cancel:Ke.optional(),requests:nt({sampling:nt({createMessage:Ke.optional()}).optional(),elicitation:nt({create:Ke.optional()}).optional()}).optional()}),h6=nt({list:Ke.optional(),cancel:Ke.optional(),requests:nt({tools:nt({call:Ke.optional()}).optional()}).optional()}),g6=C({experimental:Pe(w(),Ke).optional(),sampling:C({context:Ke.optional(),tools:Ke.optional()}).optional(),elicitation:f6.optional(),roots:C({listChanged:qe().optional()}).optional(),tasks:m6.optional()}),v6=Ot.extend({protocolVersion:w(),capabilities:g6,clientInfo:rS}),cg=Xe.extend({method:R("initialize"),params:v6});var y6=C({experimental:Pe(w(),Ke).optional(),logging:Ke.optional(),completions:Ke.optional(),prompts:C({listChanged:qe().optional()}).optional(),resources:C({subscribe:qe().optional(),listChanged:qe().optional()}).optional(),tools:C({listChanged:qe().optional()}).optional(),tasks:h6.optional()}),x6=Ye.extend({protocolVersion:w(),capabilities:y6,serverInfo:rS,instructions:w().optional()}),lg=Ft.extend({method:R("notifications/initialized"),params:qt.optional()});var kl=Xe.extend({method:R("ping"),params:Ot.optional()}),b6=C({progress:de(),total:Te(de()),message:Te(w())}),_6=C({...qt.shape,...b6.shape,progressToken:Jw}),$l=Ft.extend({method:R("notifications/progress"),params:_6}),w6=Ot.extend({cursor:Gw.optional()}),Uo=Xe.extend({params:w6.optional()}),qo=Ye.extend({nextCursor:Gw.optional()}),S6=it(["working","input_required","completed","failed","cancelled"]),Fo=C({taskId:w(),status:S6,ttl:ye([de(),Oo()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Te(de()),statusMessage:Te(w())}),Ni=Ye.extend({task:Fo}),k6=qt.merge(Fo),Lo=Ft.extend({method:R("notifications/tasks/status"),params:k6}),Il=Xe.extend({method:R("tasks/get"),params:Ot.extend({taskId:w()})}),Pl=Ye.merge(Fo),El=Xe.extend({method:R("tasks/result"),params:Ot.extend({taskId:w()})}),tQ=Ye.loose(),Tl=Uo.extend({method:R("tasks/list")}),zl=qo.extend({tasks:ee(Fo)}),Cl=Xe.extend({method:R("tasks/cancel"),params:Ot.extend({taskId:w()})}),nS=Ye.merge(Fo),iS=C({uri:w(),mimeType:Te(w()),_meta:Pe(w(),Se()).optional()}),aS=iS.extend({text:w()}),ug=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),oS=iS.extend({blob:ug}),Zo=it(["user","assistant"]),Mi=C({audience:ee(Zo).optional(),priority:de().min(0).max(1).optional(),lastModified:Mn.datetime({offset:!0}).optional()}),sS=C({...Ai.shape,...Mo.shape,uri:w(),description:Te(w()),mimeType:Te(w()),annotations:Mi.optional(),_meta:Te(nt({}))}),$6=C({...Ai.shape,...Mo.shape,uriTemplate:w(),description:Te(w()),mimeType:Te(w()),annotations:Mi.optional(),_meta:Te(nt({}))}),I6=Uo.extend({method:R("resources/list")}),P6=qo.extend({resources:ee(sS)}),E6=Uo.extend({method:R("resources/templates/list")}),T6=qo.extend({resourceTemplates:ee($6)}),pg=Ot.extend({uri:w()}),z6=pg,C6=Xe.extend({method:R("resources/read"),params:z6}),j6=Ye.extend({contents:ee(ye([aS,oS]))}),R6=Ft.extend({method:R("notifications/resources/list_changed"),params:qt.optional()}),O6=pg,D6=Xe.extend({method:R("resources/subscribe"),params:O6}),A6=pg,N6=Xe.extend({method:R("resources/unsubscribe"),params:A6}),M6=qt.extend({uri:w()}),U6=Ft.extend({method:R("notifications/resources/updated"),params:M6}),q6=C({name:w(),description:Te(w()),required:Te(qe())}),F6=C({...Ai.shape,...Mo.shape,description:Te(w()),arguments:Te(ee(q6)),_meta:Te(nt({}))}),L6=Uo.extend({method:R("prompts/list")}),Z6=qo.extend({prompts:ee(F6)}),H6=Ot.extend({name:w(),arguments:Pe(w(),w()).optional()}),V6=Xe.extend({method:R("prompts/get"),params:H6}),dg=C({type:R("text"),text:w(),annotations:Mi.optional(),_meta:Pe(w(),Se()).optional()}),fg=C({type:R("image"),data:ug,mimeType:w(),annotations:Mi.optional(),_meta:Pe(w(),Se()).optional()}),mg=C({type:R("audio"),data:ug,mimeType:w(),annotations:Mi.optional(),_meta:Pe(w(),Se()).optional()}),B6=C({type:R("tool_use"),name:w(),id:w(),input:Pe(w(),Se()),_meta:Pe(w(),Se()).optional()}),W6=C({type:R("resource"),resource:ye([aS,oS]),annotations:Mi.optional(),_meta:Pe(w(),Se()).optional()}),J6=sS.extend({type:R("resource_link")}),hg=ye([dg,fg,mg,J6,W6]),G6=C({role:Zo,content:hg}),K6=Ye.extend({description:w().optional(),messages:ee(G6)}),X6=Ft.extend({method:R("notifications/prompts/list_changed"),params:qt.optional()}),Y6=C({title:w().optional(),readOnlyHint:qe().optional(),destructiveHint:qe().optional(),idempotentHint:qe().optional(),openWorldHint:qe().optional()}),Q6=C({taskSupport:it(["required","optional","forbidden"]).optional()}),cS=C({...Ai.shape,...Mo.shape,description:w().optional(),inputSchema:C({type:R("object"),properties:Pe(w(),Ke).optional(),required:ee(w()).optional()}).catchall(Se()),outputSchema:C({type:R("object"),properties:Pe(w(),Ke).optional(),required:ee(w()).optional()}).catchall(Se()).optional(),annotations:Y6.optional(),execution:Q6.optional(),_meta:Pe(w(),Se()).optional()}),gg=Uo.extend({method:R("tools/list")}),eD=qo.extend({tools:ee(cS)}),jl=Ye.extend({content:ee(hg).default([]),structuredContent:Pe(w(),Se()).optional(),isError:qe().optional()}),rQ=jl.or(Ye.extend({toolResult:Se()})),tD=Ao.extend({name:w(),arguments:Pe(w(),Se()).optional()}),Ho=Xe.extend({method:R("tools/call"),params:tD}),rD=Ft.extend({method:R("notifications/tools/list_changed"),params:qt.optional()}),nQ=C({autoRefresh:qe().default(!0),debounceMs:de().int().nonnegative().default(300)}),Vo=it(["debug","info","notice","warning","error","critical","alert","emergency"]),nD=Ot.extend({level:Vo}),vg=Xe.extend({method:R("logging/setLevel"),params:nD}),iD=qt.extend({level:Vo,logger:w().optional(),data:Se()}),aD=Ft.extend({method:R("notifications/message"),params:iD}),oD=C({name:w().optional()}),sD=C({hints:ee(oD).optional(),costPriority:de().min(0).max(1).optional(),speedPriority:de().min(0).max(1).optional(),intelligencePriority:de().min(0).max(1).optional()}),cD=C({mode:it(["auto","required","none"]).optional()}),lD=C({type:R("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:ee(hg).default([]),structuredContent:C({}).loose().optional(),isError:qe().optional(),_meta:Pe(w(),Se()).optional()}),uD=hl("type",[dg,fg,mg]),xl=hl("type",[dg,fg,mg,B6,lD]),pD=C({role:Zo,content:ye([xl,ee(xl)]),_meta:Pe(w(),Se()).optional()}),dD=Ao.extend({messages:ee(pD),modelPreferences:sD.optional(),systemPrompt:w().optional(),includeContext:it(["none","thisServer","allServers"]).optional(),temperature:de().optional(),maxTokens:de().int(),stopSequences:ee(w()).optional(),metadata:Ke.optional(),tools:ee(cS).optional(),toolChoice:cD.optional()}),fD=Xe.extend({method:R("sampling/createMessage"),params:dD}),yg=Ye.extend({model:w(),stopReason:Te(it(["endTurn","stopSequence","maxTokens"]).or(w())),role:Zo,content:uD}),xg=Ye.extend({model:w(),stopReason:Te(it(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:Zo,content:ye([xl,ee(xl)])}),mD=C({type:R("boolean"),title:w().optional(),description:w().optional(),default:qe().optional()}),hD=C({type:R("string"),title:w().optional(),description:w().optional(),minLength:de().optional(),maxLength:de().optional(),format:it(["email","uri","date","date-time"]).optional(),default:w().optional()}),gD=C({type:it(["number","integer"]),title:w().optional(),description:w().optional(),minimum:de().optional(),maximum:de().optional(),default:de().optional()}),vD=C({type:R("string"),title:w().optional(),description:w().optional(),enum:ee(w()),default:w().optional()}),yD=C({type:R("string"),title:w().optional(),description:w().optional(),oneOf:ee(C({const:w(),title:w()})),default:w().optional()}),xD=C({type:R("string"),title:w().optional(),description:w().optional(),enum:ee(w()),enumNames:ee(w()).optional(),default:w().optional()}),bD=ye([vD,yD]),_D=C({type:R("array"),title:w().optional(),description:w().optional(),minItems:de().optional(),maxItems:de().optional(),items:C({type:R("string"),enum:ee(w())}),default:ee(w()).optional()}),wD=C({type:R("array"),title:w().optional(),description:w().optional(),minItems:de().optional(),maxItems:de().optional(),items:C({anyOf:ee(C({const:w(),title:w()}))}),default:ee(w()).optional()}),SD=ye([_D,wD]),kD=ye([xD,bD,SD]),$D=ye([kD,mD,hD,gD]),ID=Ao.extend({mode:R("form").optional(),message:w(),requestedSchema:C({type:R("object"),properties:Pe(w(),$D),required:ee(w()).optional()})}),PD=Ao.extend({mode:R("url"),message:w(),elicitationId:w(),url:w().url()}),ED=ye([ID,PD]),TD=Xe.extend({method:R("elicitation/create"),params:ED}),zD=qt.extend({elicitationId:w()}),CD=Ft.extend({method:R("notifications/elicitation/complete"),params:zD}),Rl=Ye.extend({action:it(["accept","decline","cancel"]),content:yl(t=>t===null?void 0:t,Pe(w(),ye([w(),de(),qe(),ee(w())])).optional())}),jD=C({type:R("ref/resource"),uri:w()});var RD=C({type:R("ref/prompt"),name:w()}),OD=Ot.extend({ref:ye([RD,jD]),argument:C({name:w(),value:w()}),context:C({arguments:Pe(w(),w()).optional()}).optional()}),DD=Xe.extend({method:R("completion/complete"),params:OD});var AD=Ye.extend({completion:nt({values:ee(w()).max(100),total:Te(de().int()),hasMore:Te(qe())})}),ND=C({uri:w().startsWith("file://"),name:w().optional(),_meta:Pe(w(),Se()).optional()}),MD=Xe.extend({method:R("roots/list"),params:Ot.optional()}),bg=Ye.extend({roots:ee(ND)}),UD=Ft.extend({method:R("notifications/roots/list_changed"),params:qt.optional()}),iQ=ye([kl,cg,DD,vg,V6,L6,I6,E6,C6,D6,N6,Ho,gg,Il,El,Tl,Cl]),aQ=ye([Sl,$l,lg,UD,Lo]),oQ=ye([wl,yg,xg,Rl,bg,Pl,zl,Ni]),sQ=ye([kl,fD,TD,MD,Il,El,Tl,Cl]),cQ=ye([Sl,$l,aD,U6,R6,rD,X6,Lo,CD]),lQ=ye([wl,x6,AD,K6,Z6,P6,T6,j6,jl,eD,Pl,zl,Ni]),G=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===oe.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new rg(i.elicitations,r)}return new t(e,r,n)}},rg=class extends G{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(oe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ln(t){return t==="completed"||t==="failed"||t==="cancelled"}var qD=Symbol("Let zodToJsonSchema decide on which parser to use");var ZQ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _g(t){let r=nl(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=B0(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function wg(t,e){let r=sn(t,e);if(!r.success)throw r.error;return r.data}var BD=6e4,Ol=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(Sl,r=>{this._oncancel(r)}),this.setNotificationHandler($l,r=>{this._onprogress(r)}),this.setRequestHandler(kl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Il,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new G(oe.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(El,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.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 p=c,d=new G(p.error.code,p.error.message,p.error.data);u(d)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(a,n.sessionId);if(!o)throw new G(oe.InvalidParams,`Task not found: ${a}`);if(!ln(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(ln(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[cn]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(Tl,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new G(oe.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Cl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new G(oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(ln(i.status))throw new G(oe.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new G(oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof G?i:new G(oe.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,r,n,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),G.fromError(oe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),No(a)||eS(a)?this._onresponse(a):ag(a)?this._onrequest(a,o):Qw(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 r=G.fromError(oe.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,a=e.params?._meta?.[cn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:oe.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=Kw(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 p={relatedRequestId:e.id};a&&(p.relatedTask={taskId:a}),await this.notification(u,p)},sendRequest:async(u,p,d)=>{let f={...d,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,p,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(o.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async u=>{if(o.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:oe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),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(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),No(e))n(e);else{let o=new G(e.error.code,e.error.message,e.error.data);n(o)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(No(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,r))}}if(a||this._progressHandlers.delete(r),No(e))i(e);else{let o=G.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,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(o){yield{type:"error",error:o instanceof G?o:new G(oe.InternalError,String(o))}}return}let a;try{let o=await this.request(e,Ni,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new G(oe.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},ln(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new G(oe.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new G(oe.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof G?o:new G(oe.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=S=>{u(S)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(S){p(S);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[cn]:c}});let m=S=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(S)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let _=S instanceof G?S:new G(oe.RequestTimeout,String(S));u(_)};this._responseHandlers.set(d,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return u(S);try{let _=sn(r,S.result);_.success?l(_.data):u(_.error)}catch(_){u(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??BD,g=()=>m(G.fromError(oe.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let S=_=>{let k=this._responseHandlers.get(d);k?k(_):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,S),this._enqueueTaskMessage(x,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(d),u(_)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(S=>{this._cleanupTimeout(d),u(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Pl,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},zl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},nS,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[cn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.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"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[cn]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[cn]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=_g(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=wg(e,i);return Promise.resolve(r(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,r){let n=_g(e);this._notificationHandlers.set(n,i=>{let a=wg(e,i);return Promise.resolve(r(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){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,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&ag(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new G(oe.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,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,a)=>{if(r.aborted){a(new G(oe.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new G(oe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let a=await n.getTask(i,r);if(!a)throw new G(oe.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=Lo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),ln(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new G(oe.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(ln(s.status))throw new G(oe.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let l=Lo.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ln(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function lS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function uS(t,e){let r={...t};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=r[i];lS(o)&&lS(a)?r[i]={...o,...a}:r[i]=a}return r}var K1=Pd(sy(),1),X1=Pd(G1(),1);function AU(){let t=new K1.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,X1.default)(t),t}var vu=class{constructor(e){this._ajv=e??AU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var yu=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Y1(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Q1(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var xu=class extends Ol{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Vo.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new vu,this.setRequestHandler(cg,n=>this._oninitialize(n)),this.setNotificationHandler(lg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(vg,async(n,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=n.params,s=Vo.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new yu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=uS(this._capabilities,e)}setRequestHandler(e,r){let i=nl(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(Oi(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=sn(Ho,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new G(oe.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,d=await Promise.resolve(r(c,l));if(p.task){let m=sn(Ni,d);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new G(oe.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=sn(jl,d);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new G(oe.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}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){Q1(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Y1(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ww.includes(r)?r:ng,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"},wl)}async createMessage(e,r){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 n=e.messages[e.messages.length-1],i=Array.isArray(n.content)?n.content:[n.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(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))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},xg,r):this.request({method:"sampling/createMessage",params:e},yg,r)}async elicitInput(e,r){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},Rl,r)}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},Rl,r);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new G(oe.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof G?o:new G(oe.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}createElicitationCompletionNotifier(e,r){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}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},bg,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 t$ from"node:process";var bu=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
99
99
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),NU(r)}clear(){this._buffer=void 0}};function NU(t){return tS.parse(JSON.parse(t))}function e$(t){return JSON.stringify(t)+`
|
|
100
|
-
`}var _u=class{constructor(e=t$.stdin,r=t$.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new bu,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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(r=>{let n=e$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var wu={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.'},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."}},required:["action"]}};var Su={name:"mutate_instances",description:"Create, delete, clone, move, rename, or pivot instances. [PRO] create_tree, mass_create, mass_delete, mass_duplicate, smart_duplicate.",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"],description:"Mutation action. Basic: create, create_with_props, delete, clone, move, rename, pivot. [PRO]: create_tree, mass_create, mass_delete, mass_duplicate, smart_duplicate."},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."},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.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},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.",items:{type:"number"},minItems:12,maxItems:12},offset:{type:"object",description:"Relative offset to move by (ignores position/cframe). Used by: pivot, smart_duplicate.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},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",properties:{className:{type:"string"},name:{type:"string"},parentPath:{type:"string"},properties:{type:"object",additionalProperties:!0}},required:["className","name","parentPath"]}},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."},spacing:{type:"object",description:"[PRO] Spacing between duplicated instances. Used by: smart_duplicate. Alias for offset.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}},required:["action"]}};var ku={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."},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",enum:["add","subtract","multiply","divide"],description:"[PRO] Mathematical operation for relative property change. Used by: set_relative."},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."}},required:["action"]}};var $u={name:"manage_scripts",description:"Manage script source code: read, write, create, delete, edit lines, search. [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","get_dependencies","replace"],description:"Script action. Basic: get_source, set_source, create, delete, edit_replace, edit_insert, edit_delete, search, get_dependencies. [PRO]: replace."},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."},source:{type:"string",description:"Script source code. Used by: set_source (required), create (optional initial source)."},scriptType:{type:"string",enum:["Script","LocalScript","ModuleScript"],description:"Type of script to create. Used by: create."},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: edit_replace, edit_delete."},endLine:{type:"number",description:"Ending line number, 1-based inclusive. Used by: edit_replace, edit_delete."},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."}},required:["action"]}};var Iu={name:"manage_lighting",description:"[PRO] Configure environment: lighting, atmosphere, sky, terrain properties, time of day.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["lighting","atmosphere","sky","terrain_props","time"],description:"[PRO] Environment action. lighting: set Lighting service properties. atmosphere: set Atmosphere properties. sky: set Sky properties. terrain_props: set Terrain water/visual properties. time: set time of day."},properties:{type:"object",description:"Dictionary of properties to set. Used by: lighting, atmosphere, sky, terrain_props. Supports Color3 {r,g,b} (0-255), numbers, booleans, Enum strings.",additionalProperties:!0},createIfMissing:{type:"boolean",description:"Create Atmosphere/Sky instance if missing. Used by: atmosphere, sky. Default: true."},time:{type:"string",description:'Time string in "HH:MM:SS" format (e.g., "14:30:00"). Used by: time. Provide this OR clockTime.'},clockTime:{type:"number",description:"Numeric time in 24-hour format (e.g., 14.5 for 2:30 PM). Used by: time. Provide this OR time."}},required:["action"]}};var Pu={name:"manage_selection",description:"Get, set, or clear selection. [PRO] context, details, add/remove items, watch changes.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set","clear","cached","context","details","add","remove","watch"],description:"Selection action. Basic: get (current selection), set (replace selection), clear (deselect all), cached (from cache without round-trip). [PRO]: context (detailed with source/properties), details (hierarchical with ancestors/descendants), add (add to selection), remove (remove from selection), watch (monitor changes)."},paths:{type:"array",description:"Array of instance paths. Used by: set (required), add (required), remove (required).",items:{type:"string"}},maxAge:{type:"number",description:"Maximum age of cached data in milliseconds. Used by: cached. Default: 30000. Set to 0 for any age."},maxDepth:{type:"number",description:"[PRO] Maximum depth for descendant tree traversal. Used by: details. Default: 1."},includeSource:{type:"boolean",description:"[PRO] Include script source code. Used by: context. Default: true."},includeProperties:{type:"boolean",description:"[PRO] Include all readable properties. Used by: context. Default: true."},includeChildren:{type:"boolean",description:"[PRO] Include immediate children. Used by: context. Default: false."},includeAncestors:{type:"boolean",description:"[PRO] Include full ancestor chain. Used by: details. Default: false."}},required:["action"]}};var Eu={name:"manage_camera",description:"Camera operations: get info, focus on instance by path or position, get suggested view.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["info","focus_path","focus_position","suggest"],description:"Camera action. info: get current camera position, rotation, FOV, viewport size. focus_path: move camera to focus on instance by path. focus_position: move camera to focus on world position. suggest: get suggested camera view for a target."},path:{type:"string",description:"Instance path to focus on. Used by: focus_path (if not provided, focuses on selection), suggest (if not provided, uses selection)."},position:{type:"object",description:"World position to focus on as Vector3. Used by: focus_position (required).",properties:{x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},z:{type:"number",description:"Z coordinate"}},required:["x","y","z"]},distance:{type:"number",description:"Distance from target in studs. Used by: focus_path, focus_position. Auto-calculated if not provided."},duration:{type:"number",description:"Animation duration in seconds. Used by: focus_path, focus_position. Default: 0.5."},offset:{type:"object",description:"Camera offset direction from target (normalized and scaled by distance). Used by: focus_path, focus_position. Default: {x:1, y:0.5, z:1}.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},lookAt:{type:"object",description:"Point for camera to look at. Used by: focus_position.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},respectAutoFocusSetting:{type:"boolean",description:"If true, only focus when plugin Auto Focus setting is enabled. Used by: focus_path, focus_position. Default: false."}},required:["action"]}};var Tu={name:"manage_tween",description:"[PRO] Tween service: create, play, pause, cancel tweens for smooth animations.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","play","pause","cancel"],description:"[PRO] Tween action. create: create a new tween with target properties. play: play a created tween. pause: pause a running tween. cancel: cancel a tween."},path:{type:"string",description:"Instance path to tween. Used by: create (required)."},tweenInfo:{type:"object",description:"Tween configuration. Used by: create.",properties:{time:{type:"number",description:"Duration in seconds. Default: 1."},easingStyle:{type:"string",description:'Easing style (e.g., "Linear", "Quad", "Cubic", "Sine", "Bounce", "Elastic"). Default: "Quad".'},easingDirection:{type:"string",enum:["In","Out","InOut"],description:'Easing direction. Default: "Out".'},repeatCount:{type:"number",description:"Number of times to repeat. -1 for infinite. Default: 0."},reverses:{type:"boolean",description:"Whether the tween reverses on each repeat. Default: false."},delayTime:{type:"number",description:"Delay before tween starts in seconds. Default: 0."}}},properties:{type:"object",description:"Target property values to tween to. Used by: create. Supports Vector3, Color3, numbers, etc.",additionalProperties:!0},tweenId:{type:"string",description:"Tween identifier returned by create. Used by: play, pause, cancel."}},required:["action"]}};var zu={name:"manage_audio",description:"[PRO] Audio management: play, stop, pause, resume sounds. Set audio listener.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["play","stop","pause","resume","set_listener"],description:"[PRO] Audio action. play: play a sound (creates Sound if needed). stop: stop a playing sound. pause: pause a playing sound. resume: resume a paused sound. set_listener: set the audio listener type/target."},path:{type:"string",description:"Path to the Sound instance or parent to create Sound in. Used by: play, stop, pause, resume."},soundId:{type:"string",description:'Roblox sound asset ID (e.g., "rbxassetid://1234567"). Used by: play (if creating a new Sound).'},volume:{type:"number",description:"Sound volume (0-10). Used by: play. Default: 0.5."},looped:{type:"boolean",description:"Whether the sound loops. Used by: play. Default: false."},playbackSpeed:{type:"number",description:"Playback speed multiplier. Used by: play. Default: 1."},listenerType:{type:"string",enum:["Camera","CFrame","ObjectPosition","ObjectCFrame"],description:"Listener type for SoundService. Used by: set_listener."},listenerPath:{type:"string",description:"Instance path for ObjectPosition/ObjectCFrame listener type. Used by: set_listener."}},required:["action"]}};var Cu={name:"manage_animation",description:"[PRO] Animation: load, play, stop animations. Get animation tracks from humanoid/controller.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["load","play","stop","get_tracks"],description:"[PRO] Animation action. load: load an animation on a Humanoid/AnimationController. play: play a loaded animation track. stop: stop a playing animation. get_tracks: list all loaded animation tracks."},path:{type:"string",description:"Path to the Humanoid, AnimationController, or Model containing one. Used by: load, play, stop, get_tracks."},animationId:{type:"string",description:'Roblox animation asset ID (e.g., "rbxassetid://1234567"). Used by: load.'},trackId:{type:"string",description:"Animation track identifier returned by load. Used by: play (required), stop (required)."},speed:{type:"number",description:"Playback speed multiplier. Used by: play. Default: 1."},fadeTime:{type:"number",description:"Fade time in seconds when starting/stopping. Used by: play, stop. Default: 0.1."},weight:{type:"number",description:"Animation weight (0-1) for blending. Used by: play. Default: 1."},priority:{type:"string",enum:["Core","Idle","Movement","Action","Action2","Action3","Action4"],description:"Animation priority. Used by: play."}},required:["action"]}};var ju={name:"manage_physics",description:"[PRO] Physics collision groups: register, set collidable between groups, list groups.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["register_group","set_collidable","get_groups"],description:"[PRO] Physics action. register_group: register a new collision group with PhysicsService. set_collidable: set whether two groups can collide. get_groups: list all registered collision groups."},groupName:{type:"string",description:"Collision group name. Used by: register_group (required)."},group1:{type:"string",description:"First collision group name. Used by: set_collidable (required)."},group2:{type:"string",description:"Second collision group name. Used by: set_collidable (required)."},collidable:{type:"boolean",description:"Whether the two groups can collide. Used by: set_collidable (required)."}},required:["action"]}};var Ru={name:"manage_effects",description:"[PRO] Particle effects: emit particles, clear all particles, toggle effect enabled state.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["emit","clear","toggle"],description:"[PRO] Effects action. emit: emit a burst of particles from a ParticleEmitter. clear: clear all particles from a ParticleEmitter or all emitters under an instance. toggle: enable or disable a ParticleEmitter, Beam, Trail, or other effect."},path:{type:"string",description:"Path to the effect instance (ParticleEmitter, Beam, Trail) or parent containing effects. Used by: emit, clear, toggle."},count:{type:"number",description:"Number of particles to emit in a burst. Used by: emit. Default: 16."},enabled:{type:"boolean",description:"Enable or disable the effect. Used by: toggle."}},required:["action"]}};var Ou={name:"manage_terrain",description:"[PRO] Terrain operations: fill shapes, clear regions, replace materials, manage colors, read/write voxels, generate procedural terrain, smooth terrain.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["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"],description:"[PRO] Terrain action. fill_block/fill_ball/fill_cylinder/fill_wedge: fill shapes with material. clear_region/clear_bounds: clear terrain. replace_material: swap materials in region. colors_get/colors_set: manage material colors. read_voxel: single voxel. read_voxels/write_voxels: bulk voxels. generate: procedural terrain. smooth: smooth terrain."},material:{type:"string",description:"Terrain material name (e.g., Grass, Rock, Water, Sand, Slate, Concrete). Used by: fill_*, replace_material, colors_get, colors_set."},center:{type:"object",description:"Center position as Vector3. Used by: fill_ball.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},position:{type:"object",description:"Position as Vector3. Used by: read_voxel.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},cframe:{type:"object",description:"Position and rotation for fill shapes. Used by: fill_block, fill_cylinder, fill_wedge.",properties:{position:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},rotation:{type:"object",description:"Optional rotation in degrees.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}},required:["position"]},size:{type:"object",description:"Size in studs. Used by: fill_block, fill_wedge.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},radius:{type:"number",description:"Radius in studs. Used by: fill_ball, fill_cylinder."},height:{type:"number",description:"Height in studs. Used by: fill_cylinder."},region:{type:"object",description:"Rectangular region with min/max corners. Used by: clear_region, replace_material, read_voxels, write_voxels, generate, smooth.",properties:{min:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["min","max"]},min:{type:"object",description:"Minimum corner for bounds-based clear. Used by: clear_bounds.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",description:"Maximum corner for bounds-based clear. Used by: clear_bounds.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},sourceMaterial:{type:"string",description:"Material to replace. Used by: replace_material."},targetMaterial:{type:"string",description:"Replacement material. Used by: replace_material."},color:{type:"object",description:"RGB color (0-255). Used by: colors_set.",properties:{r:{type:"number",minimum:0,maximum:255},g:{type:"number",minimum:0,maximum:255},b:{type:"number",minimum:0,maximum:255}},required:["r","g","b"]},resolution:{type:"number",description:"Voxel resolution (studs per voxel). Used by: read_voxels, write_voxels. Default: 4."},materials:{type:"array",description:"3D array of material names [x][y][z]. Used by: write_voxels.",items:{type:"array",items:{type:"array",items:{type:"string"}}}},occupancy:{type:"array",description:"3D array of occupancy values [x][y][z] (0-1). Used by: write_voxels.",items:{type:"array",items:{type:"array",items:{type:"number",minimum:0,maximum:1}}}},baseHeight:{type:"number",description:"Base terrain height in studs. Used by: generate. Default: 32."},amplitude:{type:"number",description:"Height variation amplitude in studs. Used by: generate. Default: 24."},frequency:{type:"number",description:"Noise frequency (0.001-0.1). Used by: generate. Default: 0.01.",minimum:.001,maximum:.1},seed:{type:"number",description:"Random seed for terrain generation. Used by: generate."},layers:{type:"array",description:"Material layers by height. Used by: generate. Each: {material, maxHeight}.",items:{type:"object",properties:{material:{type:"string"},maxHeight:{type:"number"}},required:["material","maxHeight"]}},intensity:{type:"number",description:"Smoothing intensity (0-1). Used by: smooth. Default: 0.5.",minimum:0,maximum:1}},required:["action"]}};var Du={name:"spatial_query",description:"[PRO] Spatial queries: raycast, find ground, check placement, multi-raycast, scan area, find flat areas, find spawn positions, analyze walkable, spatial map, find empty space, get bounds, snap to grid, check collision.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["raycast","find_ground","check_placement","multi_raycast","scan_area","find_flat","find_spawn","analyze_walkable","spatial_map","find_space","bounds","snap_grid","collision"],description:"[PRO] Spatial action. raycast: single ray. find_ground: ground below point. check_placement: collision-free placement check. multi_raycast: batch rays. scan_area: heightmap generation. find_flat: flat areas for building. find_spawn: spawn positions. analyze_walkable: walkability grid. spatial_map: all BasePart positions. find_space: empty space for object. bounds: bounding box. snap_grid: snap position to grid. collision: AABB collision check."},origin:{type:"object",description:"Ray origin as Vector3. Used by: raycast.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},direction:{type:"object",description:"Ray direction and length as Vector3. Used by: raycast.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},maxDistance:{type:"number",description:"Maximum distance for ground search. Used by: find_ground. Default: 1000."},position:{type:"object",description:"Position as Vector3. Used by: find_ground (cast from here), check_placement (center), collision (hypothetical position).",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},size:{type:"object",description:"Size as Vector3. Used by: check_placement (object size), find_space (required space size), scan_area (area X/Z dimensions).",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},filterType:{type:"string",enum:["Exclude","Include"],description:'Raycast filter type. Used by: raycast, multi_raycast. Default: "Exclude".'},filterList:{type:"array",description:"Instance paths to filter. Used by: raycast, multi_raycast, find_ground, check_placement, scan_area. Alias: filterInstances.",items:{type:"string"}},filterInstances:{type:"array",description:"Instance paths to filter (alias for filterList). Used by: raycast, multi_raycast, find_ground, check_placement, scan_area.",items:{type:"string"}},ignoreWater:{type:"boolean",description:"Ignore terrain water. Used by: raycast, multi_raycast. Default: false."},rays:{type:"array",description:"Array of ray specifications. Used by: multi_raycast. Max 50 rays.",items:{type:"object",properties:{origin:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},direction:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["origin","direction"]},maxItems:50},center:{type:"object",description:"Center point for area scan. Used by: scan_area.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},area:{type:"object",description:"Bounding box for analysis. Used by: analyze_walkable. Contains min/max.",properties:{min:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["min","max"]},searchArea:{type:"object",description:"Bounding box for search. Used by: find_flat, find_spawn, find_space.",properties:{min:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["min","max"]},minSize:{type:"object",description:"Minimum flat area size. Used by: find_flat.",properties:{x:{type:"number"},z:{type:"number"}},required:["x","z"]},maxSlope:{type:"number",description:"Maximum slope in degrees. Used by: find_flat (default: 10), analyze_walkable (default: 45)."},resolution:{type:"number",description:"Grid resolution in studs. Used by: scan_area, analyze_walkable. Default: 4."},gridSize:{type:"number",description:"Grid snap size in studs. Used by: snap_grid (default: 4), find_space (default: 4)."},path:{type:"string",description:"Instance path. Used by: bounds (optional), snap_grid (required), collision (required), spatial_map (rootPath alias)."},paths:{type:"array",description:"Multiple instance paths for batch bounds. Used by: bounds.",items:{type:"string"}},tolerance:{type:"number",description:"Height variation tolerance in studs. Used by: find_flat."},gridSnap:{type:"number",description:"Grid snap size. Alias for gridSize."},axes:{type:"array",description:'Axes to snap. Used by: snap_grid. Default: ["x","y","z"]. Use ["x","z"] for horizontal only.',items:{type:"string",enum:["x","y","z"]}},ignorePaths:{type:"array",description:"Instance paths to ignore in collision check. Used by: collision.",items:{type:"string"}},offset:{type:"number",description:"Vertical offset for ground position. Used by: find_ground. Default: 0."},rotation:{type:"object",description:"Rotation in degrees. Used by: check_placement.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},checkGround:{type:"boolean",description:"Verify ground support for placement. Used by: check_placement. Default: true."},spawnSize:{type:"object",description:"Size of spawning entity. Used by: find_spawn. Default: {x:4, y:5, z:4}.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},minSpacing:{type:"number",description:"Minimum distance between spawn positions. Used by: find_spawn. Default: 10."},preferOutdoor:{type:"boolean",description:"Prefer open sky positions. Used by: find_spawn. Default: false."},count:{type:"number",description:"Number of results to find. Used by: find_spawn. Default: 10."},characterHeight:{type:"number",description:"Character height for clearance checks. Used by: analyze_walkable. Default: 5."},maxStepHeight:{type:"number",description:"Maximum step height. Used by: analyze_walkable. Default: 2."},rootPath:{type:"string",description:'Root path for spatial map scan. Used by: spatial_map. Default: "game.Workspace".'},includeModels:{type:"boolean",description:"Include Model bounding boxes. Used by: spatial_map. Default: true."},maxResults:{type:"number",description:"Maximum results. Used by: spatial_map (default: 500), scan_area (default: 500), find_flat (default: 10)."},padding:{type:"number",description:"Minimum distance from other objects. Used by: find_space. Default: 1."}},required:["action"]}};var Au={name:"manage_assets",description:"[PRO] Asset management: insert models by ID, get asset info, search creator store, insert free models/packages, export selection.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["insert","info","search","search_insert","insert_free","insert_package","export"],description:"[PRO] Asset action. insert: insert model by asset ID. info: get asset metadata. search: search Creator Store. search_insert: search and insert first match. insert_free: insert free model. insert_package: insert package. export: export current selection."},assetId:{type:"number",description:"Roblox asset ID. Used by: insert (required), info (required), insert_free (required), insert_package (required)."},parent:{type:"string",description:'Parent path for inserted asset. Used by: insert, search_insert, insert_free, insert_package. Default: "game.Workspace".'},name:{type:"string",description:"Optional name for inserted instance."},position:{type:"object",description:"Position to place the model. Used by: insert, insert_free.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},query:{type:"string",description:'Search keyword. Used by: search (required), search_insert (required). E.g., "monster", "tree", "car".'},maxResults:{type:"number",description:"Maximum search results. Used by: search. Default: 10."},category:{type:"string",description:"Asset category filter. Used by: search."},sortType:{type:"string",description:"Sort order for search results. Used by: search."},format:{type:"string",description:"Export format. Used by: export."},includeProperties:{type:"boolean",description:"Include all properties in export. Used by: export. Default: false."},includeChildren:{type:"boolean",description:"Include children in export. Used by: export. Default: false."},maxDepth:{type:"number",description:"Maximum depth for recursive child export. Used by: export. Default: 5."}},required:["action"]}};var Nu={name:"manage_sync",description:"[PRO] Project sync management: status, config, history, direction settings, read/write synced files.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","config","history","directions","read_file","write_file","progress"],description:"[PRO] Sync action. status: get sync status for a place. config: get sync configuration. history: get change history. directions: get per-type sync directions. read_file: read a synced file. write_file: write to a synced file. progress: get real-time sync progress and bandwidth."},placeId:{type:"number",description:"Place ID for sync operations. Used by: status, config, history, directions."},instancePath:{type:"string",description:"Instance path for file read/write. Used by: read_file, write_file."},content:{type:"string",description:"File content to write. Used by: write_file."},query:{type:"object",description:"Query parameters for history. Used by: history.",properties:{limit:{type:"number",description:"Maximum entries to return."},offset:{type:"number",description:"Number of entries to skip."}}}},required:["action"]}};var Mu={name:"workspace_state",description:"[PRO] Workspace state: full sync, snapshot, recent changes, viewport info.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["sync","snapshot","changes","viewport"],description:"[PRO] State action. sync: fetch current Workspace state (hierarchy, history, stats). snapshot: get full instance tree structure. changes: get recent changes (added/removed/modified). viewport: get camera position, FOV, viewport size, selection bounds."},includeMetadata:{type:"boolean",description:"Include metadata (instance counts, timestamps). Used by: sync. Default: true."},limit:{type:"number",description:"Maximum number of changes to return. Used by: changes. Default: 20."},includeCameraInfo:{type:"boolean",description:"Include camera position and settings. Used by: viewport. Default: true."},includeSelectionBounds:{type:"boolean",description:"Include current selection bounds info. Used by: viewport. Default: true."}},required:["action"]}};var Uu={name:"manage_logs",description:"Output logs: get filtered logs, clear buffer, get recent errors.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","clear","errors"],description:"Log action. get: retrieve logs with optional type/limit/since filter. clear: clear internal log buffer. errors: quick access to recent errors only."},level:{type:"string",enum:["all","error","warning","info"],description:'Log level filter. Used by: get. Default: "all".'},limit:{type:"number",description:"Maximum entries to return. Used by: get (default: 100, max: 500), errors (default: 20, max: 100)."},pattern:{type:"string",description:"Text pattern to filter log messages. Used by: get."},since:{type:"number",description:"Unix timestamp in milliseconds. Only logs after this time. Used by: get."}},required:["action"]}};var qu={name:"system_info",description:"System info: ping, connection status, usage tier. [PRO] place info, services list, studio settings, run command.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["ping","connection","usage","place_info","services","studio_settings","run_command"],description:"System action. Basic: ping (test connection, returns pong), connection (server/plugin connection info with session IDs), usage (current tier: basic/pro). [PRO]: place_info (place ID, name, game ID, creator), services (list all Roblox services), studio_settings (Studio preferences), run_command (execute Studio command)."},message:{type:"string",description:"Optional message to echo back. Used by: ping."},command:{type:"string",description:'[PRO] Studio command to execute (e.g., "SelectAll", "Copy", "Paste", "Delete", "Undo", "Redo"). Used by: run_command.'}},required:["action"]}};var Fu={name:"batch_execute",description:'[PRO] Execute multiple commands in a single batch. Each command is an object with "tool" name and "args". Commands execute sequentially; optionally continue on error.',inputSchema:{type:"object",properties:{commands:{type:"array",description:"Array of commands to execute sequentially. Each command specifies a tool name and its arguments.",items:{type:"object",properties:{tool:{type:"string",description:'Tool name to invoke (e.g., "mutate_instances", "manage_properties").'},args:{type:"object",description:"Arguments to pass to the tool, including action and other parameters.",additionalProperties:!0}},required:["tool","args"]}},stopOnError:{type:"boolean",description:"If true, stop executing remaining commands when one fails. Default: true."}},required:["commands"]}};var Lu={name:"execute_luau",description:"[PRO] Execute arbitrary Luau code in Roblox Studio sandbox. Blocked services: HttpService, DataStoreService, MessagingService. Cannot access CoreGui/CorePackages.",inputSchema:{type:"object",properties:{source:{type:"string",description:"Luau source code to execute. The code runs in a sandboxed environment with access to game services (except blocked ones). Return values are serialized and sent back as the tool result."}},required:["source"]}};var ws=[wu,Su,ku,$u,Iu,Pu,Eu,Tu,zu,Cu,ju,Ru,Ou,Du,Au,Nu,Mu,Uu,qu,Fu,Lu];var uc=Pd(rC(),1);import{randomUUID as Kr}from"crypto";import{createServer as YB}from"http";import{promises as gd}from"fs";import Db from"path";import*as gb from"path";import*as nC from"os";function Pn(){try{return gb.join(process.cwd(),"data")}catch{return gb.join(nC.homedir(),".weppy-roblox-mcp","data")}}import{createHash as RV,createHmac as OV,randomUUID as DV}from"crypto";var Pa=class extends Error{statusCode;constructor(e,r){super(e),this.name="LicenseApiError",this.statusCode=r}};function AV(t){return new Promise(e=>setTimeout(e,t))}function NV(t){return RV("sha256").update(t,"utf8").digest("hex")}function MV(t,e){return OV("sha256",t).update(e,"utf8").digest("hex")}function vb(t){let e={canUsePro:!1,status:"unlicensed",checkedAt:Math.floor(Date.now()/1e3)};if(!t||typeof t!="object")return e;let r=t,n=typeof r.status=="string"?r.status:"unlicensed",i=new Set(["active","unknown","grace","revoked","invalid","unlicensed"]),a={canUsePro:r.canUsePro===!0,status:i.has(n)?n:"unlicensed",checkedAt:typeof r.checkedAt=="number"?r.checkedAt:e.checkedAt};if(typeof r.maskedKey=="string"&&(a.maskedKey=r.maskedKey),(r.billingState==="ok"||r.billingState==="cancelled"||r.billingState==="expired"||r.billingState==="payment_failed"||r.billingState==="refunded"||r.billingState==="chargeback"||r.billingState==="unknown")&&(a.billingState=r.billingState),typeof r.reason=="string"&&(a.reason=r.reason),(r.decisionSource==="provider_live"||r.decisionSource==="provider_webhook"||r.decisionSource==="license_server_cache")&&(a.decisionSource=r.decisionSource),r.abuse&&typeof r.abuse=="object"){let o=r.abuse;(o.blocked===!0||o.blocked===!1)&&(a.abuse={blocked:o.blocked===!0},typeof o.blockedUntil=="number"&&(a.abuse.blockedUntil=o.blockedUntil),typeof o.blockReason=="string"&&(a.abuse.blockReason=o.blockReason))}return typeof r.restoreToken=="string"&&r.restoreToken.length>0&&(a.restoreToken=r.restoreToken),typeof r.lastLicenseServerSuccessAt=="number"&&(a.lastLicenseServerSuccessAt=r.lastLicenseServerSuccessAt,a.lastSuccessfulCheckAt=r.lastLicenseServerSuccessAt),typeof r.graceUntil=="number"&&(a.graceUntil=r.graceUntil,a.fallbackUntil=r.graceUntil),typeof r.lastSuccessfulCheckAt=="number"&&(a.lastSuccessfulCheckAt=r.lastSuccessfulCheckAt),typeof r.nextRecheckAt=="number"&&(a.nextRecheckAt=r.nextRecheckAt),typeof r.fallbackUntil=="number"&&(a.fallbackUntil=r.fallbackUntil),typeof a.lastSuccessfulCheckAt=="number"&&a.lastLicenseServerSuccessAt===void 0&&(a.lastLicenseServerSuccessAt=a.lastSuccessfulCheckAt),typeof a.fallbackUntil=="number"&&a.graceUntil===void 0&&(a.graceUntil=a.fallbackUntil),a}var Kp=class{config;constructor(e){this.config=e}isConfigured(){return this.config.baseUrl.length>0&&this.config.projectId.length>0&&this.config.provider.length>0&&this.config.mcpVersion.length>0&&this.config.sharedSecret.length>0}getActionPath(e,r){let n=encodeURIComponent(this.config.projectId),i=encodeURIComponent(e);return`/v1/projects/${n}/providers/${i}/license/${r}`}async signedRequest(e,r,n){let i=JSON.stringify(n),a=Math.floor(Date.now()/1e3).toString(),o=DV(),s=NV(i),c=new URL(r,this.config.baseUrl),l=`${c.pathname}${c.search}`,u=`${e}
|
|
100
|
+
`}var _u=class{constructor(e=t$.stdin,r=t$.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new bu,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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(r=>{let n=e$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var wu={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.'},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."}},required:["action"]}};var Su={name:"mutate_instances",description:"Create, delete, clone, move, rename, or pivot instances. [PRO] create_tree, mass_create, mass_delete, mass_duplicate, smart_duplicate.",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"],description:"Mutation action. Basic: create, create_with_props, delete, clone, move, rename, pivot. [PRO]: create_tree, mass_create, mass_delete, mass_duplicate, smart_duplicate."},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."},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.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},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.",items:{type:"number"},minItems:12,maxItems:12},offset:{type:"object",description:"Relative offset to move by (ignores position/cframe). Used by: pivot, smart_duplicate.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},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",properties:{className:{type:"string"},name:{type:"string"},parentPath:{type:"string"},properties:{type:"object",additionalProperties:!0}},required:["className","name","parentPath"]}},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."},spacing:{type:"object",description:"[PRO] Spacing between duplicated instances. Used by: smart_duplicate. Alias for offset.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}},required:["action"]}};var ku={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."},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",enum:["add","subtract","multiply","divide"],description:"[PRO] Mathematical operation for relative property change. Used by: set_relative."},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."}},required:["action"]}};var $u={name:"manage_scripts",description:"Manage script source code: read, write, create, delete, edit lines, search. [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","get_dependencies","replace"],description:"Script action. Basic: get_source, set_source, create, delete, edit_replace, edit_insert, edit_delete, search, get_dependencies. [PRO]: replace."},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."},source:{type:"string",description:"Script source code. Used by: set_source (required), create (optional initial source)."},scriptType:{type:"string",enum:["Script","LocalScript","ModuleScript"],description:"Type of script to create. Used by: create."},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: edit_replace, edit_delete."},endLine:{type:"number",description:"Ending line number, 1-based inclusive. Used by: edit_replace, edit_delete."},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."}},required:["action"]}};var Iu={name:"manage_lighting",description:"[PRO] Configure environment: lighting, atmosphere, sky, terrain properties, time of day.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["lighting","atmosphere","sky","terrain_props","time"],description:"[PRO] Environment action. lighting: set Lighting service properties. atmosphere: set Atmosphere properties. sky: set Sky properties. terrain_props: set Terrain water/visual properties. time: set time of day."},properties:{type:"object",description:"Dictionary of properties to set. Used by: lighting, atmosphere, sky, terrain_props. Supports Color3 {r,g,b} (0-255), numbers, booleans, Enum strings.",additionalProperties:!0},createIfMissing:{type:"boolean",description:"Create Atmosphere/Sky instance if missing. Used by: atmosphere, sky. Default: true."},time:{type:"string",description:'Time string in "HH:MM:SS" format (e.g., "14:30:00"). Used by: time. Provide this OR clockTime.'},clockTime:{type:"number",description:"Numeric time in 24-hour format (e.g., 14.5 for 2:30 PM). Used by: time. Provide this OR time."}},required:["action"]}};var Pu={name:"manage_selection",description:"Get, set, or clear selection. [PRO] context, details, add/remove items, watch changes.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set","clear","cached","context","details","add","remove","watch"],description:"Selection action. Basic: get (current selection), set (replace selection), clear (deselect all), cached (from cache without round-trip). [PRO]: context (detailed with source/properties), details (hierarchical with ancestors/descendants), add (add to selection), remove (remove from selection), watch (monitor changes)."},paths:{type:"array",description:"Array of instance paths. Used by: set (required), add (required), remove (required).",items:{type:"string"}},maxAge:{type:"number",description:"Maximum age of cached data in milliseconds. Used by: cached. Default: 30000. Set to 0 for any age."},maxDepth:{type:"number",description:"[PRO] Maximum depth for descendant tree traversal. Used by: details. Default: 1."},includeSource:{type:"boolean",description:"[PRO] Include script source code. Used by: context. Default: true."},includeProperties:{type:"boolean",description:"[PRO] Include all readable properties. Used by: context. Default: true."},includeChildren:{type:"boolean",description:"[PRO] Include immediate children. Used by: context. Default: false."},includeAncestors:{type:"boolean",description:"[PRO] Include full ancestor chain. Used by: details. Default: false."}},required:["action"]}};var Eu={name:"manage_camera",description:"Camera operations: get info, focus on instance by path or position, get suggested view.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["info","focus_path","focus_position","suggest"],description:"Camera action. info: get current camera position, rotation, FOV, viewport size. focus_path: move camera to focus on instance by path. focus_position: move camera to focus on world position. suggest: get suggested camera view for a target."},path:{type:"string",description:"Instance path to focus on. Used by: focus_path (if not provided, focuses on selection), suggest (if not provided, uses selection)."},position:{type:"object",description:"World position to focus on as Vector3. Used by: focus_position (required).",properties:{x:{type:"number",description:"X coordinate"},y:{type:"number",description:"Y coordinate"},z:{type:"number",description:"Z coordinate"}},required:["x","y","z"]},distance:{type:"number",description:"Distance from target in studs. Used by: focus_path, focus_position. Auto-calculated if not provided."},duration:{type:"number",description:"Animation duration in seconds. Used by: focus_path, focus_position. Default: 0.5."},offset:{type:"object",description:"Camera offset direction from target (normalized and scaled by distance). Used by: focus_path, focus_position. Default: {x:1, y:0.5, z:1}.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},lookAt:{type:"object",description:"Point for camera to look at. Used by: focus_position.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},respectAutoFocusSetting:{type:"boolean",description:"If true, only focus when plugin Auto Focus setting is enabled. Used by: focus_path, focus_position. Default: false."}},required:["action"]}};var Tu={name:"manage_tween",description:"[PRO] Tween service: create, play, pause, cancel tweens for smooth animations.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","play","pause","cancel"],description:"[PRO] Tween action. create: create a new tween with target properties. play: play a created tween. pause: pause a running tween. cancel: cancel a tween."},path:{type:"string",description:"Instance path to tween. Used by: create (required)."},tweenInfo:{type:"object",description:"Tween configuration. Used by: create.",properties:{time:{type:"number",description:"Duration in seconds. Default: 1."},easingStyle:{type:"string",description:'Easing style (e.g., "Linear", "Quad", "Cubic", "Sine", "Bounce", "Elastic"). Default: "Quad".'},easingDirection:{type:"string",enum:["In","Out","InOut"],description:'Easing direction. Default: "Out".'},repeatCount:{type:"number",description:"Number of times to repeat. -1 for infinite. Default: 0."},reverses:{type:"boolean",description:"Whether the tween reverses on each repeat. Default: false."},delayTime:{type:"number",description:"Delay before tween starts in seconds. Default: 0."}}},properties:{type:"object",description:"Target property values to tween to. Used by: create. Supports Vector3, Color3, numbers, etc.",additionalProperties:!0},tweenId:{type:"string",description:"Tween identifier returned by create. Used by: play, pause, cancel."}},required:["action"]}};var zu={name:"manage_audio",description:"[PRO] Audio management: play, stop, pause, resume sounds. Set audio listener.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["play","stop","pause","resume","set_listener"],description:"[PRO] Audio action. play: play a sound (creates Sound if needed). stop: stop a playing sound. pause: pause a playing sound. resume: resume a paused sound. set_listener: set the audio listener type/target."},path:{type:"string",description:"Path to the Sound instance or parent to create Sound in. Used by: play, stop, pause, resume."},soundId:{type:"string",description:'Roblox sound asset ID (e.g., "rbxassetid://1234567"). Used by: play (if creating a new Sound).'},volume:{type:"number",description:"Sound volume (0-10). Used by: play. Default: 0.5."},looped:{type:"boolean",description:"Whether the sound loops. Used by: play. Default: false."},playbackSpeed:{type:"number",description:"Playback speed multiplier. Used by: play. Default: 1."},listenerType:{type:"string",enum:["Camera","CFrame","ObjectPosition","ObjectCFrame"],description:"Listener type for SoundService. Used by: set_listener."},listenerPath:{type:"string",description:"Instance path for ObjectPosition/ObjectCFrame listener type. Used by: set_listener."}},required:["action"]}};var Cu={name:"manage_animation",description:"[PRO] Animation: load, play, stop animations. Get animation tracks from humanoid/controller.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["load","play","stop","get_tracks"],description:"[PRO] Animation action. load: load an animation on a Humanoid/AnimationController. play: play a loaded animation track. stop: stop a playing animation. get_tracks: list all loaded animation tracks."},path:{type:"string",description:"Path to the Humanoid, AnimationController, or Model containing one. Used by: load, play, stop, get_tracks."},animationId:{type:"string",description:'Roblox animation asset ID (e.g., "rbxassetid://1234567"). Used by: load.'},trackId:{type:"string",description:"Animation track identifier returned by load. Used by: play (required), stop (required)."},speed:{type:"number",description:"Playback speed multiplier. Used by: play. Default: 1."},fadeTime:{type:"number",description:"Fade time in seconds when starting/stopping. Used by: play, stop. Default: 0.1."},weight:{type:"number",description:"Animation weight (0-1) for blending. Used by: play. Default: 1."},priority:{type:"string",enum:["Core","Idle","Movement","Action","Action2","Action3","Action4"],description:"Animation priority. Used by: play."}},required:["action"]}};var ju={name:"manage_physics",description:"[PRO] Physics collision groups: register, set collidable between groups, list groups.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["register_group","set_collidable","get_groups"],description:"[PRO] Physics action. register_group: register a new collision group with PhysicsService. set_collidable: set whether two groups can collide. get_groups: list all registered collision groups."},groupName:{type:"string",description:"Collision group name. Used by: register_group (required)."},group1:{type:"string",description:"First collision group name. Used by: set_collidable (required)."},group2:{type:"string",description:"Second collision group name. Used by: set_collidable (required)."},collidable:{type:"boolean",description:"Whether the two groups can collide. Used by: set_collidable (required)."}},required:["action"]}};var Ru={name:"manage_effects",description:"[PRO] Particle effects: emit particles, clear all particles, toggle effect enabled state.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["emit","clear","toggle"],description:"[PRO] Effects action. emit: emit a burst of particles from a ParticleEmitter. clear: clear all particles from a ParticleEmitter or all emitters under an instance. toggle: enable or disable a ParticleEmitter, Beam, Trail, or other effect."},path:{type:"string",description:"Path to the effect instance (ParticleEmitter, Beam, Trail) or parent containing effects. Used by: emit, clear, toggle."},count:{type:"number",description:"Number of particles to emit in a burst. Used by: emit. Default: 16."},enabled:{type:"boolean",description:"Enable or disable the effect. Used by: toggle."}},required:["action"]}};var Ou={name:"manage_terrain",description:"[PRO] Terrain operations: fill shapes, clear regions, replace materials, manage colors, read/write voxels, generate procedural terrain, smooth terrain.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["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"],description:"[PRO] Terrain action. fill_block/fill_ball/fill_cylinder/fill_wedge: fill shapes with material. clear_region/clear_bounds: clear terrain. replace_material: swap materials in region. colors_get/colors_set: manage material colors. read_voxel: single voxel. read_voxels/write_voxels: bulk voxels. generate: procedural terrain. smooth: smooth terrain."},material:{type:"string",description:"Terrain material name (e.g., Grass, Rock, Water, Sand, Slate, Concrete). Used by: fill_*, replace_material, colors_get, colors_set."},center:{type:"object",description:"Center position as Vector3. Used by: fill_ball.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},position:{type:"object",description:"Position as Vector3. Used by: read_voxel.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},cframe:{type:"object",description:"Position and rotation for fill shapes. Used by: fill_block, fill_cylinder, fill_wedge.",properties:{position:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},rotation:{type:"object",description:"Optional rotation in degrees.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}},required:["position"]},size:{type:"object",description:"Size in studs. Used by: fill_block, fill_wedge.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},radius:{type:"number",description:"Radius in studs. Used by: fill_ball, fill_cylinder."},height:{type:"number",description:"Height in studs. Used by: fill_cylinder."},region:{type:"object",description:"Rectangular region with min/max corners. Used by: clear_region, replace_material, read_voxels, write_voxels, generate, smooth.",properties:{min:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["min","max"]},min:{type:"object",description:"Minimum corner for bounds-based clear. Used by: clear_bounds.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",description:"Maximum corner for bounds-based clear. Used by: clear_bounds.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},sourceMaterial:{type:"string",description:"Material to replace. Used by: replace_material."},targetMaterial:{type:"string",description:"Replacement material. Used by: replace_material."},color:{type:"object",description:"RGB color (0-255). Used by: colors_set.",properties:{r:{type:"number",minimum:0,maximum:255},g:{type:"number",minimum:0,maximum:255},b:{type:"number",minimum:0,maximum:255}},required:["r","g","b"]},resolution:{type:"number",description:"Voxel resolution (studs per voxel). Used by: read_voxels, write_voxels. Default: 4."},materials:{type:"array",description:"3D array of material names [x][y][z]. Used by: write_voxels.",items:{type:"array",items:{type:"array",items:{type:"string"}}}},occupancy:{type:"array",description:"3D array of occupancy values [x][y][z] (0-1). Used by: write_voxels.",items:{type:"array",items:{type:"array",items:{type:"number",minimum:0,maximum:1}}}},baseHeight:{type:"number",description:"Base terrain height in studs. Used by: generate. Default: 32."},amplitude:{type:"number",description:"Height variation amplitude in studs. Used by: generate. Default: 24."},frequency:{type:"number",description:"Noise frequency (0.001-0.1). Used by: generate. Default: 0.01.",minimum:.001,maximum:.1},seed:{type:"number",description:"Random seed for terrain generation. Used by: generate."},layers:{type:"array",description:"Material layers by height. Used by: generate. Each: {material, maxHeight}.",items:{type:"object",properties:{material:{type:"string"},maxHeight:{type:"number"}},required:["material","maxHeight"]}},intensity:{type:"number",description:"Smoothing intensity (0-1). Used by: smooth. Default: 0.5.",minimum:0,maximum:1}},required:["action"]}};var Du={name:"spatial_query",description:"[PRO] Spatial queries: raycast, find ground, check placement, multi-raycast, scan area, find flat areas, find spawn positions, analyze walkable, spatial map, find empty space, get bounds, snap to grid, check collision.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["raycast","find_ground","check_placement","multi_raycast","scan_area","find_flat","find_spawn","analyze_walkable","spatial_map","find_space","bounds","snap_grid","collision"],description:"[PRO] Spatial action. raycast: single ray. find_ground: ground below point. check_placement: collision-free placement check. multi_raycast: batch rays. scan_area: heightmap generation. find_flat: flat areas for building. find_spawn: spawn positions. analyze_walkable: walkability grid. spatial_map: all BasePart positions. find_space: empty space for object. bounds: bounding box. snap_grid: snap position to grid. collision: AABB collision check."},origin:{type:"object",description:"Ray origin as Vector3. Used by: raycast.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},direction:{type:"object",description:"Ray direction and length as Vector3. Used by: raycast.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},maxDistance:{type:"number",description:"Maximum distance for ground search. Used by: find_ground. Default: 1000."},position:{type:"object",description:"Position as Vector3. Used by: find_ground (cast from here), check_placement (center), collision (hypothetical position).",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},size:{type:"object",description:"Size as Vector3. Used by: check_placement (object size), find_space (required space size), scan_area (area X/Z dimensions).",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},filterType:{type:"string",enum:["Exclude","Include"],description:'Raycast filter type. Used by: raycast, multi_raycast. Default: "Exclude".'},filterList:{type:"array",description:"Instance paths to filter. Used by: raycast, multi_raycast, find_ground, check_placement, scan_area. Alias: filterInstances.",items:{type:"string"}},filterInstances:{type:"array",description:"Instance paths to filter (alias for filterList). Used by: raycast, multi_raycast, find_ground, check_placement, scan_area.",items:{type:"string"}},ignoreWater:{type:"boolean",description:"Ignore terrain water. Used by: raycast, multi_raycast. Default: false."},rays:{type:"array",description:"Array of ray specifications. Used by: multi_raycast. Max 50 rays.",items:{type:"object",properties:{origin:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},direction:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["origin","direction"]},maxItems:50},center:{type:"object",description:"Center point for area scan. Used by: scan_area.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},area:{type:"object",description:"Bounding box for analysis. Used by: analyze_walkable. Contains min/max.",properties:{min:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["min","max"]},searchArea:{type:"object",description:"Bounding box for search. Used by: find_flat, find_spawn, find_space.",properties:{min:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},max:{type:"object",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]}},required:["min","max"]},minSize:{type:"object",description:"Minimum flat area size. Used by: find_flat.",properties:{x:{type:"number"},z:{type:"number"}},required:["x","z"]},maxSlope:{type:"number",description:"Maximum slope in degrees. Used by: find_flat (default: 10), analyze_walkable (default: 45)."},resolution:{type:"number",description:"Grid resolution in studs. Used by: scan_area, analyze_walkable. Default: 4."},gridSize:{type:"number",description:"Grid snap size in studs. Used by: snap_grid (default: 4), find_space (default: 4)."},path:{type:"string",description:"Instance path. Used by: bounds (optional), snap_grid (required), collision (required), spatial_map (rootPath alias)."},paths:{type:"array",description:"Multiple instance paths for batch bounds. Used by: bounds.",items:{type:"string"}},tolerance:{type:"number",description:"Height variation tolerance in studs. Used by: find_flat."},gridSnap:{type:"number",description:"Grid snap size. Alias for gridSize."},axes:{type:"array",description:'Axes to snap. Used by: snap_grid. Default: ["x","y","z"]. Use ["x","z"] for horizontal only.',items:{type:"string",enum:["x","y","z"]}},ignorePaths:{type:"array",description:"Instance paths to ignore in collision check. Used by: collision.",items:{type:"string"}},offset:{type:"number",description:"Vertical offset for ground position. Used by: find_ground. Default: 0."},rotation:{type:"object",description:"Rotation in degrees. Used by: check_placement.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},checkGround:{type:"boolean",description:"Verify ground support for placement. Used by: check_placement. Default: true."},spawnSize:{type:"object",description:"Size of spawning entity. Used by: find_spawn. Default: {x:4, y:5, z:4}.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},minSpacing:{type:"number",description:"Minimum distance between spawn positions. Used by: find_spawn. Default: 10."},preferOutdoor:{type:"boolean",description:"Prefer open sky positions. Used by: find_spawn. Default: false."},count:{type:"number",description:"Number of results to find. Used by: find_spawn. Default: 10."},characterHeight:{type:"number",description:"Character height for clearance checks. Used by: analyze_walkable. Default: 5."},maxStepHeight:{type:"number",description:"Maximum step height. Used by: analyze_walkable. Default: 2."},rootPath:{type:"string",description:'Root path for spatial map scan. Used by: spatial_map. Default: "game.Workspace".'},includeModels:{type:"boolean",description:"Include Model bounding boxes. Used by: spatial_map. Default: true."},maxResults:{type:"number",description:"Maximum results. Used by: spatial_map (default: 500), scan_area (default: 500), find_flat (default: 10)."},padding:{type:"number",description:"Minimum distance from other objects. Used by: find_space. Default: 1."}},required:["action"]}};var Au={name:"manage_assets",description:"[PRO] Asset management: insert models by ID, get asset info, search creator store, insert free models/packages, export selection.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["insert","info","search","search_insert","insert_free","insert_package","export"],description:"[PRO] Asset action. insert: insert model by asset ID. info: get asset metadata. search: search Creator Store. search_insert: search and insert first match. insert_free: insert free model. insert_package: insert package. export: export current selection."},assetId:{type:"number",description:"Roblox asset ID. Used by: insert (required), info (required), insert_free (required), insert_package (required)."},parent:{type:"string",description:'Parent path for inserted asset. Used by: insert, search_insert, insert_free, insert_package. Default: "game.Workspace".'},name:{type:"string",description:"Optional name for inserted instance."},position:{type:"object",description:"Position to place the model. Used by: insert, insert_free.",properties:{x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["x","y","z"]},query:{type:"string",description:'Search keyword. Used by: search (required), search_insert (required). E.g., "monster", "tree", "car".'},maxResults:{type:"number",description:"Maximum search results. Used by: search. Default: 10."},category:{type:"string",description:"Asset category filter. Used by: search."},sortType:{type:"string",description:"Sort order for search results. Used by: search."},format:{type:"string",description:"Export format. Used by: export."},includeProperties:{type:"boolean",description:"Include all properties in export. Used by: export. Default: false."},includeChildren:{type:"boolean",description:"Include children in export. Used by: export. Default: false."},maxDepth:{type:"number",description:"Maximum depth for recursive child export. Used by: export. Default: 5."}},required:["action"]}};var Nu={name:"manage_sync",description:"[PRO] Project sync management: status, config, history, direction settings, read/write synced files.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","config","history","directions","read_file","write_file","progress"],description:"[PRO] Sync action. status: get sync status for a place. config: get sync configuration. history: get change history. directions: get per-type sync directions. read_file: read a synced file. write_file: write to a synced file. progress: get real-time sync progress and bandwidth."},placeId:{type:"number",description:"Place ID for sync operations. Used by: status, config, history, directions."},instancePath:{type:"string",description:"Instance path for file read/write. Used by: read_file, write_file."},content:{type:"string",description:"File content to write. Used by: write_file."},query:{type:"object",description:"Query parameters for history. Used by: history.",properties:{limit:{type:"number",description:"Maximum entries to return."},offset:{type:"number",description:"Number of entries to skip."}}}},required:["action"]}};var Mu={name:"workspace_state",description:"[PRO] Workspace state: full sync, snapshot, recent changes, viewport info.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["sync","snapshot","changes","viewport"],description:"[PRO] State action. sync: fetch current Workspace state (hierarchy, history, stats). snapshot: get full instance tree structure. changes: get recent changes (added/removed/modified). viewport: get camera position, FOV, viewport size, selection bounds."},includeMetadata:{type:"boolean",description:"Include metadata (instance counts, timestamps). Used by: sync. Default: true."},limit:{type:"number",description:"Maximum number of changes to return. Used by: changes. Default: 20."},includeCameraInfo:{type:"boolean",description:"Include camera position and settings. Used by: viewport. Default: true."},includeSelectionBounds:{type:"boolean",description:"Include current selection bounds info. Used by: viewport. Default: true."}},required:["action"]}};var Uu={name:"manage_logs",description:"Output logs: get filtered logs, clear buffer, get recent errors.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","clear","errors"],description:"Log action. get: retrieve logs with optional type/limit/since filter. clear: clear internal log buffer. errors: quick access to recent errors only."},level:{type:"string",enum:["all","error","warning","info"],description:'Log level filter. Used by: get. Default: "all".'},limit:{type:"number",description:"Maximum entries to return. Used by: get (default: 100, max: 500), errors (default: 20, max: 100)."},pattern:{type:"string",description:"Text pattern to filter log messages. Used by: get."},since:{type:"number",description:"Unix timestamp in milliseconds. Only logs after this time. Used by: get."}},required:["action"]}};var qu={name:"system_info",description:"System info: ping, connection status, usage tier. [PRO] place info, services list, studio settings.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["ping","connection","usage","place_info","services","studio_settings"],description:"System action. Basic: ping (test connection, returns pong), connection (server/plugin connection info with session IDs), usage (current tier: basic/pro). [PRO]: place_info (place ID, name, game ID, creator), services (list all Roblox services), studio_settings (Studio preferences)."},message:{type:"string",description:"Optional message to echo back. Used by: ping."}},required:["action"]}};var Fu={name:"batch_execute",description:'[PRO] Execute multiple commands in a single batch. Each command is an object with "tool" name and "args". Commands execute sequentially; optionally continue on error.',inputSchema:{type:"object",properties:{commands:{type:"array",description:"Array of commands to execute sequentially. Each command specifies a tool name and its arguments.",items:{type:"object",properties:{tool:{type:"string",description:'Tool name to invoke (e.g., "mutate_instances", "manage_properties").'},args:{type:"object",description:"Arguments to pass to the tool, including action and other parameters.",additionalProperties:!0}},required:["tool","args"]}},stopOnError:{type:"boolean",description:"If true, stop executing remaining commands when one fails. Default: true."}},required:["commands"]}};var Lu={name:"execute_luau",description:"[PRO] Execute arbitrary Luau code in Roblox Studio sandbox. Blocked services: HttpService, DataStoreService, MessagingService. Cannot access CoreGui/CorePackages.",inputSchema:{type:"object",properties:{source:{type:"string",description:"Luau source code to execute. The code runs in a sandboxed environment with access to game services (except blocked ones). Return values are serialized and sent back as the tool result."}},required:["source"]}};var ws=[wu,Su,ku,$u,Iu,Pu,Eu,Tu,zu,Cu,ju,Ru,Ou,Du,Au,Nu,Mu,Uu,qu,Fu,Lu];var uc=Pd(rC(),1);import{randomUUID as Kr}from"crypto";import{createServer as YB}from"http";import{promises as gd}from"fs";import Db from"path";import*as gb from"path";import*as nC from"os";function Pn(){try{return gb.join(process.cwd(),"data")}catch{return gb.join(nC.homedir(),".weppy-roblox-mcp","data")}}import{createHash as RV,createHmac as OV,randomUUID as DV}from"crypto";var Pa=class extends Error{statusCode;constructor(e,r){super(e),this.name="LicenseApiError",this.statusCode=r}};function AV(t){return new Promise(e=>setTimeout(e,t))}function NV(t){return RV("sha256").update(t,"utf8").digest("hex")}function MV(t,e){return OV("sha256",t).update(e,"utf8").digest("hex")}function vb(t){let e={canUsePro:!1,status:"unlicensed",checkedAt:Math.floor(Date.now()/1e3)};if(!t||typeof t!="object")return e;let r=t,n=typeof r.status=="string"?r.status:"unlicensed",i=new Set(["active","unknown","grace","revoked","invalid","unlicensed"]),a={canUsePro:r.canUsePro===!0,status:i.has(n)?n:"unlicensed",checkedAt:typeof r.checkedAt=="number"?r.checkedAt:e.checkedAt};if(typeof r.maskedKey=="string"&&(a.maskedKey=r.maskedKey),(r.billingState==="ok"||r.billingState==="cancelled"||r.billingState==="expired"||r.billingState==="payment_failed"||r.billingState==="refunded"||r.billingState==="chargeback"||r.billingState==="unknown")&&(a.billingState=r.billingState),typeof r.reason=="string"&&(a.reason=r.reason),(r.decisionSource==="provider_live"||r.decisionSource==="provider_webhook"||r.decisionSource==="license_server_cache")&&(a.decisionSource=r.decisionSource),r.abuse&&typeof r.abuse=="object"){let o=r.abuse;(o.blocked===!0||o.blocked===!1)&&(a.abuse={blocked:o.blocked===!0},typeof o.blockedUntil=="number"&&(a.abuse.blockedUntil=o.blockedUntil),typeof o.blockReason=="string"&&(a.abuse.blockReason=o.blockReason))}return typeof r.restoreToken=="string"&&r.restoreToken.length>0&&(a.restoreToken=r.restoreToken),typeof r.lastLicenseServerSuccessAt=="number"&&(a.lastLicenseServerSuccessAt=r.lastLicenseServerSuccessAt,a.lastSuccessfulCheckAt=r.lastLicenseServerSuccessAt),typeof r.graceUntil=="number"&&(a.graceUntil=r.graceUntil,a.fallbackUntil=r.graceUntil),typeof r.lastSuccessfulCheckAt=="number"&&(a.lastSuccessfulCheckAt=r.lastSuccessfulCheckAt),typeof r.nextRecheckAt=="number"&&(a.nextRecheckAt=r.nextRecheckAt),typeof r.fallbackUntil=="number"&&(a.fallbackUntil=r.fallbackUntil),typeof a.lastSuccessfulCheckAt=="number"&&a.lastLicenseServerSuccessAt===void 0&&(a.lastLicenseServerSuccessAt=a.lastSuccessfulCheckAt),typeof a.fallbackUntil=="number"&&a.graceUntil===void 0&&(a.graceUntil=a.fallbackUntil),a}var Kp=class{config;constructor(e){this.config=e}isConfigured(){return this.config.baseUrl.length>0&&this.config.projectId.length>0&&this.config.provider.length>0&&this.config.mcpVersion.length>0&&this.config.sharedSecret.length>0}getActionPath(e,r){let n=encodeURIComponent(this.config.projectId),i=encodeURIComponent(e);return`/v1/projects/${n}/providers/${i}/license/${r}`}async signedRequest(e,r,n){let i=JSON.stringify(n),a=Math.floor(Date.now()/1e3).toString(),o=DV(),s=NV(i),c=new URL(r,this.config.baseUrl),l=`${c.pathname}${c.search}`,u=`${e}
|
|
101
101
|
${l}
|
|
102
102
|
${a}
|
|
103
103
|
${o}
|
|
@@ -106,7 +106,7 @@ ${s}`,p=MV(this.config.sharedSecret,u),d={"content-type":"application/json","x-w
|
|
|
106
106
|
Stack: ${e.stack}`;if(typeof e=="object")try{return`
|
|
107
107
|
`+JSON.stringify(e,null,2).replace(/\n/g,`
|
|
108
108
|
`)}catch{return`
|
|
109
|
-
[Circular or non-serializable object]`}return` ${String(e)}`}static log(e,r,n){if(!this.shouldLog(e))return;let i=this.getTimestamp(),a=Yp[e],o=this.formatData(n),s=`${Yp.gray}[${i}]${Yp.reset} ${a}[${e.toUpperCase()}]${Yp.reset} ${r}${o}`;console.error(s)}static debug(e,r){this.log("debug",e,r)}static info(e,r){this.log("info",e,r)}static warn(e,r){this.log("warn",e,r)}static error(e,r){this.log("error",e,r)}},y=yb;var Le="1.2.1";import X from"path";import{randomUUID as qC}from"crypto";import{promises as pe}from"fs";var Ea=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,aC=new Set,xb=typeof process=="object"&&process?process:{},oC=(t,e,r,n)=>{typeof xb.emitWarning=="function"?xb.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Qp=globalThis.AbortController,iC=globalThis.AbortSignal;if(typeof Qp>"u"){iC=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Qp=class{constructor(){e()}signal=new iC;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=xb.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,oC("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 UV=t=>!aC.has(t),fce=Symbol("type"),En=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),sC=t=>En(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ta:null:null,Ta=class extends Array{constructor(e){super(e),this.fill(0)}},bb=class t{heap;length;static#c=!1;static create(e){let r=sC(e);if(!r)return[];t.#c=!0;let n=new t(e,r);return t.#c=!1,n}constructor(e,r){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},ed=class t{#c;#p;#h;#g;#z;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#v;#n;#r;#e;#l;#d;#s;#a;#y;#o;#x;#b;#f;#_;#I;#u;static unsafeExposeInternals(e){return{starts:e.#b,ttls:e.#f,sizes:e.#x,keyMap:e.#n,keyList:e.#r,valList:e.#e,next:e.#l,prev:e.#d,get head(){return e.#s},get tail(){return e.#a},free:e.#y,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,a)=>e.#O(r,n,i,a),moveToTail:r=>e.#T(r),indexes:r=>e.#w(r),rindexes:r=>e.#S(r),isStale:r=>e.#m(r)}}get max(){return this.#c}get maxSize(){return this.#p}get calculatedSize(){return this.#v}get size(){return this.#i}get fetchMethod(){return this.#z}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#g}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:d,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:x,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:_,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:$,ignoreFetchAbort:D}=e;if(r!==0&&!En(r))throw new TypeError("max option must be a nonnegative integer");let Z=r?sC(r):Array;if(!Z)throw new Error("invalid max value: "+r);if(this.#c=r,this.#p=f,this.maxEntrySize=m||this.#p,this.sizeCalculation=h,this.sizeCalculation){if(!this.#p&&!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(x!==void 0&&typeof x!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=x,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#z=g,this.#I=!!g,this.#n=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#l=new Z(r),this.#d=new Z(r),this.#s=0,this.#a=0,this.#y=bb.create(r),this.#i=0,this.#v=0,typeof l=="function"&&(this.#h=l),typeof u=="function"?(this.#g=u,this.#o=[]):(this.#g=void 0,this.#o=void 0),this.#_=!!this.#h,this.#u=!!this.#g,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!D,this.maxEntrySize!==0){if(this.#p!==0&&!En(this.#p))throw new TypeError("maxSize must be a positive integer if specified");if(!En(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!_,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=En(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!En(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#c===0&&this.ttl===0&&this.#p===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#p){let ge="LRU_CACHE_UNBOUNDED";UV(ge)&&(aC.add(ge),oC("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ge,t))}}getRemainingTTL(e){return this.#n.has(e)?1/0:0}#D(){let e=new Ta(this.#c),r=new Ta(this.#c);this.#f=e,this.#b=r,this.#A=(a,o,s=Ea.now())=>{if(r[a]=o!==0?s:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(a)&&this.#k(this.#r[a],"expire")},o+1);c.unref&&c.unref()}},this.#P=a=>{r[a]=e[a]!==0?Ea.now():0},this.#$=(a,o)=>{if(e[o]){let s=e[o],c=r[o];if(!s||!c)return;a.ttl=s,a.start=c,a.now=n||i();let l=a.now-c;a.remainingTTL=s-l}};let n=0,i=()=>{let a=Ea.now();if(this.ttlResolution>0){n=a;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#n.get(a);if(o===void 0)return 0;let s=e[o],c=r[o];if(!s||!c)return 1/0;let l=(n||i())-c;return s-l},this.#m=a=>{let o=r[a],s=e[a];return!!s&&!!o&&(n||i())-o>s}}#P=()=>{};#$=()=>{};#A=()=>{};#m=()=>!1;#F(){let e=new Ta(this.#c);this.#v=0,this.#x=e,this.#E=r=>{this.#v-=e[r],e[r]=0},this.#N=(r,n,i,a)=>{if(this.#t(n))return 0;if(!En(i))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(i=a(n,r),!En(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.#j=(r,n,i)=>{if(e[r]=n,this.#p){let a=this.#p-e[r];for(;this.#v>a;)this.#R(!0)}this.#v+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#v)}}#E=e=>{};#j=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#w({allowStale:e=this.allowStale}={}){if(this.#i)for(let r=this.#a;!(!this.#M(r)||((e||!this.#m(r))&&(yield r),r===this.#s));)r=this.#d[r]}*#S({allowStale:e=this.allowStale}={}){if(this.#i)for(let r=this.#s;!(!this.#M(r)||((e||!this.#m(r))&&(yield r),r===this.#a));)r=this.#l[r]}#M(e){return e!==void 0&&this.#n.get(this.#r[e])===e}*entries(){for(let e of this.#w())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#w()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#S()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#w())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let n of this.#w()){let i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;if(a!==void 0&&e(a,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#w()){let i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;a!==void 0&&e.call(r,a,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#S()){let i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;a!==void 0&&e.call(r,a,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#S({allowStale:!0}))this.#m(r)&&(this.#k(this.#r[r],"expire"),e=!0);return e}info(e){let r=this.#n.get(e);if(r===void 0)return;let n=this.#e[r],i=this.#t(n)?n.__staleWhileFetching:n;if(i===void 0)return;let a={value:i};if(this.#f&&this.#b){let o=this.#f[r],s=this.#b[r];if(o&&s){let c=o-(Ea.now()-s);a.ttl=c,a.start=Date.now()}}return this.#x&&(a.size=this.#x[r]),a}dump(){let e=[];for(let r of this.#w({allowStale:!0})){let n=this.#r[r],i=this.#e[r],a=this.#t(i)?i.__staleWhileFetching:i;if(a===void 0||n===void 0)continue;let o={value:a};if(this.#f&&this.#b){o.ttl=this.#f[r];let s=Ea.now()-this.#b[r];o.start=Math.floor(Date.now()-s)}this.#x&&(o.size=this.#x[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ea.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#N(e,r,n.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let p=this.#i===0?void 0:this.#n.get(e);if(p===void 0)p=this.#i===0?this.#a:this.#y.length!==0?this.#y.pop():this.#i===this.#c?this.#R(!1):this.#i,this.#r[p]=e,this.#e[p]=r,this.#n.set(e,p),this.#l[this.#a]=p,this.#d[p]=this.#a,this.#a=p,this.#i++,this.#j(p,u,c),c&&(c.set="add"),l=!1;else{this.#T(p);let d=this.#e[p];if(r!==d){if(this.#I&&this.#t(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!o&&(this.#_&&this.#h?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"]))}else o||(this.#_&&this.#h?.(d,e,"set"),this.#u&&this.#o?.push([d,e,"set"]));if(this.#E(p),this.#j(p,u,c),this.#e[p]=r,c){c.set="replace";let f=d&&this.#t(d)?d.__staleWhileFetching:d;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(i!==0&&!this.#f&&this.#D(),this.#f&&(l||this.#A(p,i,a),c&&this.#$(c,p)),!o&&this.#u&&this.#o){let d=this.#o,f;for(;f=d?.shift();)this.#g?.(...f)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#s];if(this.#R(!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,r;for(;r=e?.shift();)this.#g?.(...r)}}}#R(e){let r=this.#s,n=this.#r[r],i=this.#e[r];return this.#I&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#h?.(i,n,"evict"),this.#u&&this.#o?.push([i,n,"evict"])),this.#E(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#y.push(r)),this.#i===1?(this.#s=this.#a=0,this.#y.length=0):this.#s=this.#l[r],this.#n.delete(n),this.#i--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,a=this.#n.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.#$(i,a));else return n&&this.#P(a),i&&(i.has="hit",this.#$(i,a)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#n.get(e);if(i===void 0||!n&&this.#m(i))return;let a=this.#e[i];return this.#t(a)?a.__staleWhileFetching:a}#O(e,r,n,i){let a=r===void 0?void 0:this.#e[r];if(this.#t(a))return a;let o=new Qp,{signal:s}=n;s?.addEventListener("abort",()=>o.abort(s.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:i},l=(h,g=!1)=>{let{aborted:x}=o.signal,S=n.ignoreFetchAbort&&h!==void 0;if(n.status&&(x&&!g?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,S&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),x&&!S&&!g)return p(o.signal.reason);let _=f;return this.#e[r]===f&&(h===void 0?_.__staleWhileFetching?this.#e[r]=_.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,h,c.options))),h},u=h=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=h),p(h)),p=h=>{let{aborted:g}=o.signal,x=g&&n.allowStaleOnFetchAbort,S=x||n.allowStaleOnFetchRejection,_=S||n.noDeleteOnFetchRejection,k=f;if(this.#e[r]===f&&(!_||k.__staleWhileFetching===void 0?this.#k(e,"fetch"):x||(this.#e[r]=k.__staleWhileFetching)),S)return n.status&&k.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),k.__staleWhileFetching;if(k.__returned===k)throw h},d=(h,g)=>{let x=this.#z?.(e,a,c);x&&x instanceof Promise&&x.then(S=>h(S===void 0?void 0:S),g),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(h(void 0),n.allowStaleOnFetchAbort&&(h=S=>l(S,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(l,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return r===void 0?(this.set(e,m,{...c.options,status:void 0}),r=this.#n.get(e)):this.#e[r]=m,m}#t(e){if(!this.#I)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Qp}async fetch(e,r={}){let{allowStale:n=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:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:x,signal:S}=r;if(!this.#I)return x&&(x.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,status:x});let _={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:s,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:x,signal:S},k=this.#n.get(e);if(k===void 0){x&&(x.fetch="miss");let $=this.#O(e,k,_,h);return $.__returned=$}else{let $=this.#e[k];if(this.#t($)){let Ze=n&&$.__staleWhileFetching!==void 0;return x&&(x.fetch="inflight",Ze&&(x.returnedStale=!0)),Ze?$.__staleWhileFetching:$.__returned=$}let D=this.#m(k);if(!g&&!D)return x&&(x.fetch="hit"),this.#T(k),i&&this.#P(k),x&&this.#$(x,k),$;let Z=this.#O(e,k,_,h),Be=Z.__staleWhileFetching!==void 0&&n;return x&&(x.fetch=D?"stale":"refresh",Be&&D&&(x.returnedStale=!0)),Be?Z.__staleWhileFetching:Z.__returned=Z}}async forceFetch(e,r={}){let n=await this.fetch(e,r);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,r={}){let n=this.#C;if(!n)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:a,...o}=r,s=this.get(e,o);if(!a&&s!==void 0)return s;let c=n(e,s,{options:o,context:i});return this.set(e,c,o),c}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=r,s=this.#n.get(e);if(s!==void 0){let c=this.#e[s],l=this.#t(c);return o&&this.#$(o,s),this.#m(s)?(o&&(o.get="stale"),l?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(a||this.#k(e,"expire"),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),l?c.__staleWhileFetching:(this.#T(s),i&&this.#P(s),c))}else o&&(o.get="miss")}#U(e,r){this.#d[r]=e,this.#l[e]=r}#T(e){e!==this.#a&&(e===this.#s?this.#s=this.#l[e]:this.#U(this.#d[e],this.#l[e]),this.#U(this.#a,e),this.#a=e)}delete(e){return this.#k(e,"delete")}#k(e,r){let n=!1;if(this.#i!==0){let i=this.#n.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.#q(r);else{this.#E(i);let a=this.#e[i];if(this.#t(a)?a.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#h?.(a,e,r),this.#u&&this.#o?.push([a,e,r])),this.#n.delete(e),this.#r[i]=void 0,this.#e[i]=void 0,i===this.#a)this.#a=this.#d[i];else if(i===this.#s)this.#s=this.#l[i];else{let o=this.#d[i];this.#l[o]=this.#l[i];let s=this.#l[i];this.#d[s]=this.#d[i]}this.#i--,this.#y.push(i)}}if(this.#u&&this.#o?.length){let i=this.#o,a;for(;a=i?.shift();)this.#g?.(...a)}return n}clear(){return this.#q("delete")}#q(e){for(let r of this.#S({allowStale:!0})){let n=this.#e[r];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#r[r];this.#_&&this.#h?.(n,i,e),this.#u&&this.#o?.push([n,i,e])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#b&&(this.#f.fill(0),this.#b.fill(0)),this.#x&&this.#x.fill(0),this.#s=0,this.#a=0,this.#y.length=0,this.#v=0,this.#i=0,this.#u&&this.#o){let r=this.#o,n;for(;n=r?.shift();)this.#g?.(...n)}}};import je from"path";import{promises as Et}from"fs";var qV=["CoreGui","CorePackages","RobloxScript","RobloxScriptSecurity"],FV=["Workspace","Lighting","ReplicatedStorage","ServerStorage","ServerScriptService","StarterGui","StarterPlayer","StarterPack","ReplicatedFirst","SoundService","Chat","LocalizationService"];function cC(t){let e=t.replace(/[^a-zA-Z0-9-]/g,"_");return e=e.replace(/_+/g,"_"),e=e.replace(/^_|_$/g,""),e=e.slice(0,40),e=e.replace(/_$/g,""),e}function LV(t){let e=je.join(t,"roblox-project-sync");return{syncRoot:e,explorerRoot:je.join(e,"explorer"),excludePatterns:["*.Terrain","*.Camera"],excludeClasses:["Terrain","Camera"],propertyMode:"standard",maxDepth:20,maxInstances:25e3,directorySizeWarning:500*1024*1024,directorySizeLimit:1024*1024*1024,reverseSyncMode:"manual"}}var td=class{config;placeRootCache=new Map;async backupAndDeletePlaceDir(e,r){let n=this.config.syncRoot,i=new Date().toISOString().replace(/[:.]/g,"-"),a=je.join(n,"_deleted-place-backups",`place_${e}`),o=je.join(n,r),s=`${i}_${r}`,c=je.join(a,s);await Et.mkdir(a,{recursive:!0}),await Et.cp(o,c,{recursive:!0,force:!0}),await Et.rm(o,{recursive:!0,force:!0}),y.info("Backed up and deleted duplicate place directory",{placeId:e,from:r,backupTo:je.relative(n,c)})}constructor(e){this.config=LV(e??process.cwd())}getConfig(){return{...this.config}}getSyncRoot(){return this.config.syncRoot}getPlaceRoot(e){let r=this.placeRootCache.get(e);return r?je.join(this.config.syncRoot,r):je.join(this.config.syncRoot,`place_${e}`)}async resolvePlaceRoot(e,r){let n=this.config.syncRoot,i=`place_${e}`,a=r?cC(r):"",o=a?`${i}_${a}`:i;await Et.mkdir(n,{recursive:!0});let s=new RegExp(`^place_${e}(?:_.*)?$`),c=async()=>(await Et.readdir(n,{withFileTypes:!0})).filter(m=>m.isDirectory()&&s.test(m.name)).map(m=>m.name).sort(),l=await c(),u=a?o:this.placeRootCache.get(e)&&s.test(this.placeRootCache.get(e))?this.placeRootCache.get(e):l[0]??o;if(l.length>0&&!l.includes(u)){let f=l[0],m=je.join(n,f),h=je.join(n,u);try{await Et.rename(m,h),y.info("Migrated place directory",{from:f,to:u})}catch(g){y.warn("Failed to migrate place directory, using existing",{from:f,to:u,error:g instanceof Error?g.message:String(g)}),u=f}}let p=je.join(n,u);await Et.mkdir(p,{recursive:!0}),l=await c();let d=l.filter(f=>f!==u);for(let f of d)try{await this.backupAndDeletePlaceDir(e,f)}catch(m){y.warn("Failed to backup/delete duplicate place directory",{placeId:e,duplicate:f,error:m instanceof Error?m.message:String(m)})}return this.placeRootCache.set(e,u),p}async promotePlaceRoot(e,r,n){let i=this.config.syncRoot,a=n?cC(n):"",o=a?`place_${r}_${a}`:`place_${r}`,s=null;try{let p=await Et.readdir(i,{withFileTypes:!0}),d=new RegExp(`^place_${e}(?:_.*)?$`);for(let f of p)if(f.isDirectory()&&d.test(f.name)){s=f.name;break}}catch{}if(!s)return y.info("No existing directory for place promotion, creating new",{oldId:e,newId:r}),this.resolvePlaceRoot(r,n);let c=je.join(i,s),l=je.join(i,o);try{await Et.rename(c,l),y.info("Place directory promoted",{from:s,to:o})}catch(p){return y.warn("Failed to rename place directory during promotion, creating new",{from:s,to:o,error:p instanceof Error?p.message:String(p)}),this.placeRootCache.delete(e),this.resolvePlaceRoot(r,n)}this.placeRootCache.delete(e),this.placeRootCache.set(r,o);let u=je.join(l,".sync-meta.json");try{let p=await Et.readFile(u,"utf-8"),d=JSON.parse(p);d.placeId=r,n&&(d.placeName=n),await Et.writeFile(u,JSON.stringify(d,null,2)+`
|
|
109
|
+
[Circular or non-serializable object]`}return` ${String(e)}`}static log(e,r,n){if(!this.shouldLog(e))return;let i=this.getTimestamp(),a=Yp[e],o=this.formatData(n),s=`${Yp.gray}[${i}]${Yp.reset} ${a}[${e.toUpperCase()}]${Yp.reset} ${r}${o}`;console.error(s)}static debug(e,r){this.log("debug",e,r)}static info(e,r){this.log("info",e,r)}static warn(e,r){this.log("warn",e,r)}static error(e,r){this.log("error",e,r)}},y=yb;var Le="1.2.2";import X from"path";import{randomUUID as qC}from"crypto";import{promises as pe}from"fs";var Ea=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,aC=new Set,xb=typeof process=="object"&&process?process:{},oC=(t,e,r,n)=>{typeof xb.emitWarning=="function"?xb.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Qp=globalThis.AbortController,iC=globalThis.AbortSignal;if(typeof Qp>"u"){iC=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Qp=class{constructor(){e()}signal=new iC;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=xb.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,oC("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 UV=t=>!aC.has(t),fce=Symbol("type"),En=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),sC=t=>En(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ta:null:null,Ta=class extends Array{constructor(e){super(e),this.fill(0)}},bb=class t{heap;length;static#c=!1;static create(e){let r=sC(e);if(!r)return[];t.#c=!0;let n=new t(e,r);return t.#c=!1,n}constructor(e,r){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},ed=class t{#c;#p;#h;#g;#z;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#v;#n;#r;#e;#l;#d;#s;#a;#y;#o;#x;#b;#f;#_;#I;#u;static unsafeExposeInternals(e){return{starts:e.#b,ttls:e.#f,sizes:e.#x,keyMap:e.#n,keyList:e.#r,valList:e.#e,next:e.#l,prev:e.#d,get head(){return e.#s},get tail(){return e.#a},free:e.#y,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,a)=>e.#O(r,n,i,a),moveToTail:r=>e.#T(r),indexes:r=>e.#w(r),rindexes:r=>e.#S(r),isStale:r=>e.#m(r)}}get max(){return this.#c}get maxSize(){return this.#p}get calculatedSize(){return this.#v}get size(){return this.#i}get fetchMethod(){return this.#z}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#g}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:d,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:x,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:_,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:$,ignoreFetchAbort:D}=e;if(r!==0&&!En(r))throw new TypeError("max option must be a nonnegative integer");let Z=r?sC(r):Array;if(!Z)throw new Error("invalid max value: "+r);if(this.#c=r,this.#p=f,this.maxEntrySize=m||this.#p,this.sizeCalculation=h,this.sizeCalculation){if(!this.#p&&!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(x!==void 0&&typeof x!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=x,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#z=g,this.#I=!!g,this.#n=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#l=new Z(r),this.#d=new Z(r),this.#s=0,this.#a=0,this.#y=bb.create(r),this.#i=0,this.#v=0,typeof l=="function"&&(this.#h=l),typeof u=="function"?(this.#g=u,this.#o=[]):(this.#g=void 0,this.#o=void 0),this.#_=!!this.#h,this.#u=!!this.#g,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!D,this.maxEntrySize!==0){if(this.#p!==0&&!En(this.#p))throw new TypeError("maxSize must be a positive integer if specified");if(!En(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!_,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=En(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!En(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#c===0&&this.ttl===0&&this.#p===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#p){let ge="LRU_CACHE_UNBOUNDED";UV(ge)&&(aC.add(ge),oC("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ge,t))}}getRemainingTTL(e){return this.#n.has(e)?1/0:0}#D(){let e=new Ta(this.#c),r=new Ta(this.#c);this.#f=e,this.#b=r,this.#A=(a,o,s=Ea.now())=>{if(r[a]=o!==0?s:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(a)&&this.#k(this.#r[a],"expire")},o+1);c.unref&&c.unref()}},this.#P=a=>{r[a]=e[a]!==0?Ea.now():0},this.#$=(a,o)=>{if(e[o]){let s=e[o],c=r[o];if(!s||!c)return;a.ttl=s,a.start=c,a.now=n||i();let l=a.now-c;a.remainingTTL=s-l}};let n=0,i=()=>{let a=Ea.now();if(this.ttlResolution>0){n=a;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#n.get(a);if(o===void 0)return 0;let s=e[o],c=r[o];if(!s||!c)return 1/0;let l=(n||i())-c;return s-l},this.#m=a=>{let o=r[a],s=e[a];return!!s&&!!o&&(n||i())-o>s}}#P=()=>{};#$=()=>{};#A=()=>{};#m=()=>!1;#F(){let e=new Ta(this.#c);this.#v=0,this.#x=e,this.#E=r=>{this.#v-=e[r],e[r]=0},this.#N=(r,n,i,a)=>{if(this.#t(n))return 0;if(!En(i))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(i=a(n,r),!En(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.#j=(r,n,i)=>{if(e[r]=n,this.#p){let a=this.#p-e[r];for(;this.#v>a;)this.#R(!0)}this.#v+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#v)}}#E=e=>{};#j=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#w({allowStale:e=this.allowStale}={}){if(this.#i)for(let r=this.#a;!(!this.#M(r)||((e||!this.#m(r))&&(yield r),r===this.#s));)r=this.#d[r]}*#S({allowStale:e=this.allowStale}={}){if(this.#i)for(let r=this.#s;!(!this.#M(r)||((e||!this.#m(r))&&(yield r),r===this.#a));)r=this.#l[r]}#M(e){return e!==void 0&&this.#n.get(this.#r[e])===e}*entries(){for(let e of this.#w())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#w()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#S()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#w())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let n of this.#w()){let i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;if(a!==void 0&&e(a,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#w()){let i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;a!==void 0&&e.call(r,a,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#S()){let i=this.#e[n],a=this.#t(i)?i.__staleWhileFetching:i;a!==void 0&&e.call(r,a,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#S({allowStale:!0}))this.#m(r)&&(this.#k(this.#r[r],"expire"),e=!0);return e}info(e){let r=this.#n.get(e);if(r===void 0)return;let n=this.#e[r],i=this.#t(n)?n.__staleWhileFetching:n;if(i===void 0)return;let a={value:i};if(this.#f&&this.#b){let o=this.#f[r],s=this.#b[r];if(o&&s){let c=o-(Ea.now()-s);a.ttl=c,a.start=Date.now()}}return this.#x&&(a.size=this.#x[r]),a}dump(){let e=[];for(let r of this.#w({allowStale:!0})){let n=this.#r[r],i=this.#e[r],a=this.#t(i)?i.__staleWhileFetching:i;if(a===void 0||n===void 0)continue;let o={value:a};if(this.#f&&this.#b){o.ttl=this.#f[r];let s=Ea.now()-this.#b[r];o.start=Math.floor(Date.now()-s)}this.#x&&(o.size=this.#x[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ea.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#N(e,r,n.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let p=this.#i===0?void 0:this.#n.get(e);if(p===void 0)p=this.#i===0?this.#a:this.#y.length!==0?this.#y.pop():this.#i===this.#c?this.#R(!1):this.#i,this.#r[p]=e,this.#e[p]=r,this.#n.set(e,p),this.#l[this.#a]=p,this.#d[p]=this.#a,this.#a=p,this.#i++,this.#j(p,u,c),c&&(c.set="add"),l=!1;else{this.#T(p);let d=this.#e[p];if(r!==d){if(this.#I&&this.#t(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!o&&(this.#_&&this.#h?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"]))}else o||(this.#_&&this.#h?.(d,e,"set"),this.#u&&this.#o?.push([d,e,"set"]));if(this.#E(p),this.#j(p,u,c),this.#e[p]=r,c){c.set="replace";let f=d&&this.#t(d)?d.__staleWhileFetching:d;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(i!==0&&!this.#f&&this.#D(),this.#f&&(l||this.#A(p,i,a),c&&this.#$(c,p)),!o&&this.#u&&this.#o){let d=this.#o,f;for(;f=d?.shift();)this.#g?.(...f)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#s];if(this.#R(!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,r;for(;r=e?.shift();)this.#g?.(...r)}}}#R(e){let r=this.#s,n=this.#r[r],i=this.#e[r];return this.#I&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#h?.(i,n,"evict"),this.#u&&this.#o?.push([i,n,"evict"])),this.#E(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#y.push(r)),this.#i===1?(this.#s=this.#a=0,this.#y.length=0):this.#s=this.#l[r],this.#n.delete(n),this.#i--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,a=this.#n.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.#$(i,a));else return n&&this.#P(a),i&&(i.has="hit",this.#$(i,a)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#n.get(e);if(i===void 0||!n&&this.#m(i))return;let a=this.#e[i];return this.#t(a)?a.__staleWhileFetching:a}#O(e,r,n,i){let a=r===void 0?void 0:this.#e[r];if(this.#t(a))return a;let o=new Qp,{signal:s}=n;s?.addEventListener("abort",()=>o.abort(s.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:i},l=(h,g=!1)=>{let{aborted:x}=o.signal,S=n.ignoreFetchAbort&&h!==void 0;if(n.status&&(x&&!g?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,S&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),x&&!S&&!g)return p(o.signal.reason);let _=f;return this.#e[r]===f&&(h===void 0?_.__staleWhileFetching?this.#e[r]=_.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,h,c.options))),h},u=h=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=h),p(h)),p=h=>{let{aborted:g}=o.signal,x=g&&n.allowStaleOnFetchAbort,S=x||n.allowStaleOnFetchRejection,_=S||n.noDeleteOnFetchRejection,k=f;if(this.#e[r]===f&&(!_||k.__staleWhileFetching===void 0?this.#k(e,"fetch"):x||(this.#e[r]=k.__staleWhileFetching)),S)return n.status&&k.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),k.__staleWhileFetching;if(k.__returned===k)throw h},d=(h,g)=>{let x=this.#z?.(e,a,c);x&&x instanceof Promise&&x.then(S=>h(S===void 0?void 0:S),g),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(h(void 0),n.allowStaleOnFetchAbort&&(h=S=>l(S,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(l,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return r===void 0?(this.set(e,m,{...c.options,status:void 0}),r=this.#n.get(e)):this.#e[r]=m,m}#t(e){if(!this.#I)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Qp}async fetch(e,r={}){let{allowStale:n=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:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:x,signal:S}=r;if(!this.#I)return x&&(x.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,status:x});let _={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:s,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:x,signal:S},k=this.#n.get(e);if(k===void 0){x&&(x.fetch="miss");let $=this.#O(e,k,_,h);return $.__returned=$}else{let $=this.#e[k];if(this.#t($)){let Ze=n&&$.__staleWhileFetching!==void 0;return x&&(x.fetch="inflight",Ze&&(x.returnedStale=!0)),Ze?$.__staleWhileFetching:$.__returned=$}let D=this.#m(k);if(!g&&!D)return x&&(x.fetch="hit"),this.#T(k),i&&this.#P(k),x&&this.#$(x,k),$;let Z=this.#O(e,k,_,h),Be=Z.__staleWhileFetching!==void 0&&n;return x&&(x.fetch=D?"stale":"refresh",Be&&D&&(x.returnedStale=!0)),Be?Z.__staleWhileFetching:Z.__returned=Z}}async forceFetch(e,r={}){let n=await this.fetch(e,r);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,r={}){let n=this.#C;if(!n)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:a,...o}=r,s=this.get(e,o);if(!a&&s!==void 0)return s;let c=n(e,s,{options:o,context:i});return this.set(e,c,o),c}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=r,s=this.#n.get(e);if(s!==void 0){let c=this.#e[s],l=this.#t(c);return o&&this.#$(o,s),this.#m(s)?(o&&(o.get="stale"),l?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(a||this.#k(e,"expire"),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),l?c.__staleWhileFetching:(this.#T(s),i&&this.#P(s),c))}else o&&(o.get="miss")}#U(e,r){this.#d[r]=e,this.#l[e]=r}#T(e){e!==this.#a&&(e===this.#s?this.#s=this.#l[e]:this.#U(this.#d[e],this.#l[e]),this.#U(this.#a,e),this.#a=e)}delete(e){return this.#k(e,"delete")}#k(e,r){let n=!1;if(this.#i!==0){let i=this.#n.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.#q(r);else{this.#E(i);let a=this.#e[i];if(this.#t(a)?a.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#h?.(a,e,r),this.#u&&this.#o?.push([a,e,r])),this.#n.delete(e),this.#r[i]=void 0,this.#e[i]=void 0,i===this.#a)this.#a=this.#d[i];else if(i===this.#s)this.#s=this.#l[i];else{let o=this.#d[i];this.#l[o]=this.#l[i];let s=this.#l[i];this.#d[s]=this.#d[i]}this.#i--,this.#y.push(i)}}if(this.#u&&this.#o?.length){let i=this.#o,a;for(;a=i?.shift();)this.#g?.(...a)}return n}clear(){return this.#q("delete")}#q(e){for(let r of this.#S({allowStale:!0})){let n=this.#e[r];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#r[r];this.#_&&this.#h?.(n,i,e),this.#u&&this.#o?.push([n,i,e])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#b&&(this.#f.fill(0),this.#b.fill(0)),this.#x&&this.#x.fill(0),this.#s=0,this.#a=0,this.#y.length=0,this.#v=0,this.#i=0,this.#u&&this.#o){let r=this.#o,n;for(;n=r?.shift();)this.#g?.(...n)}}};import je from"path";import{promises as Et}from"fs";var qV=["CoreGui","CorePackages","RobloxScript","RobloxScriptSecurity"],FV=["Workspace","Lighting","ReplicatedStorage","ServerStorage","ServerScriptService","StarterGui","StarterPlayer","StarterPack","ReplicatedFirst","SoundService","Chat","LocalizationService"];function cC(t){let e=t.replace(/[^a-zA-Z0-9-]/g,"_");return e=e.replace(/_+/g,"_"),e=e.replace(/^_|_$/g,""),e=e.slice(0,40),e=e.replace(/_$/g,""),e}function LV(t){let e=je.join(t,"roblox-project-sync");return{syncRoot:e,explorerRoot:je.join(e,"explorer"),excludePatterns:["*.Terrain","*.Camera"],excludeClasses:["Terrain","Camera"],propertyMode:"standard",maxDepth:20,maxInstances:25e3,directorySizeWarning:500*1024*1024,directorySizeLimit:1024*1024*1024,reverseSyncMode:"manual"}}var td=class{config;placeRootCache=new Map;async backupAndDeletePlaceDir(e,r){let n=this.config.syncRoot,i=new Date().toISOString().replace(/[:.]/g,"-"),a=je.join(n,"_deleted-place-backups",`place_${e}`),o=je.join(n,r),s=`${i}_${r}`,c=je.join(a,s);await Et.mkdir(a,{recursive:!0}),await Et.cp(o,c,{recursive:!0,force:!0}),await Et.rm(o,{recursive:!0,force:!0}),y.info("Backed up and deleted duplicate place directory",{placeId:e,from:r,backupTo:je.relative(n,c)})}constructor(e){this.config=LV(e??process.cwd())}getConfig(){return{...this.config}}getSyncRoot(){return this.config.syncRoot}getPlaceRoot(e){let r=this.placeRootCache.get(e);return r?je.join(this.config.syncRoot,r):je.join(this.config.syncRoot,`place_${e}`)}async resolvePlaceRoot(e,r){let n=this.config.syncRoot,i=`place_${e}`,a=r?cC(r):"",o=a?`${i}_${a}`:i;await Et.mkdir(n,{recursive:!0});let s=new RegExp(`^place_${e}(?:_.*)?$`),c=async()=>(await Et.readdir(n,{withFileTypes:!0})).filter(m=>m.isDirectory()&&s.test(m.name)).map(m=>m.name).sort(),l=await c(),u=a?o:this.placeRootCache.get(e)&&s.test(this.placeRootCache.get(e))?this.placeRootCache.get(e):l[0]??o;if(l.length>0&&!l.includes(u)){let f=l[0],m=je.join(n,f),h=je.join(n,u);try{await Et.rename(m,h),y.info("Migrated place directory",{from:f,to:u})}catch(g){y.warn("Failed to migrate place directory, using existing",{from:f,to:u,error:g instanceof Error?g.message:String(g)}),u=f}}let p=je.join(n,u);await Et.mkdir(p,{recursive:!0}),l=await c();let d=l.filter(f=>f!==u);for(let f of d)try{await this.backupAndDeletePlaceDir(e,f)}catch(m){y.warn("Failed to backup/delete duplicate place directory",{placeId:e,duplicate:f,error:m instanceof Error?m.message:String(m)})}return this.placeRootCache.set(e,u),p}async promotePlaceRoot(e,r,n){let i=this.config.syncRoot,a=n?cC(n):"",o=a?`place_${r}_${a}`:`place_${r}`,s=null;try{let p=await Et.readdir(i,{withFileTypes:!0}),d=new RegExp(`^place_${e}(?:_.*)?$`);for(let f of p)if(f.isDirectory()&&d.test(f.name)){s=f.name;break}}catch{}if(!s)return y.info("No existing directory for place promotion, creating new",{oldId:e,newId:r}),this.resolvePlaceRoot(r,n);let c=je.join(i,s),l=je.join(i,o);try{await Et.rename(c,l),y.info("Place directory promoted",{from:s,to:o})}catch(p){return y.warn("Failed to rename place directory during promotion, creating new",{from:s,to:o,error:p instanceof Error?p.message:String(p)}),this.placeRootCache.delete(e),this.resolvePlaceRoot(r,n)}this.placeRootCache.delete(e),this.placeRootCache.set(r,o);let u=je.join(l,".sync-meta.json");try{let p=await Et.readFile(u,"utf-8"),d=JSON.parse(p);d.placeId=r,n&&(d.placeName=n),await Et.writeFile(u,JSON.stringify(d,null,2)+`
|
|
110
110
|
`,"utf-8"),y.info("Updated .sync-meta.json with new placeId",{newId:r})}catch{}return l}getExplorerRoot(e){return e!==void 0?je.join(this.getPlaceRoot(e),"explorer"):this.config.explorerRoot}getMetaFilePath(e){return e!==void 0?je.join(this.getPlaceRoot(e),".sync-meta.json"):je.join(this.config.syncRoot,".sync-meta.json")}getIndexFilePath(e){return e!==void 0?je.join(this.getPlaceRoot(e),".sync-index.json"):je.join(this.config.syncRoot,".sync-index.json")}getHistoryPath(e){return e!==void 0?je.join(this.getPlaceRoot(e),"history.jsonl"):je.join(this.config.syncRoot,"history.jsonl")}getChangeLogPath(e){return e!==void 0?je.join(this.getPlaceRoot(e),"changes.log"):je.join(this.config.syncRoot,"changes.log")}getPropertyMode(){return this.config.propertyMode}getMaxInstances(){return this.config.maxInstances}getMaxDepth(){return this.config.maxDepth}getReverseSyncMode(){return this.config.reverseSyncMode}isExcluded(e,r){for(let n of qV)if(e.includes(n))return!0;if(this.config.excludeClasses.includes(r))return!0;for(let n of this.config.excludePatterns)if(n.startsWith("*.")){let i=n.slice(2);if(e.endsWith("."+i)||e===i)return!0}else if(e.includes(n))return!0;return!1}isSyncableService(e){return FV.includes(e)}updateConfig(e){this.config={...this.config,...e},y.debug("SyncConfig updated",e)}setPropertyMode(e){this.config.propertyMode=e,y.debug(`Property mode set to '${e}'`)}setReverseSyncMode(e){this.config.reverseSyncMode=e,y.debug(`Reverse sync mode set to '${e}'`)}async loadFromMeta(){let e=this.getMetaFilePath();try{let r=await Et.readFile(e,"utf-8"),n=JSON.parse(r);if(n.excludePatterns&&(this.config.excludePatterns=n.excludePatterns),n.propertyMode){let i=n.propertyMode;this.config.propertyMode=i==="common"||i==="full"?"standard":n.propertyMode}y.info("Loaded sync config from .sync-meta.json")}catch(r){r.code==="ENOENT"?y.debug(".sync-meta.json not found \u2014 using defaults"):y.warn("Failed to read .sync-meta.json \u2014 using defaults",r)}}async saveToMeta(e){let r=this.getMetaFilePath();try{await Et.mkdir(je.dirname(r),{recursive:!0}),await Et.writeFile(r,JSON.stringify(e,null,2)+`
|
|
111
111
|
`,"utf-8"),y.info("Saved sync metadata to .sync-meta.json")}catch(n){throw y.error("Failed to save .sync-meta.json",n),n}}};import ne from"path";import{createHash as WV}from"crypto";import{promises as Ca}from"fs";var ic={Script:".server.luau",LocalScript:".client.luau",ModuleScript:".module.luau"},Tn=new Set(["Script","LocalScript","ModuleScript"]),ZV=new Set(["StringValue","IntValue","BoolValue","NumberValue","ObjectValue","Color3Value","Vector3Value","CFrameValue","BrickColorValue","RayValue"]),HV=new Set(["Folder","Model","Configuration","Camera","WorldModel"]),_b=new Set(["Workspace","Lighting","ReplicatedFirst","ReplicatedStorage","ServerScriptService","ServerStorage","StarterGui","StarterPack","StarterPlayer","SoundService","Teams","Chat","LocalizationService","TestService"]);function lC(t){return Tn.has(t)?"script":ZV.has(t)?"value":HV.has(t)?"container":_b.has(t)?"service":"data"}var rd={scripts:"forward",values:"forward",containers:"forward",data:"forward",services:"forward"};function uC(t){switch(t){case"scriptSourceChanged":return"scripts";case"propertyChanged":return"data";case"instanceAdded":case"instanceRemoved":case"instanceRenamed":case"instanceMoved":return"containers";default:return"data"}}function pC(t){return t.endsWith(".server.luau")||t.endsWith(".client.luau")||t.endsWith(".module.luau")?"scripts":t.endsWith(".value.json")?"values":t.endsWith("_props.json")?"data":"containers"}var VV=/[.\[\]"']/;function dC(t){return t.length===0||VV.test(t)}function fC(t){let e=t.replace(/\\/g,"\\\\");return e.includes('"')?e.includes("'")?`"${e.replace(/"/g,'\\"')}"`:`'${e}'`:`"${e}"`}function BV(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="\\"&&r+1<t.length){e+=t[r+1]??"",r++;continue}e+=n}return e}function za(t){let e=[],r=0,n=t.length;for(;r<n;){let i=t[r];if(!i)break;if(i==="."){r++;continue}if(i==="["){for(r++;r<n&&/\s/.test(t[r]??"");)r++;let s=t[r];if(s==='"'||s==="'"){r++;let u="";for(;r<n;){let p=t[r];if(!p)break;if(p==="\\"&&r+1<n){u+=`${p}${t[r+1]??""}`,r+=2;continue}if(p===s){r++;break}u+=p,r++}for(;r<n&&/\s/.test(t[r]??"");)r++;t[r]==="]"&&r++,e.push(BV(u));continue}let c="";for(;r<n&&t[r]!=="]";)c+=t[r]??"",r++;t[r]==="]"&&r++;let l=c.trim();l.length>0&&e.push(l);continue}let a=r;for(;r<n;){let s=t[r];if(s==="."||s==="[")break;r++}let o=t.slice(a,r).trim();o.length>0&&e.push(o)}return e}function Er(t){let e=za(t);return e[0]==="game"?e.slice(1):e}function cr(t){if(t.length===0)return"";let e="";for(let r=0;r<t.length;r++){let n=t[r]??"";if(r===0){e=dC(n)?`[${fC(n)}]`:n;continue}dC(n)?e+=`[${fC(n)}]`:e+=`.${n}`}return e}function ui(t){let e=za(t);return e[e.length-1]??""}function nd(t){let e=za(t);return e.length<=1?"":cr(e.slice(0,-1))}function id(t,e){let r=za(t);return r.length===0?e:(r[r.length-1]=e,cr(r))}var JV=/[*:"<>|?\\/[\]]/g;function GV(t,e){let r=ne.resolve(t),n=ne.resolve(e),i=ne.relative(r,n);return i===""||!i.startsWith("..")&&!ne.isAbsolute(i)}var ja=class{explorerRoot;syncRoot;studioHashes=new Map;fileHashes=new Map;nameCounters=new Map;nameMapping=new Map;reverseNameMapping=new Map;constructor(e,r){this.syncRoot=ne.resolve(e),this.explorerRoot=ne.resolve(r)}resolveFilePath(e){return this.resolveChildrenDir(e)}resolveChildrenDir(e){let r=Er(e).map(i=>this.sanitizeName(i)),n=ne.resolve(this.explorerRoot,...r);return this.validatePathSecurity(n),n}resolvePropsPath(e){let r=Er(e).map(s=>this.sanitizeName(s));if(r.length===0)throw new Error("Cannot resolve props path for empty instance path");let n=r[r.length-1],i=r.slice(0,-1),a=ne.resolve(this.explorerRoot,...i),o=ne.join(a,`${n}._props.json`);return this.validatePathSecurity(o),o}resolveParentDir(e){let r=Er(e).map(a=>this.sanitizeName(a));if(r.length<=1)return this.explorerRoot;let n=r.slice(0,-1),i=ne.resolve(this.explorerRoot,...n);return this.validatePathSecurity(i),i}resolveScriptPath(e,r,n){let i=ic[r],a=this.sanitizeName(ui(e)||"_unnamed"),o=this.resolveParentDir(e);return ne.join(o,`${a}${i}`)}resolveValuePath(e){let r=Er(e).map(s=>this.sanitizeName(s));if(r.length===0)throw new Error("Cannot resolve value path for empty instance path");let n=r[r.length-1],i=r.slice(0,-1),a=ne.resolve(this.explorerRoot,...i),o=ne.join(a,`${n}.value.json`);return this.validatePathSecurity(o),o}sanitizeName(e){if(e===".."||e===".")return"_";let r=e.replace(JV,"_").trim();return r=r.replace(/\.\./g,"_"),r.length===0?"_unnamed":r}resolveNameCollision(e,r){let n=this.nameCounters.get(e);n||(n=new Map,this.nameCounters.set(e,n));let i=n.get(r);if(i===void 0)return n.set(r,1),r;let a=i+1;return n.set(r,a),`${r}_${a}`}resetNameCounters(){this.nameCounters.clear(),this.nameMapping.clear(),this.reverseNameMapping.clear()}registerCollision(e,r,n){let i=ui(e)||"_unnamed",a=this.sanitizeName(i),o=this.resolveNameCollision(n,a),s=r??1,c=`${e}#${s}`;this.nameMapping.set(c,o);let l=`${n}/${o}`;return this.reverseNameMapping.set(l,{instancePath:e,siblingIndex:s}),o}getResolvedName(e,r){return this.nameMapping.get(`${e}#${r}`)}getOriginalInstance(e,r){return this.reverseNameMapping.get(`${e}/${r}`)}resetNameMappings(){this.nameMapping.clear(),this.reverseNameMapping.clear()}mergeNameMappingsFrom(e){let r=e.explorerRoot,n=this.explorerRoot;for(let[i,a]of e.nameMapping)this.nameMapping.set(i,a);for(let[i,a]of e.reverseNameMapping)if(i.startsWith(r)){let o=i.slice(r.length),s=n+o;this.reverseNameMapping.set(s,a)}else this.reverseNameMapping.set(i,a)}getNameMappings(){return new Map(this.nameMapping)}getReverseNameMappings(){return new Map(this.reverseNameMapping)}validatePathSecurity(e){let r=ne.resolve(e);if(!GV(this.explorerRoot,r))throw new Error(`Path traversal detected: resolved path "${r}" is outside explorerRoot "${this.explorerRoot}"`)}computeHash(e){return WV("md5").update(e,"utf-8").digest("hex")}hasChanged(e,r){let n=this.computeHash(r);return this.studioHashes.get(e)!==n}updateHash(e,r){this.studioHashes.set(e,this.computeHash(r))}updateFileHash(e,r){this.fileHashes.set(e,this.computeHash(r))}updateBothHashes(e,r){let n=this.computeHash(r);this.studioHashes.set(e,n),this.fileHashes.set(e,n)}updateHashByValue(e,r){this.studioHashes.set(e,r)}updateFileHashByValue(e,r){this.fileHashes.set(e,r)}removeHash(e){this.studioHashes.delete(e),this.fileHashes.delete(e)}removeHashesUnder(e){let r=e.endsWith(ne.sep)?e:e+ne.sep;for(let n of this.studioHashes.keys())(n.startsWith(r)||n===e)&&this.studioHashes.delete(n);for(let n of this.fileHashes.keys())(n.startsWith(r)||n===e)&&this.fileHashes.delete(n)}getHash(e){return this.studioHashes.get(e)}getFileHash(e){return this.fileHashes.get(e)}getAllHashes(){return new Map(this.studioHashes)}getAllFileHashes(){return new Map(this.fileHashes)}clearAllHashes(){this.studioHashes.clear(),this.fileHashes.clear()}hasEntry(e){return this.studioHashes.has(e)||this.fileHashes.has(e)}get hashCount(){return this.studioHashes.size}getFileStatus(e,r){let n=this.studioHashes.get(e),i=this.fileHashes.get(e);if(!n||!i)return"synced";if(r===void 0)return n===i?"synced":"studio-modified";let a=r!==i,o=n!==i;return!a&&!o?"synced":a&&!o?"file-modified":!a&&o?"studio-modified":"conflict"}async scanForFileModifications(){let e=[],r=[],n=[];for(let[i]of this.fileHashes){let a=ne.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 p=await Ca.readFile(i,"utf-8");s=this.computeHash(p)}catch(p){if(p.code==="ENOENT"){let d=this.resolveInstancePathFromFsPath(i);d&&n.push({fsPath:i,relPath:a,instancePath:d,fileType:o});continue}y.warn("Failed to read file for scanning",{path:i,error:p instanceof Error?p.message:String(p)});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"&&r.push(u)}return{modified:e,conflicts:r,deleted:n}}resolveFile(e,r,n){if(r==="apply-studio"){let i=this.studioHashes.get(e);i&&this.fileHashes.set(e,i)}else r==="apply-file"&&n&&this.fileHashes.set(e,n)}async getModifiedFiles(){let e=[],r=new Set;for(let i of this.fileHashes.keys())r.add(ne.resolve(i));for(let i of this.studioHashes.keys())r.add(ne.resolve(i));for(let[i]of this.fileHashes){let a=ne.resolve(i),o=ne.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 p=await Ca.readFile(a,"utf-8");l=this.computeHash(p)}catch(p){if(p.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 n=await this.collectTrackedFiles(this.explorerRoot);for(let i of n){let a=ne.resolve(i);if(r.has(a))continue;let o=ne.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 r=[],n;try{n=await Ca.readdir(e,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return r;throw i}for(let i of n){let a=ne.join(e,i.name);if(i.isDirectory()){let s=await this.collectTrackedFiles(a);r.push(...s);continue}if(!i.isFile())continue;let o=this.getFileTypeFromPath(a);(o==="script"||o==="props"||o==="value")&&r.push(a)}return r}getFileTypeFromPath(e){let r=ne.basename(e);return r.endsWith("._props.json")?"props":r.endsWith(".value.json")?"value":r==="_tree.json"?"tree":r.endsWith(".luau")?"script":"unknown"}resolveInstancePathFromFsPath(e){let r=ne.basename(e);if(r==="_tree.json")return null;let n=ne.relative(this.explorerRoot,e);if(n.startsWith(".."))return null;let i=n.split(ne.sep).filter(a=>a.length>0);if(r.endsWith("._props.json")){let a=r.slice(0,-12),o=i.slice(0,-1);return cr(["game",...o,a])}if(r.endsWith(".value.json")){let a=r.slice(0,-11),o=i.slice(0,-1);return cr(["game",...o,a])}if(r.endsWith(".luau")){let a=r;for(let s of[".server.luau",".client.luau",".module.luau"])if(a.endsWith(s)){a=a.slice(0,-s.length);break}let o=i.slice(0,-1);return cr(["game",...o,a])}return null}async loadFromDisk(){let e=ne.join(this.syncRoot,".sync-index.json");try{let r=await Ca.readFile(e,"utf-8"),n=JSON.parse(r);if(n.version!==1){y.warn("Unsupported .sync-index.json version, ignoring",{version:n.version});return}let i=0;for(let[a,o]of Object.entries(n.files)){let s=ne.resolve(this.syncRoot,a);this.studioHashes.set(s,o.studioHash),this.fileHashes.set(s,o.fileHash),i++}if(n.nameMappings)for(let[a,o]of Object.entries(n.nameMappings))this.nameMapping.set(a,o);if(n.reverseNameMappings)for(let[a,o]of Object.entries(n.reverseNameMappings)){let s=a.startsWith("/")?a:ne.resolve(this.explorerRoot,a);this.reverseNameMapping.set(s,o)}y.info("Loaded sync index from disk",{entries:i,nameMappings:this.nameMapping.size})}catch(r){if(r.code==="ENOENT"){y.info("No existing .sync-index.json found, starting fresh");return}y.warn("Failed to load .sync-index.json",{error:r instanceof Error?r.message:String(r)})}}async saveToDisk(){let e=ne.join(this.syncRoot,".sync-index.json"),r=this.toSyncIndexData();await Ca.mkdir(ne.dirname(e),{recursive:!0});let n=JSON.stringify(r,null,2);await Ca.writeFile(e,n,"utf-8"),y.debug("Saved sync index to disk",{entries:this.studioHashes.size})}toSyncIndexData(){let e=new Date().toISOString(),r={},n=new Set([...this.studioHashes.keys(),...this.fileHashes.keys()]);for(let a of n){let o=ne.relative(this.syncRoot,a),s=this.studioHashes.get(a)??"",c=this.fileHashes.get(a)??s,l="synced";s&&c&&s!==c&&(l="studio-modified"),r[o]={studioHash:s,fileHash:c,lastStudioSync:e,status:l}}let i={version:1,files:r};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=ne.relative(this.explorerRoot,o),l=c.startsWith("..")?o:c;a[l]=s}i.reverseNameMappings=a}return i}getInstancePath(e){let n=ne.relative(this.explorerRoot,e).split(ne.sep).filter(i=>i.length>0);return cr(["game",...n])}getExplorerRoot(){return this.explorerRoot}getSyncRoot(){return this.syncRoot}};import Ge from"path";import{promises as Me}from"fs";import{randomUUID as KV}from"crypto";var mC=1e3,hC=1e4,gC=50,XV=1e3,ac=class{config;index;changeLogBuffer=[];historyBuffer=[];flushTimer=null;onWriteCallback;placeId;constructor(e,r,n){this.config=e,this.index=r,this.placeId=n}setOnWriteCallback(e){this.onWriteCallback=e}async writeProps(e,r){let n=this.index.resolvePropsPath(e),i=JSON.stringify(r,null,2);if(!this.index.hasChanged(n,i))return!1;try{return await this.ensureDir(Ge.dirname(n)),await this.atomicWrite(n,i),await this.updateSyncIndex(n,i),this.appendChangeLog(`WRITE ${this.relativePath(n)}`),this.appendHistory({timestamp:new Date().toISOString(),type:"write",direction:"forward",path:e,details:"props"}),!0}catch(a){this.handleDiskError(a,"writeProps",n)}}async writeScript(e,r,n,i){let a=this.index.resolveScriptPath(e,r,i),o=n;if(!this.index.hasChanged(a,o))return!1;try{return await this.ensureDir(Ge.dirname(a)),await this.atomicWrite(a,o),await this.updateSyncIndex(a,o),this.appendChangeLog(`WRITE ${this.relativePath(a)}`),this.appendHistory({timestamp:new Date().toISOString(),type:"write",direction:"forward",path:e,details:`script:${r}`}),!0}catch(s){this.handleDiskError(s,"writeScript",a)}}async writeValue(e,r){let n=this.index.resolveValuePath(e),i=JSON.stringify(r,null,2);if(!this.index.hasChanged(n,i))return!1;try{return await this.ensureDir(Ge.dirname(n)),await this.atomicWrite(n,i),await this.updateSyncIndex(n,i),this.appendChangeLog(`WRITE ${this.relativePath(n)}`),this.appendHistory({timestamp:new Date().toISOString(),type:"write",direction:"forward",path:e,details:`value:${r.className}`}),!0}catch(a){this.handleDiskError(a,"writeValue",n)}}async writeTree(e,r){let n=Ge.join(this.index.getExplorerRoot(),e),i=Ge.join(n,"_tree.json"),a=JSON.stringify(r,null,2);if(!this.index.hasChanged(i,a))return!1;try{return await this.ensureDir(n),await this.atomicWrite(i,a),await this.updateSyncIndex(i,a),this.appendChangeLog(`WRITE ${this.relativePath(i)}`),!0}catch(o){this.handleDiskError(o,"writeTree",i)}}async writeSyncMeta(e){await this.config.saveToMeta(e)}async writeInstance(e){let r=!1,n=!1,i=!1;switch(lC(e.className)){case"script":{if(r=await this.writeProps(e.path,this.buildPropsData(e)),e.scriptSource!==void 0&&(n=await this.writeScript(e.path,e.className,e.scriptSource,e.hasChildren)),e.hasChildren||e.childCount>0){let o=this.index.resolveChildrenDir(e.path);await this.ensureDir(o)}break}case"value":{let o={className:e.className,value:e.properties.Value??null};i=await this.writeValue(e.path,o);let s={...e.properties};delete s.Value;let c=Object.keys(s).length>0,l=e.attributes&&Object.keys(e.attributes).length>0,u=e.tags&&e.tags.length>0;if(c||l||u){let p={name:e.name,className:e.className,properties:s};l&&(p.attributes=e.attributes),u&&(p.tags=e.tags),r=await this.writeProps(e.path,p)}if(e.hasChildren||e.childCount>0){let p=this.index.resolveChildrenDir(e.path);await this.ensureDir(p)}break}case"container":{let o=this.index.resolveChildrenDir(e.path);await this.ensureDir(o),e.className!=="Folder"&&(r=await this.writeProps(e.path,this.buildPropsData(e)));break}case"service":case"data":{if(r=await this.writeProps(e.path,this.buildPropsData(e)),e.hasChildren||e.childCount>0){let o=this.index.resolveChildrenDir(e.path);await this.ensureDir(o)}break}}return{propsWritten:r,scriptWritten:n,valueWritten:i}}buildPropsData(e){let r={name:e.name,className:e.className,properties:e.properties};return e.attributes&&Object.keys(e.attributes).length>0&&(r.attributes=e.attributes),e.tags&&e.tags.length>0&&(r.tags=e.tags),r}async removeInstance(e){try{let r=this.index.resolvePropsPath(e);await this.tryUnlink(r),this.index.removeHash(r);for(let a of Tn){let o=this.index.resolveScriptPath(e,a,!1);await this.tryUnlink(o)&&this.index.removeHash(o)}let n=this.index.resolveValuePath(e);await this.tryUnlink(n)&&this.index.removeHash(n);let i=this.index.resolveChildrenDir(e);try{await Me.rm(i,{recursive:!0,force:!0})}catch{}this.index.removeHashesUnder(i),this.appendChangeLog(`DELETE ${e}`),this.appendHistory({timestamp:new Date().toISOString(),type:"delete",direction:"forward",path:e})}catch(r){this.handleDiskError(r,"removeInstance",e)}}async renameInstance(e,r,n){try{let i=this.index.resolvePropsPath(e),a=this.index.resolvePropsPath(r);if(await this.tryRename(i,a)){this.migrateSingleHash(i,a);try{let u=await Me.readFile(a,"utf-8"),p=JSON.parse(u);if(p.name!==n){p.name=n;let d=JSON.stringify(p,null,2);await this.atomicWrite(a,d),await this.updateSyncIndex(a,d)}}catch{}}for(let u of Tn){let p=this.index.resolveScriptPath(e,u,!1),d=this.index.resolveScriptPath(r,u,!1);if(await this.tryRename(p,d)){this.migrateSingleHash(p,d);break}}let o=this.index.resolveValuePath(e),s=this.index.resolveValuePath(r);await this.tryRename(o,s)&&this.migrateSingleHash(o,s);let c=this.index.resolveChildrenDir(e),l=this.index.resolveChildrenDir(r);await this.tryRename(c,l)&&this.migrateHashes(c,l),this.appendChangeLog(`RENAME ${this.relativePath(i)} -> ${this.relativePath(a)}`),this.appendHistory({timestamp:new Date().toISOString(),type:"rename",direction:"forward",path:r,details:`from:${e}`})}catch(i){this.handleDiskError(i,"renameInstance",e)}}async moveInstance(e,r){try{let n=this.index.resolveParentDir(r);await this.ensureDir(n);let i=this.index.resolvePropsPath(e),a=this.index.resolvePropsPath(r);await this.tryCopyFile(i,a)&&(await this.tryUnlink(i),this.migrateSingleHash(i,a));for(let u of Tn){let p=this.index.resolveScriptPath(e,u,!1),d=this.index.resolveScriptPath(r,u,!1);if(await this.tryCopyFile(p,d)){await this.tryUnlink(p),this.migrateSingleHash(p,d);break}}let o=this.index.resolveValuePath(e),s=this.index.resolveValuePath(r);await this.tryCopyFile(o,s)&&(await this.tryUnlink(o),this.migrateSingleHash(o,s));let c=this.index.resolveChildrenDir(e),l=this.index.resolveChildrenDir(r);try{(await Me.stat(c)).isDirectory()&&(await this.copyDirectory(c,l),await Me.rm(c,{recursive:!0,force:!0}),this.migrateHashes(c,l))}catch{}this.appendChangeLog(`MOVE ${this.relativePath(i)} -> ${this.relativePath(a)}`),this.appendHistory({timestamp:new Date().toISOString(),type:"move",direction:"forward",path:r,details:`from:${e}`})}catch(n){this.handleDiskError(n,"moveInstance",e)}}async updateProperties(e,r){let n=this.index.resolvePropsPath(e);try{let i=await Me.readFile(n,"utf-8"),a=JSON.parse(i);for(let[s,c]of Object.entries(r))a.properties[s]=c;let o=JSON.stringify(a,null,2);return this.index.hasChanged(n,o)?(await this.atomicWrite(n,o),await this.updateSyncIndex(n,o),this.appendChangeLog(`UPDATE ${this.relativePath(n)} (bulk properties)`),this.appendHistory({timestamp:new Date().toISOString(),type:"update",direction:"forward",path:e,details:"bulk properties"}),!0):!1}catch(i){if(i.code==="ENOENT")return y.warn(`updateProperties: _props.json not found for ${e}`),!1;this.handleDiskError(i,"updateProperties",n)}}async updateProperty(e,r,n){let i=this.index.resolvePropsPath(e);try{let a=await Me.readFile(i,"utf-8"),o=JSON.parse(a);o.properties[r]=n;let s=JSON.stringify(o,null,2);return this.index.hasChanged(i,s)?(await this.atomicWrite(i,s),await this.updateSyncIndex(i,s),this.appendChangeLog(`UPDATE ${this.relativePath(i)} (${r})`),this.appendHistory({timestamp:new Date().toISOString(),type:"update",direction:"forward",path:e,details:`property:${r}`}),!0):!1}catch(a){if(a.code==="ENOENT")return y.warn(`updateProperty: _props.json not found for ${e}`),!1;this.handleDiskError(a,"updateProperty",i)}}async addToTree(e,r){let n=this.extractServiceName(e),i=Ge.join(this.index.getExplorerRoot(),n,"_tree.json");try{let a=await Me.readFile(i,"utf-8"),o=JSON.parse(a),s=this.findTreeNode(o,e);if(s){s.children||(s.children=[]);let l=s.children.findIndex(u=>u.name===r.name);l>=0?s.children[l]=r:(s.children.push(r),s.childCount=s.children.length)}else{let l=o.children.findIndex(u=>u.name===r.name);l>=0?o.children[l]=r:(o.children.push(r),o.childCount=o.children.length)}o.syncedAt=new Date().toISOString();let c=JSON.stringify(o,null,2);await this.atomicWrite(i,c),await this.updateSyncIndex(i,c)}catch(a){if(a.code==="ENOENT"){y.warn(`addToTree: _tree.json not found for ${e}`);return}this.handleDiskError(a,"addToTree",i)}}async removeFromTree(e,r){let n=this.extractServiceName(e),i=Ge.join(this.index.getExplorerRoot(),n,"_tree.json");try{let a=await Me.readFile(i,"utf-8"),o=JSON.parse(a),s=this.findTreeNode(o,e);s&&s.children?(s.children=s.children.filter(l=>l.name!==r),s.childCount=s.children.length):(o.children=o.children.filter(l=>l.name!==r),o.childCount=o.children.length),o.syncedAt=new Date().toISOString();let c=JSON.stringify(o,null,2);await this.atomicWrite(i,c),await this.updateSyncIndex(i,c)}catch(a){if(a.code==="ENOENT"){y.warn(`removeFromTree: _tree.json not found for ${e}`);return}this.handleDiskError(a,"removeFromTree",i)}}async renameInTree(e,r,n){let i=this.extractServiceName(e),a=this.extractServiceName(r);if(!i||!a)return;if(i!==a){await this.moveInTree(e,r);return}let o=Ge.join(this.index.getExplorerRoot(),i,"_tree.json");try{let s=await Me.readFile(o,"utf-8"),c=JSON.parse(s),l=this.findTreeNode(c,e);if(!l){y.warn("renameInTree: node not found",{oldPath:e,newPath:r});return}l.name=n,c.syncedAt=new Date().toISOString();let u=JSON.stringify(c,null,2);await this.atomicWrite(o,u),await this.updateSyncIndex(o,u)}catch(s){if(s.code==="ENOENT"){y.warn(`renameInTree: _tree.json not found for ${i}`);return}this.handleDiskError(s,"renameInTree",o)}}async moveInTree(e,r){let n=this.extractServiceName(e),i=this.extractServiceName(r);if(!n||!i)return;let a=Ge.join(this.index.getExplorerRoot(),n,"_tree.json"),o=Ge.join(this.index.getExplorerRoot(),i,"_tree.json");try{let s=await Me.readFile(a,"utf-8"),c=JSON.parse(s),l=this.detachTreeNode(c,e);if(!l){y.warn("moveInTree: node not found",{oldPath:e,newPath:r});return}let u=this.getLeafName(r);if(u&&(l.name=u),n===i){let g=this.getParentPath(r);if(!g)return;this.insertTreeNode(c,g,l),c.syncedAt=new Date().toISOString();let x=JSON.stringify(c,null,2);await this.atomicWrite(a,x),await this.updateSyncIndex(a,x);return}let p=await Me.readFile(o,"utf-8"),d=JSON.parse(p),f=this.getParentPath(r);if(!f)return;this.insertTreeNode(d,f,l),c.syncedAt=new Date().toISOString(),d.syncedAt=new Date().toISOString();let m=JSON.stringify(c,null,2),h=JSON.stringify(d,null,2);await this.atomicWrite(a,m),await this.atomicWrite(o,h),await this.updateSyncIndex(a,m),await this.updateSyncIndex(o,h)}catch(s){if(s.code==="ENOENT"){y.warn("moveInTree: _tree.json not found",{oldService:n,newService:i});return}this.handleDiskError(s,"moveInTree",`${e} -> ${r}`)}}async atomicWrite(e,r){let n=".tmp."+KV().slice(0,8),i=e+n;try{await Me.writeFile(i,r,"utf-8"),await Me.rename(i,e),this.onWriteCallback?.(e)}catch(a){throw await Me.unlink(i).catch(()=>{}),a}}async ensureDir(e){await Me.mkdir(e,{recursive:!0})}handleDiskError(e,r,n){let i=e.code;if(i==="ENOSPC")throw new Error(`Disk full: cannot write sync file at ${n} (operation: ${r})`);if(i==="EPERM"||i==="EACCES")throw new Error(`Permission denied: cannot write to ${n} (operation: ${r})`);let a=e instanceof Error?e.message:String(e);throw new Error(`SyncWriter.${r} failed for ${n}: ${a}`)}appendHistory(e){this.historyBuffer.push(JSON.stringify(e)),this.historyBuffer.length>=gC&&this.flushHistory()}async flushHistory(){if(this.historyBuffer.length===0)return;let e=this.historyBuffer.splice(0),r=this.config.getHistoryPath(this.placeId);try{await this.ensureDir(Ge.dirname(r));let n=[];try{n=(await Me.readFile(r,"utf-8")).split(`
|
|
112
112
|
`).filter(s=>s.length>0)}catch{}let i=[...n,...e],a=i.length>hC?i.slice(i.length-hC):i;await this.atomicWrite(r,a.join(`
|
|
@@ -126,7 +126,7 @@ ${s}`,p=MV(this.config.sharedSecret,u),d={"content-type":"application/json","x-w
|
|
|
126
126
|
`)+`
|
|
127
127
|
`;await gd.appendFile(l,p,"utf-8");try{let d="";try{d=await gd.readFile(u,"utf-8")}catch{}let m=(d+p).split(`
|
|
128
128
|
`).slice(-500).join(`
|
|
129
|
-
`);await gd.writeFile(u,m,"utf-8")}catch(d){y.warn("Failed to update current.log",{error:d})}y.debug("Logs received from plugin",{count:i.logs.length,clientId:n||"legacy",logFile:c}),r.json({status:"ok",logsReceived:i.logs.length,logFile:c})}catch(i){y.error("Error handling logs",i),r.status(500).json({error:"Internal server error"})}}handleShutdown(e,r){let n=e.ip||e.socket.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){y.warn("Shutdown request rejected from non-localhost",{ip:n}),r.status(403).json({error:"Forbidden: localhost only"});return}y.info("Shutdown request received, initiating graceful shutdown",{requestedBy:n,uptime:Date.now()-this.startTime}),r.json({status:"shutting_down",message:"Server will shutdown gracefully",pid:process.pid}),setTimeout(async()=>{try{await this.stop(),y.info("Graceful shutdown completed"),process.exit(0)}catch(a){y.error("Error during graceful shutdown",a),process.exit(1)}},100)}getCachedSelection(e=3e4,r){if(this.cachedSelectionMap.size===0)return null;let n;if(r)n=this.cachedSelectionMap.get(r);else for(let a of this.cachedSelectionMap.values())(!n||a.timestamp>n.timestamp)&&(n=a);if(!n)return null;let i=Date.now()-n.timestamp;return e===0||i<=e?n:null}async getConnectionInfo(){if(this.isClientMode)try{let n=await fetch(`${this.baseUrl}/connection-info`);if(n.ok)return await n.json()}catch(n){y.warn("Failed to fetch connection info from server",{error:n})}let e=Date.now(),r=3e4;for(let[n,i]of this.pluginClients)e-i.lastSeen>r&&(this.pluginClients.delete(n),this.pendingCommands.delete(n));return this.cleanStaleMcpInstances(),{serverInstanceId:this.instanceId,sessionId:this.sessionId,mcpVersion:Le,uptime:e-this.startTime,serverStartTime:this.startTime,serverExecutable:process.execPath,serverHost:this.config.httpHost,serverPort:this.config.httpPort,serverPid:process.pid,mcpInstances:[{instanceId:this.instanceId,pid:process.pid,connectedAt:this.startTime,isServer:!0,cwd:process.cwd()},...Array.from(this.mcpInstances.values())],mcpInstanceCount:this.mcpInstances.size+1}}async executeCommandViaHttp(e,r){let n=Kr();if(y.debug("Executing command via HTTP (client mode)",{action:e,requestId:n,baseUrl:this.baseUrl}),!this.clientModeUpstreamReachable&&!await this.probeClientModeUpstreamHealth("execute-fast-fail-check"))return{requestId:n,success:!1,error:this.buildUpstreamDownError(e)};try{let i=new AbortController,a=setTimeout(()=>i.abort(),Math.max(this.config.requestTimeout,5e3)),o=await fetch(`${this.baseUrl}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,requestId:n,params:r}),signal:i.signal});if(clearTimeout(a),!o.ok){let c=await o.text();throw new Error(`HTTP ${o.status}: ${c}`)}let s=await o.json();return this.markClientModeUpstreamHealthy(),s}catch(i){let a=await this.probeClientModeUpstreamHealth("execute-error");return y.error("HTTP execute command failed",i),a?{requestId:n,success:!1,error:i instanceof Error?i.message:"Unknown error"}:{requestId:n,success:!1,error:this.buildUpstreamDownError(e)}}}async executeCommand(e,r){if(this.isClientMode)return this.executeCommandViaHttp(e,r);let n=Kr();y.debug("Executing command",{action:e,requestId:n,params:r});let i=new Promise((a,o)=>{let s=setTimeout(()=>{this.commandQueue.delete(n),o(new Error(`Command timeout after ${this.config.requestTimeout}ms: ${e}`))},this.config.requestTimeout),c={requestId:n,action:e,params:r,timestamp:Date.now(),resolve:a,reject:o,timeoutId:s};this.commandQueue.set(n,c)});return this.broadcastCommand({event:"command",id:Kr(),data:{action:e,requestId:n,params:r}}),i}async checkExistingServer(){let e=await this.fetchStatus(this.baseUrl,2e3);return e&&y.info("Existing HTTP Bridge detected",{status:e.status,uptime:e.uptime,version:e.version,pid:e.pid}),e}async fetchStatus(e,r,n){try{let i=new AbortController,a=setTimeout(()=>i.abort(),r),o=n?`${e}/status?instanceId=${encodeURIComponent(n)}`:`${e}/status`,s=await fetch(o,{signal:i.signal});return clearTimeout(a),s.ok?await s.json():null}catch{return null}}markClientModeUpstreamHealthy(){let e=!this.clientModeUpstreamReachable;this.clientModeUpstreamReachable=!0,this.clientModeConsecutiveHealthFailures=0,this.clientModeLastHealthSuccessAt=Date.now(),this.clientModeLastHealthError=null,e&&y.info("Client mode upstream server recovered",{baseUrl:this.baseUrl})}markClientModeUpstreamFailure(e){this.clientModeConsecutiveHealthFailures+=1,this.clientModeLastHealthFailureAt=Date.now(),this.clientModeLastHealthError=e,this.clientModeConsecutiveHealthFailures>=ZC&&this.clientModeUpstreamReachable&&(this.clientModeUpstreamReachable=!1,y.warn("Client mode upstream server is unreachable",{baseUrl:this.baseUrl,consecutiveFailures:this.clientModeConsecutiveHealthFailures,threshold:ZC,error:e}))}buildUpstreamDownError(e){let r=this.clientModeLastHealthFailureAt?new Date(this.clientModeLastHealthFailureAt).toISOString():"unknown",n=this.clientModeLastHealthError||"unknown";return`UPSTREAM_SERVER_DOWN: Cannot execute "${e}" because MCP server at ${this.baseUrl} is unreachable (lastFailure=${r}, error=${n})`}async probeClientModeUpstreamHealth(e){return await this.fetchStatus(this.baseUrl,eW,this.instanceId)?(this.markClientModeUpstreamHealthy(),!0):(this.markClientModeUpstreamFailure(`status probe failed (${e})`),!1)}startClientModeHealthChecks(){this.stopClientModeHealthChecks(),this.clientModeConsecutiveHealthFailures=0,this.clientModeUpstreamReachable=!0,this.clientModeLastHealthError=null,this.clientModeHealthTimer=setInterval(()=>{this.probeClientModeUpstreamHealth("heartbeat")},QB),this.probeClientModeUpstreamHealth("startup")}stopClientModeHealthChecks(){this.clientModeHealthTimer&&(clearInterval(this.clientModeHealthTimer),this.clientModeHealthTimer=null)}async registerWithServer(){try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3),n=await fetch(`${this.baseUrl}/register-mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instanceId:this.instanceId,pid:process.pid,cwd:process.cwd(),aiClientName:this.aiClientName||void 0}),signal:e.signal});if(clearTimeout(r),n.ok){let i=await n.json();return y.info("Registered with existing server",{serverInstanceId:i.serverInstanceId,myInstanceId:this.instanceId}),!0}return!1}catch(e){return y.warn("Failed to register with existing server",{error:e}),!1}}async start(){let e=await this.checkExistingServer();if(e)if(y.info("Existing MCP server found, switching to CLIENT MODE",{existingPid:e.pid,existingUptime:e.uptime,existingConnectedClients:e.connectedClients}),this.isClientMode=!0,await this.registerWithServer()){this.startClientModeHealthChecks(),y.info("HTTP Bridge started in CLIENT MODE",{serverUrl:this.baseUrl,myPid:process.pid,myInstanceId:this.instanceId});return}else y.warn("Failed to register with server, will try to start as server");return new Promise((r,n)=>{this.server=YB(this.app),this.server.on("error",async i=>{i.code==="EADDRINUSE"?(y.info("Port in use, switching to CLIENT MODE",{port:this.config.httpPort}),this.isClientMode=!0,await this.registerWithServer()?(this.startClientModeHealthChecks(),y.info("HTTP Bridge started in CLIENT MODE (after EADDRINUSE)",{serverUrl:this.baseUrl,myPid:process.pid}),r()):n(new Error(`Port ${this.config.httpPort} is in use but failed to connect as client. Check if the existing server is responsive: curl ${this.baseUrl}/status`))):n(i)}),this.server.listen(this.config.httpPort,this.config.httpHost,async()=>{this.isClientMode=!1,this.stopClientModeHealthChecks(),this.clientModeUpstreamReachable=!0,this.clientModeConsecutiveHealthFailures=0,this.clientModeLastHealthError=null,this.clientModeLastHealthSuccessAt=null,this.clientModeLastHealthFailureAt=null,this.config.httpHost!=="127.0.0.1"&&this.config.httpHost!=="localhost"&&y.warn("HTTP_HOST is not localhost -- sync data may be exposed",{host:this.config.httpHost});try{this.syncController=new hd,await this.syncController.initialize(),y.info("SyncController initialized")}catch(i){y.error("Failed to initialize SyncController",i instanceof Error?i:new Error(String(i)))}y.info("HTTP Bridge started in SERVER MODE",{host:this.config.httpHost,port:this.config.httpPort,pid:process.pid,instanceId:this.instanceId}),r()})})}async stop(){if(y.info("Stopping HTTP Bridge",{isClientMode:this.isClientMode}),this.isClientMode){this.stopClientModeHealthChecks();try{await fetch(`${this.baseUrl}/unregister-mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instanceId:this.instanceId})}),y.info("Unregistered from server")}catch{}y.info("Client mode - stopped");return}if(this.syncController){try{await this.syncController.shutdown()}catch(e){y.error("Error shutting down SyncController",e instanceof Error?e:new Error(String(e)))}this.syncController=null}for(let e of this.sseClients)e.end();this.sseClients.clear();for(let[e,r]of this.commandQueue)clearTimeout(r.timeoutId),r.reject(new Error("Server shutting down")),this.commandQueue.delete(e);this.server&&await new Promise(e=>{this.server.close(()=>{y.info("HTTP server closed"),e()})})}getIsClientMode(){return this.isClientMode}},HC=Ab;var tW=new Set(["get_selection_context","get_selection_details","add_to_selection","remove_from_selection","watch_selection","get_place_info","get_services","get_studio_settings","run_command","replace_in_scripts","execute_script","get_file_tree","get_project_structure","search_by_property","search_by_tag","get_descendants","get_ancestors","mass_create_instances","mass_delete_instances","mass_set_property","mass_get_property","mass_duplicate","smart_duplicate","batch_execute","modify_children","insert_model","get_asset_info","search_creator_store","search_and_insert_model","insert_free_model","insert_package","export_selection","set_lighting","set_atmosphere","set_sky","set_terrain","set_time_of_day","sync_workspace_state","get_workspace_snapshot","get_recent_changes","get_viewport_info","clear_change_history","get_workspace_metadata","get_script_list","get_selection_info","clear_state_cache","get_spatial_map","find_empty_space","get_bounds","snap_to_grid","check_collision","raycast","find_ground","check_placement","multi_raycast","scan_area","find_flat_areas","find_spawn_positions","analyze_walkable_area","terrain_fill_block","terrain_fill_ball","terrain_fill_cylinder","terrain_fill_wedge","terrain_clear","terrain_clear_region","terrain_replace_material","terrain_get_material_color","terrain_set_material_color","terrain_read_voxel","terrain_read_voxels","terrain_write_voxels","terrain_generate","terrain_smooth","set_calculated_property","set_relative_property","create_instance_tree","create_tween","play_tween","pause_tween","cancel_tween","play_sound","stop_sound","pause_sound","resume_sound","set_listener","load_animation","play_animation","stop_animation","get_animation_tracks","register_collision_group","set_collidable","get_collision_groups","emit_particles","clear_particles","toggle_effect","extended_get_property","extended_set_property","extended_call_method","extended_get_properties","extended_set_properties","extended_call_methods","execute_luau","sync_status","sync_config","sync_history","sync_directions","sync_read_file","sync_write_file","sync_progress"]);function pc(t){return tW.has(t)?"pro":"basic"}var rW={query_instances:{discriminator:"action",mapping:{get:"get_instance",children:"get_instance_children",find_child:"find_first_child",find_descendant:"find_first_descendant",wait_for_child:"wait_for_child",class_info:"get_class_info",search_name:"search_by_name",search_class:"search_by_class",search_property:"search_by_property",search_tag:"search_by_tag",file_tree:"get_file_tree",project_structure:"get_project_structure",descendants:"get_descendants",ancestors:"get_ancestors"},paramAliases:{search_by_name:{query:"pattern"},search_by_property:{root:"rootPath"},search_by_tag:{root:"rootPath"},get_project_structure:{root:"rootPath"}}},mutate_instances:{discriminator:"action",mapping:{create:"create_instance",create_with_props:"create_instance_with_properties",delete:"delete_instance",clone:"clone_instance",move:"move_instance",rename:"rename_instance",pivot:"pivot_to",create_tree:"create_instance_tree",mass_create:"mass_create_instances",mass_delete:"mass_delete_instances",mass_duplicate:"mass_duplicate",smart_duplicate:"smart_duplicate"},paramAliases:{clone_instance:{path:"sourcePath"}}},manage_properties:{discriminator:"action",mapping:{get:"get_property",set:"set_property",get_all:"get_all_properties",set_multiple:"set_multiple_properties",get_attr:"get_attribute",set_attr:"set_attribute",get_all_attrs:"get_all_attributes",delete_attr:"delete_attribute",add_tag:"add_tag",remove_tag:"remove_tag",check_tag:"has_tag",get_tags:"get_tags",get_tagged:"get_tagged",set_calculated:"set_calculated_property",set_relative:"set_relative_property",mass_set:"mass_set_property",mass_get:"mass_get_property",modify_children:"modify_children"},paramAliases:{get_tagged:{tagName:"tag",root:"rootPath"},set_relative_property:{amount:"value"}}},manage_scripts:{discriminator:"action",mapping:{get_source:"get_script_source",set_source:"set_script_source",create:"create_script",delete:"delete_script",edit_replace:"edit_script_lines",edit_insert:"insert_script_lines",edit_delete:"delete_script_lines",search:"search_in_scripts",replace:"replace_in_scripts",get_dependencies:"get_script_dependencies"},paramAliases:{replace_in_scripts:{pattern:"searchPattern"},edit_script_lines:{newLines:"newContent"},insert_script_lines:{lines:"content"}}},manage_lighting:{discriminator:"action",mapping:{lighting:"set_lighting",atmosphere:"set_atmosphere",sky:"set_sky",terrain_props:"set_terrain",time:"set_time_of_day"}},manage_selection:{discriminator:"action",mapping:{get:"get_selection",set:"set_selection",clear:"clear_selection",cached:"get_cached_selection",context:"get_selection_context",details:"get_selection_details",add:"add_to_selection",remove:"remove_from_selection",watch:"watch_selection"}},manage_camera:{discriminator:"action",mapping:{info:"get_camera_info",focus_path:"focus_camera_path",focus_position:"focus_camera_position",suggest:"get_suggested_camera_view"},paramAliases:{get_suggested_camera_view:{path:"targetPath"}}},manage_tween:{discriminator:"action",mapping:{create:"create_tween",play:"play_tween",pause:"pause_tween",cancel:"cancel_tween"}},manage_audio:{discriminator:"action",mapping:{play:"play_sound",stop:"stop_sound",pause:"pause_sound",resume:"resume_sound",set_listener:"set_listener"}},manage_animation:{discriminator:"action",mapping:{load:"load_animation",play:"play_animation",stop:"stop_animation",get_tracks:"get_animation_tracks"}},manage_physics:{discriminator:"action",mapping:{register_group:"register_collision_group",set_collidable:"set_collidable",get_groups:"get_collision_groups"}},manage_effects:{discriminator:"action",mapping:{emit:"emit_particles",clear:"clear_particles",toggle:"toggle_effect"}},manage_terrain:{discriminator:"action",mapping:{fill_block:"terrain_fill_block",fill_ball:"terrain_fill_ball",fill_cylinder:"terrain_fill_cylinder",fill_wedge:"terrain_fill_wedge",clear_region:"terrain_clear",clear_bounds:"terrain_clear_region",replace_material:"terrain_replace_material",colors_get:"terrain_get_material_color",colors_set:"terrain_set_material_color",read_voxel:"terrain_read_voxel",read_voxels:"terrain_read_voxels",write_voxels:"terrain_write_voxels",generate:"terrain_generate",smooth:"terrain_smooth"}},spatial_query:{discriminator:"action",mapping:{raycast:"raycast",find_ground:"find_ground",check_placement:"check_placement",multi_raycast:"multi_raycast",scan_area:"scan_area",find_flat:"find_flat_areas",find_spawn:"find_spawn_positions",analyze_walkable:"analyze_walkable_area",spatial_map:"get_spatial_map",find_space:"find_empty_space",bounds:"get_bounds",snap_grid:"snap_to_grid",collision:"check_collision"},paramAliases:{get_spatial_map:{path:"rootPath"}}},manage_assets:{discriminator:"action",mapping:{insert:"insert_model",info:"get_asset_info",search:"search_creator_store",search_insert:"search_and_insert_model",insert_free:"insert_free_model",insert_package:"insert_package",export:"export_selection"},paramAliases:{search_creator_store:{maxResults:"limit"}}},manage_sync:{discriminator:"action",mapping:{status:"sync_status",config:"sync_config",history:"sync_history",directions:"sync_directions",read_file:"sync_read_file",write_file:"sync_write_file",progress:"sync_progress"}},workspace_state:{discriminator:"action",mapping:{sync:"sync_workspace_state",snapshot:"get_workspace_snapshot",changes:"get_recent_changes",viewport:"get_viewport_info"}},manage_logs:{discriminator:"action",mapping:{get:"get_output_logs",clear:"clear_output_logs",errors:"get_recent_errors"},paramAliases:{get_output_logs:{level:"type"}}},system_info:{discriminator:"action",mapping:{ping:"ping",connection:"get_connection_info",usage:"get_usage_status",place_info:"get_place_info",services:"get_services",studio_settings:"get_studio_settings",run_command:"run_command"}}};function Nb(t,e){let r=rW[t];if(!r){if(t==="batch_execute"&&Array.isArray(e.commands)){let c=e.commands.map(l=>Nb(l.tool,l.args||{}));return{action:t,params:{...e,commands:c}}}return{action:t,params:e}}let n=e[r.discriminator],i=r.mapping[n];if(!i){let c=Object.keys(r.mapping).join(", ");throw new Error(`Invalid ${r.discriminator} "${n}" for tool "${t}". Valid values: ${c}`)}let{[r.discriminator]:a,...o}=e,s=r.paramAliases?.[i];if(s)for(let[c,l]of Object.entries(s))c in o&&!(l in o)&&(o[l]=o[c],delete o[c]);return{action:i,params:o}}var nW={manage_scripts:["scripts"],manage_properties:["values","data"],mutate_instances:["containers"],manage_lighting:["services"]},iW=new Set(["manage_sync"]),aW=new Set(["query_instances","manage_selection","manage_camera","manage_tween","manage_audio","manage_animation","manage_physics","manage_effects","manage_terrain","spatial_query","manage_assets","workspace_state","manage_logs","system_info","batch_execute","execute_luau"]);function VC(t,e,r){if(iW.has(t))return{target:"internal"};if(aW.has(t))return{target:"plugin"};let n=nW[t];if(!n||!r)return{target:"plugin"};try{let i=r.getStatusSummary();if(!i||!i.active)return{target:"plugin"};for(let a of n)if(r.getDirectionForCategory(a)==="reverse")return{target:"disk"}}catch{}return{target:"plugin"}}import*as zr from"fs";import*as Da from"path";import{randomUUID as BC}from"crypto";var oW=new Map([["query_instances","instance"],["mutate_instances","instance"],["manage_properties","property"],["manage_scripts","script"],["manage_lighting","environment"],["manage_selection","selection"],["manage_camera","camera"],["manage_tween","tween"],["manage_audio","audio"],["manage_animation","animation"],["manage_physics","physics"],["manage_effects","effects"],["manage_terrain","terrain"],["spatial_query","spatial"],["manage_assets","asset"],["manage_sync","sync"],["workspace_state","state"],["manage_logs","log"],["system_info","connection"],["batch_execute","bulk"],["execute_luau","script"]]);function ur(t){return oW.get(t)||"unknown"}var sW={enableHistory:!1,enableStatistics:!0,dataDir:Pn(),maxHistoryFileSize:10*1024*1024,maxHistoryFiles:100};function Mb(){return{version:1,lastUpdated:new Date().toISOString(),totalSessions:0,totalCalls:0,totalSuccessCalls:0,totalFailedCalls:0,tools:{},tierSummary:{basic:{totalCalls:0,successCount:0,failureCount:0},pro:{totalCalls:0,successCount:0,failureCount:0}},categorySummary:{}}}var yd=class{config;sessionId="";sequenceNumber=0;statistics;historyDir;statisticsDir;historyFilePath=null;statisticsFilePath;failureLogPath;initialized=!1;saveStatisticsDebounceTimer=null;pendingStatisticsSave=!1;constructor(e={}){this.config={...sW,...e},this.historyDir=Da.join(this.config.dataDir,"history"),this.statisticsDir=Da.join(this.config.dataDir,"statistics"),this.statisticsFilePath=Da.join(this.statisticsDir,"tool-stats.json"),this.failureLogPath=Da.join(this.statisticsDir,"failures.jsonl"),this.statistics=Mb()}async initialize(e){this.sessionId=e,this.sequenceNumber=0;try{if(!this.config.enableHistory&&!this.config.enableStatistics){this.initialized=!0,y.info("Tool history manager initialized (all features disabled)",{sessionId:e});return}if(await this.ensureDirectories(),await this.loadStatistics(),this.statistics.totalSessions++,this.config.enableHistory){let r=new Date().toISOString().split("T")[0],n=`session-${e}-${r}.jsonl`;this.historyFilePath=Da.join(this.historyDir,n);let i={sessionId:e,startTime:new Date().toISOString(),totalCommands:0,pid:process.pid,version:Le};await zr.promises.appendFile(this.historyFilePath,`# SESSION_START ${JSON.stringify(i)}
|
|
129
|
+
`);await gd.writeFile(u,m,"utf-8")}catch(d){y.warn("Failed to update current.log",{error:d})}y.debug("Logs received from plugin",{count:i.logs.length,clientId:n||"legacy",logFile:c}),r.json({status:"ok",logsReceived:i.logs.length,logFile:c})}catch(i){y.error("Error handling logs",i),r.status(500).json({error:"Internal server error"})}}handleShutdown(e,r){let n=e.ip||e.socket.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){y.warn("Shutdown request rejected from non-localhost",{ip:n}),r.status(403).json({error:"Forbidden: localhost only"});return}y.info("Shutdown request received, initiating graceful shutdown",{requestedBy:n,uptime:Date.now()-this.startTime}),r.json({status:"shutting_down",message:"Server will shutdown gracefully",pid:process.pid}),setTimeout(async()=>{try{await this.stop(),y.info("Graceful shutdown completed"),process.exit(0)}catch(a){y.error("Error during graceful shutdown",a),process.exit(1)}},100)}getCachedSelection(e=3e4,r){if(this.cachedSelectionMap.size===0)return null;let n;if(r)n=this.cachedSelectionMap.get(r);else for(let a of this.cachedSelectionMap.values())(!n||a.timestamp>n.timestamp)&&(n=a);if(!n)return null;let i=Date.now()-n.timestamp;return e===0||i<=e?n:null}async getConnectionInfo(){if(this.isClientMode)try{let n=await fetch(`${this.baseUrl}/connection-info`);if(n.ok)return await n.json()}catch(n){y.warn("Failed to fetch connection info from server",{error:n})}let e=Date.now(),r=3e4;for(let[n,i]of this.pluginClients)e-i.lastSeen>r&&(this.pluginClients.delete(n),this.pendingCommands.delete(n));return this.cleanStaleMcpInstances(),{serverInstanceId:this.instanceId,sessionId:this.sessionId,mcpVersion:Le,uptime:e-this.startTime,serverStartTime:this.startTime,serverExecutable:process.execPath,serverHost:this.config.httpHost,serverPort:this.config.httpPort,serverPid:process.pid,mcpInstances:[{instanceId:this.instanceId,pid:process.pid,connectedAt:this.startTime,isServer:!0,cwd:process.cwd()},...Array.from(this.mcpInstances.values())],mcpInstanceCount:this.mcpInstances.size+1}}async executeCommandViaHttp(e,r){let n=Kr();if(y.debug("Executing command via HTTP (client mode)",{action:e,requestId:n,baseUrl:this.baseUrl}),!this.clientModeUpstreamReachable&&!await this.probeClientModeUpstreamHealth("execute-fast-fail-check"))return{requestId:n,success:!1,error:this.buildUpstreamDownError(e)};try{let i=new AbortController,a=setTimeout(()=>i.abort(),Math.max(this.config.requestTimeout,5e3)),o=await fetch(`${this.baseUrl}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,requestId:n,params:r}),signal:i.signal});if(clearTimeout(a),!o.ok){let c=await o.text();throw new Error(`HTTP ${o.status}: ${c}`)}let s=await o.json();return this.markClientModeUpstreamHealthy(),s}catch(i){let a=await this.probeClientModeUpstreamHealth("execute-error");return y.error("HTTP execute command failed",i),a?{requestId:n,success:!1,error:i instanceof Error?i.message:"Unknown error"}:{requestId:n,success:!1,error:this.buildUpstreamDownError(e)}}}async executeCommand(e,r){if(this.isClientMode)return this.executeCommandViaHttp(e,r);let n=Kr();y.debug("Executing command",{action:e,requestId:n,params:r});let i=new Promise((a,o)=>{let s=setTimeout(()=>{this.commandQueue.delete(n),o(new Error(`Command timeout after ${this.config.requestTimeout}ms: ${e}`))},this.config.requestTimeout),c={requestId:n,action:e,params:r,timestamp:Date.now(),resolve:a,reject:o,timeoutId:s};this.commandQueue.set(n,c)});return this.broadcastCommand({event:"command",id:Kr(),data:{action:e,requestId:n,params:r}}),i}async checkExistingServer(){let e=await this.fetchStatus(this.baseUrl,2e3);return e&&y.info("Existing HTTP Bridge detected",{status:e.status,uptime:e.uptime,version:e.version,pid:e.pid}),e}async fetchStatus(e,r,n){try{let i=new AbortController,a=setTimeout(()=>i.abort(),r),o=n?`${e}/status?instanceId=${encodeURIComponent(n)}`:`${e}/status`,s=await fetch(o,{signal:i.signal});return clearTimeout(a),s.ok?await s.json():null}catch{return null}}markClientModeUpstreamHealthy(){let e=!this.clientModeUpstreamReachable;this.clientModeUpstreamReachable=!0,this.clientModeConsecutiveHealthFailures=0,this.clientModeLastHealthSuccessAt=Date.now(),this.clientModeLastHealthError=null,e&&y.info("Client mode upstream server recovered",{baseUrl:this.baseUrl})}markClientModeUpstreamFailure(e){this.clientModeConsecutiveHealthFailures+=1,this.clientModeLastHealthFailureAt=Date.now(),this.clientModeLastHealthError=e,this.clientModeConsecutiveHealthFailures>=ZC&&this.clientModeUpstreamReachable&&(this.clientModeUpstreamReachable=!1,y.warn("Client mode upstream server is unreachable",{baseUrl:this.baseUrl,consecutiveFailures:this.clientModeConsecutiveHealthFailures,threshold:ZC,error:e}))}buildUpstreamDownError(e){let r=this.clientModeLastHealthFailureAt?new Date(this.clientModeLastHealthFailureAt).toISOString():"unknown",n=this.clientModeLastHealthError||"unknown";return`UPSTREAM_SERVER_DOWN: Cannot execute "${e}" because MCP server at ${this.baseUrl} is unreachable (lastFailure=${r}, error=${n})`}async probeClientModeUpstreamHealth(e){return await this.fetchStatus(this.baseUrl,eW,this.instanceId)?(this.markClientModeUpstreamHealthy(),!0):(this.markClientModeUpstreamFailure(`status probe failed (${e})`),!1)}startClientModeHealthChecks(){this.stopClientModeHealthChecks(),this.clientModeConsecutiveHealthFailures=0,this.clientModeUpstreamReachable=!0,this.clientModeLastHealthError=null,this.clientModeHealthTimer=setInterval(()=>{this.probeClientModeUpstreamHealth("heartbeat")},QB),this.probeClientModeUpstreamHealth("startup")}stopClientModeHealthChecks(){this.clientModeHealthTimer&&(clearInterval(this.clientModeHealthTimer),this.clientModeHealthTimer=null)}async registerWithServer(){try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3),n=await fetch(`${this.baseUrl}/register-mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instanceId:this.instanceId,pid:process.pid,cwd:process.cwd(),aiClientName:this.aiClientName||void 0}),signal:e.signal});if(clearTimeout(r),n.ok){let i=await n.json();return y.info("Registered with existing server",{serverInstanceId:i.serverInstanceId,myInstanceId:this.instanceId}),!0}return!1}catch(e){return y.warn("Failed to register with existing server",{error:e}),!1}}async start(){let e=await this.checkExistingServer();if(e)if(y.info("Existing MCP server found, switching to CLIENT MODE",{existingPid:e.pid,existingUptime:e.uptime,existingConnectedClients:e.connectedClients}),this.isClientMode=!0,await this.registerWithServer()){this.startClientModeHealthChecks(),y.info("HTTP Bridge started in CLIENT MODE",{serverUrl:this.baseUrl,myPid:process.pid,myInstanceId:this.instanceId});return}else y.warn("Failed to register with server, will try to start as server");return new Promise((r,n)=>{this.server=YB(this.app),this.server.on("error",async i=>{i.code==="EADDRINUSE"?(y.info("Port in use, switching to CLIENT MODE",{port:this.config.httpPort}),this.isClientMode=!0,await this.registerWithServer()?(this.startClientModeHealthChecks(),y.info("HTTP Bridge started in CLIENT MODE (after EADDRINUSE)",{serverUrl:this.baseUrl,myPid:process.pid}),r()):n(new Error(`Port ${this.config.httpPort} is in use but failed to connect as client. Check if the existing server is responsive: curl ${this.baseUrl}/status`))):n(i)}),this.server.listen(this.config.httpPort,this.config.httpHost,async()=>{this.isClientMode=!1,this.stopClientModeHealthChecks(),this.clientModeUpstreamReachable=!0,this.clientModeConsecutiveHealthFailures=0,this.clientModeLastHealthError=null,this.clientModeLastHealthSuccessAt=null,this.clientModeLastHealthFailureAt=null,this.config.httpHost!=="127.0.0.1"&&this.config.httpHost!=="localhost"&&y.warn("HTTP_HOST is not localhost -- sync data may be exposed",{host:this.config.httpHost});try{this.syncController=new hd,await this.syncController.initialize(),y.info("SyncController initialized")}catch(i){y.error("Failed to initialize SyncController",i instanceof Error?i:new Error(String(i)))}y.info("HTTP Bridge started in SERVER MODE",{host:this.config.httpHost,port:this.config.httpPort,pid:process.pid,instanceId:this.instanceId}),r()})})}async stop(){if(y.info("Stopping HTTP Bridge",{isClientMode:this.isClientMode}),this.isClientMode){this.stopClientModeHealthChecks();try{await fetch(`${this.baseUrl}/unregister-mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instanceId:this.instanceId})}),y.info("Unregistered from server")}catch{}y.info("Client mode - stopped");return}if(this.syncController){try{await this.syncController.shutdown()}catch(e){y.error("Error shutting down SyncController",e instanceof Error?e:new Error(String(e)))}this.syncController=null}for(let e of this.sseClients)e.end();this.sseClients.clear();for(let[e,r]of this.commandQueue)clearTimeout(r.timeoutId),r.reject(new Error("Server shutting down")),this.commandQueue.delete(e);this.server&&await new Promise(e=>{this.server.close(()=>{y.info("HTTP server closed"),e()})})}getIsClientMode(){return this.isClientMode}},HC=Ab;var tW=new Set(["get_selection_context","get_selection_details","add_to_selection","remove_from_selection","watch_selection","get_place_info","get_services","get_studio_settings","replace_in_scripts","execute_script","get_file_tree","get_project_structure","search_by_property","search_by_tag","get_descendants","get_ancestors","mass_create_instances","mass_delete_instances","mass_set_property","mass_get_property","mass_duplicate","smart_duplicate","batch_execute","modify_children","insert_model","get_asset_info","search_creator_store","search_and_insert_model","insert_free_model","insert_package","export_selection","set_lighting","set_atmosphere","set_sky","set_terrain","set_time_of_day","sync_workspace_state","get_workspace_snapshot","get_recent_changes","get_viewport_info","clear_change_history","get_workspace_metadata","get_script_list","get_selection_info","clear_state_cache","get_spatial_map","find_empty_space","get_bounds","snap_to_grid","check_collision","raycast","find_ground","check_placement","multi_raycast","scan_area","find_flat_areas","find_spawn_positions","analyze_walkable_area","terrain_fill_block","terrain_fill_ball","terrain_fill_cylinder","terrain_fill_wedge","terrain_clear","terrain_clear_region","terrain_replace_material","terrain_get_material_color","terrain_set_material_color","terrain_read_voxel","terrain_read_voxels","terrain_write_voxels","terrain_generate","terrain_smooth","set_calculated_property","set_relative_property","create_instance_tree","create_tween","play_tween","pause_tween","cancel_tween","play_sound","stop_sound","pause_sound","resume_sound","set_listener","load_animation","play_animation","stop_animation","get_animation_tracks","register_collision_group","set_collidable","get_collision_groups","emit_particles","clear_particles","toggle_effect","extended_get_property","extended_set_property","extended_call_method","extended_get_properties","extended_set_properties","extended_call_methods","execute_luau","sync_status","sync_config","sync_history","sync_directions","sync_read_file","sync_write_file","sync_progress"]);function pc(t){return tW.has(t)?"pro":"basic"}var rW={query_instances:{discriminator:"action",mapping:{get:"get_instance",children:"get_instance_children",find_child:"find_first_child",find_descendant:"find_first_descendant",wait_for_child:"wait_for_child",class_info:"get_class_info",search_name:"search_by_name",search_class:"search_by_class",search_property:"search_by_property",search_tag:"search_by_tag",file_tree:"get_file_tree",project_structure:"get_project_structure",descendants:"get_descendants",ancestors:"get_ancestors"},paramAliases:{search_by_name:{query:"pattern"},search_by_property:{root:"rootPath"},search_by_tag:{root:"rootPath"},get_project_structure:{root:"rootPath"}}},mutate_instances:{discriminator:"action",mapping:{create:"create_instance",create_with_props:"create_instance_with_properties",delete:"delete_instance",clone:"clone_instance",move:"move_instance",rename:"rename_instance",pivot:"pivot_to",create_tree:"create_instance_tree",mass_create:"mass_create_instances",mass_delete:"mass_delete_instances",mass_duplicate:"mass_duplicate",smart_duplicate:"smart_duplicate"},paramAliases:{clone_instance:{path:"sourcePath"}}},manage_properties:{discriminator:"action",mapping:{get:"get_property",set:"set_property",get_all:"get_all_properties",set_multiple:"set_multiple_properties",get_attr:"get_attribute",set_attr:"set_attribute",get_all_attrs:"get_all_attributes",delete_attr:"delete_attribute",add_tag:"add_tag",remove_tag:"remove_tag",check_tag:"has_tag",get_tags:"get_tags",get_tagged:"get_tagged",set_calculated:"set_calculated_property",set_relative:"set_relative_property",mass_set:"mass_set_property",mass_get:"mass_get_property",modify_children:"modify_children"},paramAliases:{get_tagged:{tagName:"tag",root:"rootPath"},set_relative_property:{amount:"value"}}},manage_scripts:{discriminator:"action",mapping:{get_source:"get_script_source",set_source:"set_script_source",create:"create_script",delete:"delete_script",edit_replace:"edit_script_lines",edit_insert:"insert_script_lines",edit_delete:"delete_script_lines",search:"search_in_scripts",replace:"replace_in_scripts",get_dependencies:"get_script_dependencies"},paramAliases:{replace_in_scripts:{pattern:"searchPattern"},edit_script_lines:{newLines:"newContent"},insert_script_lines:{lines:"content"}}},manage_lighting:{discriminator:"action",mapping:{lighting:"set_lighting",atmosphere:"set_atmosphere",sky:"set_sky",terrain_props:"set_terrain",time:"set_time_of_day"}},manage_selection:{discriminator:"action",mapping:{get:"get_selection",set:"set_selection",clear:"clear_selection",cached:"get_cached_selection",context:"get_selection_context",details:"get_selection_details",add:"add_to_selection",remove:"remove_from_selection",watch:"watch_selection"}},manage_camera:{discriminator:"action",mapping:{info:"get_camera_info",focus_path:"focus_camera_path",focus_position:"focus_camera_position",suggest:"get_suggested_camera_view"},paramAliases:{get_suggested_camera_view:{path:"targetPath"}}},manage_tween:{discriminator:"action",mapping:{create:"create_tween",play:"play_tween",pause:"pause_tween",cancel:"cancel_tween"}},manage_audio:{discriminator:"action",mapping:{play:"play_sound",stop:"stop_sound",pause:"pause_sound",resume:"resume_sound",set_listener:"set_listener"}},manage_animation:{discriminator:"action",mapping:{load:"load_animation",play:"play_animation",stop:"stop_animation",get_tracks:"get_animation_tracks"}},manage_physics:{discriminator:"action",mapping:{register_group:"register_collision_group",set_collidable:"set_collidable",get_groups:"get_collision_groups"}},manage_effects:{discriminator:"action",mapping:{emit:"emit_particles",clear:"clear_particles",toggle:"toggle_effect"}},manage_terrain:{discriminator:"action",mapping:{fill_block:"terrain_fill_block",fill_ball:"terrain_fill_ball",fill_cylinder:"terrain_fill_cylinder",fill_wedge:"terrain_fill_wedge",clear_region:"terrain_clear",clear_bounds:"terrain_clear_region",replace_material:"terrain_replace_material",colors_get:"terrain_get_material_color",colors_set:"terrain_set_material_color",read_voxel:"terrain_read_voxel",read_voxels:"terrain_read_voxels",write_voxels:"terrain_write_voxels",generate:"terrain_generate",smooth:"terrain_smooth"}},spatial_query:{discriminator:"action",mapping:{raycast:"raycast",find_ground:"find_ground",check_placement:"check_placement",multi_raycast:"multi_raycast",scan_area:"scan_area",find_flat:"find_flat_areas",find_spawn:"find_spawn_positions",analyze_walkable:"analyze_walkable_area",spatial_map:"get_spatial_map",find_space:"find_empty_space",bounds:"get_bounds",snap_grid:"snap_to_grid",collision:"check_collision"},paramAliases:{get_spatial_map:{path:"rootPath"}}},manage_assets:{discriminator:"action",mapping:{insert:"insert_model",info:"get_asset_info",search:"search_creator_store",search_insert:"search_and_insert_model",insert_free:"insert_free_model",insert_package:"insert_package",export:"export_selection"},paramAliases:{search_creator_store:{maxResults:"limit"}}},manage_sync:{discriminator:"action",mapping:{status:"sync_status",config:"sync_config",history:"sync_history",directions:"sync_directions",read_file:"sync_read_file",write_file:"sync_write_file",progress:"sync_progress"}},workspace_state:{discriminator:"action",mapping:{sync:"sync_workspace_state",snapshot:"get_workspace_snapshot",changes:"get_recent_changes",viewport:"get_viewport_info"}},manage_logs:{discriminator:"action",mapping:{get:"get_output_logs",clear:"clear_output_logs",errors:"get_recent_errors"},paramAliases:{get_output_logs:{level:"type"}}},system_info:{discriminator:"action",mapping:{ping:"ping",connection:"get_connection_info",usage:"get_usage_status",place_info:"get_place_info",services:"get_services",studio_settings:"get_studio_settings"}}};function Nb(t,e){let r=rW[t];if(!r){if(t==="batch_execute"&&Array.isArray(e.commands)){let c=e.commands.map(l=>Nb(l.tool,l.args||{}));return{action:t,params:{...e,commands:c}}}return{action:t,params:e}}let n=e[r.discriminator],i=r.mapping[n];if(!i){let c=Object.keys(r.mapping).join(", ");throw new Error(`Invalid ${r.discriminator} "${n}" for tool "${t}". Valid values: ${c}`)}let{[r.discriminator]:a,...o}=e,s=r.paramAliases?.[i];if(s)for(let[c,l]of Object.entries(s))c in o&&!(l in o)&&(o[l]=o[c],delete o[c]);return{action:i,params:o}}var nW={manage_scripts:["scripts"],manage_properties:["values","data"],mutate_instances:["containers"],manage_lighting:["services"]},iW=new Set(["manage_sync"]),aW=new Set(["query_instances","manage_selection","manage_camera","manage_tween","manage_audio","manage_animation","manage_physics","manage_effects","manage_terrain","spatial_query","manage_assets","workspace_state","manage_logs","system_info","batch_execute","execute_luau"]);function VC(t,e,r){if(iW.has(t))return{target:"internal"};if(aW.has(t))return{target:"plugin"};let n=nW[t];if(!n||!r)return{target:"plugin"};try{let i=r.getStatusSummary();if(!i||!i.active)return{target:"plugin"};for(let a of n)if(r.getDirectionForCategory(a)==="reverse")return{target:"disk"}}catch{}return{target:"plugin"}}import*as zr from"fs";import*as Da from"path";import{randomUUID as BC}from"crypto";var oW=new Map([["query_instances","instance"],["mutate_instances","instance"],["manage_properties","property"],["manage_scripts","script"],["manage_lighting","environment"],["manage_selection","selection"],["manage_camera","camera"],["manage_tween","tween"],["manage_audio","audio"],["manage_animation","animation"],["manage_physics","physics"],["manage_effects","effects"],["manage_terrain","terrain"],["spatial_query","spatial"],["manage_assets","asset"],["manage_sync","sync"],["workspace_state","state"],["manage_logs","log"],["system_info","connection"],["batch_execute","bulk"],["execute_luau","script"]]);function ur(t){return oW.get(t)||"unknown"}var sW={enableHistory:!1,enableStatistics:!0,dataDir:Pn(),maxHistoryFileSize:10*1024*1024,maxHistoryFiles:100};function Mb(){return{version:1,lastUpdated:new Date().toISOString(),totalSessions:0,totalCalls:0,totalSuccessCalls:0,totalFailedCalls:0,tools:{},tierSummary:{basic:{totalCalls:0,successCount:0,failureCount:0},pro:{totalCalls:0,successCount:0,failureCount:0}},categorySummary:{}}}var yd=class{config;sessionId="";sequenceNumber=0;statistics;historyDir;statisticsDir;historyFilePath=null;statisticsFilePath;failureLogPath;initialized=!1;saveStatisticsDebounceTimer=null;pendingStatisticsSave=!1;constructor(e={}){this.config={...sW,...e},this.historyDir=Da.join(this.config.dataDir,"history"),this.statisticsDir=Da.join(this.config.dataDir,"statistics"),this.statisticsFilePath=Da.join(this.statisticsDir,"tool-stats.json"),this.failureLogPath=Da.join(this.statisticsDir,"failures.jsonl"),this.statistics=Mb()}async initialize(e){this.sessionId=e,this.sequenceNumber=0;try{if(!this.config.enableHistory&&!this.config.enableStatistics){this.initialized=!0,y.info("Tool history manager initialized (all features disabled)",{sessionId:e});return}if(await this.ensureDirectories(),await this.loadStatistics(),this.statistics.totalSessions++,this.config.enableHistory){let r=new Date().toISOString().split("T")[0],n=`session-${e}-${r}.jsonl`;this.historyFilePath=Da.join(this.historyDir,n);let i={sessionId:e,startTime:new Date().toISOString(),totalCommands:0,pid:process.pid,version:Le};await zr.promises.appendFile(this.historyFilePath,`# SESSION_START ${JSON.stringify(i)}
|
|
130
130
|
`)}this.initialized=!0,y.info("Tool history manager initialized",{sessionId:e,historyEnabled:this.config.enableHistory,statisticsEnabled:this.config.enableStatistics,dataDir:this.config.dataDir})}catch(r){throw y.error("Failed to initialize tool history manager",r),r}}async ensureDirectories(){await zr.promises.mkdir(this.historyDir,{recursive:!0}),await zr.promises.mkdir(this.statisticsDir,{recursive:!0})}async loadStatistics(){try{let e=await zr.promises.readFile(this.statisticsFilePath,"utf-8");this.statistics=JSON.parse(e),y.debug("Loaded existing statistics",{totalCalls:this.statistics.totalCalls,totalSessions:this.statistics.totalSessions})}catch(e){e.code==="ENOENT"?(this.statistics=Mb(),y.debug("No existing statistics file, starting fresh")):(y.error("Failed to load statistics, starting fresh",e),this.statistics=Mb())}}async saveStatistics(){if(this.config.enableStatistics){if(this.saveStatisticsDebounceTimer){this.pendingStatisticsSave=!0;return}this.statistics.lastUpdated=new Date().toISOString();try{await zr.promises.writeFile(this.statisticsFilePath,JSON.stringify(this.statistics,null,2))}catch(e){y.error("Failed to save statistics",e)}this.saveStatisticsDebounceTimer=setTimeout(async()=>{this.saveStatisticsDebounceTimer=null,this.pendingStatisticsSave&&(this.pendingStatisticsSave=!1,await this.saveStatistics())},1e3)}}async recordSuccess(e,r,n,i,a){if(!this.initialized){y.warn("Tool history manager not initialized, skipping record");return}let o=pc(e),s=ur(e),c=new Date().toISOString();if(this.config.enableStatistics&&(this.updateToolStats(e,s,o,!0,i,c),await this.saveStatistics()),this.config.enableHistory&&this.historyFilePath){this.sequenceNumber++;let l={id:BC(),sessionId:this.sessionId,timestamp:c,sequenceNumber:this.sequenceNumber,toolName:e,category:s,tier:o,parameters:r,result:n,executionTimeMs:i,clientId:a};try{await zr.promises.appendFile(this.historyFilePath,JSON.stringify(l)+`
|
|
131
131
|
`)}catch(u){y.error("Failed to write history entry",u)}}}async recordFailure(e,r,n,i,a){if(!this.initialized){y.warn("Tool history manager not initialized, skipping record");return}let o=pc(e),s=ur(e),c=new Date().toISOString();if(this.config.enableStatistics){this.updateToolStats(e,s,o,!1,i||0,c),await this.saveStatistics();let l={id:BC(),sessionId:this.sessionId,timestamp:c,toolName:e,category:s,tier:o,parameters:r,errorMessage:n,errorCode:a,executionTimeMs:i};try{await zr.promises.appendFile(this.failureLogPath,JSON.stringify(l)+`
|
|
132
132
|
`)}catch(u){y.error("Failed to write failure log",u)}}}updateToolStats(e,r,n,i,a,o){this.statistics.totalCalls++,i?this.statistics.totalSuccessCalls++:this.statistics.totalFailedCalls++,this.statistics.tierSummary[n].totalCalls++,i?this.statistics.tierSummary[n].successCount++:this.statistics.tierSummary[n].failureCount++,this.statistics.categorySummary[r]||(this.statistics.categorySummary[r]={totalCalls:0,successCount:0,failureCount:0}),this.statistics.categorySummary[r].totalCalls++,i?this.statistics.categorySummary[r].successCount++:this.statistics.categorySummary[r].failureCount++,this.statistics.tools[e]||(this.statistics.tools[e]={toolName:e,category:r,tier:n,totalCalls:0,successCount:0,failureCount:0,totalExecutionTimeMs:0,avgExecutionTimeMs:0,firstUsed:o,lastUsed:o});let s=this.statistics.tools[e];s.totalCalls++,s.totalExecutionTimeMs+=a,s.avgExecutionTimeMs=Math.round(s.totalExecutionTimeMs/s.totalCalls),s.lastUsed=o,i?s.successCount++:s.failureCount++}getStatistics(){return{...this.statistics}}getTopTools(e=10){return Object.values(this.statistics.tools).sort((r,n)=>n.totalCalls-r.totalCalls).slice(0,e)}async shutdown(){if(this.initialized){if(this.saveStatisticsDebounceTimer&&(clearTimeout(this.saveStatisticsDebounceTimer),this.saveStatisticsDebounceTimer=null),this.config.enableStatistics){this.statistics.lastUpdated=new Date().toISOString();try{await zr.promises.writeFile(this.statisticsFilePath,JSON.stringify(this.statistics,null,2))}catch(e){y.error("Failed to save final statistics",e)}}if(this.config.enableHistory&&this.historyFilePath){let e={sessionId:this.sessionId,startTime:"",endTime:new Date().toISOString(),totalCommands:this.sequenceNumber,pid:process.pid,version:Le};try{await zr.promises.appendFile(this.historyFilePath,`# SESSION_END ${JSON.stringify(e)}
|