@flowcast/mcp 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/flowcast.mjs +2 -2
  2. package/package.json +1 -1
package/flowcast.mjs CHANGED
@@ -39,7 +39,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
39
39
  `:`[${n[c]}\r
40
40
  ]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function al(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ye.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Vt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ye.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=il(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===ye.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ye.ZodBranded&&t.keyType._def.type._def.typeName===ye.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=ol(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function X_(t,e){if(e.mapStrategy==="record")return al(t,e);let r=Ke(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Vt(e),n=Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Vt(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function K_(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function J_(t){return t.target==="openAi"?void 0:{not:Vt({...t,currentPath:[...t.currentPath,"not"]})}}function Q_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var la={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function t2(t,e){if(e.target==="openApi3")return e2(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in la&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=la[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return e2(t,e)}var e2=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ke(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function r2(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:la[t.innerType._def.typeName],nullable:!0}:{type:[la[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Ke(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Ke(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function n2(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Rf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?pt(r,"minimum",n.value,n.message,e):pt(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),pt(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?pt(r,"maximum",n.value,n.message,e):pt(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),pt(r,"maximum",n.value,n.message,e));break;case"multipleOf":pt(r,"multipleOf",n.value,n.message,e);break}return r}function s2(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let d=k6(c);d&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),d=!1);let l=Ke(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,d||s.push(a))}s.length&&(n.required=s);let i=S6(t,e);return i!==void 0&&(n.additionalProperties=i),n}function S6(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ke(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function k6(t){try{return t.isOptional()}catch{return!0}}var o2=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Ke(t.innerType._def,e);let r=Ke(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Vt(e)},r]}:Vt(e)};var i2=(t,e)=>{if(e.pipeStrategy==="input")return Ke(t.in._def,e);if(e.pipeStrategy==="output")return Ke(t.out._def,e);let r=Ke(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ke(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function a2(t,e){return Ke(t.type._def,e)}function c2(t,e){let n={type:"array",uniqueItems:!0,items:Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&pt(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&pt(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function l2(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ke(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ke(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ke(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function u2(t){return{not:Vt(t)}}function d2(t){return Vt(t)}var h2=(t,e)=>Ke(t.innerType._def,e);var f2=(t,e,r)=>{switch(e){case ye.ZodString:return il(t,r);case ye.ZodNumber:return n2(t,r);case ye.ZodObject:return s2(t,r);case ye.ZodBigInt:return B_(t,r);case ye.ZodBoolean:return V_();case ye.ZodDate:return Pf(t,r);case ye.ZodUndefined:return u2(r);case ye.ZodNull:return Q_(r);case ye.ZodArray:return Z_(t,r);case ye.ZodUnion:case ye.ZodDiscriminatedUnion:return t2(t,r);case ye.ZodIntersection:return G_(t,r);case ye.ZodTuple:return l2(t,r);case ye.ZodRecord:return al(t,r);case ye.ZodLiteral:return W_(t,r);case ye.ZodEnum:return H_(t);case ye.ZodNativeEnum:return K_(t);case ye.ZodNullable:return r2(t,r);case ye.ZodOptional:return o2(t,r);case ye.ZodMap:return X_(t,r);case ye.ZodSet:return c2(t,r);case ye.ZodLazy:return()=>t.getter()._def;case ye.ZodPromise:return a2(t,r);case ye.ZodNaN:case ye.ZodNever:return J_(r);case ye.ZodEffects:return U_(t,r);case ye.ZodAny:return Vt(r);case ye.ZodUnknown:return d2(r);case ye.ZodDefault:return F_(t,r);case ye.ZodBranded:return ol(t,r);case ye.ZodReadonly:return h2(t,r);case ye.ZodCatch:return q_(t,r);case ye.ZodPipeline:return i2(t,r);case ye.ZodFunction:case ye.ZodVoid:case ye.ZodSymbol:return;default:return(n=>{})(e)}};function Ke(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==j_)return a}if(n&&!r){let a=$6(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=f2(t,t.typeName,e),i=typeof o=="function"?Ke(o(),e):o;if(i&&E6(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var $6=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sl(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Vt(e)):e.$refStrategy==="seen"?Vt(e):void 0}},E6=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var zf=(t,e)=>{let r=L_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[d,l])=>({...c,[d]:Ke(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??Vt(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Ke(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??Vt(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function T6(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Af(t,e){return en(t)?ef(t,{target:T6(e?.target),io:e?.pipeStrategy??"input"}):zf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Of(t){let r=ds(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Nf(t,e){let r=us(t,e);if(!r.success)throw r.error;return r.data}var R6=6e4,cl=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(Bc,r=>{this._oncancel(r)}),this.setNotificationHandler(qc,r=>{this._onprogress(r)}),this.setRequestHandler(Vc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Fc,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Be(Ge.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Hc,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,d=c.id,l=this._requestResolvers.get(d);if(l)if(this._requestResolvers.delete(d),a.type==="response")l(c);else{let u=c,f=new Be(u.error.code,u.error.message,u.error.data);l(f)}else{let u=a.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new Be(Ge.InvalidParams,`Task not found: ${o}`);if(!fs(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(fs(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[hs]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Gc,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new Be(Ge.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Yc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Be(Ge.InvalidParams,`Task not found: ${r.params.taskId}`);if(fs(s.status))throw new Be(Ge.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Be(Ge.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof Be?s:new Be(Ge.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_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),Be.fromError(Ge.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),ea(o)||$_(o)?this._onresponse(o):pf(o)?this._onrequest(o,i):k_(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Be.fromError(Ge.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,s=this._transport,o=e.params?._meta?.[hs]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Ge.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId).catch(u=>this._onerror(new Error(`Failed to enqueue error response: ${u}`))):s?.send(l).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=w_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,d={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let u={relatedRequestId:e.id};o&&(u.relatedTask={taskId:o}),await this.notification(l,u)},sendRequest:async(l,u,f)=>{if(i.signal.aborted)throw new Be(Ge.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let m=p.relatedTask?.taskId??o;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,u,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,d)).then(async l=>{if(i.signal.aborted)return;let u={result:l,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:u,timestamp:Date.now()},s?.sessionId):await s?.send(u)},async l=>{if(i.signal.aborted)return;let u={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Ge.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId):await s?.send(u)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ea(e))n(e);else{let i=new Be(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===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 o=!1;if(ea(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ea(e))s(e);else{let i=Be.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof Be?i:new Be(Ge.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Uo,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Be(Ge.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},fs(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new Be(Ge.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Be(Ge.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Be?i:new Be(Ge.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((d,l)=>{let u=_=>{l(_)};if(!this._transport){u(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){u(_);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[hs]:c}});let m=_=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let g=_ instanceof Be?_:new Be(Ge.RequestTimeout,String(_));l(g)};this._responseHandlers.set(f,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let g=us(r,_.result);g.success?d(g.data):l(g.error)}catch(g){l(g)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let y=n?.timeout??R6,k=()=>m(Be.fromError(Ge.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(f,y,n?.maxTotalTimeout,k,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let _=g=>{let E=this._responseHandlers.get(f);E?E(g):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(x,{type:"request",message:p,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(f),l(g)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Uc,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},Wc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},R_,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 a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[hs]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,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 a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[hs]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[hs]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Of(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Nf(e,s);return Promise.resolve(r(i,o))})}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=Of(e);this._notificationHandlers.set(n,s=>{let o=Nf(e,s);return Promise.resolve(r(o))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&pf(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new Be(Ge.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new Be(Ge.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new Be(Ge.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new Be(Ge.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=oa.parse({method:"notifications/tasks/status",params:a});await this.notification(c),fs(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new Be(Ge.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(fs(a.status))throw new Be(Ge.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let d=oa.parse({method:"notifications/tasks/status",params:c});await this.notification(d),fs(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function p2(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function m2(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];p2(i)&&p2(o)?r[s]={...i,...o}:r[s]=o}return r}var iv=Ni(wm(),1),av=Ni(ov(),1);function IR(){let t=new iv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,av.default)(t),t}var ql=class{constructor(e){this._ajv=e??IR()}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 Fl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],d=c.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),u=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==u.size||![...l].every(f=>u.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},ca,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Wo,r)}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 cv(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 lv(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 Ul=class extends cl{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(aa.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new ql,this.setRequestHandler(_f,n=>this._oninitialize(n)),this.setNotificationHandler(bf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler($f,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=aa.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Fl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=m2(this._capabilities,e)}setRequestHandler(e,r){let s=ds(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(en(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,d)=>{let l=us(Go,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Be(Ge.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:u}=l.data,f=await Promise.resolve(r(c,d));if(u.task){let m=us(Uo,f);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new Be(Ge.InvalidParams,`Invalid task creation result: ${y}`)}return m.data}let p=us(rl,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new Be(Ge.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(e,a)}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){lv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&cv(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:b_.includes(r)?r:hf,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"},Zc)}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],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(d=>d.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(d=>d.type==="tool_use");if(o){if(s.some(d=>d.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 d=new Set(a.filter(u=>u.type==="tool_use").map(u=>u.id)),l=new Set(s.filter(u=>u.type==="tool_result").map(u=>u.toolUseId));if(d.size!==l.size||![...d].every(u=>l.has(u)))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},Ef,r):this.request({method:"sampling/createMessage",params:e},ca,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 s=e;return this.request({method:"elicitation/create",params:s},Wo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Wo,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new Be(Ge.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Be?i:new Be(Ge.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},Tf,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"})}};var dv=Symbol.for("mcp.completable");function Pm(t){return!!t&&typeof t=="object"&&dv in t}function hv(t){return t[dv]?.complete}var uv;(function(t){t.Completable="McpCompletable"})(uv||(uv={}));var Hl=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",s=0,o=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");let i=e.indexOf("}",s);if(i===-1)throw new Error("Unclosed template expression");if(o++,o>1e4)throw new Error("Template contains too many expressions (max 10000)");let a=e.slice(s+1,i),c=this.getOperator(a),d=a.includes("*"),l=this.getNames(a),u=l[0];for(let f of l)t.validateLength(f,1e6,"Variable name");r.push({name:u,operator:c,names:l,exploded:d}),s=i+1}else n+=e[s],s++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let i=e.names.map(c=>{let d=r[c];if(d===void 0)return"";let l=Array.isArray(d)?d.map(u=>this.encodeValue(u,e.operator)).join(","):this.encodeValue(d.toString(),e.operator);return`${c}=${l}`}).filter(c=>c.length>0);return i.length===0?"":(e.operator==="?"?"?":"&")+i.join("&")}if(e.names.length>1){let i=e.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[e.name];if(n===void 0)return"";let o=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(let s of this.parts){if(typeof s=="string"){r+=s;continue}let o=this.expandPart(s,e);o&&((s.operator==="?"||s.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let o of e.names)t.validateLength(o,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){let i=e.names[o],a=o===0?"\\"+e.operator:"&";r.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return r}let n,s=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:s}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let a of this.parts)if(typeof a=="string")r+=this.escapeRegExp(a);else{let c=this.partToRegExp(a);for(let{pattern:d,name:l}of c)r+=d,n.push({name:l,exploded:a.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let s=new RegExp(r),o=e.match(s);if(!o)return null;let i={};for(let a=0;a<n.length;a++){let{name:c,exploded:d}=n[a],l=o[a+1],u=c.replace("*","");d&&l.includes(",")?i[u]=l.split(","):i[u]=l}return i}};var zR=/^[A-Za-z0-9._-]{1,128}$/;function AR(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!zR.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function OR(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Mm(t){let e=AR(t);return OR(t,e.warnings),e.isValid}var Gl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}};var Wl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ul(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Gl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(xs(tl)),this.server.assertCanSetRequestHandler(xs(Go)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(tl,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=qo(r.inputSchema);return s?Af(s,{strictUnions:!0,pipeStrategy:"input"}):NR})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=qo(r.outputSchema);s&&(n.outputSchema=Af(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Go,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Be(Ge.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Be(Ge.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new Be(Ge.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new Be(Ge.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof Be&&n.code===Ge.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=qo(e.inputSchema)??e.inputSchema,i=await zc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ac(a);throw new Be(Ge.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Be(Ge.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=qo(e.outputSchema),o=await zc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Ac(i);throw new Be(Ge.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,d=a.task,l=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let u=await n.taskStore.getTask(c);if(!u)throw new Be(Ge.InternalError,`Task ${c} not found during polling`);d=u}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(xs(nl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(nl,async e=>{switch(e.params.ref.type){case"ref/prompt":return O_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return N_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Be(Ge.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Be(Ge.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Be(Ge.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return La;let o=ds(n.argsSchema)?.[e.params.argument.name];if(!Pm(o))return La;let i=hv(o);if(!i)return La;let a=await i(e.params.argument.value,e.params.context);return pv(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return La;throw new Be(Ge.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return La;let o=await s(e.params.argument.value,e.params.context);return pv(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(xs(Xc)),this.server.assertCanSetRequestHandler(xs(Kc)),this.server.assertCanSetRequestHandler(xs(Jc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Xc,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Kc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Jc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new Be(Ge.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new Be(Ge.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(xs(Qc)),this.server.assertCanSetRequestHandler(xs(el)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Qc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?CR(r.argsSchema):void 0}))})),this.server.setRequestHandler(el,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Be(Ge.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Be(Ge.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=qo(n.argsSchema),o=await zc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",d=Ac(c);throw new Be(Ge.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:no(s),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=no(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,s&&Object.values(s).some(c=>{let d=c instanceof Pr?c._def?.innerType:c;return Pm(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,d){Mm(e);let l={title:r,description:n,inputSchema:fv(s),outputSchema:fv(o),annotations:i,execution:a,_meta:c,handler:d,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(typeof u.name=="string"&&Mm(u.name),delete this._registeredTools[e],u.name&&(this._registeredTools[u.name]=l)),typeof u.title<"u"&&(l.title=u.title),typeof u.description<"u"&&(l.description=u.description),typeof u.paramsSchema<"u"&&(l.inputSchema=no(u.paramsSchema)),typeof u.outputSchema<"u"&&(l.outputSchema=no(u.outputSchema)),typeof u.callback<"u"&&(l.handler=u.callback),typeof u.annotations<"u"&&(l.annotations=u.annotations),typeof u._meta<"u"&&(l._meta=u._meta),typeof u.enabled<"u"&&(l.enabled=u.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Im(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Im(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:d}=r;return this._createRegisteredTool(e,s,o,i,a,c,{taskSupport:"forbidden"},d,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Yl=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new Hl(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},NR={type:"object",properties:{}};function mv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function gv(t){return"_def"in t||"_zod"in t||mv(t)}function Im(t){return typeof t!="object"||t===null||gv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(mv)}function fv(t){if(t){if(Im(t))return no(t);if(!gv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function CR(t){let e=ds(t);return e?Object.entries(e).map(([r,n])=>{let s=Wg(n),o=Yg(n);return{name:r,description:s,required:!o}}):[]}function xs(t){let r=ds(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function pv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var La={completion:{values:[],hasMore:!1}};import bv from"node:process";var Xl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
41
41
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),jR(r)}clear(){this._buffer=void 0}};function jR(t){return E_.parse(JSON.parse(t))}function _v(t){return JSON.stringify(t)+`
42
- `}var Kl=class{constructor(e=bv.stdin,r=bv.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Xl,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=_v(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{accessSync as GN,constants as WN,writeFileSync as YN,mkdirSync as _x}from"node:fs";import{fileURLToPath as XN,pathToFileURL as bx}from"node:url";import{tmpdir as mx}from"node:os";import{createServer as KN}from"node:http";import*as nr from"node:path";var Hr=["alloy","ash","ballad","coral","echo","fable","marin","nova","onyx","sage","shimmer","verse","cedar"],DR="cedar",Jl={alloy:"neutral, balanced",ash:"warm, expressive",ballad:"soft, mellow",coral:"bright, friendly",echo:"calm, measured",fable:"storytelling, animated",marin:"natural, conversational",nova:"energetic, upbeat",onyx:"deep, authoritative",sage:"steady, thoughtful",shimmer:"light, gentle",verse:"lively, dynamic",cedar:"warm, natural (default)"};function yv(t){return t&&Hr.includes(t)?t:DR}var LR="TTS voice (default cedar). Options: "+Hr.join(", ")+".",ZR=W.object({find:W.string().min(1).describe('Exact existing snippet to anchor the change \u2014 smallest unique text, whitespace exact. Insert by keeping the anchor inside `replace`; delete with replace "".'),replace:W.string().describe("What `find` becomes \u2014 only the changed region types out."),occurrence:W.number().int().positive().optional().describe("1-based which occurrence of `find` when it is not unique (default 1).")}),BR=W.object({say:W.string().optional().describe("Narration for this step \u2014 one short beat (4\u201314 words), spoken + captioned. Write the whole script and chop it into beats that flow continuously; split compound sentences. Highlight syncs to the beat start."),file:W.string().optional().describe("File to show this step (created if new, becomes the active tab). Omit to keep the current file. A step with `file` + no `code` just switches tabs."),code:W.string().optional().describe("Full contents of `file` \u2014 ONLY to introduce a file the first time (shown instantly, not typed). To change an existing file use `edits`. For a deliberate full rewrite set `rewrite:true`."),edits:W.array(ZR).optional().describe("Small find/replace edits to the current file (these type out). Prefer over resending `code`. A step uses EITHER `code` OR `edits`, never both."),rewrite:W.boolean().optional().describe("Set true only for a deliberate full-file rewrite via `code` on a non-empty file."),typing:W.boolean().optional().describe("Animate `edits` as typing (default true)."),highlightCode:W.string().optional().describe("Preferred way to point at code: an EXACT, UNIQUE snippet of the current file to highlight \u2014 a single token/line, or a whole multi-line block. Found as-it-stands each step, so it never drifts when edits move lines."),highlight:W.tuple([W.number(),W.number()]).optional().describe("Highlight a line range [start,end] (1-based, inclusive). Prefer `highlightCode` once the file has been edited."),terminal:W.string().optional().describe('Text appended to the terminal panel this step (e.g. "$ npm test\\n\u2713 3 passed").'),chapter:W.string().optional().describe("If set, starts a named chapter marker on the timeline."),holdMs:W.number().optional().describe("Step duration in ms (default derived from narration + typing).")}),zm={title:W.string().describe("Title of the walkthrough (player header + filename)."),outputPath:W.string().optional().describe("Optional path to also write the .html to (absolute, or relative to the server cwd)."),voiceName:W.enum(Hr).optional().describe(LR),voiceTone:W.string().optional().describe('How the narrator should sound, matched to the topic (e.g. "calm and precise", "upbeat and encouraging"). Default relaxed-senior-engineer.'),intro:W.string().optional().describe("Opening line spoken before step 1 (a short hook). Default title-based; '' to skip. Don't also write your own welcome step."),outro:W.string().optional().describe("Closing recap line spoken after the last step. Default title-based; '' to skip. Don't write your own."),files:W.array(W.object({path:W.string(),content:W.string().optional()})).optional().describe("Pre-existing files present in FULL from t=0 \u2014 put already-written code here with its `content`. Steps then show + highlight them (no typing)."),steps:W.array(BR).min(1).describe("Ordered timeline as a LESSON: open on the problem/why, build ONE idea per beat (short `say` + tight `highlightCode`), grouped into named chapters, then recap. Lean high \u2014 many short beats; the `say` lines read as one continuous script.")},aq=W.object(zm);var Om=[],Sv=[];(()=>{let t="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,r=0;e<t.length;e++)(e%2?Sv:Om).push(r=r+t[e])})();function VR(t){if(t<768)return!1;for(let e=0,r=Om.length;;){let n=e+r>>1;if(t<Om[n])r=n;else if(t>=Sv[n])e=n+1;else return!0;if(e==r)return!1}}function vv(t){return t>=127462&&t<=127487}var wv=8205;function kv(t,e,r=!0,n=!0){return(r?$v:qR)(t,e,n)}function $v(t,e,r){if(e==t.length)return e;e&&Ev(t.charCodeAt(e))&&Tv(t.charCodeAt(e-1))&&e--;let n=Am(t,e);for(e+=xv(n);e<t.length;){let s=Am(t,e);if(n==wv||s==wv||r&&VR(s))e+=xv(s),n=s;else if(vv(s)){let o=0,i=e-2;for(;i>=0&&vv(Am(t,i));)o++,i-=2;if(o%2==0)break;e+=2}else break}return e}function qR(t,e,r){for(;e>0;){let n=$v(t,e-2,r);if(n<e)return n;e--}return 0}function Am(t,e){let r=t.charCodeAt(e);if(!Tv(r)||e+1==t.length)return r;let n=t.charCodeAt(e+1);return Ev(n)?(r-55296<<10)+(n-56320)+65536:r}function Ev(t){return t>=56320&&t<57344}function Tv(t){return t>=55296&&t<56320}function xv(t){return t<65536?1:2}var tr=class t{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,r,n){[e,r]=_i(this,e,r);let s=[];return this.decompose(0,e,s,2),n.length&&n.decompose(0,n.length,s,3),this.decompose(r,this.length,s,1),pi.from(s,this.length-(r-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,r=this.length){[e,r]=_i(this,e,r);let n=[];return this.decompose(e,r,n,0),pi.from(n,r-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let r=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),s=new bo(this),o=new bo(e);for(let i=r,a=r;;){if(s.next(i),o.next(i),i=0,s.lineBreak!=o.lineBreak||s.done!=o.done||s.value!=o.value)return!1;if(a+=s.value.length,s.done||a>=n)return!0}}iter(e=1){return new bo(this,e)}iterRange(e,r=this.length){return new nu(this,e,r)}iterLines(e,r){let n;if(e==null)n=this.iter();else{r==null&&(r=this.lines+1);let s=this.line(e).from;n=this.iterRange(s,Math.max(s,r==this.lines+1?this.length:r<=1?0:this.line(r-1).to))}return new su(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?t.empty:e.length<=32?new Gr(e):pi.from(Gr.split(e,[]))}},Gr=class t extends tr{constructor(e,r=FR(e)){super(),this.text=e,this.length=r}get lines(){return this.text.length}get children(){return null}lineInner(e,r,n,s){for(let o=0;;o++){let i=this.text[o],a=s+i.length;if((r?n:a)>=e)return new Cm(s,a,n,i);s=a+1,n++}}decompose(e,r,n,s){let o=e<=0&&r>=this.length?this:new t(Rv(this.text,e,r),Math.min(r,this.length)-Math.max(0,e));if(s&1){let i=n.pop(),a=ru(o.text,i.text.slice(),0,o.length);if(a.length<=32)n.push(new t(a,i.length+o.length));else{let c=a.length>>1;n.push(new t(a.slice(0,c)),new t(a.slice(c)))}}else n.push(o)}replace(e,r,n){if(!(n instanceof t))return super.replace(e,r,n);[e,r]=_i(this,e,r);let s=ru(this.text,ru(n.text,Rv(this.text,0,e)),r),o=this.length+n.length-(r-e);return s.length<=32?new t(s,o):pi.from(t.split(s,[]),o)}sliceString(e,r=this.length,n=`
42
+ `}var Kl=class{constructor(e=bv.stdin,r=bv.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Xl,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=_v(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{accessSync as GN,constants as WN,writeFileSync as YN,mkdirSync as _x}from"node:fs";import{fileURLToPath as XN,pathToFileURL as bx}from"node:url";import{tmpdir as mx}from"node:os";import{createServer as KN}from"node:http";import*as nr from"node:path";var Hr=["alloy","ash","ballad","coral","echo","fable","marin","nova","onyx","sage","shimmer","verse","cedar"],DR="cedar",Jl={alloy:"neutral, balanced",ash:"warm, expressive",ballad:"soft, mellow",coral:"bright, friendly",echo:"calm, measured",fable:"storytelling, animated",marin:"natural, conversational",nova:"energetic, upbeat",onyx:"deep, authoritative",sage:"steady, thoughtful",shimmer:"light, gentle",verse:"lively, dynamic",cedar:"warm, natural (default)"};function yv(t){return t&&Hr.includes(t)?t:DR}var LR="TTS voice (default cedar). Options: "+Hr.join(", ")+".",ZR=W.object({find:W.string().min(1).describe('Exact existing snippet to anchor the change \u2014 smallest unique text, whitespace exact. Insert by keeping the anchor inside `replace`; delete with replace "".'),replace:W.string().describe("What `find` becomes \u2014 only the changed region types out."),occurrence:W.number().int().positive().optional().describe("1-based which occurrence of `find` when it is not unique (default 1).")}),BR=W.object({say:W.string().optional().describe("Narration for this step \u2014 one short beat (4\u201314 words), spoken + captioned. Write the whole script and chop it into beats that flow continuously; split compound sentences. Highlight syncs to the beat start."),file:W.string().optional().describe("File to show this step (created if new, becomes the active tab). Omit to keep the current file. A step with `file` + no `code` just switches tabs."),code:W.string().optional().describe("Full contents of `file` \u2014 ONLY to introduce a file the first time (shown instantly, not typed). To change an existing file use `edits`. For a deliberate full rewrite set `rewrite:true`."),edits:W.array(ZR).optional().describe("Small find/replace edits to the current file (these type out). Prefer over resending `code`. A step uses EITHER `code` OR `edits`, never both."),rewrite:W.boolean().optional().describe("Set true only for a deliberate full-file rewrite via `code` on a non-empty file."),typing:W.boolean().optional().describe("Animate `edits` as typing (default true)."),highlightCode:W.string().optional().describe("Preferred way to point at code: an EXACT, UNIQUE snippet of the current file to highlight \u2014 a single token/line, or a whole multi-line block. Found as-it-stands each step, so it never drifts when edits move lines."),highlight:W.array(W.number()).length(2).optional().describe("Highlight a line range [start,end] (1-based, inclusive). Prefer `highlightCode` once the file has been edited."),terminal:W.string().optional().describe('Text appended to the terminal panel this step (e.g. "$ npm test\\n\u2713 3 passed").'),chapter:W.string().optional().describe("If set, starts a named chapter marker on the timeline."),holdMs:W.number().optional().describe("Step duration in ms (default derived from narration + typing).")}),zm={title:W.string().describe("Title of the walkthrough (player header + filename)."),outputPath:W.string().optional().describe("Optional path to also write the .html to (absolute, or relative to the server cwd)."),voiceName:W.enum(Hr).optional().describe(LR),voiceTone:W.string().optional().describe('How the narrator should sound, matched to the topic (e.g. "calm and precise", "upbeat and encouraging"). Default relaxed-senior-engineer.'),intro:W.string().optional().describe("Opening line spoken before step 1 (a short hook). Default title-based; '' to skip. Don't also write your own welcome step."),outro:W.string().optional().describe("Closing recap line spoken after the last step. Default title-based; '' to skip. Don't write your own."),files:W.array(W.object({path:W.string(),content:W.string().optional()})).optional().describe("Pre-existing files present in FULL from t=0 \u2014 put already-written code here with its `content`. Steps then show + highlight them (no typing)."),steps:W.array(BR).min(1).describe("Ordered timeline as a LESSON: open on the problem/why, build ONE idea per beat (short `say` + tight `highlightCode`), grouped into named chapters, then recap. Lean high \u2014 many short beats; the `say` lines read as one continuous script.")},aq=W.object(zm);var Om=[],Sv=[];(()=>{let t="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,r=0;e<t.length;e++)(e%2?Sv:Om).push(r=r+t[e])})();function VR(t){if(t<768)return!1;for(let e=0,r=Om.length;;){let n=e+r>>1;if(t<Om[n])r=n;else if(t>=Sv[n])e=n+1;else return!0;if(e==r)return!1}}function vv(t){return t>=127462&&t<=127487}var wv=8205;function kv(t,e,r=!0,n=!0){return(r?$v:qR)(t,e,n)}function $v(t,e,r){if(e==t.length)return e;e&&Ev(t.charCodeAt(e))&&Tv(t.charCodeAt(e-1))&&e--;let n=Am(t,e);for(e+=xv(n);e<t.length;){let s=Am(t,e);if(n==wv||s==wv||r&&VR(s))e+=xv(s),n=s;else if(vv(s)){let o=0,i=e-2;for(;i>=0&&vv(Am(t,i));)o++,i-=2;if(o%2==0)break;e+=2}else break}return e}function qR(t,e,r){for(;e>0;){let n=$v(t,e-2,r);if(n<e)return n;e--}return 0}function Am(t,e){let r=t.charCodeAt(e);if(!Tv(r)||e+1==t.length)return r;let n=t.charCodeAt(e+1);return Ev(n)?(r-55296<<10)+(n-56320)+65536:r}function Ev(t){return t>=56320&&t<57344}function Tv(t){return t>=55296&&t<56320}function xv(t){return t<65536?1:2}var tr=class t{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,r,n){[e,r]=_i(this,e,r);let s=[];return this.decompose(0,e,s,2),n.length&&n.decompose(0,n.length,s,3),this.decompose(r,this.length,s,1),pi.from(s,this.length-(r-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,r=this.length){[e,r]=_i(this,e,r);let n=[];return this.decompose(e,r,n,0),pi.from(n,r-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let r=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),s=new bo(this),o=new bo(e);for(let i=r,a=r;;){if(s.next(i),o.next(i),i=0,s.lineBreak!=o.lineBreak||s.done!=o.done||s.value!=o.value)return!1;if(a+=s.value.length,s.done||a>=n)return!0}}iter(e=1){return new bo(this,e)}iterRange(e,r=this.length){return new nu(this,e,r)}iterLines(e,r){let n;if(e==null)n=this.iter();else{r==null&&(r=this.lines+1);let s=this.line(e).from;n=this.iterRange(s,Math.max(s,r==this.lines+1?this.length:r<=1?0:this.line(r-1).to))}return new su(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?t.empty:e.length<=32?new Gr(e):pi.from(Gr.split(e,[]))}},Gr=class t extends tr{constructor(e,r=FR(e)){super(),this.text=e,this.length=r}get lines(){return this.text.length}get children(){return null}lineInner(e,r,n,s){for(let o=0;;o++){let i=this.text[o],a=s+i.length;if((r?n:a)>=e)return new Cm(s,a,n,i);s=a+1,n++}}decompose(e,r,n,s){let o=e<=0&&r>=this.length?this:new t(Rv(this.text,e,r),Math.min(r,this.length)-Math.max(0,e));if(s&1){let i=n.pop(),a=ru(o.text,i.text.slice(),0,o.length);if(a.length<=32)n.push(new t(a,i.length+o.length));else{let c=a.length>>1;n.push(new t(a.slice(0,c)),new t(a.slice(c)))}}else n.push(o)}replace(e,r,n){if(!(n instanceof t))return super.replace(e,r,n);[e,r]=_i(this,e,r);let s=ru(this.text,ru(n.text,Rv(this.text,0,e)),r),o=this.length+n.length-(r-e);return s.length<=32?new t(s,o):pi.from(t.split(s,[]),o)}sliceString(e,r=this.length,n=`
43
43
  `){[e,r]=_i(this,e,r);let s="";for(let o=0,i=0;o<=r&&i<this.text.length;i++){let a=this.text[i],c=o+a.length;o>e&&i&&(s+=n),e<c&&r>o&&(s+=a.slice(Math.max(0,e-o),r-o)),o=c+1}return s}flatten(e){for(let r of this.text)e.push(r)}scanIdentical(){return 0}static split(e,r){let n=[],s=-1;for(let o of e)n.push(o),s+=o.length+1,n.length==32&&(r.push(new t(n,s)),n=[],s=-1);return s>-1&&r.push(new t(n,s)),r}},pi=class t extends tr{constructor(e,r){super(),this.children=e,this.length=r,this.lines=0;for(let n of e)this.lines+=n.lines}lineInner(e,r,n,s){for(let o=0;;o++){let i=this.children[o],a=s+i.length,c=n+i.lines-1;if((r?c:a)>=e)return i.lineInner(e,r,n,s);s=a+1,n=c+1}}decompose(e,r,n,s){for(let o=0,i=0;i<=r&&o<this.children.length;o++){let a=this.children[o],c=i+a.length;if(e<=c&&r>=i){let d=s&((i<=e?1:0)|(c>=r?2:0));i>=e&&c<=r&&!d?n.push(a):a.decompose(e-i,r-i,n,d)}i=c+1}}replace(e,r,n){if([e,r]=_i(this,e,r),n.lines<this.lines)for(let s=0,o=0;s<this.children.length;s++){let i=this.children[s],a=o+i.length;if(e>=o&&r<=a){let c=i.replace(e-o,r-o,n),d=this.lines-i.lines+c.lines;if(c.lines<d>>4&&c.lines>d>>6){let l=this.children.slice();return l[s]=c,new t(l,this.length-(r-e)+n.length)}return super.replace(o,a,c)}o=a+1}return super.replace(e,r,n)}sliceString(e,r=this.length,n=`
44
44
  `){[e,r]=_i(this,e,r);let s="";for(let o=0,i=0;o<this.children.length&&i<=r;o++){let a=this.children[o],c=i+a.length;i>e&&o&&(s+=n),e<c&&r>i&&(s+=a.sliceString(e-i,r-i,n)),i=c+1}return s}flatten(e){for(let r of this.children)r.flatten(e)}scanIdentical(e,r){if(!(e instanceof t))return 0;let n=0,[s,o,i,a]=r>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=r,o+=r){if(s==i||o==a)return n;let c=this.children[s],d=e.children[o];if(c!=d)return n+c.scanIdentical(d,r);n+=c.length+1}}static from(e,r=e.reduce((n,s)=>n+s.length+1,-1)){let n=0;for(let p of e)n+=p.lines;if(n<32){let p=[];for(let m of e)m.flatten(p);return new Gr(p,r)}let s=Math.max(32,n>>5),o=s<<1,i=s>>1,a=[],c=0,d=-1,l=[];function u(p){let m;if(p.lines>o&&p instanceof t)for(let y of p.children)u(y);else p.lines>i&&(c>i||!c)?(f(),a.push(p)):p instanceof Gr&&c&&(m=l[l.length-1])instanceof Gr&&p.lines+m.lines<=32?(c+=p.lines,d+=p.length+1,l[l.length-1]=new Gr(m.text.concat(p.text),m.length+1+p.length)):(c+p.lines>s&&f(),c+=p.lines,d+=p.length+1,l.push(p))}function f(){c!=0&&(a.push(l.length==1?l[0]:t.from(l,d)),d=-1,c=l.length=0)}for(let p of e)u(p);return f(),a.length==1?a[0]:new t(a,r)}};tr.empty=new Gr([""],0);function FR(t){let e=-1;for(let r of t)e+=r.length+1;return e}function ru(t,e,r=0,n=1e9){for(let s=0,o=0,i=!0;o<t.length&&s<=n;o++){let a=t[o],c=s+a.length;c>=r&&(c>n&&(a=a.slice(0,n-s)),s<r&&(a=a.slice(r-s)),i?(e[e.length-1]+=a,i=!1):e.push(a)),s=c+1}return e}function Rv(t,e,r){return ru(t,[""],e,r)}var bo=class{constructor(e,r=1){this.dir=r,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[r>0?1:(e instanceof Gr?e.text.length:e.children.length)<<1]}nextInner(e,r){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,s=this.nodes[n],o=this.offsets[n],i=o>>1,a=s instanceof Gr?s.text.length:s.children.length;if(i==(r>0?a:0)){if(n==0)return this.done=!0,this.value="",this;r>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((o&1)==(r>0?0:1)){if(this.offsets[n]+=r,e==0)return this.lineBreak=!0,this.value=`
45
45
  `,this;e--}else if(s instanceof Gr){let c=s.text[i+(r<0?-1:0)];if(this.offsets[n]+=r,c.length>Math.max(0,e))return this.value=e==0?c:r>0?c.slice(e):c.slice(0,c.length-e),this;e-=c.length}else{let c=s.children[i+(r<0?-1:0)];e>c.length?(e-=c.length,this.offsets[n]+=r):(r<0&&this.offsets[n]--,this.nodes.push(c),this.offsets.push(r>0?1:(c instanceof Gr?c.text.length:c.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},nu=class{constructor(e,r,n){this.value="",this.done=!1,this.cursor=new bo(e,r>n?-1:1),this.pos=r>n?e.length:0,this.from=Math.min(r,n),this.to=Math.max(r,n)}nextInner(e,r){if(r<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,r<0?this.pos-this.to:this.from-this.pos);let n=r<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*r,this.value=s.length<=n?s:r<0?s.slice(s.length-n):s.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},su=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:r,lineBreak:n,value:s}=this.inner.next(e);return r&&this.afterBreak?(this.value="",this.afterBreak=!1):r?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(tr.prototype[Symbol.iterator]=function(){return this.iter()},bo.prototype[Symbol.iterator]=nu.prototype[Symbol.iterator]=su.prototype[Symbol.iterator]=function(){return this});var Cm=class{constructor(e,r,n,s){this.from=e,this.to=r,this.number=n,this.text=s}get length(){return this.to-this.from}};function _i(t,e,r){return e=Math.max(0,Math.min(t.length,e)),[e,Math.max(e,Math.min(t.length,r))]}function Pv(t,e,r=!0,n=!0){return kv(t,e,r,n)}var jm=/\r\n?|\n/,Ss=function(t){return t[t.Simple=0]="Simple",t[t.TrackDel=1]="TrackDel",t[t.TrackBefore=2]="TrackBefore",t[t.TrackAfter=3]="TrackAfter",t}(Ss||(Ss={})),yo=class t{constructor(e){this.sections=e}get length(){let e=0;for(let r=0;r<this.sections.length;r+=2)e+=this.sections[r];return e}get newLength(){let e=0;for(let r=0;r<this.sections.length;r+=2){let n=this.sections[r+1];e+=n<0?this.sections[r]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let r=0,n=0,s=0;r<this.sections.length;){let o=this.sections[r++],i=this.sections[r++];i<0?(e(n,s,o),s+=o):s+=i,n+=o}}iterChangedRanges(e,r=!1){Dm(this,e,r)}get invertedDesc(){let e=[];for(let r=0;r<this.sections.length;){let n=this.sections[r++],s=this.sections[r++];s<0?e.push(n,s):e.push(s,n)}return new t(e)}composeDesc(e){return this.empty?e:e.empty?this:Ov(this,e)}mapDesc(e,r=!1){return e.empty?this:Lm(this,e,r)}mapPos(e,r=-1,n=Ss.Simple){let s=0,o=0;for(let i=0;i<this.sections.length;){let a=this.sections[i++],c=this.sections[i++],d=s+a;if(c<0){if(d>e)return o+(e-s);o+=a}else{if(n!=Ss.Simple&&d>=e&&(n==Ss.TrackDel&&s<e&&d>e||n==Ss.TrackBefore&&s<e||n==Ss.TrackAfter&&d>e))return null;if(d>e||d==e&&r<0&&!a)return e==s||r<0?o:o+c;o+=c}s=d}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return o}touchesRange(e,r=e){for(let n=0,s=0;n<this.sections.length&&s<=r;){let o=this.sections[n++],i=this.sections[n++],a=s+o;if(i>=0&&s<=r&&a>=e)return s<e&&a>r?"cover":!0;s=a}return!1}toString(){let e="";for(let r=0;r<this.sections.length;){let n=this.sections[r++],s=this.sections[r++];e+=(e?" ":"")+n+(s>=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(r=>typeof r!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new t(e)}static create(e){return new t(e)}},ln=class t extends yo{constructor(e,r){super(e),this.inserted=r}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Dm(this,(r,n,s,o,i)=>e=e.replace(s,s+(n-r),i),!1),e}mapDesc(e,r=!1){return Lm(this,e,r,!0)}invert(e){let r=this.sections.slice(),n=[];for(let s=0,o=0;s<r.length;s+=2){let i=r[s],a=r[s+1];if(a>=0){r[s]=a,r[s+1]=i;let c=s>>1;for(;n.length<c;)n.push(tr.empty);n.push(i?e.slice(o,o+i):tr.empty)}o+=i}return new t(r,n)}compose(e){return this.empty?e:e.empty?this:Ov(this,e,!0)}map(e,r=!1){return e.empty?this:Lm(this,e,r,!0)}iterChanges(e,r=!1){Dm(this,e,r)}get desc(){return yo.create(this.sections)}filter(e){let r=[],n=[],s=[],o=new vo(this);e:for(let i=0,a=0;;){let c=i==e.length?1e9:e[i++];for(;a<c||a==c&&o.len==0;){if(o.done)break e;let l=Math.min(o.len,c-a);_r(s,l,-1);let u=o.ins==-1?-1:o.off==0?o.ins:0;_r(r,l,u),u>0&&ks(n,r,o.text),o.forward(l),a+=l}let d=e[i++];for(;a<d;){if(o.done)break e;let l=Math.min(o.len,d-a);_r(r,l,-1),_r(s,l,o.ins==-1?-1:o.off==0?o.ins:0),o.forward(l),a+=l}}return{changes:new t(r,n),filtered:yo.create(s)}}toJSON(){let e=[];for(let r=0;r<this.sections.length;r+=2){let n=this.sections[r],s=this.sections[r+1];s<0?e.push(n):s==0?e.push([n]):e.push([n].concat(this.inserted[r>>1].toJSON()))}return e}static of(e,r,n){let s=[],o=[],i=0,a=null;function c(l=!1){if(!l&&!s.length)return;i<r&&_r(s,r-i,-1);let u=new t(s,o);a=a?a.compose(u.map(a)):u,s=[],o=[],i=0}function d(l){if(Array.isArray(l))for(let u of l)d(u);else if(l instanceof t){if(l.length!=r)throw new RangeError(`Mismatched change set length (got ${l.length}, expected ${r})`);c(),a=a?a.compose(l.map(a)):l}else{let{from:u,to:f=u,insert:p}=l;if(u>f||u<0||f>r)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${r})`);let m=p?typeof p=="string"?tr.of(p.split(n||jm)):p:tr.empty,y=m.length;if(u==f&&y==0)return;u<i&&c(),u>i&&_r(s,u-i,-1),_r(s,f-u,y),ks(o,s,m),i=f}}return d(e),c(!a),a}static empty(e){return new t(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let r=[],n=[];for(let s=0;s<e.length;s++){let o=e[s];if(typeof o=="number")r.push(o,-1);else{if(!Array.isArray(o)||typeof o[0]!="number"||o.some((i,a)=>a&&typeof i!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(o.length==1)r.push(o[0],0);else{for(;n.length<s;)n.push(tr.empty);n[s]=tr.of(o.slice(1)),r.push(o[0],n[s].length)}}}return new t(r,n)}static createSet(e,r){return new t(e,r)}};function _r(t,e,r,n=!1){if(e==0&&r<=0)return;let s=t.length-2;s>=0&&r<=0&&r==t[s+1]?t[s]+=e:s>=0&&e==0&&t[s]==0?t[s+1]+=r:n?(t[s]+=e,t[s+1]+=r):t.push(e,r)}function ks(t,e,r){if(r.length==0)return;let n=e.length-2>>1;if(n<t.length)t[t.length-1]=t[t.length-1].append(r);else{for(;t.length<n;)t.push(tr.empty);t.push(r)}}function Dm(t,e,r){let n=t.inserted;for(let s=0,o=0,i=0;i<t.sections.length;){let a=t.sections[i++],c=t.sections[i++];if(c<0)s+=a,o+=a;else{let d=s,l=o,u=tr.empty;for(;d+=a,l+=c,c&&n&&(u=u.append(n[i-2>>1])),!(r||i==t.sections.length||t.sections[i+1]<0);)a=t.sections[i++],c=t.sections[i++];e(s,d,o,l,u),s=d,o=l}}}function Lm(t,e,r,n=!1){let s=[],o=n?[]:null,i=new vo(t),a=new vo(e);for(let c=-1;;){if(i.done&&a.len||a.done&&i.len)throw new Error("Mismatched change set lengths");if(i.ins==-1&&a.ins==-1){let d=Math.min(i.len,a.len);_r(s,d,-1),i.forward(d),a.forward(d)}else if(a.ins>=0&&(i.ins<0||c==i.i||i.off==0&&(a.len<i.len||a.len==i.len&&!r))){let d=a.len;for(_r(s,a.ins,-1);d;){let l=Math.min(i.len,d);i.ins>=0&&c<i.i&&i.len<=l&&(_r(s,0,i.ins),o&&ks(o,s,i.text),c=i.i),i.forward(l),d-=l}a.next()}else if(i.ins>=0){let d=0,l=i.len;for(;l;)if(a.ins==-1){let u=Math.min(l,a.len);d+=u,l-=u,a.forward(u)}else if(a.ins==0&&a.len<l)l-=a.len,a.next();else break;_r(s,d,c<i.i?i.ins:0),o&&c<i.i&&ks(o,s,i.text),c=i.i,i.forward(i.len-l)}else{if(i.done&&a.done)return o?ln.createSet(s,o):yo.create(s);throw new Error("Mismatched change set lengths")}}}function Ov(t,e,r=!1){let n=[],s=r?[]:null,o=new vo(t),i=new vo(e);for(let a=!1;;){if(o.done&&i.done)return s?ln.createSet(n,s):yo.create(n);if(o.ins==0)_r(n,o.len,0,a),o.next();else if(i.len==0&&!i.done)_r(n,0,i.ins,a),s&&ks(s,n,i.text),i.next();else{if(o.done||i.done)throw new Error("Mismatched change set lengths");{let c=Math.min(o.len2,i.len),d=n.length;if(o.ins==-1){let l=i.ins==-1?-1:i.off?0:i.ins;_r(n,c,l,a),s&&l&&ks(s,n,i.text)}else i.ins==-1?(_r(n,o.off?0:o.len,c,a),s&&ks(s,n,o.textBit(c))):(_r(n,o.off?0:o.len,i.off?0:i.ins,a),s&&!i.off&&ks(s,n,i.text));a=(o.ins>c||i.ins>=0&&i.len>c)&&(a||n.length>d),o.forward2(c),i.forward(c)}}}}var vo=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,r=this.i-2>>1;return r>=e.length?tr.empty:e[r]}textBit(e){let{inserted:r}=this.set,n=this.i-2>>1;return n>=r.length&&!e?tr.empty:r[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},fi=class t{constructor(e,r,n){this.from=e,this.to=r,this.flags=n}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,r=-1){let n,s;return this.empty?n=s=e.mapPos(this.from,r):(n=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),n==this.from&&s==this.to?this:new t(n,s,this.flags)}extend(e,r=e,n=0){if(e<=this.anchor&&r>=this.anchor)return Cr.range(e,r,void 0,void 0,n);let s=Math.abs(e-this.anchor)>Math.abs(r-this.anchor)?e:r;return Cr.range(this.anchor,s,void 0,void 0,n)}eq(e,r=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!r||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return Cr.range(e.anchor,e.head)}static create(e,r,n){return new t(e,r,n)}},Cr=class t{constructor(e,r){this.ranges=e,this.mainIndex=r}map(e,r=-1){return e.empty?this:t.create(this.ranges.map(n=>n.map(e,r)),this.mainIndex)}eq(e,r=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],r))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new t([this.main],0)}addRange(e,r=!0){return t.create([e].concat(this.ranges),r?0:this.mainIndex+1)}replaceRange(e,r=this.mainIndex){let n=this.ranges.slice();return n[r]=e,t.create(n,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new t(e.ranges.map(r=>fi.fromJSON(r)),e.main)}static single(e,r=e){return new t([t.range(e,r)],0)}static create(e,r=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let n=0,s=0;s<e.length;s++){let o=e[s];if(o.empty?o.from<=n:o.from<n)return t.normalized(e.slice(),r);n=o.to}return new t(e,r)}static cursor(e,r=0,n,s){return fi.create(e,e,(r==0?0:r<0?8:16)|(n==null?7:Math.min(6,n))|(s??16777215)<<6)}static range(e,r,n,s,o){let i=(n??16777215)<<6|(s==null?7:Math.min(6,s));return!o&&e!=r&&(o=r<e?1:-1),r<e?fi.create(r,e,48|i):fi.create(e,r,(o?o<0?8:16:0)|i)}static normalized(e,r=0){let n=e[r];e.sort((s,o)=>s.from-o.from),r=e.indexOf(n);for(let s=1;s<e.length;s++){let o=e[s],i=e[s-1];if(o.empty?o.from<=i.to:o.from<i.to){let a=i.from,c=Math.max(o.to,i.to);s<=r&&r--,e.splice(--s,2,o.anchor>o.head?t.range(c,a):t.range(a,c))}}return new t(e,r)}};function Nv(t,e){for(let r of t.ranges)if(r.to>e)throw new RangeError("Selection points outside of document")}var Ym=0,Wr=class t{constructor(e,r,n,s,o){this.combine=e,this.compareInput=r,this.compare=n,this.isStatic=s,this.id=Ym++,this.default=e([]),this.extensions=typeof o=="function"?o(this):o}get reader(){return this}static define(e={}){return new t(e.combine||(r=>r),e.compareInput||((r,n)=>r===n),e.compare||(e.combine?(r,n)=>r===n:Xm),!!e.static,e.enables)}of(e){return new mi([],this,0,e)}compute(e,r){if(this.isStatic)throw new Error("Can't compute a static facet");return new mi(e,this,1,r)}computeN(e,r){if(this.isStatic)throw new Error("Can't compute a static facet");return new mi(e,this,2,r)}from(e,r){return r||(r=n=>n),this.compute([e],n=>r(n.field(e)))}};function Xm(t,e){return t==e||t.length==e.length&&t.every((r,n)=>r===e[n])}var mi=class{constructor(e,r,n,s){this.dependencies=e,this.facet=r,this.type=n,this.value=s,this.id=Ym++}dynamicSlot(e){var r;let n=this.value,s=this.facet.compareInput,o=this.id,i=e[o]>>1,a=this.type==2,c=!1,d=!1,l=[];for(let u of this.dependencies)u=="doc"?c=!0:u=="selection"?d=!0:((r=e[u.id])!==null&&r!==void 0?r:1)&1||l.push(e[u.id]);return{create(u){return u.values[i]=n(u),1},update(u,f){if(c&&f.docChanged||d&&(f.docChanged||f.selection)||Zm(u,l)){let p=n(u);if(a?!Mv(p,u.values[i],s):!s(p,u.values[i]))return u.values[i]=p,1}return 0},reconfigure:(u,f)=>{let p,m=f.config.address[o];if(m!=null){let y=cu(f,m);if(this.dependencies.every(k=>k instanceof Wr?f.facet(k)===u.facet(k):k instanceof bi?f.field(k,!1)==u.field(k,!1):!0)||(a?Mv(p=n(u),y,s):s(p=n(u),y)))return u.values[i]=y,0}else p=n(u);return u.values[i]=p,1}}}};function Mv(t,e,r){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!r(t[n],e[n]))return!1;return!0}function Zm(t,e){let r=!1;for(let n of e)Ba(t,n)&1&&(r=!0);return r}function UR(t,e,r){let n=r.map(c=>t[c.id]),s=r.map(c=>c.type),o=n.filter(c=>!(c&1)),i=t[e.id]>>1;function a(c){let d=[];for(let l=0;l<n.length;l++){let u=cu(c,n[l]);if(s[l]==2)for(let f of u)d.push(f);else d.push(u)}return e.combine(d)}return{create(c){for(let d of n)Ba(c,d);return c.values[i]=a(c),1},update(c,d){if(!Zm(c,o))return 0;let l=a(c);return e.compare(l,c.values[i])?0:(c.values[i]=l,1)},reconfigure(c,d){let l=Zm(c,n),u=d.config.facets[e.id],f=d.facet(e);if(u&&!l&&Xm(r,u))return c.values[i]=f,0;let p=a(c);return e.compare(p,f)?(c.values[i]=f,0):(c.values[i]=p,1)}}}var Ql=Wr.define({static:!0}),bi=class t{constructor(e,r,n,s,o){this.id=e,this.createF=r,this.updateF=n,this.compareF=s,this.spec=o,this.provides=void 0}static define(e){let r=new t(Ym++,e.create,e.update,e.compare||((n,s)=>n===s),e);return e.provide&&(r.provides=e.provide(r)),r}create(e){let r=e.facet(Ql).find(n=>n.field==this);return(r?.create||this.createF)(e)}slot(e){let r=e[this.id]>>1;return{create:n=>(n.values[r]=this.create(n),1),update:(n,s)=>{let o=n.values[r],i=this.updateF(o,s);return this.compareF(o,i)?0:(n.values[r]=i,1)},reconfigure:(n,s)=>{let o=n.facet(Ql),i=s.facet(Ql),a;return(a=o.find(c=>c.field==this))&&a!=i.find(c=>c.field==this)?(n.values[r]=a.create(n),1):s.config.address[this.id]!=null?(n.values[r]=s.field(this),0):(n.values[r]=this.create(n),1)}}}init(e){return[this,Ql.of({field:this,create:e})]}get extension(){return this}},go={lowest:4,low:3,default:2,high:1,highest:0};function Za(t){return e=>new ou(e,t)}var dq={highest:Za(go.highest),high:Za(go.high),default:Za(go.default),low:Za(go.low),lowest:Za(go.lowest)},ou=class{constructor(e,r){this.inner=e,this.prec=r}},iu=class t{of(e){return new Va(this,e)}reconfigure(e){return t.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},Va=class{constructor(e,r){this.compartment=e,this.inner=r}},au=class t{constructor(e,r,n,s,o,i){for(this.base=e,this.compartments=r,this.dynamicSlots=n,this.address=s,this.staticValues=o,this.facets=i,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let r=this.address[e.id];return r==null?e.default:this.staticValues[r>>1]}static resolve(e,r,n){let s=[],o=Object.create(null),i=new Map;for(let f of HR(e,r,i))f instanceof bi?s.push(f):(o[f.facet.id]||(o[f.facet.id]=[])).push(f);let a=Object.create(null),c=[],d=[];for(let f of s)a[f.id]=d.length<<1,d.push(p=>f.slot(p));let l=n?.config.facets;for(let f in o){let p=o[f],m=p[0].facet,y=l&&l[f]||[];if(p.every(k=>k.type==0))if(a[m.id]=c.length<<1|1,Xm(y,p))c.push(n.facet(m));else{let k=m.combine(p.map(x=>x.value));c.push(n&&m.compare(k,n.facet(m))?n.facet(m):k)}else{for(let k of p)k.type==0?(a[k.id]=c.length<<1|1,c.push(k.value)):(a[k.id]=d.length<<1,d.push(x=>k.dynamicSlot(x)));a[m.id]=d.length<<1,d.push(k=>UR(k,m,p))}}let u=d.map(f=>f(a));return new t(e,i,u,a,c,o)}};function HR(t,e,r){let n=[[],[],[],[],[]],s=new Map;function o(i,a){let c=s.get(i);if(c!=null){if(c<=a)return;let d=n[c].indexOf(i);d>-1&&n[c].splice(d,1),i instanceof Va&&r.delete(i.compartment)}if(s.set(i,a),Array.isArray(i))for(let d of i)o(d,a);else if(i instanceof Va){if(r.has(i.compartment))throw new RangeError("Duplicate use of compartment in extensions");let d=e.get(i.compartment)||i.inner;r.set(i.compartment,d),o(d,a)}else if(i instanceof ou)o(i.inner,i.prec);else if(i instanceof bi)n[a].push(i),i.provides&&o(i.provides,a);else if(i instanceof mi)n[a].push(i),i.facet.extensions&&o(i.facet.extensions,go.default);else{let d=i.extension;if(!d)throw new Error(`Unrecognized extension value in extension set (${i}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);o(d,a)}}return o(t,go.default),n.reduce((i,a)=>i.concat(a))}function Ba(t,e){if(e&1)return 2;let r=e>>1,n=t.status[r];if(n==4)throw new Error("Cyclic dependency between fields and/or facets");if(n&2)return n;t.status[r]=4;let s=t.computeSlot(t,t.config.dynamicSlots[r]);return t.status[r]=2|s}function cu(t,e){return e&1?t.config.staticValues[e>>1]:t.values[e>>1]}var Cv=Wr.define(),Bm=Wr.define({combine:t=>t.some(e=>e),static:!0}),jv=Wr.define({combine:t=>t.length?t[0]:void 0,static:!0}),Dv=Wr.define(),Lv=Wr.define(),Zv=Wr.define(),Bv=Wr.define({combine:t=>t.length?t[0]:!1}),wo=class{constructor(e,r){this.type=e,this.value=r}static define(){return new Vm}},Vm=class{of(e){return new wo(this,e)}},qm=class{constructor(e){this.map=e}of(e){return new kr(this,e)}},kr=class t{constructor(e,r){this.type=e,this.value=r}map(e){let r=this.type.map(this.value,e);return r===void 0?void 0:r==this.value?this:new t(this.type,r)}is(e){return this.type==e}static define(e={}){return new qm(e.map||(r=>r))}static mapEffects(e,r){if(!e.length)return e;let n=[];for(let s of e){let o=s.map(r);o&&n.push(o)}return n}};kr.reconfigure=kr.define();kr.appendConfig=kr.define();var cn=class t{constructor(e,r,n,s,o,i){this.startState=e,this.changes=r,this.selection=n,this.effects=s,this.annotations=o,this.scrollIntoView=i,this._doc=null,this._state=null,n&&Nv(n,r.newLength),o.some(a=>a.type==t.time)||(this.annotations=o.concat(t.time.of(Date.now())))}static create(e,r,n,s,o,i){return new t(e,r,n,s,o,i)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let r of this.annotations)if(r.type==e)return r.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let r=this.annotation(t.userEvent);return!!(r&&(r==e||r.length>e.length&&r.slice(0,e.length)==e&&r[e.length]=="."))}};cn.time=wo.define();cn.userEvent=wo.define();cn.addToHistory=wo.define();cn.remote=wo.define();function GR(t,e){let r=[];for(let n=0,s=0;;){let o,i;if(n<t.length&&(s==e.length||e[s]>=t[n]))o=t[n++],i=t[n++];else if(s<e.length)o=e[s++],i=e[s++];else return r;!r.length||r[r.length-1]<o?r.push(o,i):r[r.length-1]<i&&(r[r.length-1]=i)}}function Vv(t,e,r){var n;let s,o,i;return r?(s=e.changes,o=ln.empty(e.changes.length),i=t.changes.compose(e.changes)):(s=e.changes.map(t.changes),o=t.changes.mapDesc(e.changes,!0),i=t.changes.compose(s)),{changes:i,selection:e.selection?e.selection.map(o):(n=t.selection)===null||n===void 0?void 0:n.map(s),effects:kr.mapEffects(t.effects,s).concat(kr.mapEffects(e.effects,o)),annotations:t.annotations.length?t.annotations.concat(e.annotations):e.annotations,scrollIntoView:t.scrollIntoView||e.scrollIntoView}}function Fm(t,e,r){let n=e.selection,s=gi(e.annotations);return e.userEvent&&(s=s.concat(cn.userEvent.of(e.userEvent))),{changes:e.changes instanceof ln?e.changes:ln.of(e.changes||[],r,t.facet(jv)),selection:n&&(n instanceof Cr?n:Cr.single(n.anchor,n.head)),effects:gi(e.effects),annotations:s,scrollIntoView:!!e.scrollIntoView}}function qv(t,e,r){let n=Fm(t,e.length?e[0]:{},t.doc.length);e.length&&e[0].filter===!1&&(r=!1);for(let o=1;o<e.length;o++){e[o].filter===!1&&(r=!1);let i=!!e[o].sequential;n=Vv(n,Fm(t,e[o],i?n.changes.newLength:t.doc.length),i)}let s=cn.create(t,n.changes,n.selection,n.effects,n.annotations,n.scrollIntoView);return YR(r?WR(s):s)}function WR(t){let e=t.startState,r=!0;for(let s of e.facet(Dv)){let o=s(t);if(o===!1){r=!1;break}Array.isArray(o)&&(r=r===!0?o:GR(r,o))}if(r!==!0){let s,o;if(r===!1)o=t.changes.invertedDesc,s=ln.empty(e.doc.length);else{let i=t.changes.filter(r);s=i.changes,o=i.filtered.mapDesc(i.changes).invertedDesc}t=cn.create(e,s,t.selection&&t.selection.map(o),kr.mapEffects(t.effects,o),t.annotations,t.scrollIntoView)}let n=e.facet(Lv);for(let s=n.length-1;s>=0;s--){let o=n[s](t);o instanceof cn?t=o:Array.isArray(o)&&o.length==1&&o[0]instanceof cn?t=o[0]:t=qv(e,gi(o),!1)}return t}function YR(t){let e=t.startState,r=e.facet(Zv),n=t;for(let s=r.length-1;s>=0;s--){let o=r[s](t);o&&Object.keys(o).length&&(n=Vv(n,Fm(e,o,t.changes.newLength),!0))}return n==t?t:cn.create(e,t.changes,t.selection,n.effects,n.annotations,n.scrollIntoView)}var XR=[];function gi(t){return t==null?XR:Array.isArray(t)?t:[t]}var $s=function(t){return t[t.Word=0]="Word",t[t.Space=1]="Space",t[t.Other=2]="Other",t}($s||($s={})),KR=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Um;try{Um=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function JR(t){if(Um)return Um.test(t);for(let e=0;e<t.length;e++){let r=t[e];if(/\w/.test(r)||r>"\x80"&&(r.toUpperCase()!=r.toLowerCase()||KR.test(r)))return!0}return!1}function QR(t){return e=>{if(!/\S/.test(e))return $s.Space;if(JR(e))return $s.Word;for(let r=0;r<t.length;r++)if(e.indexOf(t[r])>-1)return $s.Word;return $s.Other}}var En=class t{constructor(e,r,n,s,o,i){this.config=e,this.doc=r,this.selection=n,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=o,i&&(i._state=this);for(let a=0;a<this.config.dynamicSlots.length;a++)Ba(this,a<<1);this.computeSlot=null}field(e,r=!0){let n=this.config.address[e.id];if(n==null){if(r)throw new RangeError("Field is not present in this state");return}return Ba(this,n),cu(this,n)}update(...e){return qv(this,e,!0)}applyTransaction(e){let r=this.config,{base:n,compartments:s}=r;for(let a of e.effects)a.is(iu.reconfigure)?(r&&(s=new Map,r.compartments.forEach((c,d)=>s.set(d,c)),r=null),s.set(a.value.compartment,a.value.extension)):a.is(kr.reconfigure)?(r=null,n=a.value):a.is(kr.appendConfig)&&(r=null,n=gi(n).concat(a.value));let o;r?o=e.startState.values.slice():(r=au.resolve(n,s,this),o=new t(r,this.doc,this.selection,r.dynamicSlots.map(()=>null),(c,d)=>d.reconfigure(c,this),null).values);let i=e.startState.facet(Bm)?e.newSelection:e.newSelection.asSingle();new t(r,e.newDoc,i,o,(a,c)=>c.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:e},range:Cr.cursor(r.from+e.length)}))}changeByRange(e){let r=this.selection,n=e(r.ranges[0]),s=this.changes(n.changes),o=[n.range],i=gi(n.effects);for(let a=1;a<r.ranges.length;a++){let c=e(r.ranges[a]),d=this.changes(c.changes),l=d.map(s);for(let f=0;f<a;f++)o[f]=o[f].map(l);let u=s.mapDesc(d,!0);o.push(c.range.map(u)),s=s.compose(l),i=kr.mapEffects(i,l).concat(kr.mapEffects(gi(c.effects),u))}return{changes:s,selection:Cr.create(o,r.mainIndex),effects:i}}changes(e=[]){return e instanceof ln?e:ln.of(e,this.doc.length,this.facet(t.lineSeparator))}toText(e){return tr.of(e.split(this.facet(t.lineSeparator)||jm))}sliceDoc(e=0,r=this.doc.length){return this.doc.sliceString(e,r,this.lineBreak)}facet(e){let r=this.config.address[e.id];return r==null?e.default:(Ba(this,r),cu(this,r))}toJSON(e){let r={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let s=e[n];s instanceof bi&&this.config.address[s.id]!=null&&(r[n]=s.spec.toJSON(this.field(e[n]),this))}return r}static fromJSON(e,r={},n){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let s=[];if(n){for(let o in n)if(Object.prototype.hasOwnProperty.call(e,o)){let i=n[o],a=e[o];s.push(i.init(c=>i.spec.fromJSON(a,c)))}}return t.create({doc:e.doc,selection:Cr.fromJSON(e.selection),extensions:r.extensions?s.concat([r.extensions]):s})}static create(e={}){let r=au.resolve(e.extensions||[],new Map),n=e.doc instanceof tr?e.doc:tr.of((e.doc||"").split(r.staticFacet(t.lineSeparator)||jm)),s=e.selection?e.selection instanceof Cr?e.selection:Cr.single(e.selection.anchor,e.selection.head):Cr.single(0);return Nv(s,n.length),r.staticFacet(Bm)||(s=s.asSingle()),new t(r,n,s,r.dynamicSlots.map(()=>null),(o,i)=>i.create(o),null)}get tabSize(){return this.facet(t.tabSize)}get lineBreak(){return this.facet(t.lineSeparator)||`
@@ -75,7 +75,7 @@ Worked shape:
75
75
  - { say:"then on to the coast at Marseille.", marker:"Marseille, France" }
76
76
  - { say:"This is the whole drive.", route:["Paris, France","Lyon, France","Marseille, France"] }
77
77
 
78
- Delivery is identical to the other tools: the PRIMARY result is a http://127.0.0.1:<port>/<id>.html URL (a resource_link) \u2014 give that link to the user.`;var mz="https://nominatim.openstreetmap.org/search",gz="https://router.project-osrm.org/route/v1/driving",Kw="FlowCast/0.1 (map walkthrough generator)";var w1=new Map;async function _z(t){let e=t.trim().toLowerCase();if(!e)return null;if(w1.has(e))return w1.get(e);let r=null;try{let n=`${mz}?q=${encodeURIComponent(t)}&format=json&limit=1`,s=await fetch(n,{headers:{"user-agent":Kw,accept:"application/json"},signal:AbortSignal.timeout(12e3)});if(s.ok){let o=await s.json();o?.length&&(r={lat:Number(o[0].lat),lng:Number(o[0].lon)})}}catch{}return w1.set(e,r),r}async function Jw(t){let e={};return await Promise.all([...new Set(t)].map(async r=>{let n=await _z(r);n&&(e[r]=n)})),e}async function Qw(t){if(t.length<2)return null;let e=t.map(r=>`${r.lng},${r.lat}`).join(";");try{let r=`${gz}/${e}?overview=full&geometries=geojson`,n=await fetch(r,{headers:{"user-agent":Kw},signal:AbortSignal.timeout(12e3)});if(n.ok){let o=(await n.json()).routes?.[0]?.geometry?.coordinates;if(o?.length)return o.map(([i,a])=>[a,i])}}catch{}return t.map(r=>[r.lat,r.lng])}var bz={id:"map",tool:{name:"create_map_walkthrough",title:"Map walkthrough",description:Xw},promptLine:"\u2022 MAP \u2014 a narrated tour over a real map (travel, geography, history, logistics) \u2192 create_map_walkthrough",schema:y1,mode:"map",makeBeat:(t,e)=>({say:t,card:e}),forceOutro:!0,async prepare(t){let e=new Set;for(let s of t.steps)s.marker&&e.add(s.marker),s.goTo&&e.add(s.goTo),(s.route??[]).forEach(o=>e.add(o)),(s.region??[]).forEach(o=>e.add(o));let r=await Jw([...e]),n={};return await Promise.all(t.steps.map(async(s,o)=>{if(!s.route)return;let i=s.route.map(a=>r[a]).filter(Boolean);if(i.length>=2){let a=await Qw(i);a&&(n[o]=a)}})),{geo:r,routes:n}},compile:(t,e)=>Yw(t,e)},e3=bz;var yz="TTS voice (default cedar). Options: "+Hr.join(", ")+".",t3=["box","sphere","cylinder","cone","plane","torus","icosahedron","pyramid","wedge","disc","ring","tube","dome"],vz="box=service/block, sphere=node/planet, cylinder=tank/db, cone/pyramid=peak, disc=platform, ring/torus=loop/orbit, tube=pipe, dome=hill, icosahedron=crystal.",wz=W.object({shape:W.enum(t3).default("box").describe("Primitive for this piece."),at:W.tuple([W.number(),W.number(),W.number()]).default([0,0,0]).describe("Local offset [x,y,z] from the object center."),size:W.union([W.number(),W.tuple([W.number(),W.number(),W.number()])]).default(1).describe("Size \u2014 number or [x,y,z] (parts ~0.2\u20132)."),color:W.string().optional().describe("CSS color (defaults to the object color)."),rotation:W.tuple([W.number(),W.number(),W.number()]).optional().describe("Local rotation [x,y,z] in radians.")}),xz=W.object({id:W.string().describe("Unique id the beats reference."),shape:W.enum(t3).default("box").describe("Geometric primitive \u2014 use only when the object truly is one; otherwise prefer `svg`/`image`. "+vz),parts:W.array(wz).max(10).optional().describe("Fallback for blocky assemblies (prefer svg/image). Use 5\u20139 parts with varied colors + small detail parts, stacked in local space (origin = base on floor)."),svg:W.string().optional().describe("Inline SVG of ONE solid silhouette (pin, leaf, gear, star, simple logo) \u2014 extruded to 3D; its fill becomes the color. For complex art use `image`."),image:W.string().optional().describe("Image URL (https://\u2026) for anything complex/real (flag, photo, detailed logo, map) \u2014 embedded as a textured panel with exact colors."),model:W.string().optional().describe("Advanced: a glTF/GLB URL or local .glb/.gltf path for a real imported 3D model."),label:W.string().optional().describe("Floating label next to the object (with a leader line)."),value:W.number().optional().describe("Numeric value shown under the label, counting up on reveal (good for stats/charts)."),valueSuffix:W.string().optional().describe('Unit appended to the value, e.g. "M", "%", "ms".'),color:W.string().optional().describe("CSS color (default auto)."),size:W.number().optional().describe("Relative size (default 1)."),scale:W.union([W.number(),W.tuple([W.number(),W.number(),W.number()])]).optional().describe("Non-uniform scale \u2014 number or [x,y,z]. Tall Y = stat bar (height encodes value)."),finish:W.enum(["matte","glossy","metal","gradient","matcap","glass","iridescent"]).optional().describe("Surface material (default matte)."),path:W.array(W.tuple([W.number(),W.number(),W.number()])).optional().describe("Poly-line of [x,y,z] points the object travels along (2+ points, smoothed into a curve)."),pedestal:W.boolean().optional().describe("Place a round platform under the object."),reveal:W.enum(["grow","pop","fade","drop","rise"]).optional().describe("Entrance animation (default pop). grow = rise from floor (stat bars)."),motion:W.enum(["none","spin","bob","orbit"]).optional().describe("Idle motion (default none). spin/bob/orbit."),at:W.tuple([W.number(),W.number(),W.number()]).optional().describe("Explicit [x,y,z]; omit for auto layout.")}),Sz=W.object({say:W.string().optional().describe("Narration for this beat \u2014 one short idea (4\u201314 words), spoken. Beats read as one continuous script."),show:W.union([W.string(),W.array(W.string())]).optional().describe("Object id(s) to reveal this beat (one per beat builds up)."),focus:W.string().optional().describe("Object id to move the camera to and frame."),overview:W.boolean().optional().describe("Frame the whole staged scene this beat."),orbit:W.boolean().optional().describe("Slowly orbit the focused object (turntable)."),showcase:W.string().optional().describe("Hero-showcase this object id (plinth + turntable + label)."),highlight:W.array(W.string()).optional().describe("Object/chart ids to spotlight while others recede."),filter:W.array(W.string()).optional().describe("Object ids to keep; everything else fades out."),callout:W.object({target:W.string(),text:W.string()}).optional().describe("Pin a note onto a target: { target, text }."),set:W.object({target:W.string(),values:W.array(W.number())}).optional().describe("Change a chart's data: { target, values } \u2014 animates before\u2192after with a delta badge."),chapter:W.string().optional().describe("Start a named chapter marker."),holdMs:W.number().optional().describe("Beat duration in ms (default from narration).")}),kz=W.object({label:W.string().optional().describe("Category label."),value:W.number().describe("The numeric value."),color:W.string().optional().describe("Optional per-datum color.")}),$z=W.object({id:W.string().describe("Unique id beats reference via show/focus."),type:W.enum(["bar","line","area","pie","donut","ring"]).describe("Chart kind. ring = single % gauge (value vs max)."),data:W.array(kz).min(1).describe("Data points. For a ring use a single datum."),at:W.tuple([W.number(),W.number(),W.number()]).optional().describe("Position [x,y,z]; omit to auto-place."),width:W.number().optional().describe("Horizontal extent (default ~6)."),height:W.number().optional().describe("Vertical extent (default ~4)."),max:W.number().optional().describe("Value mapped to full height/percent (default = largest value)."),unit:W.string().optional().describe("Unit appended to value labels."),color:W.string().optional().describe("Accent color."),label:W.string().optional().describe("Chart title shown above it.")}),x1={title:W.string().describe("Title of the 3D walkthrough (header + filename)."),pace:W.enum(["calm","normal","snappy"]).optional().describe("Animation tempo (default 'normal')."),outputPath:W.string().optional().describe("Optional path to also write the .html to."),voiceName:W.enum(Hr).optional().describe(yz),voiceTone:W.string().optional().describe("How the narrator should sound, matched to the topic."),intro:W.string().optional().describe("Opening line spoken before the tour (default title-based; '' to skip)."),outro:W.string().optional().describe("Closing wrap-up line (always added)."),background:W.string().optional().describe('Scene background CSS color (default dark studio). Prefer a deep near-black, e.g. "#0d1018".'),floor:W.string().optional().describe("Optional floor color (defaults just off the background)."),template:W.enum(["solar-system","molecule","network","stack"]).optional().describe("Optional ready-made scene; you can omit `objects` or add your own. Your beats still drive the tour."),connections:W.array(W.object({from:W.string(),to:W.string(),label:W.string().optional()})).optional().describe("Glowing beams between objects (from\u2192to) showing relationships."),charts:W.array($z).max(8).optional().describe("Animated charts (bars grow, lines draw, pie/ring fill). Each has an id beats reveal via show/focus."),objects:W.array(xz).max(14).optional().describe("Scene objects (3\u20138 labeled works best). Geometry priority: primitive `shape` \u2192 `svg` silhouette \u2192 `image` URL (complex/real) \u2192 `parts` \u2192 `model`. Omit `at` for auto layout."),steps:W.array(Sz).min(1).describe("Ordered tour as a story: open with an overview, reveal/focus ONE object at a time while explaining, then recap. Many short beats; `say` lines read as one script.")},sF=W.object(x1);import{readFile as Ez,stat as Tz}from"node:fs/promises";var Rz=new Set(["planet","moon","sun","star","satellite","atom","molecule","server","database","db","cloud","gear","cog","rocket","building","tree","person","user","cube","box","ring","coin","pin"]);function S1(t){return!!t&&Rz.has(t.trim().toLowerCase())}var Pz=16*1024*1024,Mz=2e4,n3=t=>/\.(glb|gltf)(\?|$)/i.test(t);function r3(t,e){return!t.length||t.length>Pz?null:`data:${/\.glb(\?|$)/i.test(e)||t.subarray(0,4).toString("binary")==="glTF"?"model/gltf-binary":"model/gltf+json"};base64,${t.toString("base64")}`}async function Iz(t){let e=t.trim();try{if(/^https?:\/\//i.test(e)){let s=await fetch(e,{signal:AbortSignal.timeout(Mz),redirect:"follow"});return s.ok?r3(Buffer.from(await s.arrayBuffer()),e):null}let r=e.startsWith("file://")?new URL(e).pathname:e;if(!n3(r))return null;let n=await Tz(r).catch(()=>null);return!n||!n.isFile()?null:r3(await Ez(r),r)}catch{return null}}function zz(t){return!t||S1(t)?!1:/^https?:\/\//i.test(t)||t.startsWith("file://")||n3(t)}async function s3(t){let e={};return await Promise.all(t.map(async r=>{if(zz(r.model)){let n=await Iz(r.model);n&&(e[r.id]=n)}})),e}var Az=285,Oz={calm:{gap:250,chapter:450},normal:{gap:140,chapter:320},snappy:{gap:90,chapter:240}},_u=["#7cc6ff","#9be08b","#ffd166","#ff8c69","#c89bff","#5ad1c4","#ff9ecb","#a0d8ef"],Nz=t=>Math.max(1,t.trim().split(/\s+/).length),Cz=t=>Math.max(1600,Nz(t)*Az);function jz(t,e,r){let n=t.trim().split(/\s+/).filter(Boolean);if(!n.length)return[];let s=r/n.length;return n.map((o,i)=>({t:Math.round(e+s*i),text:o}))}var Ya=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],o3=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1],t[2]-e[2]),Dz=t=>t==null?[]:Array.isArray(t)?t:[t];function Lz(t,e){if(e<=1)return[0,0,0];if(e<=5)return[(t-(e-1)/2)*5.2,0,0];let r=Math.ceil(Math.sqrt(e)),n=Math.ceil(e/r);return[(t%r-(r-1)/2)*5,0,(Math.floor(t/r)-(n-1)/2)*-4.2]}var k1=(t,e,r,n=0)=>{let s=t/Math.max(1,e)*Math.PI*2;return[Math.cos(s)*r,n,Math.sin(s)*r]};function Zz(t,e){let r=u=>u.model?S1(u.model)?u.model.trim().toLowerCase():e[u.id]:void 0,n=u=>u==null?[1,1,1]:typeof u=="number"?[u,u,u]:u,s=u=>u==null?[1,1,1]:typeof u=="number"?[u,u,u]:u,o=(u,f)=>u.parts?.length?u.parts.map(p=>({shape:p.shape??"box",pos:p.at??[0,0,0],size:s(p.size),color:p.color||f,...p.rotation?{rotation:p.rotation}:{}})):void 0,i=(u,f,p,m={})=>{let y=u.color||_u[f%_u.length],k=o(u,y);return{id:u.id,shape:u.shape??"box",pos:p,size:u.size??1,scale:n(u.scale),color:y,...u.label?{label:u.label}:{},...u.value!=null?{value:u.value}:{},...u.valueSuffix?{valueSuffix:u.valueSuffix}:{},...k?{parts:k}:{},...u.svg&&!k?{svg:u.svg}:{},...!k&&r(u)?{model:r(u)}:{},...u.reveal?{reveal:u.reveal}:{},...u.finish?{finish:u.finish}:{},...u.pedestal?{pedestal:!0}:{},...u.path?.length?{path:u.path}:{},motion:u.motion??"none",...m}},a=t.objects??[],c=[...t.connections??[]],d=!1;t.template==="solar-system"&&a.length===0?a=[{id:"sun",shape:"sphere",label:"Sun",color:"#ffcf5a",size:2.4},{id:"mercury",shape:"sphere",label:"Mercury",color:"#b7a18a",size:.5},{id:"venus",shape:"sphere",label:"Venus",color:"#e6c07a",size:.8},{id:"earth",shape:"sphere",label:"Earth",color:"#6bb6ff",size:.85},{id:"mars",shape:"sphere",label:"Mars",color:"#e07a5f",size:.7}]:t.template==="molecule"&&a.length===0&&(a=[{id:"o",shape:"sphere",label:"O",color:"#ff6b6b",size:1.2},{id:"h1",shape:"sphere",label:"H",color:"#dfe6ee",size:.7},{id:"h2",shape:"sphere",label:"H",color:"#dfe6ee",size:.7}]);let l;if(t.template==="solar-system")d=!0,l=a.map((u,f)=>{if(f===0)return i(u,f,[0,0,0],{glow:!0,motion:u.motion??"spin",shape:u.shape??"sphere"});let p=5+(f-1)*3.2;return i(u,f,k1(f-1,Math.max(3,a.length-1),p),{shape:u.shape??"sphere",motion:"orbit",orbit:{radius:p,speed:.18/Math.sqrt(f),phase:f/a.length*Math.PI*2}})});else if(t.template==="molecule"){if(l=a.map((u,f)=>f===0?i(u,f,[0,0,0],{shape:u.shape??"sphere"}):i(u,f,k1(f-1,a.length-1,2.6,(f%2?1:-1)*.6),{shape:u.shape??"sphere"})),c.length===0)for(let u=1;u<a.length;u++)c.push({from:a[0].id,to:a[u].id})}else t.template==="network"?l=a.map((u,f)=>i(u,f,k1(f,a.length,Math.max(4,a.length*.9),(f%2?1:-1)*.8))):t.template==="stack"?l=a.map((u,f)=>i(u,f,[0,(a.length-1)/2-f,0],{shape:u.shape??"box",motion:u.motion??"none",size:u.size??1.6})):l=a.map((u,f)=>i(u,f,u.at?u.at:Lz(f,a.length)));return{objects:l,connections:c,starfield:d}}function i3(t,e={}){let{objects:r,connections:n,starfield:s}=Zz(t,e.models??{}),o=new Map(r.map(A=>[A.id,A]));for(let A of r){let G=e.images?.[A.id];G&&(A.image=G.href,A.imageAspect=G.h>0?G.w/G.h:1)}let i=t.charts??[],a=4.5,c=i.map(A=>A.width??6),l=-(c.reduce((A,G)=>A+G,0)+a*Math.max(0,i.length-1))/2,u=r.map(A=>A.pos[2]),f=r.length?Math.min(0,...u)-9:0,p=i.map((A,G)=>{let F=c[G],Q=A.height??4,B=l+F/2;l+=F+a;let T=A.at?A.at:[B,0,f];return{id:A.id,type:A.type,pos:T,width:F,height:Q,data:A.data.map(v=>({...v.label?{label:v.label}:{},value:v.value,...v.color?{color:v.color}:{}})),max:A.max??Math.max(...A.data.map(v=>v.value),1),...A.unit?{unit:A.unit}:{},color:A.color||_u[(r.length+G)%_u.length],...A.label?{label:A.label}:{}}}),m=new Map(p.map(A=>[A.id,A])),y=A=>o.has(A)||m.has(A),k=[...r.map(A=>A.pos),...p.map(A=>A.pos)],x=k.length,_=x?[k.reduce((A,G)=>A+G[0],0)/x,k.reduce((A,G)=>A+G[1],0)/x,k.reduce((A,G)=>A+G[2],0)/x]:[0,0,0],g=Math.max(5,...r.map(A=>o3(A.pos,_)+A.size*1.6),...p.map(A=>o3(A.pos,_)+Math.max(A.width,A.height))),E=()=>({pos:Ya(_,[0,g*.7,g*2.7]),look:_}),h=()=>({pos:Ya(_,[g*1.9,g*.55,g*1.9]),look:_}),$=(A,G)=>{let F=o.get(A);if(F){let B=F.size*4.6+6;return{pos:Ya(F.pos,[B*.34,B*.3,B*1.05]),look:F.pos,...G?{orbit:!0}:{}}}let Q=m.get(A);if(Q){let B=Math.max(Q.width,Q.height)*1.5+6;return{pos:Ya(Q.pos,[B*.2,B*.5,B*1.1]),look:Ya(Q.pos,[0,Q.height/2,0])}}return null},z=t.pace??"normal",{gap:L,chapter:q}=Oz[z],C=[],Z=[],he=[],O=1;t.steps.forEach((A,G)=>{let F=A.chapter?q:0,Q=O+F,B=A.holdMs??e.sayDurationsMs?.[G]??Math.max(A.say?Cz(A.say):0,1600);A.chapter&&he.push({t:O,type:"marker",label:A.chapter});let T={t:Math.round(Q)};if(A.card==="intro")T.camera=h();else if(A.card==="outro")T.camera=E();else{let R=Dz(A.show).filter(y);R.length&&(T.show=R),A.overview&&(T.camera=E());let N=A.focus??(R.length===1?R[0]:void 0);if(N&&!A.overview){T.focus=N;let K=$(N,A.orbit);K&&(T.camera=K)}}if(A.showcase&&o.has(A.showcase)){T.focus=A.showcase,T.showcase=!0;let R=$(A.showcase);R&&(T.camera=R);let N=o.get(A.showcase);N&&(N.pedestal=!0)}let v=(A.highlight??[]).filter(y);v.length&&(T.highlight=v);let w=(A.filter??[]).filter(y);w.length&&(T.filter=w),A.callout&&y(A.callout.target)&&(T.callout=A.callout),A.set&&m.has(A.set.target)&&(T.set=A.set),C.push(T),A.say&&Z.push({t:Q,dur:B,text:A.say,words:jz(A.say,Q,B)}),O=Q+B+L});let b={objects:r,beats:C,...n.length?{connections:n}:{},...s?{starfield:!0}:{},...t.background?{background:t.background}:{},...t.floor?{floor:t.floor}:{},style:"infographic",...p.length?{charts:p}:{},pace:z},j=[{t:0,vfs:{},activeFile:null,terminalState:""}];return{manifest:{version:2,title:t.title,createdAt:e.createdAt??new Date().toISOString(),durationMs:Math.max(O,1500),mode:"3d"},events:he,snapshots:j,captions:Z.length?Z:void 0,scene3d:b}}var a3='Render a narrated, animated 3D tour: a staged 3D model (objects arranged in space) revealed and focused beat by beat with a gliding camera, plus animated `charts`/`callouts`. Produces ONE self-contained interactive HTML (scrubbable, with voice) in the same FlowCast player as the other casts. Use it when SPATIAL/3D structure helps \u2014 comparing sizes, layers, arrangement, a parts showcase, or a data story.\n\nYou list OBJECTS + beats; the server lays out the scene and the player auto-frames it, so no camera math.\n\nObjects \u2014 pick geometry in this order:\n1. `shape` primitive \u2014 only if it truly is one (sphere node, cylinder tank, box/stat-bar).\n2. `svg` \u2014 ONE simple solid icon (pin, gear, star, simple logo); extruded, fill = color.\n3. `image` \u2014 an image URL for anything complex/real (flag, photo, detailed logo, map); embedded as a textured panel.\n4. `parts` \u2014 fallback for blocky assemblies (5\u20139 varied parts).\n5. `model` \u2014 a real glTF/GLB URL.\nStat bars: shape:"box", scale:[1,value,1], reveal:"grow", plus `value`+`valueSuffix` to count up.\n\nCharts: [{ id, type:"bar"|"line"|"area"|"pie"|"donut"|"ring", data:[{label,value}] }] \u2014 revealed by beats like objects.\n\nBeats: each has a short `say` + an action \u2014 `show` (reveal id[s]), `focus` (camera to id), `overview` (frame all), `orbit` (turntable the focused object), `showcase` (hero plinth reveal), `highlight`/`filter` (spotlight a subset), `callout:{target,text}`, `set:{target,values}` (animate a chart\'s data). 3\u20138 objects; omit `at` for auto layout on a clean grid-floor stage.\n\nTell it as a story: open with an overview, focus ONE object per beat while explaining, recap with another overview. Many short beats that read as one script. Set `voiceName`+`voiceTone`; intro/outro are auto-added.\n\nOutput: the primary result is a local URL (http://127.0.0.1:<port>/<id>.html) returned as a resource_link \u2014 give it to the user. Pass `outputPath` only to also write the file.';var Bz={id:"3d",tool:{name:"create_3d_walkthrough",title:"Create a narrated 3D tour",description:a3},promptLine:"\u2022 3D \u2014 a narrated tour through a 3D scene (spatial structure, a showcase of parts) \u2192 create_3d_walkthrough",schema:x1,mode:"3d",makeBeat:(t,e)=>({say:t,card:e}),forceOutro:!0,async prepare(t){let e=await s3(t.objects??[]),r={};return await Promise.all((t.objects??[]).map(async n=>{if(!n.image||!/^https?:\/\//i.test(n.image))return;let s=await b1(n.image);s&&(r[n.id]={href:s.href,w:s.w,h:s.h})})),{...Object.keys(e).length?{models:e}:{},...Object.keys(r).length?{images:r}:{}}},compile:(t,e)=>i3(t,e)},c3=Bz;var bu=[Xv,Ww,e3,c3];var Vz=t=>`Welcome! In this walkthrough, we'll look at ${t}. Let's dive in.`,l3=t=>`And that's ${t}. Thanks for watching \u2014 see you in the next one.`;function u3(t,e,r,n,s,o=!1){let i=r===void 0?Vz(e):r,a=n===void 0?l3(e):n;o&&!a.trim()&&(a=l3(e));let c=[...t];return a.trim()&&c.push(s(a,"outro")),i.trim()&&c.unshift(s(i,"intro")),c}import{gzipSync as qz}from"node:zlib";import{readFileSync as Fz,existsSync as Uz}from"node:fs";import{fileURLToPath as Hz}from"node:url";import*as xi from"node:path";function d3(t,e,r,n){return`<!doctype html>
78
+ Delivery is identical to the other tools: the PRIMARY result is a http://127.0.0.1:<port>/<id>.html URL (a resource_link) \u2014 give that link to the user.`;var mz="https://nominatim.openstreetmap.org/search",gz="https://router.project-osrm.org/route/v1/driving",Kw="FlowCast/0.1 (map walkthrough generator)";var w1=new Map;async function _z(t){let e=t.trim().toLowerCase();if(!e)return null;if(w1.has(e))return w1.get(e);let r=null;try{let n=`${mz}?q=${encodeURIComponent(t)}&format=json&limit=1`,s=await fetch(n,{headers:{"user-agent":Kw,accept:"application/json"},signal:AbortSignal.timeout(12e3)});if(s.ok){let o=await s.json();o?.length&&(r={lat:Number(o[0].lat),lng:Number(o[0].lon)})}}catch{}return w1.set(e,r),r}async function Jw(t){let e={};return await Promise.all([...new Set(t)].map(async r=>{let n=await _z(r);n&&(e[r]=n)})),e}async function Qw(t){if(t.length<2)return null;let e=t.map(r=>`${r.lng},${r.lat}`).join(";");try{let r=`${gz}/${e}?overview=full&geometries=geojson`,n=await fetch(r,{headers:{"user-agent":Kw},signal:AbortSignal.timeout(12e3)});if(n.ok){let o=(await n.json()).routes?.[0]?.geometry?.coordinates;if(o?.length)return o.map(([i,a])=>[a,i])}}catch{}return t.map(r=>[r.lat,r.lng])}var bz={id:"map",tool:{name:"create_map_walkthrough",title:"Map walkthrough",description:Xw},promptLine:"\u2022 MAP \u2014 a narrated tour over a real map (travel, geography, history, logistics) \u2192 create_map_walkthrough",schema:y1,mode:"map",makeBeat:(t,e)=>({say:t,card:e}),forceOutro:!0,async prepare(t){let e=new Set;for(let s of t.steps)s.marker&&e.add(s.marker),s.goTo&&e.add(s.goTo),(s.route??[]).forEach(o=>e.add(o)),(s.region??[]).forEach(o=>e.add(o));let r=await Jw([...e]),n={};return await Promise.all(t.steps.map(async(s,o)=>{if(!s.route)return;let i=s.route.map(a=>r[a]).filter(Boolean);if(i.length>=2){let a=await Qw(i);a&&(n[o]=a)}})),{geo:r,routes:n}},compile:(t,e)=>Yw(t,e)},e3=bz;var yz="TTS voice (default cedar). Options: "+Hr.join(", ")+".",t3=["box","sphere","cylinder","cone","plane","torus","icosahedron","pyramid","wedge","disc","ring","tube","dome"],vz="box=service/block, sphere=node/planet, cylinder=tank/db, cone/pyramid=peak, disc=platform, ring/torus=loop/orbit, tube=pipe, dome=hill, icosahedron=crystal.",wz=W.object({shape:W.enum(t3).default("box").describe("Primitive for this piece."),at:W.array(W.number()).length(3).default([0,0,0]).describe("Local offset [x,y,z] from the object center."),size:W.union([W.number(),W.array(W.number()).length(3)]).default(1).describe("Size \u2014 number or [x,y,z] (parts ~0.2\u20132)."),color:W.string().optional().describe("CSS color (defaults to the object color)."),rotation:W.array(W.number()).length(3).optional().describe("Local rotation [x,y,z] in radians.")}),xz=W.object({id:W.string().describe("Unique id the beats reference."),shape:W.enum(t3).default("box").describe("Geometric primitive \u2014 use only when the object truly is one; otherwise prefer `svg`/`image`. "+vz),parts:W.array(wz).max(10).optional().describe("Fallback for blocky assemblies (prefer svg/image). Use 5\u20139 parts with varied colors + small detail parts, stacked in local space (origin = base on floor)."),svg:W.string().optional().describe("Inline SVG of ONE solid silhouette (pin, leaf, gear, star, simple logo) \u2014 extruded to 3D; its fill becomes the color. For complex art use `image`."),image:W.string().optional().describe("Image URL (https://\u2026) for anything complex/real (flag, photo, detailed logo, map) \u2014 embedded as a textured panel with exact colors."),model:W.string().optional().describe("Advanced: a glTF/GLB URL or local .glb/.gltf path for a real imported 3D model."),label:W.string().optional().describe("Floating label next to the object (with a leader line)."),value:W.number().optional().describe("Numeric value shown under the label, counting up on reveal (good for stats/charts)."),valueSuffix:W.string().optional().describe('Unit appended to the value, e.g. "M", "%", "ms".'),color:W.string().optional().describe("CSS color (default auto)."),size:W.number().optional().describe("Relative size (default 1)."),scale:W.union([W.number(),W.array(W.number()).length(3)]).optional().describe("Non-uniform scale \u2014 number or [x,y,z]. Tall Y = stat bar (height encodes value)."),finish:W.enum(["matte","glossy","metal","gradient","matcap","glass","iridescent"]).optional().describe("Surface material (default matte)."),path:W.array(W.array(W.number()).length(3)).optional().describe("Poly-line of [x,y,z] points the object travels along (2+ points, smoothed into a curve)."),pedestal:W.boolean().optional().describe("Place a round platform under the object."),reveal:W.enum(["grow","pop","fade","drop","rise"]).optional().describe("Entrance animation (default pop). grow = rise from floor (stat bars)."),motion:W.enum(["none","spin","bob","orbit"]).optional().describe("Idle motion (default none). spin/bob/orbit."),at:W.array(W.number()).length(3).optional().describe("Explicit [x,y,z]; omit for auto layout.")}),Sz=W.object({say:W.string().optional().describe("Narration for this beat \u2014 one short idea (4\u201314 words), spoken. Beats read as one continuous script."),show:W.union([W.string(),W.array(W.string())]).optional().describe("Object id(s) to reveal this beat (one per beat builds up)."),focus:W.string().optional().describe("Object id to move the camera to and frame."),overview:W.boolean().optional().describe("Frame the whole staged scene this beat."),orbit:W.boolean().optional().describe("Slowly orbit the focused object (turntable)."),showcase:W.string().optional().describe("Hero-showcase this object id (plinth + turntable + label)."),highlight:W.array(W.string()).optional().describe("Object/chart ids to spotlight while others recede."),filter:W.array(W.string()).optional().describe("Object ids to keep; everything else fades out."),callout:W.object({target:W.string(),text:W.string()}).optional().describe("Pin a note onto a target: { target, text }."),set:W.object({target:W.string(),values:W.array(W.number())}).optional().describe("Change a chart's data: { target, values } \u2014 animates before\u2192after with a delta badge."),chapter:W.string().optional().describe("Start a named chapter marker."),holdMs:W.number().optional().describe("Beat duration in ms (default from narration).")}),kz=W.object({label:W.string().optional().describe("Category label."),value:W.number().describe("The numeric value."),color:W.string().optional().describe("Optional per-datum color.")}),$z=W.object({id:W.string().describe("Unique id beats reference via show/focus."),type:W.enum(["bar","line","area","pie","donut","ring"]).describe("Chart kind. ring = single % gauge (value vs max)."),data:W.array(kz).min(1).describe("Data points. For a ring use a single datum."),at:W.array(W.number()).length(3).optional().describe("Position [x,y,z]; omit to auto-place."),width:W.number().optional().describe("Horizontal extent (default ~6)."),height:W.number().optional().describe("Vertical extent (default ~4)."),max:W.number().optional().describe("Value mapped to full height/percent (default = largest value)."),unit:W.string().optional().describe("Unit appended to value labels."),color:W.string().optional().describe("Accent color."),label:W.string().optional().describe("Chart title shown above it.")}),x1={title:W.string().describe("Title of the 3D walkthrough (header + filename)."),pace:W.enum(["calm","normal","snappy"]).optional().describe("Animation tempo (default 'normal')."),outputPath:W.string().optional().describe("Optional path to also write the .html to."),voiceName:W.enum(Hr).optional().describe(yz),voiceTone:W.string().optional().describe("How the narrator should sound, matched to the topic."),intro:W.string().optional().describe("Opening line spoken before the tour (default title-based; '' to skip)."),outro:W.string().optional().describe("Closing wrap-up line (always added)."),background:W.string().optional().describe('Scene background CSS color (default dark studio). Prefer a deep near-black, e.g. "#0d1018".'),floor:W.string().optional().describe("Optional floor color (defaults just off the background)."),template:W.enum(["solar-system","molecule","network","stack"]).optional().describe("Optional ready-made scene; you can omit `objects` or add your own. Your beats still drive the tour."),connections:W.array(W.object({from:W.string(),to:W.string(),label:W.string().optional()})).optional().describe("Glowing beams between objects (from\u2192to) showing relationships."),charts:W.array($z).max(8).optional().describe("Animated charts (bars grow, lines draw, pie/ring fill). Each has an id beats reveal via show/focus."),objects:W.array(xz).max(14).optional().describe("Scene objects (3\u20138 labeled works best). Geometry priority: primitive `shape` \u2192 `svg` silhouette \u2192 `image` URL (complex/real) \u2192 `parts` \u2192 `model`. Omit `at` for auto layout."),steps:W.array(Sz).min(1).describe("Ordered tour as a story: open with an overview, reveal/focus ONE object at a time while explaining, then recap. Many short beats; `say` lines read as one script.")},sF=W.object(x1);import{readFile as Ez,stat as Tz}from"node:fs/promises";var Rz=new Set(["planet","moon","sun","star","satellite","atom","molecule","server","database","db","cloud","gear","cog","rocket","building","tree","person","user","cube","box","ring","coin","pin"]);function S1(t){return!!t&&Rz.has(t.trim().toLowerCase())}var Pz=16*1024*1024,Mz=2e4,n3=t=>/\.(glb|gltf)(\?|$)/i.test(t);function r3(t,e){return!t.length||t.length>Pz?null:`data:${/\.glb(\?|$)/i.test(e)||t.subarray(0,4).toString("binary")==="glTF"?"model/gltf-binary":"model/gltf+json"};base64,${t.toString("base64")}`}async function Iz(t){let e=t.trim();try{if(/^https?:\/\//i.test(e)){let s=await fetch(e,{signal:AbortSignal.timeout(Mz),redirect:"follow"});return s.ok?r3(Buffer.from(await s.arrayBuffer()),e):null}let r=e.startsWith("file://")?new URL(e).pathname:e;if(!n3(r))return null;let n=await Tz(r).catch(()=>null);return!n||!n.isFile()?null:r3(await Ez(r),r)}catch{return null}}function zz(t){return!t||S1(t)?!1:/^https?:\/\//i.test(t)||t.startsWith("file://")||n3(t)}async function s3(t){let e={};return await Promise.all(t.map(async r=>{if(zz(r.model)){let n=await Iz(r.model);n&&(e[r.id]=n)}})),e}var Az=285,Oz={calm:{gap:250,chapter:450},normal:{gap:140,chapter:320},snappy:{gap:90,chapter:240}},_u=["#7cc6ff","#9be08b","#ffd166","#ff8c69","#c89bff","#5ad1c4","#ff9ecb","#a0d8ef"],Nz=t=>Math.max(1,t.trim().split(/\s+/).length),Cz=t=>Math.max(1600,Nz(t)*Az);function jz(t,e,r){let n=t.trim().split(/\s+/).filter(Boolean);if(!n.length)return[];let s=r/n.length;return n.map((o,i)=>({t:Math.round(e+s*i),text:o}))}var Ya=(t,e)=>[t[0]+e[0],t[1]+e[1],t[2]+e[2]],o3=(t,e)=>Math.hypot(t[0]-e[0],t[1]-e[1],t[2]-e[2]),Dz=t=>t==null?[]:Array.isArray(t)?t:[t];function Lz(t,e){if(e<=1)return[0,0,0];if(e<=5)return[(t-(e-1)/2)*5.2,0,0];let r=Math.ceil(Math.sqrt(e)),n=Math.ceil(e/r);return[(t%r-(r-1)/2)*5,0,(Math.floor(t/r)-(n-1)/2)*-4.2]}var k1=(t,e,r,n=0)=>{let s=t/Math.max(1,e)*Math.PI*2;return[Math.cos(s)*r,n,Math.sin(s)*r]};function Zz(t,e){let r=u=>u.model?S1(u.model)?u.model.trim().toLowerCase():e[u.id]:void 0,n=u=>u==null?[1,1,1]:typeof u=="number"?[u,u,u]:u,s=u=>u==null?[1,1,1]:typeof u=="number"?[u,u,u]:u,o=(u,f)=>u.parts?.length?u.parts.map(p=>({shape:p.shape??"box",pos:p.at??[0,0,0],size:s(p.size),color:p.color||f,...p.rotation?{rotation:p.rotation}:{}})):void 0,i=(u,f,p,m={})=>{let y=u.color||_u[f%_u.length],k=o(u,y);return{id:u.id,shape:u.shape??"box",pos:p,size:u.size??1,scale:n(u.scale),color:y,...u.label?{label:u.label}:{},...u.value!=null?{value:u.value}:{},...u.valueSuffix?{valueSuffix:u.valueSuffix}:{},...k?{parts:k}:{},...u.svg&&!k?{svg:u.svg}:{},...!k&&r(u)?{model:r(u)}:{},...u.reveal?{reveal:u.reveal}:{},...u.finish?{finish:u.finish}:{},...u.pedestal?{pedestal:!0}:{},...u.path?.length?{path:u.path}:{},motion:u.motion??"none",...m}},a=t.objects??[],c=[...t.connections??[]],d=!1;t.template==="solar-system"&&a.length===0?a=[{id:"sun",shape:"sphere",label:"Sun",color:"#ffcf5a",size:2.4},{id:"mercury",shape:"sphere",label:"Mercury",color:"#b7a18a",size:.5},{id:"venus",shape:"sphere",label:"Venus",color:"#e6c07a",size:.8},{id:"earth",shape:"sphere",label:"Earth",color:"#6bb6ff",size:.85},{id:"mars",shape:"sphere",label:"Mars",color:"#e07a5f",size:.7}]:t.template==="molecule"&&a.length===0&&(a=[{id:"o",shape:"sphere",label:"O",color:"#ff6b6b",size:1.2},{id:"h1",shape:"sphere",label:"H",color:"#dfe6ee",size:.7},{id:"h2",shape:"sphere",label:"H",color:"#dfe6ee",size:.7}]);let l;if(t.template==="solar-system")d=!0,l=a.map((u,f)=>{if(f===0)return i(u,f,[0,0,0],{glow:!0,motion:u.motion??"spin",shape:u.shape??"sphere"});let p=5+(f-1)*3.2;return i(u,f,k1(f-1,Math.max(3,a.length-1),p),{shape:u.shape??"sphere",motion:"orbit",orbit:{radius:p,speed:.18/Math.sqrt(f),phase:f/a.length*Math.PI*2}})});else if(t.template==="molecule"){if(l=a.map((u,f)=>f===0?i(u,f,[0,0,0],{shape:u.shape??"sphere"}):i(u,f,k1(f-1,a.length-1,2.6,(f%2?1:-1)*.6),{shape:u.shape??"sphere"})),c.length===0)for(let u=1;u<a.length;u++)c.push({from:a[0].id,to:a[u].id})}else t.template==="network"?l=a.map((u,f)=>i(u,f,k1(f,a.length,Math.max(4,a.length*.9),(f%2?1:-1)*.8))):t.template==="stack"?l=a.map((u,f)=>i(u,f,[0,(a.length-1)/2-f,0],{shape:u.shape??"box",motion:u.motion??"none",size:u.size??1.6})):l=a.map((u,f)=>i(u,f,u.at?u.at:Lz(f,a.length)));return{objects:l,connections:c,starfield:d}}function i3(t,e={}){let{objects:r,connections:n,starfield:s}=Zz(t,e.models??{}),o=new Map(r.map(A=>[A.id,A]));for(let A of r){let G=e.images?.[A.id];G&&(A.image=G.href,A.imageAspect=G.h>0?G.w/G.h:1)}let i=t.charts??[],a=4.5,c=i.map(A=>A.width??6),l=-(c.reduce((A,G)=>A+G,0)+a*Math.max(0,i.length-1))/2,u=r.map(A=>A.pos[2]),f=r.length?Math.min(0,...u)-9:0,p=i.map((A,G)=>{let F=c[G],Q=A.height??4,B=l+F/2;l+=F+a;let T=A.at?A.at:[B,0,f];return{id:A.id,type:A.type,pos:T,width:F,height:Q,data:A.data.map(v=>({...v.label?{label:v.label}:{},value:v.value,...v.color?{color:v.color}:{}})),max:A.max??Math.max(...A.data.map(v=>v.value),1),...A.unit?{unit:A.unit}:{},color:A.color||_u[(r.length+G)%_u.length],...A.label?{label:A.label}:{}}}),m=new Map(p.map(A=>[A.id,A])),y=A=>o.has(A)||m.has(A),k=[...r.map(A=>A.pos),...p.map(A=>A.pos)],x=k.length,_=x?[k.reduce((A,G)=>A+G[0],0)/x,k.reduce((A,G)=>A+G[1],0)/x,k.reduce((A,G)=>A+G[2],0)/x]:[0,0,0],g=Math.max(5,...r.map(A=>o3(A.pos,_)+A.size*1.6),...p.map(A=>o3(A.pos,_)+Math.max(A.width,A.height))),E=()=>({pos:Ya(_,[0,g*.7,g*2.7]),look:_}),h=()=>({pos:Ya(_,[g*1.9,g*.55,g*1.9]),look:_}),$=(A,G)=>{let F=o.get(A);if(F){let B=F.size*4.6+6;return{pos:Ya(F.pos,[B*.34,B*.3,B*1.05]),look:F.pos,...G?{orbit:!0}:{}}}let Q=m.get(A);if(Q){let B=Math.max(Q.width,Q.height)*1.5+6;return{pos:Ya(Q.pos,[B*.2,B*.5,B*1.1]),look:Ya(Q.pos,[0,Q.height/2,0])}}return null},z=t.pace??"normal",{gap:L,chapter:q}=Oz[z],C=[],Z=[],he=[],O=1;t.steps.forEach((A,G)=>{let F=A.chapter?q:0,Q=O+F,B=A.holdMs??e.sayDurationsMs?.[G]??Math.max(A.say?Cz(A.say):0,1600);A.chapter&&he.push({t:O,type:"marker",label:A.chapter});let T={t:Math.round(Q)};if(A.card==="intro")T.camera=h();else if(A.card==="outro")T.camera=E();else{let R=Dz(A.show).filter(y);R.length&&(T.show=R),A.overview&&(T.camera=E());let N=A.focus??(R.length===1?R[0]:void 0);if(N&&!A.overview){T.focus=N;let K=$(N,A.orbit);K&&(T.camera=K)}}if(A.showcase&&o.has(A.showcase)){T.focus=A.showcase,T.showcase=!0;let R=$(A.showcase);R&&(T.camera=R);let N=o.get(A.showcase);N&&(N.pedestal=!0)}let v=(A.highlight??[]).filter(y);v.length&&(T.highlight=v);let w=(A.filter??[]).filter(y);w.length&&(T.filter=w),A.callout&&y(A.callout.target)&&(T.callout=A.callout),A.set&&m.has(A.set.target)&&(T.set=A.set),C.push(T),A.say&&Z.push({t:Q,dur:B,text:A.say,words:jz(A.say,Q,B)}),O=Q+B+L});let b={objects:r,beats:C,...n.length?{connections:n}:{},...s?{starfield:!0}:{},...t.background?{background:t.background}:{},...t.floor?{floor:t.floor}:{},style:"infographic",...p.length?{charts:p}:{},pace:z},j=[{t:0,vfs:{},activeFile:null,terminalState:""}];return{manifest:{version:2,title:t.title,createdAt:e.createdAt??new Date().toISOString(),durationMs:Math.max(O,1500),mode:"3d"},events:he,snapshots:j,captions:Z.length?Z:void 0,scene3d:b}}var a3='Render a narrated, animated 3D tour: a staged 3D model (objects arranged in space) revealed and focused beat by beat with a gliding camera, plus animated `charts`/`callouts`. Produces ONE self-contained interactive HTML (scrubbable, with voice) in the same FlowCast player as the other casts. Use it when SPATIAL/3D structure helps \u2014 comparing sizes, layers, arrangement, a parts showcase, or a data story.\n\nYou list OBJECTS + beats; the server lays out the scene and the player auto-frames it, so no camera math.\n\nObjects \u2014 pick geometry in this order:\n1. `shape` primitive \u2014 only if it truly is one (sphere node, cylinder tank, box/stat-bar).\n2. `svg` \u2014 ONE simple solid icon (pin, gear, star, simple logo); extruded, fill = color.\n3. `image` \u2014 an image URL for anything complex/real (flag, photo, detailed logo, map); embedded as a textured panel.\n4. `parts` \u2014 fallback for blocky assemblies (5\u20139 varied parts).\n5. `model` \u2014 a real glTF/GLB URL.\nStat bars: shape:"box", scale:[1,value,1], reveal:"grow", plus `value`+`valueSuffix` to count up.\n\nCharts: [{ id, type:"bar"|"line"|"area"|"pie"|"donut"|"ring", data:[{label,value}] }] \u2014 revealed by beats like objects.\n\nBeats: each has a short `say` + an action \u2014 `show` (reveal id[s]), `focus` (camera to id), `overview` (frame all), `orbit` (turntable the focused object), `showcase` (hero plinth reveal), `highlight`/`filter` (spotlight a subset), `callout:{target,text}`, `set:{target,values}` (animate a chart\'s data). 3\u20138 objects; omit `at` for auto layout on a clean grid-floor stage.\n\nTell it as a story: open with an overview, focus ONE object per beat while explaining, recap with another overview. Many short beats that read as one script. Set `voiceName`+`voiceTone`; intro/outro are auto-added.\n\nOutput: the primary result is a local URL (http://127.0.0.1:<port>/<id>.html) returned as a resource_link \u2014 give it to the user. Pass `outputPath` only to also write the file.';var Bz={id:"3d",tool:{name:"create_3d_walkthrough",title:"Create a narrated 3D tour",description:a3},promptLine:"\u2022 3D \u2014 a narrated tour through a 3D scene (spatial structure, a showcase of parts) \u2192 create_3d_walkthrough",schema:x1,mode:"3d",makeBeat:(t,e)=>({say:t,card:e}),forceOutro:!0,async prepare(t){let e=await s3(t.objects??[]),r={};return await Promise.all((t.objects??[]).map(async n=>{if(!n.image||!/^https?:\/\//i.test(n.image))return;let s=await b1(n.image);s&&(r[n.id]={href:s.href,w:s.w,h:s.h})})),{...Object.keys(e).length?{models:e}:{},...Object.keys(r).length?{images:r}:{}}},compile:(t,e)=>i3(t,e)},c3=Bz;var bu=[Xv,Ww,e3,c3];var Vz=t=>`Welcome! In this walkthrough, we'll look at ${t}. Let's dive in.`,l3=t=>`And that's ${t}. Thanks for watching \u2014 see you in the next one.`;function u3(t,e,r,n,s,o=!1){let i=r===void 0?Vz(e):r,a=n===void 0?l3(e):n;o&&!a.trim()&&(a=l3(e));let c=[...t];return a.trim()&&c.push(s(a,"outro")),i.trim()&&c.unshift(s(i,"intro")),c}import{gzipSync as qz}from"node:zlib";import{readFileSync as Fz,existsSync as Uz}from"node:fs";import{fileURLToPath as Hz}from"node:url";import*as xi from"node:path";function d3(t,e,r,n){return`<!doctype html>
79
79
  <html lang="en">
80
80
  <head>
81
81
  <meta charset="utf-8" />
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowcast/mcp",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "FlowCast — generate interactive code/whiteboard/map/3D walkthrough casts from an MCP client.",
5
5
  "type": "module",
6
6
  "bin": {