zion-mcp 2.8.0 → 2.8.1

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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __nodeCreateRequire } from 'node:module';
2
2
  const require = __nodeCreateRequire(import.meta.url);
3
- import{a as mp,b as Fi,c as go,d as yo,f as mb,g as gb}from"./chunk-UNPVTOSR.js";import{$ as Rb,B as Ob,C as Ib,W as Ab,X as Ep,Y as Nb,Z as Cb,_ as Pb,a as yb,b as gp,c as vb,d as yp,e as D,f as Ft,g as Eb,h as Ut,i as _b,j as Sb,k as vp,l as bb,m as Tb,t as wb}from"./chunk-CAF64CO7.js";import{a as tn,b as db,c as Hn,d as te,e as mo,f as pb,g as $c,h as qi,j as hb}from"./chunk-4RMPLI2R.js";import{a as k,c as v,e as He,g as f}from"./chunk-OHILD5KP.js";var vo=v(Sp=>{f();var Bc=class extends Error{constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},_p=class extends Bc{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Sp.CommanderError=Bc;Sp.InvalidArgumentError=_p});var Kc=v(Tp=>{f();var{InvalidArgumentError:i1}=vo(),bp=class{constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:(r.push(t),r)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new i1(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function s1(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Tp.Argument=bp;Tp.humanReadableArgName=s1});var Ip=v(Op=>{f();var{humanReadableArgName:o1}=Kc(),wp=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(i=>!i._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((i,s)=>i.name().localeCompare(s.name())),r}compareOptions(t,r){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(i=>!i.hidden),n=t._getHelpOption();if(n&&!n.hidden){let i=n.short&&t._findOption(n.short),s=n.long&&t._findOption(n.long);!i&&!s?r.push(n):n.long&&!s?r.push(t.createOption(n.long,n.description)):n.short&&!i&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);r.push(...i)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>o1(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(i)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(i)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let i=t.parent;i;i=i.parent)n=i.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatItemList(t,r,n){return r.length===0?[]:[n.styleTitle(t),...r,""]}groupItems(t,r,n){let i=new Map;return t.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[])}),r.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[]),i.get(o).push(s)}),i}formatHelp(t,r){let n=r.padWidth(t,r),i=r.helpWidth??80;function s(d,p){return r.formatItem(d,n,p,r)}let o=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],a=r.commandDescription(t);a.length>0&&(o=o.concat([r.boxWrap(r.styleCommandDescription(a),i),""]));let c=r.visibleArguments(t).map(d=>s(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(t.options,r.visibleOptions(t),d=>d.helpGroupHeading??"Options:").forEach((d,p)=>{let h=d.map(g=>s(r.styleOptionTerm(r.optionTerm(g)),r.styleOptionDescription(r.optionDescription(g))));o=o.concat(this.formatItemList(p,h,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(p=>s(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(t.commands,r.visibleCommands(t),d=>d.helpGroup()||"Commands:").forEach((d,p)=>{let h=d.map(g=>s(r.styleSubcommandTerm(r.subcommandTerm(g)),r.styleSubcommandDescription(r.subcommandDescription(g))));o=o.concat(this.formatItemList(p,h,r))}),o.join(`
3
+ import{a as mp,b as Fi,c as go,d as yo,f as mb,g as gb}from"./chunk-UM6ENMTM.js";import{$ as Rb,B as Ob,C as Ib,W as Ab,X as Ep,Y as Nb,Z as Cb,_ as Pb,a as yb,b as gp,c as vb,d as yp,e as D,f as Ft,g as Eb,h as Ut,i as _b,j as Sb,k as vp,l as bb,m as Tb,t as wb}from"./chunk-M5JIBLJM.js";import{a as tn,b as db,c as Hn,d as te,e as mo,f as pb,g as $c,h as qi,j as hb}from"./chunk-XHFWXEZR.js";import{a as k,c as v,e as He,g as f}from"./chunk-WXFOSPKR.js";var vo=v(Sp=>{f();var Bc=class extends Error{constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},_p=class extends Bc{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Sp.CommanderError=Bc;Sp.InvalidArgumentError=_p});var Kc=v(Tp=>{f();var{InvalidArgumentError:i1}=vo(),bp=class{constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:(r.push(t),r)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new i1(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function s1(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Tp.Argument=bp;Tp.humanReadableArgName=s1});var Ip=v(Op=>{f();var{humanReadableArgName:o1}=Kc(),wp=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(i=>!i._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((i,s)=>i.name().localeCompare(s.name())),r}compareOptions(t,r){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(i=>!i.hidden),n=t._getHelpOption();if(n&&!n.hidden){let i=n.short&&t._findOption(n.short),s=n.long&&t._findOption(n.long);!i&&!s?r.push(n):n.long&&!s?r.push(t.createOption(n.long,n.description)):n.short&&!i&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);r.push(...i)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>o1(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(i)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(i)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let i=t.parent;i;i=i.parent)n=i.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatItemList(t,r,n){return r.length===0?[]:[n.styleTitle(t),...r,""]}groupItems(t,r,n){let i=new Map;return t.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[])}),r.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[]),i.get(o).push(s)}),i}formatHelp(t,r){let n=r.padWidth(t,r),i=r.helpWidth??80;function s(d,p){return r.formatItem(d,n,p,r)}let o=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],a=r.commandDescription(t);a.length>0&&(o=o.concat([r.boxWrap(r.styleCommandDescription(a),i),""]));let c=r.visibleArguments(t).map(d=>s(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(t.options,r.visibleOptions(t),d=>d.helpGroupHeading??"Options:").forEach((d,p)=>{let h=d.map(g=>s(r.styleOptionTerm(r.optionTerm(g)),r.styleOptionDescription(r.optionDescription(g))));o=o.concat(this.formatItemList(p,h,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(p=>s(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(t.commands,r.visibleCommands(t),d=>d.helpGroup()||"Commands:").forEach((d,p)=>{let h=d.map(g=>s(r.styleSubcommandTerm(r.subcommandTerm(g)),r.styleSubcommandDescription(r.subcommandDescription(g))));o=o.concat(this.formatItemList(p,h,r))}),o.join(`
4
4
  `)}displayWidth(t){return xb(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,r){return Math.max(r.longestOptionTermLength(t,r),r.longestGlobalOptionTermLength(t,r),r.longestSubcommandTermLength(t,r),r.longestArgumentTermLength(t,r))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,r,n,i){let o=" ".repeat(2);if(!n)return o+t;let a=t.padEnd(r+t.length-i.displayWidth(t)),c=2,l=(this.helpWidth??80)-r-c-2,d;return l<this.minWidthToWrap||i.preformatted(n)?d=n:d=i.boxWrap(n,l).replace(/\n/g,`
5
5
  `+" ".repeat(r+c)),o+a+" ".repeat(c)+d.replace(/\n/g,`
6
6
  ${o}`)}boxWrap(t,r){if(r<this.minWidthToWrap)return t;let n=t.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.push("");return}let c=[a.shift()],u=this.displayWidth(c[0]);a.forEach(l=>{let d=this.displayWidth(l);if(u+d<=r){c.push(l),u+=d;return}s.push(c.join(""));let p=l.trimStart();c=[p],u=this.displayWidth(p)}),s.push(c.join(""))}),s.join(`
@@ -1442,7 +1442,7 @@ ${String(e)}`)}catch(t){return t}},TP=e=>{if(typeof e!="object"||e===null)throw
1442
1442
  }
1443
1443
  }
1444
1444
  }
1445
- `;f();import{randomUUID as U9}from"crypto";var cL=He(Gx(),1);f();var C9=He(MD(),1),P9=He(Nf(),1),R9=He(Fs(),1),x9=He(_E(),1),D9=He(TE(),1),L9=He(CE(),1),HD=He(xf(),1),k9=He(KD(),1);var QD=HD.default;f();var WD=100*1024*1024,Lf=class{current=Promise.resolve();async run(t){let r=this.current,n=()=>{};this.current=new Promise(i=>{n=i}),await r;try{return await t()}finally{n()}}},RE=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(`Failed to download CRDT model: ${t.status} ${t.statusText}`);let r=t.body?.getReader();if(!r)throw new Error("Failed to read CRDT model response body");let n=[],i=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(i+=c.length,i>WD)throw new Error(`CRDT model is larger than ${WD} bytes`);n.push(c)}let s=new Uint8Array(i),o=0;for(let a of n)s.set(a,o),o+=a.length;return s},Qa=async(e,t)=>{try{return await t()}catch(r){return D.warn(`Optional runtime package unavailable: ${e}`,r.message),null}},YD=null,Mt=async()=>(YD??=Qa("@functorz/ztype",()=>import("./ztype-BFQK2PDI.js")).then(e=>(e?.default??e)?.com?.functorz?.ztype??null),YD),JD=null,eL=async()=>(JD??=Qa("@functorz/ztype",()=>import("./ztype-BFQK2PDI.js")).then(e=>(e?.default??e)?.kotlin?.collections??null),JD),zD=null,tL=async()=>(zD??=Mt().then(e=>e?.typesystem?.schema?.SCHEMA_VERSION??null),zD),XD=null,Wa=async()=>(XD??=Qa("@functorz/crdt-helper",()=>import("./index.cjs-JL7FJKD6.js")).then(e=>e?.Crdt??e?.default?.Crdt??null),XD),ZD=null,xE=async()=>(ZD??=Qa("json-joy/lib/json-crdt-patch/index.js",()=>import("./json-crdt-patch-X2W6V7VS.js")).then(e=>e??Qa("json-joy/lib/json-crdt/index.js",()=>import("./json-crdt-322RBKNB.js"))).then(e=>e?.Patch??e?.default?.Patch??null),ZD),Ya=e=>e?.lastUploadedSchema??null,DE=e=>[e?.project?.lastDeployedServerSchemaExId,e?.lastDeployedServerSchemaExId,e?.project?.latestDeployedServerSchema?.exId,e?.latestDeployedServerSchema?.exId].find(r=>typeof r=="string"&&r.length>0)??null,rL=e=>e==null?e:structuredClone(e),LE=(e,t)=>e?.appExId?e.appExId:t?.name??"",kE=(e,t)=>{let r=e?.typesystem?.schema?.ClientType;if(r)return t==="WECHAT_MINI_PROGRAM"?r.WECHAT_MINI_PROGRAM??r.WECHAT??r.WEB:t==="MOBILE"?r.MOBILE??r.WEB:r.WEB},Ks=e=>{let t=e?.typesystem?.schema?.Product?.[mo];if(!t)throw new Error(`ztype runtime has no Product enum member for ${mo}`);return t},nL=e=>{let t=e?.typesystem?.schema?.Locale?.EN;if(!t)throw new Error("ztype runtime has no Locale enum member for EN");return t},j9=e=>{try{return JSON.parse(JSON.stringify(e))}catch{return String(e)}},kf=e=>({componentId:e?.componentId??null,message:typeof e?.getLocalizedErrorMessage=="function"?e.getLocalizedErrorMessage("EN"):e?.message??String(e),zhMessage:typeof e?.getLocalizedErrorMessage=="function"?e.getLocalizedErrorMessage("ZH"):void 0,platform:e?.platform??null,isBackendError:!!e?.isBackendError,fullPath:j9(e?.fullPath??[])}),jf=e=>e.stableErrors.concat(e.betaErrors).filter(t=>!!t.isBackendError),iL=e=>jf(e).length,sL=(e,t)=>{if(t.__typename==="DiffItem"){let r=t.pathComponents?.at(-1)?.key??"";if(t.operation==="delete"){delete e[r];return}e[r]=structuredClone(t.newValue);return}if(t.__typename==="ArrayDiffItem"){let r=t.pathComponents?.at(-1)?.index??-1;if(!Array.isArray(e)||r<0)throw new Error("Invalid array diff target");if(t.operation==="delete"){e.splice(r,1);return}if(t.operation==="insert"){e.splice(r,0,structuredClone(t.newValue));return}e[r]=structuredClone(t.newValue)}};f();var oL=He(No(),1);import{createRequire as M9}from"module";var q9=M9(import.meta.url);var Mf=e=>{if(tn){if(e==="@functorz/ztype")return tn.ztype;if(e==="@functorz/crdt-helper")return tn.crdtHelper;if(e==="json-joy")return tn.jsonJoy}try{let t=q9(`${e}/package.json`);return t.ztypeBuild??t.version??"unknown"}catch{return"unavailable"}},F9=async()=>{if(tn)return{ztypeVersion:tn.ztype,ztypeSchemaVersion:tn.ztypeSchemaVersion};try{let e=await Mt();return{ztypeVersion:Mf("@functorz/ztype"),ztypeSchemaVersion:e?.ZTypeSystem?.getSchemaVersion?.()??"unknown"}}catch{return{ztypeVersion:Mf("@functorz/ztype"),ztypeSchemaVersion:"unavailable"}}};async function jE(){let e=db(),t=await F9();return{agentVersion:e.version??"0.0.0",nodeMajor:process.versions.node.split(".")[0],platform:process.platform,arch:process.arch,ztypeVersion:t.ztypeVersion,ztypeSchemaVersion:t.ztypeSchemaVersion,crdtHelperVersion:Mf("@functorz/crdt-helper"),jsonJoyVersion:Mf("json-joy")}}async function Hs(e,t){let[r,n,i]=await Promise.all([jE(),Cr(e),e.loadCredentials()]),s=i?oL.default.decode(i.access_token):null,o=typeof s=="object"&&s!==null?String(s.sub??s.exId??s.id??"authenticated"):"anonymous";return{...r,product:te,apiBaseUrl:n.apiBaseUrl,authUserId:o,workspaceRoot:e.getWorkspaceRoot(),typeSystemMode:qi(),startupFlags:[...t].sort()}}function aL(e,t){return JSON.stringify(e)===JSON.stringify(t)}var qE=U9(),uL=`${te}/${Hn()}`,V9=e=>{if(!e)return e;if(Array.isArray(e))return e.map(([r,n])=>[r,String(r).toLowerCase()==="authorization"?"Bearer <redacted>":n]);if(typeof e=="object"&&"forEach"in e&&typeof e.forEach=="function"){let r={};return e.forEach((n,i)=>{r[i]=i.toLowerCase()==="authorization"?"Bearer <redacted>":String(n)}),r}let t={};for(let[r,n]of Object.entries(e))t[r]=r.toLowerCase()==="authorization"?"Bearer <redacted>":String(n);return t};function FE(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.map(r=>{let n=r,i=typeof n.operation=="string"?n.operation:null,s=typeof n.errorType=="string"?n.errorType:typeof n.extensions?.classification=="string"?n.extensions.classification:null,o=typeof n.message=="string"?n.message:null;return!o&&!i&&!s?null:`${i?`${i}: `:""}${o??"GraphQL error"}${s?` (${s})`:""}`}).filter(r=>!!r);return t.length>0?t.join("; "):null}var G9=e=>{if(typeof e=="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");try{return String(e)}catch{return"<unserializable body>"}},Qs=async(e,t)=>{let r=gp();D.debug(`[HTTP] Request URL: ${e.toString()}`),t?.headers&&D.debug(`[HTTP] Request Headers: ${JSON.stringify(V9(t.headers))}`),r&&t?.body!=null&&D.debug(`[GQL] Request Body: ${G9(t.body)}`);let n=await fetch(e,t),i=null;try{i=await n.clone().text()}catch(s){D.debug(`[GQL] Response read failed: ${String(s)}`)}if(r&&D.debug(`[GQL] Response ${n.status}: ${i??"<read failed>"}`),i&&i.includes('"errors"')){let s=null;try{s=JSON.parse(i).errors}catch{s=null}let o=FE(s);o&&D.warn(`[GQL] ${n.status} errors: ${o}`)}return n};async function UE(e,t){let r=await e.getValidToken(),n=await Cr(t),i={Authorization:`Bearer ${r}`,"User-Locale":"en_US","X-SESSION-ID":qE,"X-Client":uL},s=await tL();return s&&(i["X-ZED-VERSION"]=s),process.env.REACT_APP_VERSION&&(i["X-REACT-APP-VERSION"]=process.env.REACT_APP_VERSION),new it(`${n.apiBaseUrl}/api/graphql`,{headers:i,fetch:Qs})}var ME=class extends QD{constructor(...t){super(...t),this.on("error",r=>D.debug(`[SUB] socket error: ${r.message}`))}};async function lL(e,t){let r=await e.getValidToken(),i=`${(await Cr(t)).apiBaseUrl.replace(/^http:/,"ws:").replace(/^https:/,"wss:")}/api/graphql-subscription`;return async(s,o,a)=>{let c=gp(),u={authToken:r,"X-SESSION-ID":qE,"X-Client":uL};D.debug(`[SUB] connecting ${i} params=${JSON.stringify({...u,authToken:"Bearer <redacted>"})}`);let l=new cL.SubscriptionClient(i,{lazy:!0,reconnect:!0,minTimeout:3e3,connectionParams:u},ME);l.onConnected(()=>D.debug("[SUB] connected")),l.onReconnected(()=>D.debug("[SUB] reconnected")),l.onDisconnected(()=>D.debug("[SUB] disconnected")),l.onError(h=>D.debug(`[SUB] error ${h?.message??String(h)}`));let p=[{name:"onNewCrdtPatchV2",query:XP,variables:{projectExId:s.projectExId,appExId:s.appExId??null,versionExId:s.appVersionExId??null,latestPatchExIdInClient:o}},{name:"onSchemaUploadV3",query:ZP,variables:{projectExId:s.projectExId,appExId:s.appExId??null,appVersionExId:s.appVersionExId??null}}].map(h=>(D.debug(`[SUB] subscribe ${h.name} vars=${JSON.stringify(h.variables)}`),l.request({query:h.query,variables:h.variables}).subscribe({next:g=>{c&&D.debug(`[SUB] ${h.name} event: ${JSON.stringify(g)}`),a()},error:g=>{D.warn("Schema subscription event failed",String(g)),a()}})));return{unsubscribe(){for(let h of p)h.unsubscribe();l.close(!1,!1)}}}}async function fL(e,t){if(t.projectExId)return await e.saveProjectContext(t.projectExId),t.projectExId;let r=await e.loadProjectContext();if(!r?.projectExId)throw new Error("No projectExId provided and no current project is set");return r.projectExId}async function VE(e,t,r,n){try{await e.request(pR,{projectExId:t,client:te,clientVersion:Hn(),sessionId:n??qE,agent:r??null}),D.debug(`[agent-session] started for project ${t}`)}catch(i){D.debug(`[agent-session] skipped: ${String(i)}`)}}f();f();f();import{createHash as $9}from"crypto";var B9=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),GE=e=>{if(Array.isArray(e))return e.map(r=>r===void 0?null:GE(r));if(!B9(e))return e;let t={};for(let r of Object.keys(e).sort()){let n=e[r];n!==void 0&&(t[r]=GE(n))}return t},K9=e=>JSON.stringify(GE(e)),H9=e=>$9("sha256").update(K9(e)).digest("hex"),dL=e=>({projectExId:e.projectExId,appExId:e.appExId??null,appVersionExId:e.appVersionExId??null,schemaExId:e.schemaExId??null,lastPatchExId:e.lastPatchExId??null,snapshotHash:H9(e.snapshot),deployedSchemaExId:e.deployedSchemaExId??null,checkedAt:e.checkedAt??new Date().toISOString()}),pL=(e,t)=>!e||!t?e!==t:e.schemaExId!==t.schemaExId||e.lastPatchExId!==t.lastPatchExId||e.snapshotHash!==t.snapshotHash||e.deployedSchemaExId!==t.deployedSchemaExId,qf=e=>e.changes.length>0;var hL=null,Q9=()=>(hL??=Mt().then(e=>{let t=e?.typesystem?.schema?.diff?.computeSemanticSchemaChanges;return typeof t=="function"?t:null}),hL),W9=async(e,t)=>{let r=await Q9();return r?r(e,t):{changes:[]}},$E=(e,t)=>W9(JSON.stringify(e),JSON.stringify(t));f();var Y9="Functorz";function mL(e,t,r,n){let i=e?.typesystem?.settings,s=e?.typesystem?.schema,o=t?.KtList,a=t?.KtMap;if(!i?.ExtraContext||!s?.CustomChatModelDescriptor||!s?.AIModelDescriptors||!o||!a)return D.warn("ztype ExtraContext symbols missing; schema graph will be built without custom models"),null;try{let{ExtraContext:c}=i,{AIModelDescriptors:u,CustomChatModelDescriptor:l,CustomEmbeddingModelDescriptor:d,ModelCustomParamDescriptor:p,CustomModelParam:h,CustomChatCompletionFeatures:g,Identifier:y,MediaOutputCardinality:E}=s,S=O=>a.fromJsMap(new Map(Object.entries(O??{}))),_=O=>typeof O=="string"?O==="single"?E.SINGLE:O==="multiple"?E.MULTIPLE:E.NONE:typeof O=="boolean"&&O?E.MULTIPLE:E.NONE,w=O=>new p(O.name,S(O.displayName),O.type,S(O.description)),I=O=>new h(w(O.serverUrl),w(O.apiToken),o.fromJsArray((O.extensionParams??[]).map($=>new p($.name,S($.displayName),$.type,S($.displayName))))),T=O=>O.provider===Y9&&O.customModelIdentifier?new y(O.customModelIdentifier.id,O.customModelIdentifier.namespace):null,N=(r?.chatModelDescriptors??[]).map(O=>new l(O.provider,O.name,I(O.paramToConfigure),O.delisted,new g(O.features.streamResponse,O.features.multiModal,O.features.imageInput??!1,!1,O.features.videoInput??!1,O.features.imageMessageInput??!1,!1,O.features.videoMessageInput??!1,O.features.tools,O.features.reasoningContent,O.features.imageOutput,O.features.videoOutput,_(O.features.imageOutput),_(O.features.videoOutput),null,O.features.structuredOutput),T(O))),P=(r?.embeddingModelDescriptors??[]).map(O=>new d(O.provider,O.name,I(O.paramToConfigure),T(O),O.delisted));return new c(new u(o.fromJsArray(N),o.fromJsArray(P)),a.fromJsMap(new Map),n)}catch(c){return D.warn("ztype ExtraContext construction failed; schema graph will be built without custom models",c.message),null}}f();var Cn=class extends Error{constructor(r,n){super(r);this.diagnostics=n;this.name="ZtypeValidationError"}};f();function Ff(e,t,r,n=null){let i=kE(e,r?.appType);return e.api.ZTypeCoreApi.genZTypeApiContext(t,Ks(e),i,LE(r,i),nL(e),n)}function gL(e,t){return LE(t,kE(e,t?.appType))}f();var yL={QUERY:"query",MUTATION:"mutation"},vL={SUCCESS:"2xx",PERMANENT_FAIL:"4xx",TEMPORARY_FAIL:"5xx"};function EL(e){let t=r=>{if(Array.isArray(r))return r.map(t);if(r&&typeof r=="object"){let n={};for(let[i,s]of Object.entries(r))i==="operation"&&typeof s=="string"&&yL[s]!==void 0?n[i]=yL[s]:i==="responseBranch"&&typeof s=="string"&&vL[s]!==void 0?n[i]=vL[s]:n[i]=t(s);return n}return r};return e.map(t)}function _L(e){let t=r=>typeof r=="string"&&!r.startsWith("http://")&&!r.startsWith("https://");for(let r of e){let n=r;if(!n?.args||typeof n.args!="object")continue;let i=n.args,s=[];if(n.name==="UPDATE_TPA_CONFIG")s.push(i.url);else if(n.name==="ADD_TPA_CONFIGS"&&Array.isArray(i.items))for(let o of i.items)o&&typeof o=="object"&&s.push(o.url);for(let o of s)if(t(o))return`url "${o}" is not an absolute URL. A TPA config url must include the scheme and host (e.g. https://api.example.com/v1/resource) \u2014 find the API's base URL in its documentation.`}return null}f();var Pn=e=>e==null,BE=(e,t)=>{if(Pn(e)&&Pn(t)||e===t)return!0;if(Pn(e)||Pn(t)||typeof e!="object"||typeof t!="object")return!1;let r=e,n=t,i=new Set([...Object.keys(r),...Object.keys(n)]);for(let s of i)if(!BE(r[s],n[s]))return!1;return!0};var KE=e=>{let t=new Set;for(let r of e)if(t.add(r.pathComponents.map(n=>n.index!==void 0?`[${n.index}]`:`.${n.key}`).join("").replace(/^\./,"")),t.size>=20)break;return[...t]},SL=e=>{if(e.__typename==="DiffItem")switch(e.operation){case"add":return{__typename:"DiffItem",oldValue:e.newValue,newValue:null,operation:"delete",pathComponents:e.pathComponents};case"delete":return{__typename:"DiffItem",oldValue:null,newValue:e.oldValue,operation:"add",pathComponents:e.pathComponents};case"update":return{__typename:"DiffItem",oldValue:e.newValue,newValue:e.oldValue,operation:"update",pathComponents:e.pathComponents}}else switch(e.operation){case"insert":return{__typename:"ArrayDiffItem",oldValue:e.newValue,newValue:null,previousValue:e.previousValue,nextValue:e.nextValue,operation:"delete",pathComponents:e.pathComponents};case"delete":return{__typename:"ArrayDiffItem",oldValue:null,newValue:e.oldValue,previousValue:e.previousValue,nextValue:e.nextValue,operation:"insert",pathComponents:e.pathComponents};case"update":return{__typename:"ArrayDiffItem",oldValue:e.newValue,newValue:e.oldValue,operation:"update",pathComponents:e.pathComponents}}throw new Error(`Cannot reverse diff item: ${JSON.stringify(e)}`)},J9=e=>e.key??e.index??"",z9=(e,t)=>{let r=e;for(let n of t){if(r===null||typeof r!="object")return;r=r[n]}return r},X9=(e,t)=>{if(t.__typename!=="DiffItem")return null;let r=t.pathComponents.at(-1)?.key;if(r===void 0)return null;let n=BE(e[r],t.oldValue);switch(t.operation){case"add":e[r]=t.newValue;break;case"update":if(!n)return null;e[r]=t.newValue;break;case"delete":if(!Object.prototype.hasOwnProperty.call(e,r)||!n)return null;delete e[r];break;default:return null}return t},Z9=(e,t)=>{if(t.__typename!=="ArrayDiffItem")return null;let r=t.pathComponents.at(-1)?.index;if(r===void 0||r>e.length)return null;let n=()=>BE(e[r],t.oldValue);switch(t.operation){case"insert":e.splice(r,0,t.newValue);break;case"delete":if(!n())return null;e.splice(r,1);break;case"update":if(!n())return null;e.splice(r,1,t.newValue);break;default:return null}return t},bL=(e,t)=>{let r=e,n=new WeakSet,i=o=>{if(r===null||typeof r!="object")return r;n.has(r)||(r=Array.isArray(r)?[...r]:{...r},n.add(r));let a=r;for(let c of o){let u=a[c];if(u!==null&&typeof u=="object"){if(!n.has(u)){let l=Array.isArray(u)?[...u]:{...u};n.add(l),a[c]=l}a=a[c]}else a=u}return a},s=[];for(let o of t)try{let c=o.pathComponents.map(J9).slice(0,-1);if(Pn(z9(r,c)))continue;let u=i(c);if(Array.isArray(u)){let l=Z9(u,o);l&&s.push(l)}else if(u!==null&&typeof u=="object"){let l=X9(u,o);l&&s.push(l)}}catch{continue}return s};f();var e7=3e4,Uf=class{constructor(t){this.options=t}timer=null;subscriptionHandle=null;running=!1;isActive(){return this.timer!==null||this.subscriptionHandle!==null}start(){this.timer||this.subscriptionHandle||!this.options.subscriptionFactory||this.options.subscriptionFactory(this.options.sessionKey,this.options.getLastPatchExId(),()=>{this.run()}).then(t=>{this.subscriptionHandle=t}).catch(t=>{D.warn("Schema subscription failed; falling back to polling",t.message)}).finally(()=>{this.schedulePoll()})}dispose(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.subscriptionHandle?.unsubscribe(),this.subscriptionHandle=null}schedulePoll(){!this.options.subscriptionFactory||this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.run().finally(()=>this.schedulePoll())},e7),this.timer.unref())}async run(){if(!this.running){this.running=!0;try{await this.options.refresh()}finally{this.running=!1}}}};f();var TL=(e,t)=>{let r=new WeakMap,n=o=>{let a=r.get(o);return a||(a=Array.isArray(o)?[...o]:{...o},r.set(o,a)),a},i=new WeakMap,s=n(e);for(let o of t){let a=(o?.pathComponents??[]).slice(0,-1),c=e,u=s;for(let l of a){let d=l.key??l.index??"",p=c[d];if(p===null||typeof p!="object")break;if(Array.isArray(p)){let h=i.get(p);h||(h=structuredClone(p),i.set(p,h)),u[d]=h;break}u[d]=n(p),c=p,u=u[d]}}return s};f();f();var t7=new Set(["BACKEND_ONLY","COMBINED"]),Ja=e=>!e?.appType||t7.has(e.appType)?!1:(e.project?.appList??[]).some(t=>t.appType==="BACKEND_ONLY"),OL=(e,t)=>{if(!t)return e;let r=t.model.view();return{...e,server:r?.server??null}},Vf=e=>e?.pathComponents?.[0]?.key==="server",wL=e=>typeof e=="string"&&e.length>0?e:null,HE=(e,t)=>{let r=e.serverDoc;if(r){let i=wL(r.schemaExId);return i?{ok:!0,appExId:null,schemaExId:i}:{ok:!1,error:"the backend app document has no schemaExId"}}if(e.serverDocRequired===!0)return{ok:!1,error:"this client app's server lives in the backend app's document, which did not load, so there is nothing to sync; retry, or run project sync-backend without appExId"};let n=wL(e.schemaExId);return n?{ok:!0,appExId:t,schemaExId:n}:{ok:!1,error:"the session has no schemaExId"}};f();var QE=null,IL=async e=>(QE??=e.request(JP).then(t=>(t.__type?.inputFields??[]).some(r=>r.name==="origin")).catch(()=>(QE=null,!1)),await QE?{origin:"MCP"}:{});var WE=300*1e3,r7=100,n7=50,i7=["dataModel","types"];function s7(e){let t=e.server;if(!t||typeof t!="object"||Array.isArray(t))return e;let r={};for(let i of i7){let s=t[i];s!==void 0&&(r[i]=s)}let n={};return e.version!==void 0&&(n.version=e.version),n.server=r,n}var o7={ADD_ACTION_FLOW_OUTPUT_FIELDS:"SET_ACTION_FLOW_OUTPUT",DELETE_ACTION_FLOW_OUTPUT_FIELDS:"CLEAR_ACTION_FLOW_OUTPUT",SET_ACTION_FLOW_OUTPUT:"ADD_ACTION_FLOW_OUTPUT_FIELDS",CLEAR_ACTION_FLOW_OUTPUT:"DELETE_ACTION_FLOW_OUTPUT_FIELDS"};function AL(e){return e==="post_type_system_refactor"?"post-type-system-refactor (refactored)":"pre-type-system-refactor (legacy)"}function a7(e,t,r){let n=`${e} requires a ${AL(t)} schema, but this project is ${AL(r)}.`,i=o7[e];if(i)return`${n} Use ${i} instead.`;if(t!=="post_type_system_refactor")return`${n} Use the corresponding post-type-system-refactor op instead.`;let s="The daemon auto-detects migrated projects from the loaded schema \u2014 do not force MCP_TYPE_SYSTEM=post to bypass this gate; it cannot migrate the project, and post-only config written into a pre-refactor schema is invisible to the editor.";return/^(GET_ALL_API|GET_API|ADD_API|UPDATE_API|DELETE_API)/.test(e)?`${n} API-integration workspaces only exist after the type-system refactor. ${s} To integrate an external HTTP endpoint on this project, use the TPA ops instead (third-party-api.md, e.g. ADD_TPA_CONFIGS).`:`${n} Enums and object/custom types only exist after the type-system refactor \u2014 migrate the project in the editor first. ${s}`}function c7(e){if(typeof e!="string")return e;let t=e.trim();if(!/^[[{]|^(true|false|null|-?\d)/.test(t))return e;try{return JSON.parse(t)}catch{return e}}function u7(e){if(typeof e!="string")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let r={};for(let[n,i]of Object.entries(t))r[n]=c7(i);return r}function l7(e){let t=new Set;return e.map(r=>{if(!r||typeof r!="object")return r;let n=r,i=typeof n.toolCallId=="string"&&n.toolCallId?n.toolCallId:null;if(i!==null&&t.has(i))throw new Error(`Duplicate toolCallId: ${i}`);let s=i??za();return t.add(s),i===s?n:{...n,toolCallId:s}})}function f7(e,t){if(!e)return;let r=new Map(Object.entries(e)),n=t.map((i,s)=>{if(!r.has(i))throw new Error(`Missing ztype response for tool call ${s}`);let o=r.get(i);return r.delete(i),o});if(r.size>0)throw new Error(`Unexpected ztype responses: ${[...r.keys()].join(", ")}`);return n}function d7(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?Object.values(t).find(n=>typeof n=="string")??t:t):[]}function p7(e){let t=e??{},r=t.data??{},n={},i=u7(r.responseByToolCallId??t.responseByToolCallId);i&&Object.keys(i).length>0&&(n.responses=i);let s=r.schemaDiff??t.schemaDiff;s&&(n.schemaDiff=s);let o=d7(t.errors??r.errors);return o.length>0&&(n.errors=o),n}function h7(e){let t=e??{},r=t.data?.updatedReadState;if(r!=null)return r;if(typeof t.updatedReadStateJson=="string")try{return JSON.parse(t.updatedReadStateJson)}catch{return}}function m7(e){return(e??{}).data?.touchesComponents===!0}function g7(e,t){let r=e??{};if(r.isSuccess!==!1)return{};let n={},i=typeof r.failedToolCallId=="string"?t.indexOf(r.failedToolCallId):-1;i>=0&&(n.failedIndex=i),typeof r.errorCode=="string"&&(n.errorCode=r.errorCode),r.failedBeforeExecution===!0&&(n.failedBeforeExecution=!0);let s=Array.isArray(r.detailKeys)?r.detailKeys:[],o=Array.isArray(r.detailValues)?r.detailValues:[];if(s.length>0&&s.length===o.length){let a={};s.forEach((c,u)=>{typeof c=="string"&&typeof o[u]=="string"&&(a[c]=o[u])}),Object.keys(a).length>0&&(n.errorDetails=a)}return n}async function y7(e){let r=(await Mt())?.application?.schemaops?.SchemaOpsErrorCode?.DEPENDENCY_CONFLICT?.name,i=(e.diagnostics?.stableErrors??[]).map(s=>{let o=s??{};return[o.componentId,o.message].filter(a=>typeof a=="string"&&a!=="").join(": ")}).filter(s=>s!=="");return{applied:{applied:!1,reason:"ztype validation interrupted the batch"},errors:i.length>0?i:[e.message],...typeof r=="string"?{errorCode:r}:{},errorDetails:{dependents:i.join("; ")},ztypeDiagnostics:e.diagnostics}}function v7(e){return e?e.available===!1||(e.stableErrors?.length??0)>0||(e.betaErrors?.length??0)>0:!1}var Xa=class e{constructor(t,r,n,i){this.client=t;this.sessionKey=r;this.onSchemaEvent=i;this.key=e.stringifyKey(r),this.watcher=new Uf({sessionKey:r,subscriptionFactory:n,getLastPatchExId:()=>this.lastPatchExId,refresh:()=>this.runWatchRefresh()})}crdtBinary=null;model=null;serverDoc=null;schemaGraph=null;extraContext=null;extraContextLoaded=!1;enabledProjectFeatureNames=[];appDetail=null;snapshot=null;schemaExId=null;lastPatchExId=null;appliedPatchExIds=new Set;staleReason="not loaded";lastError=null;lastZtypeDiagnostics=null;diagnosedFor=null;lastRevision=null;events=[];undoStack=[];redoStack=[];watcher;loadedAt=0;lastUsedAt=Date.now();mutex=new Lf;key;static stringifyKey(t){return[t.projectExId,t.appExId??"",t.appVersionExId??""].join(":")}isExpired(t=Date.now()){return t-this.lastUsedAt>WE}currentView(){if(!this.model)throw new Error("CRDT model not loaded");return OL(this.model.view(),this.serverDoc)}lastPatchExIds(){return[this.lastPatchExId,this.serverDoc?.lastPatchExId??null].filter(t=>typeof t=="string")}refactorState(){return this.snapshot?Sb(this.snapshot.server):null}assertToolCallsMatchTypeSystem(t){let r=this.refactorState();if(!r)throw new Error("Schema is not loaded; run schema load before calling schema tools.");for(let n of t){let i=n?.name;if(typeof i!="string")continue;let s=_b[i];if(s&&s!==r)throw new Error(a7(i,s,r))}}normalizeExternalColumnTypes(t){let r=new Set(["typeIdentifier","basicTypeNameOrTypeId"]),n={TEXT:"STRING",INTEGER:"BIGINT",FLOAT8:"DECIMAL"},i=s=>{if(Array.isArray(s))return s.map(i);if(s&&typeof s=="object"){let o={};for(let[a,c]of Object.entries(s))o[a]=r.has(a)&&typeof c=="string"&&n[c.toUpperCase()]?n[c.toUpperCase()]:i(c);return o}return s};return t.map(i)}status(){return{key:this.key,projectExId:this.sessionKey.projectExId,appExId:this.sessionKey.appExId??null,appVersionExId:this.sessionKey.appVersionExId??null,schemaExId:this.schemaExId,lastPatchExId:this.lastPatchExId,serverDocRequired:Ja(this.appDetail),serverDoc:this.serverDoc?{schemaExId:this.serverDoc.schemaExId,lastPatchExId:this.serverDoc.lastPatchExId}:null,loadedAt:this.loadedAt?new Date(this.loadedAt).toISOString():null,lastUsedAt:new Date(this.lastUsedAt).toISOString(),staleReason:this.staleReason,lastError:this.lastError,typeSystem:this.refactorState(),typeSystemMode:this.refactorState()??qi(),schemaRevision:this.lastRevision,ztypeDiagnostics:this.lastZtypeDiagnostics,crdtBinaryBytes:this.crdtBinary?.byteLength??null,hasCrdtModel:this.model!==null,hasZtypeGraph:this.schemaGraph!==null,schemaEventCount:this.events.length,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,watcherActive:this.watcher.isActive()}}state(){return{...this.status(),latestEvent:this.events.at(-1)??null}}listEvents(t,r=100){if(!t)return this.events.slice(-r);let n=this.events.findIndex(i=>i.id===t);return(n>=0?this.events.slice(n+1):this.events).slice(-r)}async checkRemoteAndSync(){return this.mutex.run(async()=>this.withErrorState(async()=>this.checkRemoteAndSyncLocked("remote")))}async load(t=!1){return this.mutex.run(async()=>this.withErrorState(()=>this.loadLocked(t)))}async sync(){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),!this.schemaExId)return this.loadLocked();let t=await this.client.request(YP,{schemaExId:this.schemaExId}),r=t.crdtSchemaBySchemaExId?.crdtPatches?.patches??[];return await this.applyNetworkPatches(r),await this.syncServerDocLocked(),this.model&&(this.snapshot=this.currentView(),await this.resolveZtypeGraph(),await this.refreshZtypeDiagnostics()),this.lastPatchExId=t.crdtSchemaBySchemaExId?.crdtPatches?.lastPatchExId??this.lastPatchExId,this.updateRevision(),this.status()}))}getSnapshot(t=!1){if(this.touch(),this.model?.view&&(this.snapshot=this.currentView()),!this.snapshot)throw new Error("Project schema is not loaded");return t?this.snapshot:s7(this.snapshot)}dataModel(){let t=this.getSnapshot().server;return!t||typeof t!="object"?null:t.dataModel??null}async save(){return this.mutex.run(async()=>this.withErrorState(async()=>{this.touch();let t=await this.currentZtypeDiagnostics(),r=await this.client.request(yv,{projectExId:this.sessionKey.projectExId,appExId:this.sessionKey.appExId??null,versionExId:this.sessionKey.appVersionExId??null});if(this.schemaExId=r.saveSchema,this.serverDoc){let n=await this.client.request(yv,{projectExId:this.sessionKey.projectExId,appExId:null,versionExId:null});this.serverDoc.schemaExId=n.saveSchema}return this.updateRevision(),{...this.status(),ztypeDiagnostics:t}}))}async validate(){return this.mutex.run(async()=>this.withErrorState(async()=>(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),this.currentZtypeDiagnostics())))}async ztypeToolCalls(t,r=!1,n=null,i=!1){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),!this.schemaGraph)throw new Error("ztype runtime is unavailable; install @functorz/ztype in this package");this.assertToolCallsMatchTypeSystem(t);let s=await Mt(),o=s?.api;if(!o?.ZTypeCoreApi||!o?.ZTypeSchemaOpsApi)throw new Error("ztype SchemaOps API is unavailable");let a=Ff(s,this.schemaGraph,this.appDetail,await this.getExtraContext(s)),c=l7(t),u=_L(c);if(u)throw new Error(u);let l=c.map(S=>S&&typeof S=="object"?S.toolCallId:void 0).filter(S=>typeof S=="string"),d=this.withProjectFeatures(o.ZTypeCoreApi,()=>o.ZTypeSchemaOpsApi.toolCalls(a,this.normalizeExternalColumnTypes(EL(c)),n??null)),p=p7(d),h=p.schemaDiff,g=f7(p.responses,l),y={},E=h7(d);if(E!=null&&(y.updatedReadState=E),g&&(y.responses=g),p.errors&&(y.errors=p.errors,Object.assign(y,g7(d,l)),y.applied={applied:!1,reason:"batch rejected by ztype"}),h&&r&&(y.schemaDiff=h),h)try{y.applied=await this.applySchemaDiffLocked(h,{skipValidation:i}),m7(d)&&(y.touchesComponents=!0)}catch(S){if(!(S instanceof Cn))throw S;let _=await y7(S);return Object.assign(y,_,{errors:[...Array.isArray(y.errors)?y.errors:[],..._.errors]}),y}return await this.attachValidationErrorIfAny(y),y}))}async attachValidationErrorIfAny(t){let r=await this.currentZtypeDiagnostics();v7(r)&&(t.ztypeDiagnostics=r)}async undo(){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),this.undoStack.length===0)return{...this.status(),undone:!1,reason:"nothing to undo"};let t=this.undoStack[this.undoStack.length-1],r=t.dataSource.map(SL).reverse(),n=await this.applyReversibleLocked(r);return n?(this.undoStack.pop(),this.redoStack.push(t),{...n,undone:!0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,reverted:t.semanticChanges??void 0,revertedPaths:KE(t.dataSource)}):{...this.status(),undone:!1,reason:"schema diverged since this change; undo no longer applies cleanly"}}))}async redo(){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),this.redoStack.length===0)return{...this.status(),redone:!1,reason:"nothing to redo"};let t=this.redoStack[this.redoStack.length-1],r=await this.applyReversibleLocked(t.dataSource);return r?(this.redoStack.pop(),this.undoStack.push(t),{...r,redone:!0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,reapplied:t.semanticChanges??void 0,reappliedPaths:KE(t.dataSource)}):{...this.status(),redone:!1,reason:"schema diverged since this change; redo no longer applies cleanly"}}))}async applyReversibleLocked(t){if(!this.model)throw new Error("CRDT model not loaded");let r=this.currentView(),n=bL(r,t);if(n.length!==t.length)return null;let i=n.filter(s=>!(s.__typename==="DiffItem"&&Pn(s.oldValue)&&Pn(s.newValue)));return i.length===0?null:this.applySchemaDiffLocked({id:za(),dataSource:i},{recordUndo:!1})}async recordUndoEntry(t,r,n){let i=await Wa();if(!i?.generateDiff)return;let s=[];i.generateDiff({before:t,after:r,prefix:[],result:s}),s.length!==0&&(this.undoStack.push({id:za(),dataSource:s,semanticChanges:n}),this.undoStack.length>n7&&this.undoStack.shift(),this.redoStack=[])}async loadLocked(t=!1){if(this.touch(),this.model&&!t&&!this.staleReason)return this.status();let n=(await this.client.request(Ei,this.sessionKey)).fetchAppDetailByExId;if(!n)throw new Error(`Project not found: ${this.sessionKey.projectExId}`);let i=Ya(n);if(!i?.crdtModelUrl||!i.exId)throw new Error("Project has no uploaded CRDT schema");let s=await RE(i.crdtModelUrl);return this.crdtBinary=s,this.appliedPatchExIds.clear(),this.lastPatchExId=null,this.serverDoc=null,this.undoStack=[],this.redoStack=[],this.appDetail=n,await this.initializeRuntime(s,i.crdtPatches?.patches??[],n),this.schemaExId=i.exId,this.lastPatchExId=i.crdtPatches?.lastPatchExId??null,this.loadedAt=Date.now(),this.model&&this.schemaGraph?this.staleReason=!this.serverDoc&&Ja(n)?"backend app document unavailable":null:this.model&&!this.schemaGraph&&(this.staleReason="ztype runtime unavailable"),this.updateRevision(),this.watcher.start(),this.status()}async applySchemaDiffLocked(t,r={}){if(Array.isArray(t.dataSource)&&t.dataSource.length===0)return{...this.status(),applied:!1,reason:"empty schema diff"};if(!this.serverDoc&&Ja(this.appDetail)&&(t.dataSource??[]).some(Vf))throw new Error("This client app's server lives in the backend app's document, which is not loaded; refusing to write server changes into the client document. Run schema load again.");let i=(r.recordUndo??process.env.MOMEN_MCP_UNDO!=="0")&&this.snapshot?TL(this.snapshot,t.dataSource??[]):null,s=this.currentRevision(),o=await Mt(),a=o?.api?.ZTypeCoreApi,c=await Wa();if(!a||!c?.executeCrdtNodeUpdateAndTransformDiff||!c.generateDiff)throw new Error("CRDT/ztype write runtime is unavailable");let u=Ff(o,this.schemaGraph,this.appDetail,await this.getExtraContext(o)),l=this.withProjectFeatures(a,()=>a.batchUpdateSchemaGraph(u,[t]));if(l?.interruptErrors?.length>0){let g={available:!0,stableErrors:[...l.interruptErrors].map(kf),betaErrors:[]};if(r.skipValidation!==!0)throw new Cn("ztype validation interrupted schema update",g)}if(!this.model)throw new Error("CRDT model not loaded");D.debug(`[Session] applying schemaDiff dataSource: ${JSON.stringify(t.dataSource).slice(0,4e3)}`);try{await this.uploadByDoc(c,t.dataSource??[],this.model)}catch(g){D.error(`[Session] CRDT apply/upload failed; reloading session to discard the diverged graph: ${g.message}`);let{undoStack:y,redoStack:E}=this;try{await this.loadLocked(!0),this.undoStack=y,this.redoStack=E}catch(S){D.error(`[Session] reload after the failed write failed too; unloading the session so the next command loads it again: ${S.message}`),this.model=null,this.snapshot=null,this.schemaGraph=null,this.schemaExId=null,this.diagnosedFor=null,this.staleReason="a write failed and the reload after it failed too"}throw g}this.schemaGraph=l.updatedGraph,this.snapshot=this.currentView();let d=await this.refreshZtypeDiagnostics(),p=this.updateRevision(),h=i&&s&&i.server!==this.snapshot.server?await $E({version:i.version,server:i.server},{version:this.snapshot.version,server:this.snapshot.server}):null;return h&&qf(h)&&s&&p&&this.appendSchemaEvent("local",s,p,h),i&&await this.recordUndoEntry(i,this.snapshot,h&&qf(h)?h:null).catch(g=>D.warn(`[Session] the write landed but its undo entry could not be recorded: ${g.message}`)),{...this.status(),ztypeDiagnostics:d,backendErrorCount:iL(d),_schema:h&&qf(h)?{change:h}:void 0}}async uploadByDoc(t,r,n){let i=this.serverDoc,s=i?r.filter(Vf):[],o=i?r.filter(c=>!Vf(c)):r,a=i&&s.length>0&&o.length>0?rL(i.model.view()):null;if(i&&s.length>0)for(let c of await this.uploadDocPatch(t,s,i.model,null,i.schemaExId))i.appliedPatchExIds.add(c.exId),i.lastPatchExId=c.exId;if(o.length!==0)try{for(let c of await this.uploadDocPatch(t,o,n,this.sessionKey.appExId??null,this.schemaExId))this.appliedPatchExIds.add(c.exId),this.lastPatchExId=c.exId}catch(c){if(i&&a){let u=[];t.generateDiff({before:i.model.view(),after:a,prefix:[],result:u}),u.length>0&&await this.uploadDocPatch(t,u,i.model,null,i.schemaExId).catch(l=>{throw new Error(`The server half of this change was saved to the backend app's document, but the client half failed (${c.message}) and reverting the server half failed too (${l.message}). Those server changes are live without their client counterparts: read the schema again before retrying, or the retry applies them a second time.`)})}throw c}}async uploadDocPatch(t,r,n,i,s){let o=t.executeCrdtNodeUpdateAndTransformDiff(r,n,this.snapshot,sL),a=za(),c=await IL(this.client);return(await this.client.request(zP,{projectExId:this.sessionKey.projectExId,appExId:i,schemaExId:s,patches:[{content:{id:a,dataSource:o.diffsFromCrdt},patchBase64:o.patchBase64,uuid:a,...c}]})).batchCreateSchemaCrdtPatch??[]}async checkRemoteAndSyncLocked(t){if(!this.model||!this.schemaExId||!this.snapshot)return await this.loadLocked(),null;let r=this.currentRevision();if(!r)return null;let n={version:this.snapshot.version,server:this.snapshot.server},s=(await this.client.request(Ei,this.sessionKey)).fetchAppDetailByExId,o=Ya(s);if(!o?.exId)return null;let a=o.crdtPatches?.lastPatchExId??null,c=o.exId,u=DE(s);if(!await this.syncServerDocLocked()&&c===this.schemaExId&&a===this.lastPatchExId&&u===this.lastRevision?.deployedSchemaExId)return this.appDetail=s??this.appDetail,this.updateRevision(),null;c!==this.schemaExId||!o.crdtModelUrl?await this.loadLocked(!0):(this.appDetail=s??this.appDetail,await this.applyNetworkPatches(o.crdtPatches?.patches??[]),this.model&&(this.snapshot=this.currentView(),await this.resolveZtypeGraph(),await this.refreshZtypeDiagnostics()),this.lastPatchExId=a,this.updateRevision());let d=this.currentRevision();if(!d||!pL(r,d))return null;let p=await $E(n,{version:this.snapshot?.version,server:this.snapshot?.server});return this.appendSchemaEvent(t==="watch"?"remote":t,r,d,p),{type:"SCHEMA_STALE",message:"Project schema changed since this session last used it; session was refreshed before executing the command.",projectExId:this.sessionKey.projectExId,fromRevision:r,toRevision:d,semanticChanges:p,detectedAt:new Date().toISOString()}}currentRevision(){return this.lastRevision??this.updateRevision()}updateRevision(){return!this.snapshot&&!this.crdtBinary?(this.lastRevision=null,null):(this.lastRevision=dL({projectExId:this.sessionKey.projectExId,appExId:this.sessionKey.appExId??this.appDetail?.appExId??null,appVersionExId:this.sessionKey.appVersionExId??null,schemaExId:this.schemaExId,lastPatchExId:this.lastPatchExId,snapshot:this.snapshot??{binaryBytes:this.crdtBinary?.byteLength??null},deployedSchemaExId:DE(this.appDetail)}),this.lastRevision)}appendSchemaEvent(t,r,n,i){let s={id:za(),type:"SCHEMA_CHANGED",source:t,projectExId:this.sessionKey.projectExId,fromRevision:r,toRevision:n,semanticChanges:i,detectedAt:new Date().toISOString()};this.events.push(s),this.events=this.events.slice(-r7),this.onSchemaEvent?.(s)}async runWatchRefresh(){let t=this.lastUsedAt;try{await this.mutex.run(async()=>{await this.withErrorState(async()=>this.checkRemoteAndSyncLocked("watch"))})}catch(r){D.warn("Schema watch refresh failed",r.message)}finally{this.lastUsedAt=t}}dispose(){this.watcher.dispose()}async initializeRuntime(t,r,n){let i=await Wa();if(!i?.initModelByBinary){this.model=null,this.snapshot={binaryBytes:t.length,patches:r},this.schemaGraph=null,this.diagnosedFor=null,this.appDetail=n,this.staleReason="CRDT runtime unavailable";return}this.model=i.initModelByBinary(t),await this.applyNetworkPatches(r),this.model&&(Ja(n)&&(this.serverDoc=await this.loadServerDoc(i).catch(s=>(D.warn("Backend app document unavailable; loading this client app's own document alone",s.message),null))),this.snapshot=this.currentView(),await this.resolveZtypeGraph(),await this.refreshZtypeDiagnostics())}async applyNetworkPatches(t){let r=t.filter(i=>!!(i?.exId&&!this.appliedPatchExIds.has(i.exId)));if(!this.model||r.length===0)return;let n=await xE();if(!n?.fromBinary)throw new Error("json-joy Patch runtime is unavailable");this.model.applyBatch(r.map(i=>n.fromBinary(Buffer.from(i.patchBase64,"base64"))));for(let i of r)this.appliedPatchExIds.add(i.exId),this.lastPatchExId=i.exId;this.snapshot=this.currentView()}async loadServerDoc(t){let r=await this.client.request(Ei,{projectExId:this.sessionKey.projectExId}),n=Ya(r.fetchAppDetailByExId);if(!n?.crdtModelUrl||!n.exId||!t.initModelByBinary)throw new Error("Could not load the backend app's document this client app's server half lives in");let i={model:t.initModelByBinary(await RE(n.crdtModelUrl)),schemaExId:n.exId,lastPatchExId:null,appliedPatchExIds:new Set};return await this.applyServerPatches(i,n.crdtPatches?.patches??[]),i.lastPatchExId=n.crdtPatches?.lastPatchExId??i.lastPatchExId,i}async applyServerPatches(t,r){let n=r.filter(s=>!!(s?.exId&&!t.appliedPatchExIds.has(s.exId)));if(n.length===0)return!1;let i=await xE();if(!i?.fromBinary)throw new Error("json-joy Patch runtime is unavailable");t.model.applyBatch(n.map(s=>i.fromBinary(Buffer.from(s.patchBase64,"base64"))));for(let s of n)t.appliedPatchExIds.add(s.exId),t.lastPatchExId=s.exId;return!0}async syncServerDocLocked(){let t=this.serverDoc;if(!t)return!1;let r=await this.client.request(Ei,{projectExId:this.sessionKey.projectExId}),n=Ya(r.fetchAppDetailByExId);if(!n?.exId)return!1;let i=n.crdtPatches?.lastPatchExId??null;return n.exId===t.schemaExId&&i===t.lastPatchExId?!1:n.exId!==t.schemaExId?(this.serverDoc=await this.loadServerDoc(await Wa()),!0):(await this.applyServerPatches(t,n.crdtPatches?.patches??[]),t.lastPatchExId=i,!0)}async resolveZtypeGraph(){let t=await Mt(),r=t?.api;if(!r?.ZTypeCoreApi||!this.snapshot){this.schemaGraph=null,this.diagnosedFor=null,this.staleReason="ztype runtime unavailable";return}let n=r.ZTypeCoreApi.parseZSchemaFromJsObject(this.snapshot),i=await this.getExtraContext(t);this.schemaGraph=this.withProjectFeatures(r.ZTypeCoreApi,()=>r.ZTypeCoreApi.resolveZSchemaToSchemaGraph(n,i))}withProjectFeatures(t,r){return t.withEnabledFeatures(this.enabledProjectFeatureNames,r)}async getExtraContext(t){if(this.extraContextLoaded)return this.extraContext;this.extraContextLoaded=!0;try{let[r,n,i]=await Promise.all([eL(),this.client.request(aR).then(s=>s.supportedCustomModelDescriptor??null).catch(s=>(D.warn("extraContext: model descriptors unavailable",s.message),null)),this.client.request(sf,{projectExId:this.sessionKey.projectExId}).then(s=>(s.features??[]).filter(o=>o.enabled).map(o=>o.featureName)).catch(s=>(D.warn("extraContext: project features unavailable; ztype runs with every feature off",s.message),[]))]);this.enabledProjectFeatureNames=i,this.extraContext=mL(t,r,n,Ks(t))}catch(r){D.warn("extraContext build failed; resolving schema without it",r.message),this.extraContext=null}return this.extraContext}diagnosticsInputs(){return{graph:this.schemaGraph,target:`${this.appDetail?.appType??""}:${this.appDetail?.appExId??""}`,extraContext:this.extraContext,featureNames:this.enabledProjectFeatureNames}}async currentZtypeDiagnostics(){let t=this.diagnosedFor,r=this.diagnosticsInputs();return this.lastZtypeDiagnostics&&t&&Object.keys(r).every(n=>t[n]===r[n])?this.lastZtypeDiagnostics:this.refreshZtypeDiagnostics()}async refreshZtypeDiagnostics(){if(this.diagnosedFor=null,this.lastZtypeDiagnostics=null,!this.schemaGraph||!this.appDetail)return this.lastZtypeDiagnostics={available:!1,stableErrors:[],betaErrors:[],error:this.staleReason??"ztype schema graph is not loaded"},this.lastZtypeDiagnostics;let t=await Mt(),r=t?.api;if(!r?.ZTypeCoreApi||!r?.ZTypeValidationApi)return this.lastZtypeDiagnostics={available:!1,stableErrors:[],betaErrors:[],error:"ztype validation API is unavailable"},this.lastZtypeDiagnostics;let n=Ff(t,this.schemaGraph,this.appDetail,await this.getExtraContext(t)),i=this.withProjectFeatures(r.ZTypeCoreApi,()=>r.ZTypeValidationApi.validateSchemaGraph(n,gL(t,this.appDetail)));return this.lastZtypeDiagnostics={available:!0,stableErrors:[...i?.errors??i?.stableErrors??[]].map(kf),betaErrors:[...i?.warnings??i?.betaErrors??[]].map(kf)},this.diagnosedFor=this.diagnosticsInputs(),this.lastZtypeDiagnostics}touch(){this.lastUsedAt=Date.now()}async withErrorState(t){try{let r=await t();return this.lastError=null,r}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}};var Gf=class{constructor(t,r){this.clientFactory=t;this.subscriptionFactory=r}sessions=new Map;emitter=new E7;clear(){for(let t of this.sessions.values())t.dispose();this.sessions.clear()}sweep(){let t=Date.now();for(let[r,n]of this.sessions.entries())n.isExpired(t)&&(n.dispose(),this.sessions.delete(r))}status(){return this.sweep(),{projectSessionIdleTtlMs:WE,sessions:[...this.sessions.values()].map(t=>t.status())}}async load(t,r=!1){return(await this.getSession(t)).load(r)}async sync(t){return(await this.getSession(t)).sync()}async snapshot(t,r=!1){return(await this.getSession(t)).getSnapshot(r)}async dataModel(t){return(await this.getSession(t)).dataModel()}async save(t){return(await this.getSession(t)).save()}async validate(t){return(await this.getSession(t)).validate()}async ztypeToolCalls(t,r,n=!1,i=null,s=!1){return(await this.getSession(t)).ztypeToolCalls(r,n,i,s)}async currentSchemaExId(t){let r=await this.getSession(t);await r.load(!1);let n=r.status().schemaExId;return typeof n=="string"?n:null}async lastPatchExIds(t){let r=await this.getSession(t);return await r.load(!1),await r.checkRemoteAndSync(),r.lastPatchExIds()}async undo(t){return(await this.getSession(t)).undo()}async redo(t){return(await this.getSession(t)).redo()}async checkRemoteAndSync(t){return(await this.getSession(t)).checkRemoteAndSync()}schemaState(t){this.sweep();let r=[...this.sessions.values()].filter(n=>!t||n.status().projectExId===t);return{projectExId:t??null,sessions:r.map(n=>n.state())}}schemaEvents(t,r,n=100){this.sweep();let i=[...this.sessions.values()].filter(s=>!t||s.status().projectExId===t);return{projectExId:t??null,events:i.flatMap(s=>s.listEvents(r,n))}}async getSession(t){this.sweep();let r=Xa.stringifyKey(t),n=this.sessions.get(r);if(n)return n;let i=new Xa(await this.clientFactory(),t,this.subscriptionFactory,s=>{this.emitter.emit("schemaChanged",s)});return this.sessions.set(r,i),i}};function qt(e,t){return{projectExId:e,appExId:t.appExId??null,appVersionExId:t.appVersionExId??null}}f();var NL=e=>e??{},Q=e=>typeof e=="string"&&e.length>0?e:void 0,ce=e=>typeof e=="string"&&e.length>0?e:null,ke=(e,t=!1)=>typeof e=="boolean"?e:t,tt=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t,Ni=e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0,Ge=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ci=(e,t)=>{let r=Q(e);if(!r)throw new Error(`${t} is required`);return r},St=(e,t)=>{if(!t)return e;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,n=Ge(r._schema);return{...r,_schema:{...n,warning:t}}}return{result:e,_schema:{warning:t}}},_7=e=>new Promise(t=>{setTimeout(t,e)}),$f=e=>{let t=e?.name;if(typeof t!="string"||t.length===0)return null;let r=typeof e?.type=="string"?e.type:"";return/IMAGE|VIDEO|FILE/.test(r)?r.includes("LIST")?`${t}_ids`:`${t}_id`:t},CL=(e,t)=>{let n=e?.tableMetadata?.find(i=>i?.name===t)?.columnMetadata?.map(i=>$f(i))?.filter(i=>i!==null);return n?.length?n.slice(0,20):["id"]},S7=/token|secret|password|privatekey|merchantkey|mchkey|apikey/i,YE=e=>{if(Array.isArray(e))return e.map(YE);if(!e||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=S7.test(r)?"<redacted>":YE(n);return t},JE=(e,t)=>ke(t.includeSecrets,!1)?e:YE(e),PL=async(e,t)=>{let r={projectExId:Q(t.projectExId),appExId:ce(t.appExId),appVersionExId:ce(t.appVersionExId)},n=await fL(e,r);if(r.appExId!==null&&r.appExId===n)throw new Error(`appExId was given the project exId (${n}). appExId names an app inside the project, never the project itself: leave it unset to address the project (its backend, and the whole schema of a single-client project), or take an app exId from \`project metadata\` -> apps[] whose appExId is non-null.`);return{...r,projectExId:n}},RL=async(e,t)=>{let r=Q(t.organizationExId),n=Q(t.projectSpaceType);if(r&&n)return{organizationExId:r,projectSpaceType:n};let s=(await e.request(nf))?.user,o=s?.currentOrganization??s?.organization??s?.organizations?.[0]??s?.joinedOrganizations?.[0];if(!o?.exId)throw new Error("No default organization found; pass organizationExId and projectSpaceType");return{organizationExId:r??o.exId,projectSpaceType:n??"PERSONAL"}},b7=async(e,t)=>((await e.request(rf,{projectName:t,paginator:{first:20}}))?.fuzzySearchProjectName?.edges??[]).find(s=>s?.node?.name===t)?.node??null,xL=async(e,t,r)=>{let n=Date.now()+r;for(;Date.now()<n;){let i=await b7(e,t);if(i)return i;await _7(2e3)}return null},DL=(e,t,r,n=!0)=>{if(Q(t.confirmProjectExId)!==e&&!(n&&ke(t.force,!1)))throw new Error(`${r} is destructive; pass confirmProjectExId=${e}`+(n?" or force=true":""))},T7=e=>e?"project"in e?e.project:"adminToken"in e?e:null:null,w7=e=>e.replace(/\/api\/graphql-v2(\/?)$/,"/api/graphql-admin$1"),Ws=async(e,t)=>{let r=await e.request(WP,t),n=T7(r?.fetchAppDetailByExIdWithoutReconcile);if(!n?.adminToken)throw new Error(`Runtime commands need the project admin token, which only project editors get; none was returned for project ${t.projectExId}`);let i=n.zeroUrl??Ft().zeroApiUrlTemplate.replace("{projectExId}",t.projectExId),s={authorization:`Bearer ${n.adminToken}`};return{adminToken:n.adminToken,zeroUrl:i,dataClient:new it(i,{headers:s,fetch:Qs}),adminClient:new it(n.adminZeroUrl??w7(i),{headers:s,fetch:Qs})}};f();f();import{promises as O7}from"fs";import I7 from"path";var A7=async(e,t)=>{let r=Q(e.cwd);if(!r)throw new Error("cwd is required");let n=I7.resolve(r);if(!(await O7.stat(n)).isDirectory())throw new Error(`Path is not a directory: ${n}`);return t.credentialStore.setWorkspaceRoot(n),t.schemaManager.clear(),t.ok({cwd:n},`Current working directory set to ${n}`)},LL={"workspace.set":A7};f();var UL=He(No(),1);f();import{createServer as kL}from"http";import N7 from"open";var Za=class{config;constructor(t){this.config=t}async findAvailablePort(t){let r=t||this.config.callbackPort||8088;return new Promise((n,i)=>{let s=kL();s.on("error",o=>{o.code==="EADDRINUSE"?n(this.findAvailablePort(r+1)):i(o)}),s.listen(r,()=>{let o=s.address(),a=typeof o=="object"&&o!==null?o.port:r;s.close(()=>n(a))})})}async authenticate(){let t=await this.findAvailablePort(),r=`http://localhost:${t}/callback`;D.info(`[JwtAuth] Using callback URL: ${r}`),D.info("[JwtAuth] Opening browser for authentication...");let n=await new Promise((i,s)=>{let o=null,a=!1,c=kL(async(u,l)=>{if(!u.url)return;let d=new URL(u.url,`http://localhost:${t}`);if(d.pathname==="/callback"){D.info(`[JwtAuth] Callback received: ${u.url}`);let p=d.searchParams.get("token");if(!p||p.trim()===""){D.info("[JwtAuth] No token parameter found in callback URL"),D.info("[JwtAuth] Available parameters:",Array.from(d.searchParams.keys()).join(", "));let g=this.errorPage("No authentication token received");l.writeHead(400,{"Content-Type":"text/html"}),l.end(g),a||(a=!0,o&&clearTimeout(o),c.close(),s(new Error("No token parameter in callback")));return}D.info(`[JwtAuth] Token received (length: ${p.length} chars)`);let h=this.successPage();l.writeHead(200,{"Content-Type":"text/html"}),l.end(h),setTimeout(()=>{a||(a=!0,o&&clearTimeout(o),c.close(),i(p))},1e3)}});c.on("error",u=>{a||(a=!0,o&&clearTimeout(o),s(u))}),c.listen(t,async()=>{let u=new URL(this.config.authEndpoint);u.searchParams.set("redirect_uri",r),D.info(`[JwtAuth] Opening: ${u.toString()}`);try{await N7(u.toString())}catch{D.info("[JwtAuth] Could not open browser automatically"),D.info("[JwtAuth] Please open this URL manually:"),D.info(u.toString())}}),o=setTimeout(()=>{a||(a=!0,c.close(),s(new Error("Authentication timeout - no response after 5 minutes")))},3e5)});return D.info("[JwtAuth] JWT token received successfully"),{access_token:n,token_type:"Bearer"}}renderPage(t){let r=t.autoClose?`
1445
+ `;f();import{randomUUID as U9}from"crypto";var cL=He(Gx(),1);f();var C9=He(MD(),1),P9=He(Nf(),1),R9=He(Fs(),1),x9=He(_E(),1),D9=He(TE(),1),L9=He(CE(),1),HD=He(xf(),1),k9=He(KD(),1);var QD=HD.default;f();var WD=100*1024*1024,Lf=class{current=Promise.resolve();async run(t){let r=this.current,n=()=>{};this.current=new Promise(i=>{n=i}),await r;try{return await t()}finally{n()}}},RE=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(`Failed to download CRDT model: ${t.status} ${t.statusText}`);let r=t.body?.getReader();if(!r)throw new Error("Failed to read CRDT model response body");let n=[],i=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(i+=c.length,i>WD)throw new Error(`CRDT model is larger than ${WD} bytes`);n.push(c)}let s=new Uint8Array(i),o=0;for(let a of n)s.set(a,o),o+=a.length;return s},Qa=async(e,t)=>{try{return await t()}catch(r){return D.warn(`Optional runtime package unavailable: ${e}`,r.message),null}},YD=null,Mt=async()=>(YD??=Qa("@functorz/ztype",()=>import("./ztype-GT63RGA2.js")).then(e=>(e?.default??e)?.com?.functorz?.ztype??null),YD),JD=null,eL=async()=>(JD??=Qa("@functorz/ztype",()=>import("./ztype-GT63RGA2.js")).then(e=>(e?.default??e)?.kotlin?.collections??null),JD),zD=null,tL=async()=>(zD??=Mt().then(e=>e?.typesystem?.schema?.SCHEMA_VERSION??null),zD),XD=null,Wa=async()=>(XD??=Qa("@functorz/crdt-helper",()=>import("./index.cjs-Q57TQ2R4.js")).then(e=>e?.Crdt??e?.default?.Crdt??null),XD),ZD=null,xE=async()=>(ZD??=Qa("json-joy/lib/json-crdt-patch/index.js",()=>import("./json-crdt-patch-FOT7IATI.js")).then(e=>e??Qa("json-joy/lib/json-crdt/index.js",()=>import("./json-crdt-5Q5CWOET.js"))).then(e=>e?.Patch??e?.default?.Patch??null),ZD),Ya=e=>e?.lastUploadedSchema??null,DE=e=>[e?.project?.lastDeployedServerSchemaExId,e?.lastDeployedServerSchemaExId,e?.project?.latestDeployedServerSchema?.exId,e?.latestDeployedServerSchema?.exId].find(r=>typeof r=="string"&&r.length>0)??null,rL=e=>e==null?e:structuredClone(e),LE=(e,t)=>e?.appExId?e.appExId:t?.name??"",kE=(e,t)=>{let r=e?.typesystem?.schema?.ClientType;if(r)return t==="WECHAT_MINI_PROGRAM"?r.WECHAT_MINI_PROGRAM??r.WECHAT??r.WEB:t==="MOBILE"?r.MOBILE??r.WEB:r.WEB},Ks=e=>{let t=e?.typesystem?.schema?.Product?.[mo];if(!t)throw new Error(`ztype runtime has no Product enum member for ${mo}`);return t},nL=e=>{let t=e?.typesystem?.schema?.Locale?.EN;if(!t)throw new Error("ztype runtime has no Locale enum member for EN");return t},j9=e=>{try{return JSON.parse(JSON.stringify(e))}catch{return String(e)}},kf=e=>({componentId:e?.componentId??null,message:typeof e?.getLocalizedErrorMessage=="function"?e.getLocalizedErrorMessage("EN"):e?.message??String(e),zhMessage:typeof e?.getLocalizedErrorMessage=="function"?e.getLocalizedErrorMessage("ZH"):void 0,platform:e?.platform??null,isBackendError:!!e?.isBackendError,fullPath:j9(e?.fullPath??[])}),jf=e=>e.stableErrors.concat(e.betaErrors).filter(t=>!!t.isBackendError),iL=e=>jf(e).length,sL=(e,t)=>{if(t.__typename==="DiffItem"){let r=t.pathComponents?.at(-1)?.key??"";if(t.operation==="delete"){delete e[r];return}e[r]=structuredClone(t.newValue);return}if(t.__typename==="ArrayDiffItem"){let r=t.pathComponents?.at(-1)?.index??-1;if(!Array.isArray(e)||r<0)throw new Error("Invalid array diff target");if(t.operation==="delete"){e.splice(r,1);return}if(t.operation==="insert"){e.splice(r,0,structuredClone(t.newValue));return}e[r]=structuredClone(t.newValue)}};f();var oL=He(No(),1);import{createRequire as M9}from"module";var q9=M9(import.meta.url);var Mf=e=>{if(tn){if(e==="@functorz/ztype")return tn.ztype;if(e==="@functorz/crdt-helper")return tn.crdtHelper;if(e==="json-joy")return tn.jsonJoy}try{let t=q9(`${e}/package.json`);return t.ztypeBuild??t.version??"unknown"}catch{return"unavailable"}},F9=async()=>{if(tn)return{ztypeVersion:tn.ztype,ztypeSchemaVersion:tn.ztypeSchemaVersion};try{let e=await Mt();return{ztypeVersion:Mf("@functorz/ztype"),ztypeSchemaVersion:e?.ZTypeSystem?.getSchemaVersion?.()??"unknown"}}catch{return{ztypeVersion:Mf("@functorz/ztype"),ztypeSchemaVersion:"unavailable"}}};async function jE(){let e=db(),t=await F9();return{agentVersion:e.version??"0.0.0",nodeMajor:process.versions.node.split(".")[0],platform:process.platform,arch:process.arch,ztypeVersion:t.ztypeVersion,ztypeSchemaVersion:t.ztypeSchemaVersion,crdtHelperVersion:Mf("@functorz/crdt-helper"),jsonJoyVersion:Mf("json-joy")}}async function Hs(e,t){let[r,n,i]=await Promise.all([jE(),Cr(e),e.loadCredentials()]),s=i?oL.default.decode(i.access_token):null,o=typeof s=="object"&&s!==null?String(s.sub??s.exId??s.id??"authenticated"):"anonymous";return{...r,product:te,apiBaseUrl:n.apiBaseUrl,authUserId:o,workspaceRoot:e.getWorkspaceRoot(),typeSystemMode:qi(),startupFlags:[...t].sort()}}function aL(e,t){return JSON.stringify(e)===JSON.stringify(t)}var qE=U9(),uL=`${te}/${Hn()}`,V9=e=>{if(!e)return e;if(Array.isArray(e))return e.map(([r,n])=>[r,String(r).toLowerCase()==="authorization"?"Bearer <redacted>":n]);if(typeof e=="object"&&"forEach"in e&&typeof e.forEach=="function"){let r={};return e.forEach((n,i)=>{r[i]=i.toLowerCase()==="authorization"?"Bearer <redacted>":String(n)}),r}let t={};for(let[r,n]of Object.entries(e))t[r]=r.toLowerCase()==="authorization"?"Bearer <redacted>":String(n);return t};function FE(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.map(r=>{let n=r,i=typeof n.operation=="string"?n.operation:null,s=typeof n.errorType=="string"?n.errorType:typeof n.extensions?.classification=="string"?n.extensions.classification:null,o=typeof n.message=="string"?n.message:null;return!o&&!i&&!s?null:`${i?`${i}: `:""}${o??"GraphQL error"}${s?` (${s})`:""}`}).filter(r=>!!r);return t.length>0?t.join("; "):null}var G9=e=>{if(typeof e=="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");try{return String(e)}catch{return"<unserializable body>"}},Qs=async(e,t)=>{let r=gp();D.debug(`[HTTP] Request URL: ${e.toString()}`),t?.headers&&D.debug(`[HTTP] Request Headers: ${JSON.stringify(V9(t.headers))}`),r&&t?.body!=null&&D.debug(`[GQL] Request Body: ${G9(t.body)}`);let n=await fetch(e,t),i=null;try{i=await n.clone().text()}catch(s){D.debug(`[GQL] Response read failed: ${String(s)}`)}if(r&&D.debug(`[GQL] Response ${n.status}: ${i??"<read failed>"}`),i&&i.includes('"errors"')){let s=null;try{s=JSON.parse(i).errors}catch{s=null}let o=FE(s);o&&D.warn(`[GQL] ${n.status} errors: ${o}`)}return n};async function UE(e,t){let r=await e.getValidToken(),n=await Cr(t),i={Authorization:`Bearer ${r}`,"User-Locale":"en_US","X-SESSION-ID":qE,"X-Client":uL},s=await tL();return s&&(i["X-ZED-VERSION"]=s),process.env.REACT_APP_VERSION&&(i["X-REACT-APP-VERSION"]=process.env.REACT_APP_VERSION),new it(`${n.apiBaseUrl}/api/graphql`,{headers:i,fetch:Qs})}var ME=class extends QD{constructor(...t){super(...t),this.on("error",r=>D.debug(`[SUB] socket error: ${r.message}`))}};async function lL(e,t){let r=await e.getValidToken(),i=`${(await Cr(t)).apiBaseUrl.replace(/^http:/,"ws:").replace(/^https:/,"wss:")}/api/graphql-subscription`;return async(s,o,a)=>{let c=gp(),u={authToken:r,"X-SESSION-ID":qE,"X-Client":uL};D.debug(`[SUB] connecting ${i} params=${JSON.stringify({...u,authToken:"Bearer <redacted>"})}`);let l=new cL.SubscriptionClient(i,{lazy:!0,reconnect:!0,minTimeout:3e3,connectionParams:u},ME);l.onConnected(()=>D.debug("[SUB] connected")),l.onReconnected(()=>D.debug("[SUB] reconnected")),l.onDisconnected(()=>D.debug("[SUB] disconnected")),l.onError(h=>D.debug(`[SUB] error ${h?.message??String(h)}`));let p=[{name:"onNewCrdtPatchV2",query:XP,variables:{projectExId:s.projectExId,appExId:s.appExId??null,versionExId:s.appVersionExId??null,latestPatchExIdInClient:o}},{name:"onSchemaUploadV3",query:ZP,variables:{projectExId:s.projectExId,appExId:s.appExId??null,appVersionExId:s.appVersionExId??null}}].map(h=>(D.debug(`[SUB] subscribe ${h.name} vars=${JSON.stringify(h.variables)}`),l.request({query:h.query,variables:h.variables}).subscribe({next:g=>{c&&D.debug(`[SUB] ${h.name} event: ${JSON.stringify(g)}`),a()},error:g=>{D.warn("Schema subscription event failed",String(g)),a()}})));return{unsubscribe(){for(let h of p)h.unsubscribe();l.close(!1,!1)}}}}async function fL(e,t){if(t.projectExId)return await e.saveProjectContext(t.projectExId),t.projectExId;let r=await e.loadProjectContext();if(!r?.projectExId)throw new Error("No projectExId provided and no current project is set");return r.projectExId}async function VE(e,t,r,n){try{await e.request(pR,{projectExId:t,client:te,clientVersion:Hn(),sessionId:n??qE,agent:r??null}),D.debug(`[agent-session] started for project ${t}`)}catch(i){D.debug(`[agent-session] skipped: ${String(i)}`)}}f();f();f();import{createHash as $9}from"crypto";var B9=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),GE=e=>{if(Array.isArray(e))return e.map(r=>r===void 0?null:GE(r));if(!B9(e))return e;let t={};for(let r of Object.keys(e).sort()){let n=e[r];n!==void 0&&(t[r]=GE(n))}return t},K9=e=>JSON.stringify(GE(e)),H9=e=>$9("sha256").update(K9(e)).digest("hex"),dL=e=>({projectExId:e.projectExId,appExId:e.appExId??null,appVersionExId:e.appVersionExId??null,schemaExId:e.schemaExId??null,lastPatchExId:e.lastPatchExId??null,snapshotHash:H9(e.snapshot),deployedSchemaExId:e.deployedSchemaExId??null,checkedAt:e.checkedAt??new Date().toISOString()}),pL=(e,t)=>!e||!t?e!==t:e.schemaExId!==t.schemaExId||e.lastPatchExId!==t.lastPatchExId||e.snapshotHash!==t.snapshotHash||e.deployedSchemaExId!==t.deployedSchemaExId,qf=e=>e.changes.length>0;var hL=null,Q9=()=>(hL??=Mt().then(e=>{let t=e?.typesystem?.schema?.diff?.computeSemanticSchemaChanges;return typeof t=="function"?t:null}),hL),W9=async(e,t)=>{let r=await Q9();return r?r(e,t):{changes:[]}},$E=(e,t)=>W9(JSON.stringify(e),JSON.stringify(t));f();var Y9="Functorz";function mL(e,t,r,n){let i=e?.typesystem?.settings,s=e?.typesystem?.schema,o=t?.KtList,a=t?.KtMap;if(!i?.ExtraContext||!s?.CustomChatModelDescriptor||!s?.AIModelDescriptors||!o||!a)return D.warn("ztype ExtraContext symbols missing; schema graph will be built without custom models"),null;try{let{ExtraContext:c}=i,{AIModelDescriptors:u,CustomChatModelDescriptor:l,CustomEmbeddingModelDescriptor:d,ModelCustomParamDescriptor:p,CustomModelParam:h,CustomChatCompletionFeatures:g,Identifier:y,MediaOutputCardinality:E}=s,S=O=>a.fromJsMap(new Map(Object.entries(O??{}))),_=O=>typeof O=="string"?O==="single"?E.SINGLE:O==="multiple"?E.MULTIPLE:E.NONE:typeof O=="boolean"&&O?E.MULTIPLE:E.NONE,w=O=>new p(O.name,S(O.displayName),O.type,S(O.description)),I=O=>new h(w(O.serverUrl),w(O.apiToken),o.fromJsArray((O.extensionParams??[]).map($=>new p($.name,S($.displayName),$.type,S($.displayName))))),T=O=>O.provider===Y9&&O.customModelIdentifier?new y(O.customModelIdentifier.id,O.customModelIdentifier.namespace):null,N=(r?.chatModelDescriptors??[]).map(O=>new l(O.provider,O.name,I(O.paramToConfigure),O.delisted,new g(O.features.streamResponse,O.features.multiModal,O.features.imageInput??!1,!1,O.features.videoInput??!1,O.features.imageMessageInput??!1,!1,O.features.videoMessageInput??!1,O.features.tools,O.features.reasoningContent,O.features.imageOutput,O.features.videoOutput,_(O.features.imageOutput),_(O.features.videoOutput),null,O.features.structuredOutput),T(O))),P=(r?.embeddingModelDescriptors??[]).map(O=>new d(O.provider,O.name,I(O.paramToConfigure),T(O),O.delisted));return new c(new u(o.fromJsArray(N),o.fromJsArray(P)),a.fromJsMap(new Map),n)}catch(c){return D.warn("ztype ExtraContext construction failed; schema graph will be built without custom models",c.message),null}}f();var Cn=class extends Error{constructor(r,n){super(r);this.diagnostics=n;this.name="ZtypeValidationError"}};f();function Ff(e,t,r,n=null){let i=kE(e,r?.appType);return e.api.ZTypeCoreApi.genZTypeApiContext(t,Ks(e),i,LE(r,i),nL(e),n)}function gL(e,t){return LE(t,kE(e,t?.appType))}f();var yL={QUERY:"query",MUTATION:"mutation"},vL={SUCCESS:"2xx",PERMANENT_FAIL:"4xx",TEMPORARY_FAIL:"5xx"};function EL(e){let t=r=>{if(Array.isArray(r))return r.map(t);if(r&&typeof r=="object"){let n={};for(let[i,s]of Object.entries(r))i==="operation"&&typeof s=="string"&&yL[s]!==void 0?n[i]=yL[s]:i==="responseBranch"&&typeof s=="string"&&vL[s]!==void 0?n[i]=vL[s]:n[i]=t(s);return n}return r};return e.map(t)}function _L(e){let t=r=>typeof r=="string"&&!r.startsWith("http://")&&!r.startsWith("https://");for(let r of e){let n=r;if(!n?.args||typeof n.args!="object")continue;let i=n.args,s=[];if(n.name==="UPDATE_TPA_CONFIG")s.push(i.url);else if(n.name==="ADD_TPA_CONFIGS"&&Array.isArray(i.items))for(let o of i.items)o&&typeof o=="object"&&s.push(o.url);for(let o of s)if(t(o))return`url "${o}" is not an absolute URL. A TPA config url must include the scheme and host (e.g. https://api.example.com/v1/resource) \u2014 find the API's base URL in its documentation.`}return null}f();var Pn=e=>e==null,BE=(e,t)=>{if(Pn(e)&&Pn(t)||e===t)return!0;if(Pn(e)||Pn(t)||typeof e!="object"||typeof t!="object")return!1;let r=e,n=t,i=new Set([...Object.keys(r),...Object.keys(n)]);for(let s of i)if(!BE(r[s],n[s]))return!1;return!0};var KE=e=>{let t=new Set;for(let r of e)if(t.add(r.pathComponents.map(n=>n.index!==void 0?`[${n.index}]`:`.${n.key}`).join("").replace(/^\./,"")),t.size>=20)break;return[...t]},SL=e=>{if(e.__typename==="DiffItem")switch(e.operation){case"add":return{__typename:"DiffItem",oldValue:e.newValue,newValue:null,operation:"delete",pathComponents:e.pathComponents};case"delete":return{__typename:"DiffItem",oldValue:null,newValue:e.oldValue,operation:"add",pathComponents:e.pathComponents};case"update":return{__typename:"DiffItem",oldValue:e.newValue,newValue:e.oldValue,operation:"update",pathComponents:e.pathComponents}}else switch(e.operation){case"insert":return{__typename:"ArrayDiffItem",oldValue:e.newValue,newValue:null,previousValue:e.previousValue,nextValue:e.nextValue,operation:"delete",pathComponents:e.pathComponents};case"delete":return{__typename:"ArrayDiffItem",oldValue:null,newValue:e.oldValue,previousValue:e.previousValue,nextValue:e.nextValue,operation:"insert",pathComponents:e.pathComponents};case"update":return{__typename:"ArrayDiffItem",oldValue:e.newValue,newValue:e.oldValue,operation:"update",pathComponents:e.pathComponents}}throw new Error(`Cannot reverse diff item: ${JSON.stringify(e)}`)},J9=e=>e.key??e.index??"",z9=(e,t)=>{let r=e;for(let n of t){if(r===null||typeof r!="object")return;r=r[n]}return r},X9=(e,t)=>{if(t.__typename!=="DiffItem")return null;let r=t.pathComponents.at(-1)?.key;if(r===void 0)return null;let n=BE(e[r],t.oldValue);switch(t.operation){case"add":e[r]=t.newValue;break;case"update":if(!n)return null;e[r]=t.newValue;break;case"delete":if(!Object.prototype.hasOwnProperty.call(e,r)||!n)return null;delete e[r];break;default:return null}return t},Z9=(e,t)=>{if(t.__typename!=="ArrayDiffItem")return null;let r=t.pathComponents.at(-1)?.index;if(r===void 0||r>e.length)return null;let n=()=>BE(e[r],t.oldValue);switch(t.operation){case"insert":e.splice(r,0,t.newValue);break;case"delete":if(!n())return null;e.splice(r,1);break;case"update":if(!n())return null;e.splice(r,1,t.newValue);break;default:return null}return t},bL=(e,t)=>{let r=e,n=new WeakSet,i=o=>{if(r===null||typeof r!="object")return r;n.has(r)||(r=Array.isArray(r)?[...r]:{...r},n.add(r));let a=r;for(let c of o){let u=a[c];if(u!==null&&typeof u=="object"){if(!n.has(u)){let l=Array.isArray(u)?[...u]:{...u};n.add(l),a[c]=l}a=a[c]}else a=u}return a},s=[];for(let o of t)try{let c=o.pathComponents.map(J9).slice(0,-1);if(Pn(z9(r,c)))continue;let u=i(c);if(Array.isArray(u)){let l=Z9(u,o);l&&s.push(l)}else if(u!==null&&typeof u=="object"){let l=X9(u,o);l&&s.push(l)}}catch{continue}return s};f();var e7=3e4,Uf=class{constructor(t){this.options=t}timer=null;subscriptionHandle=null;running=!1;isActive(){return this.timer!==null||this.subscriptionHandle!==null}start(){this.timer||this.subscriptionHandle||!this.options.subscriptionFactory||this.options.subscriptionFactory(this.options.sessionKey,this.options.getLastPatchExId(),()=>{this.run()}).then(t=>{this.subscriptionHandle=t}).catch(t=>{D.warn("Schema subscription failed; falling back to polling",t.message)}).finally(()=>{this.schedulePoll()})}dispose(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.subscriptionHandle?.unsubscribe(),this.subscriptionHandle=null}schedulePoll(){!this.options.subscriptionFactory||this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.run().finally(()=>this.schedulePoll())},e7),this.timer.unref())}async run(){if(!this.running){this.running=!0;try{await this.options.refresh()}finally{this.running=!1}}}};f();var TL=(e,t)=>{let r=new WeakMap,n=o=>{let a=r.get(o);return a||(a=Array.isArray(o)?[...o]:{...o},r.set(o,a)),a},i=new WeakMap,s=n(e);for(let o of t){let a=(o?.pathComponents??[]).slice(0,-1),c=e,u=s;for(let l of a){let d=l.key??l.index??"",p=c[d];if(p===null||typeof p!="object")break;if(Array.isArray(p)){let h=i.get(p);h||(h=structuredClone(p),i.set(p,h)),u[d]=h;break}u[d]=n(p),c=p,u=u[d]}}return s};f();f();var t7=new Set(["BACKEND_ONLY","COMBINED"]),Ja=e=>!e?.appType||t7.has(e.appType)?!1:(e.project?.appList??[]).some(t=>t.appType==="BACKEND_ONLY"),OL=(e,t)=>{if(!t)return e;let r=t.model.view();return{...e,server:r?.server??null}},Vf=e=>e?.pathComponents?.[0]?.key==="server",wL=e=>typeof e=="string"&&e.length>0?e:null,HE=(e,t)=>{let r=e.serverDoc;if(r){let i=wL(r.schemaExId);return i?{ok:!0,appExId:null,schemaExId:i}:{ok:!1,error:"the backend app document has no schemaExId"}}if(e.serverDocRequired===!0)return{ok:!1,error:"this client app's server lives in the backend app's document, which did not load, so there is nothing to sync; retry, or run project sync-backend without appExId"};let n=wL(e.schemaExId);return n?{ok:!0,appExId:t,schemaExId:n}:{ok:!1,error:"the session has no schemaExId"}};f();var QE=null,IL=async e=>(QE??=e.request(JP).then(t=>(t.__type?.inputFields??[]).some(r=>r.name==="origin")).catch(()=>(QE=null,!1)),await QE?{origin:"MCP"}:{});var WE=300*1e3,r7=100,n7=50,i7=["dataModel","types"];function s7(e){let t=e.server;if(!t||typeof t!="object"||Array.isArray(t))return e;let r={};for(let i of i7){let s=t[i];s!==void 0&&(r[i]=s)}let n={};return e.version!==void 0&&(n.version=e.version),n.server=r,n}var o7={ADD_ACTION_FLOW_OUTPUT_FIELDS:"SET_ACTION_FLOW_OUTPUT",DELETE_ACTION_FLOW_OUTPUT_FIELDS:"CLEAR_ACTION_FLOW_OUTPUT",SET_ACTION_FLOW_OUTPUT:"ADD_ACTION_FLOW_OUTPUT_FIELDS",CLEAR_ACTION_FLOW_OUTPUT:"DELETE_ACTION_FLOW_OUTPUT_FIELDS"};function AL(e){return e==="post_type_system_refactor"?"post-type-system-refactor (refactored)":"pre-type-system-refactor (legacy)"}function a7(e,t,r){let n=`${e} requires a ${AL(t)} schema, but this project is ${AL(r)}.`,i=o7[e];if(i)return`${n} Use ${i} instead.`;if(t!=="post_type_system_refactor")return`${n} Use the corresponding post-type-system-refactor op instead.`;let s="The daemon auto-detects migrated projects from the loaded schema \u2014 do not force MCP_TYPE_SYSTEM=post to bypass this gate; it cannot migrate the project, and post-only config written into a pre-refactor schema is invisible to the editor.";return/^(GET_ALL_API|GET_API|ADD_API|UPDATE_API|DELETE_API)/.test(e)?`${n} API-integration workspaces only exist after the type-system refactor. ${s} To integrate an external HTTP endpoint on this project, use the TPA ops instead (third-party-api.md, e.g. ADD_TPA_CONFIGS).`:`${n} Enums and object/custom types only exist after the type-system refactor \u2014 migrate the project in the editor first. ${s}`}function c7(e){if(typeof e!="string")return e;let t=e.trim();if(!/^[[{]|^(true|false|null|-?\d)/.test(t))return e;try{return JSON.parse(t)}catch{return e}}function u7(e){if(typeof e!="string")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let r={};for(let[n,i]of Object.entries(t))r[n]=c7(i);return r}function l7(e){let t=new Set;return e.map(r=>{if(!r||typeof r!="object")return r;let n=r,i=typeof n.toolCallId=="string"&&n.toolCallId?n.toolCallId:null;if(i!==null&&t.has(i))throw new Error(`Duplicate toolCallId: ${i}`);let s=i??za();return t.add(s),i===s?n:{...n,toolCallId:s}})}function f7(e,t){if(!e)return;let r=new Map(Object.entries(e)),n=t.map((i,s)=>{if(!r.has(i))throw new Error(`Missing ztype response for tool call ${s}`);let o=r.get(i);return r.delete(i),o});if(r.size>0)throw new Error(`Unexpected ztype responses: ${[...r.keys()].join(", ")}`);return n}function d7(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?Object.values(t).find(n=>typeof n=="string")??t:t):[]}function p7(e){let t=e??{},r=t.data??{},n={},i=u7(r.responseByToolCallId??t.responseByToolCallId);i&&Object.keys(i).length>0&&(n.responses=i);let s=r.schemaDiff??t.schemaDiff;s&&(n.schemaDiff=s);let o=d7(t.errors??r.errors);return o.length>0&&(n.errors=o),n}function h7(e){let t=e??{},r=t.data?.updatedReadState;if(r!=null)return r;if(typeof t.updatedReadStateJson=="string")try{return JSON.parse(t.updatedReadStateJson)}catch{return}}function m7(e){return(e??{}).data?.touchesComponents===!0}function g7(e,t){let r=e??{};if(r.isSuccess!==!1)return{};let n={},i=typeof r.failedToolCallId=="string"?t.indexOf(r.failedToolCallId):-1;i>=0&&(n.failedIndex=i),typeof r.errorCode=="string"&&(n.errorCode=r.errorCode),r.failedBeforeExecution===!0&&(n.failedBeforeExecution=!0);let s=Array.isArray(r.detailKeys)?r.detailKeys:[],o=Array.isArray(r.detailValues)?r.detailValues:[];if(s.length>0&&s.length===o.length){let a={};s.forEach((c,u)=>{typeof c=="string"&&typeof o[u]=="string"&&(a[c]=o[u])}),Object.keys(a).length>0&&(n.errorDetails=a)}return n}async function y7(e){let r=(await Mt())?.application?.schemaops?.SchemaOpsErrorCode?.DEPENDENCY_CONFLICT?.name,i=(e.diagnostics?.stableErrors??[]).map(s=>{let o=s??{};return[o.componentId,o.message].filter(a=>typeof a=="string"&&a!=="").join(": ")}).filter(s=>s!=="");return{applied:{applied:!1,reason:"ztype validation interrupted the batch"},errors:i.length>0?i:[e.message],...typeof r=="string"?{errorCode:r}:{},errorDetails:{dependents:i.join("; ")},ztypeDiagnostics:e.diagnostics}}function v7(e){return e?e.available===!1||(e.stableErrors?.length??0)>0||(e.betaErrors?.length??0)>0:!1}var Xa=class e{constructor(t,r,n,i){this.client=t;this.sessionKey=r;this.onSchemaEvent=i;this.key=e.stringifyKey(r),this.watcher=new Uf({sessionKey:r,subscriptionFactory:n,getLastPatchExId:()=>this.lastPatchExId,refresh:()=>this.runWatchRefresh()})}crdtBinary=null;model=null;serverDoc=null;schemaGraph=null;extraContext=null;extraContextLoaded=!1;enabledProjectFeatureNames=[];appDetail=null;snapshot=null;schemaExId=null;lastPatchExId=null;appliedPatchExIds=new Set;staleReason="not loaded";lastError=null;lastZtypeDiagnostics=null;diagnosedFor=null;lastRevision=null;events=[];undoStack=[];redoStack=[];watcher;loadedAt=0;lastUsedAt=Date.now();mutex=new Lf;key;static stringifyKey(t){return[t.projectExId,t.appExId??"",t.appVersionExId??""].join(":")}isExpired(t=Date.now()){return t-this.lastUsedAt>WE}currentView(){if(!this.model)throw new Error("CRDT model not loaded");return OL(this.model.view(),this.serverDoc)}lastPatchExIds(){return[this.lastPatchExId,this.serverDoc?.lastPatchExId??null].filter(t=>typeof t=="string")}refactorState(){return this.snapshot?Sb(this.snapshot.server):null}assertToolCallsMatchTypeSystem(t){let r=this.refactorState();if(!r)throw new Error("Schema is not loaded; run schema load before calling schema tools.");for(let n of t){let i=n?.name;if(typeof i!="string")continue;let s=_b[i];if(s&&s!==r)throw new Error(a7(i,s,r))}}normalizeExternalColumnTypes(t){let r=new Set(["typeIdentifier","basicTypeNameOrTypeId"]),n={TEXT:"STRING",INTEGER:"BIGINT",FLOAT8:"DECIMAL"},i=s=>{if(Array.isArray(s))return s.map(i);if(s&&typeof s=="object"){let o={};for(let[a,c]of Object.entries(s))o[a]=r.has(a)&&typeof c=="string"&&n[c.toUpperCase()]?n[c.toUpperCase()]:i(c);return o}return s};return t.map(i)}status(){return{key:this.key,projectExId:this.sessionKey.projectExId,appExId:this.sessionKey.appExId??null,appVersionExId:this.sessionKey.appVersionExId??null,schemaExId:this.schemaExId,lastPatchExId:this.lastPatchExId,serverDocRequired:Ja(this.appDetail),serverDoc:this.serverDoc?{schemaExId:this.serverDoc.schemaExId,lastPatchExId:this.serverDoc.lastPatchExId}:null,loadedAt:this.loadedAt?new Date(this.loadedAt).toISOString():null,lastUsedAt:new Date(this.lastUsedAt).toISOString(),staleReason:this.staleReason,lastError:this.lastError,typeSystem:this.refactorState(),typeSystemMode:this.refactorState()??qi(),schemaRevision:this.lastRevision,ztypeDiagnostics:this.lastZtypeDiagnostics,crdtBinaryBytes:this.crdtBinary?.byteLength??null,hasCrdtModel:this.model!==null,hasZtypeGraph:this.schemaGraph!==null,schemaEventCount:this.events.length,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,watcherActive:this.watcher.isActive()}}state(){return{...this.status(),latestEvent:this.events.at(-1)??null}}listEvents(t,r=100){if(!t)return this.events.slice(-r);let n=this.events.findIndex(i=>i.id===t);return(n>=0?this.events.slice(n+1):this.events).slice(-r)}async checkRemoteAndSync(){return this.mutex.run(async()=>this.withErrorState(async()=>this.checkRemoteAndSyncLocked("remote")))}async load(t=!1){return this.mutex.run(async()=>this.withErrorState(()=>this.loadLocked(t)))}async sync(){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),!this.schemaExId)return this.loadLocked();let t=await this.client.request(YP,{schemaExId:this.schemaExId}),r=t.crdtSchemaBySchemaExId?.crdtPatches?.patches??[];return await this.applyNetworkPatches(r),await this.syncServerDocLocked(),this.model&&(this.snapshot=this.currentView(),await this.resolveZtypeGraph(),await this.refreshZtypeDiagnostics()),this.lastPatchExId=t.crdtSchemaBySchemaExId?.crdtPatches?.lastPatchExId??this.lastPatchExId,this.updateRevision(),this.status()}))}getSnapshot(t=!1){if(this.touch(),this.model?.view&&(this.snapshot=this.currentView()),!this.snapshot)throw new Error("Project schema is not loaded");return t?this.snapshot:s7(this.snapshot)}dataModel(){let t=this.getSnapshot().server;return!t||typeof t!="object"?null:t.dataModel??null}async save(){return this.mutex.run(async()=>this.withErrorState(async()=>{this.touch();let t=await this.currentZtypeDiagnostics(),r=await this.client.request(yv,{projectExId:this.sessionKey.projectExId,appExId:this.sessionKey.appExId??null,versionExId:this.sessionKey.appVersionExId??null});if(this.schemaExId=r.saveSchema,this.serverDoc){let n=await this.client.request(yv,{projectExId:this.sessionKey.projectExId,appExId:null,versionExId:null});this.serverDoc.schemaExId=n.saveSchema}return this.updateRevision(),{...this.status(),ztypeDiagnostics:t}}))}async validate(){return this.mutex.run(async()=>this.withErrorState(async()=>(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),this.currentZtypeDiagnostics())))}async ztypeToolCalls(t,r=!1,n=null,i=!1){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),!this.schemaGraph)throw new Error("ztype runtime is unavailable; install @functorz/ztype in this package");this.assertToolCallsMatchTypeSystem(t);let s=await Mt(),o=s?.api;if(!o?.ZTypeCoreApi||!o?.ZTypeSchemaOpsApi)throw new Error("ztype SchemaOps API is unavailable");let a=Ff(s,this.schemaGraph,this.appDetail,await this.getExtraContext(s)),c=l7(t),u=_L(c);if(u)throw new Error(u);let l=c.map(S=>S&&typeof S=="object"?S.toolCallId:void 0).filter(S=>typeof S=="string"),d=this.withProjectFeatures(o.ZTypeCoreApi,()=>o.ZTypeSchemaOpsApi.toolCalls(a,this.normalizeExternalColumnTypes(EL(c)),n??null)),p=p7(d),h=p.schemaDiff,g=f7(p.responses,l),y={},E=h7(d);if(E!=null&&(y.updatedReadState=E),g&&(y.responses=g),p.errors&&(y.errors=p.errors,Object.assign(y,g7(d,l)),y.applied={applied:!1,reason:"batch rejected by ztype"}),h&&r&&(y.schemaDiff=h),h)try{y.applied=await this.applySchemaDiffLocked(h,{skipValidation:i}),m7(d)&&(y.touchesComponents=!0)}catch(S){if(!(S instanceof Cn))throw S;let _=await y7(S);return Object.assign(y,_,{errors:[...Array.isArray(y.errors)?y.errors:[],..._.errors]}),y}return await this.attachValidationErrorIfAny(y),y}))}async attachValidationErrorIfAny(t){let r=await this.currentZtypeDiagnostics();v7(r)&&(t.ztypeDiagnostics=r)}async undo(){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),this.undoStack.length===0)return{...this.status(),undone:!1,reason:"nothing to undo"};let t=this.undoStack[this.undoStack.length-1],r=t.dataSource.map(SL).reverse(),n=await this.applyReversibleLocked(r);return n?(this.undoStack.pop(),this.redoStack.push(t),{...n,undone:!0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,reverted:t.semanticChanges??void 0,revertedPaths:KE(t.dataSource)}):{...this.status(),undone:!1,reason:"schema diverged since this change; undo no longer applies cleanly"}}))}async redo(){return this.mutex.run(async()=>this.withErrorState(async()=>{if(this.touch(),(!this.model||!this.schemaGraph||!this.appDetail)&&await this.loadLocked(),this.redoStack.length===0)return{...this.status(),redone:!1,reason:"nothing to redo"};let t=this.redoStack[this.redoStack.length-1],r=await this.applyReversibleLocked(t.dataSource);return r?(this.redoStack.pop(),this.undoStack.push(t),{...r,redone:!0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length,reapplied:t.semanticChanges??void 0,reappliedPaths:KE(t.dataSource)}):{...this.status(),redone:!1,reason:"schema diverged since this change; redo no longer applies cleanly"}}))}async applyReversibleLocked(t){if(!this.model)throw new Error("CRDT model not loaded");let r=this.currentView(),n=bL(r,t);if(n.length!==t.length)return null;let i=n.filter(s=>!(s.__typename==="DiffItem"&&Pn(s.oldValue)&&Pn(s.newValue)));return i.length===0?null:this.applySchemaDiffLocked({id:za(),dataSource:i},{recordUndo:!1})}async recordUndoEntry(t,r,n){let i=await Wa();if(!i?.generateDiff)return;let s=[];i.generateDiff({before:t,after:r,prefix:[],result:s}),s.length!==0&&(this.undoStack.push({id:za(),dataSource:s,semanticChanges:n}),this.undoStack.length>n7&&this.undoStack.shift(),this.redoStack=[])}async loadLocked(t=!1){if(this.touch(),this.model&&!t&&!this.staleReason)return this.status();let n=(await this.client.request(Ei,this.sessionKey)).fetchAppDetailByExId;if(!n)throw new Error(`Project not found: ${this.sessionKey.projectExId}`);let i=Ya(n);if(!i?.crdtModelUrl||!i.exId)throw new Error("Project has no uploaded CRDT schema");let s=await RE(i.crdtModelUrl);return this.crdtBinary=s,this.appliedPatchExIds.clear(),this.lastPatchExId=null,this.serverDoc=null,this.undoStack=[],this.redoStack=[],this.appDetail=n,await this.initializeRuntime(s,i.crdtPatches?.patches??[],n),this.schemaExId=i.exId,this.lastPatchExId=i.crdtPatches?.lastPatchExId??null,this.loadedAt=Date.now(),this.model&&this.schemaGraph?this.staleReason=!this.serverDoc&&Ja(n)?"backend app document unavailable":null:this.model&&!this.schemaGraph&&(this.staleReason="ztype runtime unavailable"),this.updateRevision(),this.watcher.start(),this.status()}async applySchemaDiffLocked(t,r={}){if(Array.isArray(t.dataSource)&&t.dataSource.length===0)return{...this.status(),applied:!1,reason:"empty schema diff"};if(!this.serverDoc&&Ja(this.appDetail)&&(t.dataSource??[]).some(Vf))throw new Error("This client app's server lives in the backend app's document, which is not loaded; refusing to write server changes into the client document. Run schema load again.");let i=(r.recordUndo??process.env.MOMEN_MCP_UNDO!=="0")&&this.snapshot?TL(this.snapshot,t.dataSource??[]):null,s=this.currentRevision(),o=await Mt(),a=o?.api?.ZTypeCoreApi,c=await Wa();if(!a||!c?.executeCrdtNodeUpdateAndTransformDiff||!c.generateDiff)throw new Error("CRDT/ztype write runtime is unavailable");let u=Ff(o,this.schemaGraph,this.appDetail,await this.getExtraContext(o)),l=this.withProjectFeatures(a,()=>a.batchUpdateSchemaGraph(u,[t]));if(l?.interruptErrors?.length>0){let g={available:!0,stableErrors:[...l.interruptErrors].map(kf),betaErrors:[]};if(r.skipValidation!==!0)throw new Cn("ztype validation interrupted schema update",g)}if(!this.model)throw new Error("CRDT model not loaded");D.debug(`[Session] applying schemaDiff dataSource: ${JSON.stringify(t.dataSource).slice(0,4e3)}`);try{await this.uploadByDoc(c,t.dataSource??[],this.model)}catch(g){D.error(`[Session] CRDT apply/upload failed; reloading session to discard the diverged graph: ${g.message}`);let{undoStack:y,redoStack:E}=this;try{await this.loadLocked(!0),this.undoStack=y,this.redoStack=E}catch(S){D.error(`[Session] reload after the failed write failed too; unloading the session so the next command loads it again: ${S.message}`),this.model=null,this.snapshot=null,this.schemaGraph=null,this.schemaExId=null,this.diagnosedFor=null,this.staleReason="a write failed and the reload after it failed too"}throw g}this.schemaGraph=l.updatedGraph,this.snapshot=this.currentView();let d=await this.refreshZtypeDiagnostics(),p=this.updateRevision(),h=i&&s&&i.server!==this.snapshot.server?await $E({version:i.version,server:i.server},{version:this.snapshot.version,server:this.snapshot.server}):null;return h&&qf(h)&&s&&p&&this.appendSchemaEvent("local",s,p,h),i&&await this.recordUndoEntry(i,this.snapshot,h&&qf(h)?h:null).catch(g=>D.warn(`[Session] the write landed but its undo entry could not be recorded: ${g.message}`)),{...this.status(),ztypeDiagnostics:d,backendErrorCount:iL(d),_schema:h&&qf(h)?{change:h}:void 0}}async uploadByDoc(t,r,n){let i=this.serverDoc,s=i?r.filter(Vf):[],o=i?r.filter(c=>!Vf(c)):r,a=i&&s.length>0&&o.length>0?rL(i.model.view()):null;if(i&&s.length>0)for(let c of await this.uploadDocPatch(t,s,i.model,null,i.schemaExId))i.appliedPatchExIds.add(c.exId),i.lastPatchExId=c.exId;if(o.length!==0)try{for(let c of await this.uploadDocPatch(t,o,n,this.sessionKey.appExId??null,this.schemaExId))this.appliedPatchExIds.add(c.exId),this.lastPatchExId=c.exId}catch(c){if(i&&a){let u=[];t.generateDiff({before:i.model.view(),after:a,prefix:[],result:u}),u.length>0&&await this.uploadDocPatch(t,u,i.model,null,i.schemaExId).catch(l=>{throw new Error(`The server half of this change was saved to the backend app's document, but the client half failed (${c.message}) and reverting the server half failed too (${l.message}). Those server changes are live without their client counterparts: read the schema again before retrying, or the retry applies them a second time.`)})}throw c}}async uploadDocPatch(t,r,n,i,s){let o=t.executeCrdtNodeUpdateAndTransformDiff(r,n,this.snapshot,sL),a=za(),c=await IL(this.client);return(await this.client.request(zP,{projectExId:this.sessionKey.projectExId,appExId:i,schemaExId:s,patches:[{content:{id:a,dataSource:o.diffsFromCrdt},patchBase64:o.patchBase64,uuid:a,...c}]})).batchCreateSchemaCrdtPatch??[]}async checkRemoteAndSyncLocked(t){if(!this.model||!this.schemaExId||!this.snapshot)return await this.loadLocked(),null;let r=this.currentRevision();if(!r)return null;let n={version:this.snapshot.version,server:this.snapshot.server},s=(await this.client.request(Ei,this.sessionKey)).fetchAppDetailByExId,o=Ya(s);if(!o?.exId)return null;let a=o.crdtPatches?.lastPatchExId??null,c=o.exId,u=DE(s);if(!await this.syncServerDocLocked()&&c===this.schemaExId&&a===this.lastPatchExId&&u===this.lastRevision?.deployedSchemaExId)return this.appDetail=s??this.appDetail,this.updateRevision(),null;c!==this.schemaExId||!o.crdtModelUrl?await this.loadLocked(!0):(this.appDetail=s??this.appDetail,await this.applyNetworkPatches(o.crdtPatches?.patches??[]),this.model&&(this.snapshot=this.currentView(),await this.resolveZtypeGraph(),await this.refreshZtypeDiagnostics()),this.lastPatchExId=a,this.updateRevision());let d=this.currentRevision();if(!d||!pL(r,d))return null;let p=await $E(n,{version:this.snapshot?.version,server:this.snapshot?.server});return this.appendSchemaEvent(t==="watch"?"remote":t,r,d,p),{type:"SCHEMA_STALE",message:"Project schema changed since this session last used it; session was refreshed before executing the command.",projectExId:this.sessionKey.projectExId,fromRevision:r,toRevision:d,semanticChanges:p,detectedAt:new Date().toISOString()}}currentRevision(){return this.lastRevision??this.updateRevision()}updateRevision(){return!this.snapshot&&!this.crdtBinary?(this.lastRevision=null,null):(this.lastRevision=dL({projectExId:this.sessionKey.projectExId,appExId:this.sessionKey.appExId??this.appDetail?.appExId??null,appVersionExId:this.sessionKey.appVersionExId??null,schemaExId:this.schemaExId,lastPatchExId:this.lastPatchExId,snapshot:this.snapshot??{binaryBytes:this.crdtBinary?.byteLength??null},deployedSchemaExId:DE(this.appDetail)}),this.lastRevision)}appendSchemaEvent(t,r,n,i){let s={id:za(),type:"SCHEMA_CHANGED",source:t,projectExId:this.sessionKey.projectExId,fromRevision:r,toRevision:n,semanticChanges:i,detectedAt:new Date().toISOString()};this.events.push(s),this.events=this.events.slice(-r7),this.onSchemaEvent?.(s)}async runWatchRefresh(){let t=this.lastUsedAt;try{await this.mutex.run(async()=>{await this.withErrorState(async()=>this.checkRemoteAndSyncLocked("watch"))})}catch(r){D.warn("Schema watch refresh failed",r.message)}finally{this.lastUsedAt=t}}dispose(){this.watcher.dispose()}async initializeRuntime(t,r,n){let i=await Wa();if(!i?.initModelByBinary){this.model=null,this.snapshot={binaryBytes:t.length,patches:r},this.schemaGraph=null,this.diagnosedFor=null,this.appDetail=n,this.staleReason="CRDT runtime unavailable";return}this.model=i.initModelByBinary(t),await this.applyNetworkPatches(r),this.model&&(Ja(n)&&(this.serverDoc=await this.loadServerDoc(i).catch(s=>(D.warn("Backend app document unavailable; loading this client app's own document alone",s.message),null))),this.snapshot=this.currentView(),await this.resolveZtypeGraph(),await this.refreshZtypeDiagnostics())}async applyNetworkPatches(t){let r=t.filter(i=>!!(i?.exId&&!this.appliedPatchExIds.has(i.exId)));if(!this.model||r.length===0)return;let n=await xE();if(!n?.fromBinary)throw new Error("json-joy Patch runtime is unavailable");this.model.applyBatch(r.map(i=>n.fromBinary(Buffer.from(i.patchBase64,"base64"))));for(let i of r)this.appliedPatchExIds.add(i.exId),this.lastPatchExId=i.exId;this.snapshot=this.currentView()}async loadServerDoc(t){let r=await this.client.request(Ei,{projectExId:this.sessionKey.projectExId}),n=Ya(r.fetchAppDetailByExId);if(!n?.crdtModelUrl||!n.exId||!t.initModelByBinary)throw new Error("Could not load the backend app's document this client app's server half lives in");let i={model:t.initModelByBinary(await RE(n.crdtModelUrl)),schemaExId:n.exId,lastPatchExId:null,appliedPatchExIds:new Set};return await this.applyServerPatches(i,n.crdtPatches?.patches??[]),i.lastPatchExId=n.crdtPatches?.lastPatchExId??i.lastPatchExId,i}async applyServerPatches(t,r){let n=r.filter(s=>!!(s?.exId&&!t.appliedPatchExIds.has(s.exId)));if(n.length===0)return!1;let i=await xE();if(!i?.fromBinary)throw new Error("json-joy Patch runtime is unavailable");t.model.applyBatch(n.map(s=>i.fromBinary(Buffer.from(s.patchBase64,"base64"))));for(let s of n)t.appliedPatchExIds.add(s.exId),t.lastPatchExId=s.exId;return!0}async syncServerDocLocked(){let t=this.serverDoc;if(!t)return!1;let r=await this.client.request(Ei,{projectExId:this.sessionKey.projectExId}),n=Ya(r.fetchAppDetailByExId);if(!n?.exId)return!1;let i=n.crdtPatches?.lastPatchExId??null;return n.exId===t.schemaExId&&i===t.lastPatchExId?!1:n.exId!==t.schemaExId?(this.serverDoc=await this.loadServerDoc(await Wa()),!0):(await this.applyServerPatches(t,n.crdtPatches?.patches??[]),t.lastPatchExId=i,!0)}async resolveZtypeGraph(){let t=await Mt(),r=t?.api;if(!r?.ZTypeCoreApi||!this.snapshot){this.schemaGraph=null,this.diagnosedFor=null,this.staleReason="ztype runtime unavailable";return}let n=r.ZTypeCoreApi.parseZSchemaFromJsObject(this.snapshot),i=await this.getExtraContext(t);this.schemaGraph=this.withProjectFeatures(r.ZTypeCoreApi,()=>r.ZTypeCoreApi.resolveZSchemaToSchemaGraph(n,i))}withProjectFeatures(t,r){return t.withEnabledFeatures(this.enabledProjectFeatureNames,r)}async getExtraContext(t){if(this.extraContextLoaded)return this.extraContext;this.extraContextLoaded=!0;try{let[r,n,i]=await Promise.all([eL(),this.client.request(aR).then(s=>s.supportedCustomModelDescriptor??null).catch(s=>(D.warn("extraContext: model descriptors unavailable",s.message),null)),this.client.request(sf,{projectExId:this.sessionKey.projectExId}).then(s=>(s.features??[]).filter(o=>o.enabled).map(o=>o.featureName)).catch(s=>(D.warn("extraContext: project features unavailable; ztype runs with every feature off",s.message),[]))]);this.enabledProjectFeatureNames=i,this.extraContext=mL(t,r,n,Ks(t))}catch(r){D.warn("extraContext build failed; resolving schema without it",r.message),this.extraContext=null}return this.extraContext}diagnosticsInputs(){return{graph:this.schemaGraph,target:`${this.appDetail?.appType??""}:${this.appDetail?.appExId??""}`,extraContext:this.extraContext,featureNames:this.enabledProjectFeatureNames}}async currentZtypeDiagnostics(){let t=this.diagnosedFor,r=this.diagnosticsInputs();return this.lastZtypeDiagnostics&&t&&Object.keys(r).every(n=>t[n]===r[n])?this.lastZtypeDiagnostics:this.refreshZtypeDiagnostics()}async refreshZtypeDiagnostics(){if(this.diagnosedFor=null,this.lastZtypeDiagnostics=null,!this.schemaGraph||!this.appDetail)return this.lastZtypeDiagnostics={available:!1,stableErrors:[],betaErrors:[],error:this.staleReason??"ztype schema graph is not loaded"},this.lastZtypeDiagnostics;let t=await Mt(),r=t?.api;if(!r?.ZTypeCoreApi||!r?.ZTypeValidationApi)return this.lastZtypeDiagnostics={available:!1,stableErrors:[],betaErrors:[],error:"ztype validation API is unavailable"},this.lastZtypeDiagnostics;let n=Ff(t,this.schemaGraph,this.appDetail,await this.getExtraContext(t)),i=this.withProjectFeatures(r.ZTypeCoreApi,()=>r.ZTypeValidationApi.validateSchemaGraph(n,gL(t,this.appDetail)));return this.lastZtypeDiagnostics={available:!0,stableErrors:[...i?.errors??i?.stableErrors??[]].map(kf),betaErrors:[...i?.warnings??i?.betaErrors??[]].map(kf)},this.diagnosedFor=this.diagnosticsInputs(),this.lastZtypeDiagnostics}touch(){this.lastUsedAt=Date.now()}async withErrorState(t){try{let r=await t();return this.lastError=null,r}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}};var Gf=class{constructor(t,r){this.clientFactory=t;this.subscriptionFactory=r}sessions=new Map;emitter=new E7;clear(){for(let t of this.sessions.values())t.dispose();this.sessions.clear()}sweep(){let t=Date.now();for(let[r,n]of this.sessions.entries())n.isExpired(t)&&(n.dispose(),this.sessions.delete(r))}status(){return this.sweep(),{projectSessionIdleTtlMs:WE,sessions:[...this.sessions.values()].map(t=>t.status())}}async load(t,r=!1){return(await this.getSession(t)).load(r)}async sync(t){return(await this.getSession(t)).sync()}async snapshot(t,r=!1){return(await this.getSession(t)).getSnapshot(r)}async dataModel(t){return(await this.getSession(t)).dataModel()}async save(t){return(await this.getSession(t)).save()}async validate(t){return(await this.getSession(t)).validate()}async ztypeToolCalls(t,r,n=!1,i=null,s=!1){return(await this.getSession(t)).ztypeToolCalls(r,n,i,s)}async currentSchemaExId(t){let r=await this.getSession(t);await r.load(!1);let n=r.status().schemaExId;return typeof n=="string"?n:null}async lastPatchExIds(t){let r=await this.getSession(t);return await r.load(!1),await r.checkRemoteAndSync(),r.lastPatchExIds()}async undo(t){return(await this.getSession(t)).undo()}async redo(t){return(await this.getSession(t)).redo()}async checkRemoteAndSync(t){return(await this.getSession(t)).checkRemoteAndSync()}schemaState(t){this.sweep();let r=[...this.sessions.values()].filter(n=>!t||n.status().projectExId===t);return{projectExId:t??null,sessions:r.map(n=>n.state())}}schemaEvents(t,r,n=100){this.sweep();let i=[...this.sessions.values()].filter(s=>!t||s.status().projectExId===t);return{projectExId:t??null,events:i.flatMap(s=>s.listEvents(r,n))}}async getSession(t){this.sweep();let r=Xa.stringifyKey(t),n=this.sessions.get(r);if(n)return n;let i=new Xa(await this.clientFactory(),t,this.subscriptionFactory,s=>{this.emitter.emit("schemaChanged",s)});return this.sessions.set(r,i),i}};function qt(e,t){return{projectExId:e,appExId:t.appExId??null,appVersionExId:t.appVersionExId??null}}f();var NL=e=>e??{},Q=e=>typeof e=="string"&&e.length>0?e:void 0,ce=e=>typeof e=="string"&&e.length>0?e:null,ke=(e,t=!1)=>typeof e=="boolean"?e:t,tt=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t,Ni=e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0,Ge=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ci=(e,t)=>{let r=Q(e);if(!r)throw new Error(`${t} is required`);return r},St=(e,t)=>{if(!t)return e;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,n=Ge(r._schema);return{...r,_schema:{...n,warning:t}}}return{result:e,_schema:{warning:t}}},_7=e=>new Promise(t=>{setTimeout(t,e)}),$f=e=>{let t=e?.name;if(typeof t!="string"||t.length===0)return null;let r=typeof e?.type=="string"?e.type:"";return/IMAGE|VIDEO|FILE/.test(r)?r.includes("LIST")?`${t}_ids`:`${t}_id`:t},CL=(e,t)=>{let n=e?.tableMetadata?.find(i=>i?.name===t)?.columnMetadata?.map(i=>$f(i))?.filter(i=>i!==null);return n?.length?n.slice(0,20):["id"]},S7=/token|secret|password|privatekey|merchantkey|mchkey|apikey/i,YE=e=>{if(Array.isArray(e))return e.map(YE);if(!e||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=S7.test(r)?"<redacted>":YE(n);return t},JE=(e,t)=>ke(t.includeSecrets,!1)?e:YE(e),PL=async(e,t)=>{let r={projectExId:Q(t.projectExId),appExId:ce(t.appExId),appVersionExId:ce(t.appVersionExId)},n=await fL(e,r);if(r.appExId!==null&&r.appExId===n)throw new Error(`appExId was given the project exId (${n}). appExId names an app inside the project, never the project itself: leave it unset to address the project (its backend, and the whole schema of a single-client project), or take an app exId from \`project metadata\` -> apps[] whose appExId is non-null.`);return{...r,projectExId:n}},RL=async(e,t)=>{let r=Q(t.organizationExId),n=Q(t.projectSpaceType);if(r&&n)return{organizationExId:r,projectSpaceType:n};let s=(await e.request(nf))?.user,o=s?.currentOrganization??s?.organization??s?.organizations?.[0]??s?.joinedOrganizations?.[0];if(!o?.exId)throw new Error("No default organization found; pass organizationExId and projectSpaceType");return{organizationExId:r??o.exId,projectSpaceType:n??"PERSONAL"}},b7=async(e,t)=>((await e.request(rf,{projectName:t,paginator:{first:20}}))?.fuzzySearchProjectName?.edges??[]).find(s=>s?.node?.name===t)?.node??null,xL=async(e,t,r)=>{let n=Date.now()+r;for(;Date.now()<n;){let i=await b7(e,t);if(i)return i;await _7(2e3)}return null},DL=(e,t,r,n=!0)=>{if(Q(t.confirmProjectExId)!==e&&!(n&&ke(t.force,!1)))throw new Error(`${r} is destructive; pass confirmProjectExId=${e}`+(n?" or force=true":""))},T7=e=>e?"project"in e?e.project:"adminToken"in e?e:null:null,w7=e=>e.replace(/\/api\/graphql-v2(\/?)$/,"/api/graphql-admin$1"),Ws=async(e,t)=>{let r=await e.request(WP,t),n=T7(r?.fetchAppDetailByExIdWithoutReconcile);if(!n?.adminToken)throw new Error(`Runtime commands need the project admin token, which only project editors get; none was returned for project ${t.projectExId}`);let i=n.zeroUrl??Ft().zeroApiUrlTemplate.replace("{projectExId}",t.projectExId),s={authorization:`Bearer ${n.adminToken}`};return{adminToken:n.adminToken,zeroUrl:i,dataClient:new it(i,{headers:s,fetch:Qs}),adminClient:new it(n.adminZeroUrl??w7(i),{headers:s,fetch:Qs})}};f();f();import{promises as O7}from"fs";import I7 from"path";var A7=async(e,t)=>{let r=Q(e.cwd);if(!r)throw new Error("cwd is required");let n=I7.resolve(r);if(!(await O7.stat(n)).isDirectory())throw new Error(`Path is not a directory: ${n}`);return t.credentialStore.setWorkspaceRoot(n),t.schemaManager.clear(),t.ok({cwd:n},`Current working directory set to ${n}`)},LL={"workspace.set":A7};f();var UL=He(No(),1);f();import{createServer as kL}from"http";import N7 from"open";var Za=class{config;constructor(t){this.config=t}async findAvailablePort(t){let r=t||this.config.callbackPort||8088;return new Promise((n,i)=>{let s=kL();s.on("error",o=>{o.code==="EADDRINUSE"?n(this.findAvailablePort(r+1)):i(o)}),s.listen(r,()=>{let o=s.address(),a=typeof o=="object"&&o!==null?o.port:r;s.close(()=>n(a))})})}async authenticate(){let t=await this.findAvailablePort(),r=`http://localhost:${t}/callback`;D.info(`[JwtAuth] Using callback URL: ${r}`),D.info("[JwtAuth] Opening browser for authentication...");let n=await new Promise((i,s)=>{let o=null,a=!1,c=kL(async(u,l)=>{if(!u.url)return;let d=new URL(u.url,`http://localhost:${t}`);if(d.pathname==="/callback"){D.info(`[JwtAuth] Callback received: ${u.url}`);let p=d.searchParams.get("token");if(!p||p.trim()===""){D.info("[JwtAuth] No token parameter found in callback URL"),D.info("[JwtAuth] Available parameters:",Array.from(d.searchParams.keys()).join(", "));let g=this.errorPage("No authentication token received");l.writeHead(400,{"Content-Type":"text/html"}),l.end(g),a||(a=!0,o&&clearTimeout(o),c.close(),s(new Error("No token parameter in callback")));return}D.info(`[JwtAuth] Token received (length: ${p.length} chars)`);let h=this.successPage();l.writeHead(200,{"Content-Type":"text/html"}),l.end(h),setTimeout(()=>{a||(a=!0,o&&clearTimeout(o),c.close(),i(p))},1e3)}});c.on("error",u=>{a||(a=!0,o&&clearTimeout(o),s(u))}),c.listen(t,async()=>{let u=new URL(this.config.authEndpoint);u.searchParams.set("redirect_uri",r),D.info(`[JwtAuth] Opening: ${u.toString()}`);try{await N7(u.toString())}catch{D.info("[JwtAuth] Could not open browser automatically"),D.info("[JwtAuth] Please open this URL manually:"),D.info(u.toString())}}),o=setTimeout(()=>{a||(a=!0,c.close(),s(new Error("Authentication timeout - no response after 5 minutes")))},3e5)});return D.info("[JwtAuth] JWT token received successfully"),{access_token:n,token_type:"Bearer"}}renderPage(t){let r=t.autoClose?`
1446
1446
  <script>
1447
1447
  setTimeout(() => {
1448
1448
  window.close();
@@ -1535,7 +1535,7 @@ ${zf(t," ")}
1535
1535
  }
1536
1536
  }`),mk=()=>`mutation AgentRunCode($jsCode: String!, $args: JsonObject, $updateDb: Boolean!) {
1537
1537
  fz_debug_action_code(jsCode: $jsCode, args: $args, updateDb: $updateDb)
1538
- }`;var Gee=20,$ee=200,Bee=20,n_="id",i_=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ek=e=>Array.isArray(e)?e:[],Kee=(e,t)=>typeof e=="boolean"?e:e==null?t:String(e).toLowerCase()==="true",gk=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):t,yk=(e,t)=>{let r=e[t];if(typeof r!="string"||r.trim()==="")throw new Error(`'${t}' is required.`);return r},vk=(e,t,r)=>{let n=i_(e.where);if(Object.keys(n).length>0)return n;if(e[r]===!0)return{};throw new Error(`'where' is required and must not be empty \u2014 this ${t} runs against the live app and there is no change-everything option.`)},Xf=(e,t)=>{let r=Ek(e.fields).filter(n=>typeof n=="string"&&n.trim()!=="");return r.length>0?(r_(r,"fields"),r):t.length>0?t.slice(0,Bee):[n_]},Hee=e=>e.includes(n_)?e:[n_,...e],s_=(e,t,r=[])=>{if(e==="runtime.run_code")return{document:mk(),variables:{jsCode:yk(t,"jsCode"),args:i_(t.args),updateDb:Kee(t.updateDb,!1)},rootField:"fz_debug_action_code"};let n=yk(t,"tableName");switch(xn(n,"tableName"),e){case"runtime.query":return{document:lk(n,Xf(t,r)),variables:{where:t.where??{},limit:Math.min(gk(t.limit,Gee),$ee),offset:gk(t.offset,0),order_by:t.orderBy??null},rootField:n};case"runtime.aggregate":return{document:fk(n),variables:{where:t.where??{}},rootField:`${n}_aggregate`};case"runtime.insert":{let i=Ek(t.objects);if(i.length===0)throw new Error("'objects' must contain at least one row to insert.");if(i.some(s=>!s||typeof s!="object"||Array.isArray(s)))throw new Error("every entry in 'objects' must be an object of column values.");return{document:dk(n,Hee(Xf(t,r))),variables:{objects:i},rootField:`insert_${n}`}}case"runtime.update":{let i=vk(t,"update","allowUpdateAll"),s=i_(t.set);if(Object.keys(s).length===0)throw new Error("'set' must contain at least one column to change.");return{document:pk(n,Xf(t,r)),variables:{where:i,set:s},rootField:`update_${n}`}}case"runtime.delete":return{document:hk(n,Xf(t,r)),variables:{where:vk(t,"delete","allowDeleteAll")},rootField:`delete_${n}`};default:throw new Error(`'${e}' is not a planned runtime operation.`)}},_k=e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let t=Object.keys(e);return t.length===1?e[t[0]]:e};async function nc(e,t,r,n){let i=await r.checkSchema(t),s=await r.getProjectArgs(t),o=Ci(t.tableName,"tableName"),[a,c]=await Promise.all([r.schemaManager.dataModel(qt(s.projectExId,s)),Ws(r.client,s)]);uk(a,o,Ni(t.fields));let u=s_(e,{...t,tableName:o},CL(a,o)),l;try{l=await c.dataClient.request(u.document,u.variables)}catch(d){throw ck(d,o,a)}return r.ok(St(n?_k(l):l,i))}var Qee=async(e,t)=>{let r=await t.checkSchema(e),n=await t.getProjectArgs(e),i=Ci(e.query,"query"),o=await(await Ws(t.client,n)).dataClient.request(i,e.variables??{});return t.ok(St(o,r))},Wee=async(e,t)=>nc("runtime.query",e,t,!1),Yee=async(e,t)=>nc("runtime.aggregate",e,t,!1),Jee=async(e,t)=>nc("runtime.insert",e,t,!0),zee=async(e,t)=>nc("runtime.update",e,t,!0),Xee=async(e,t)=>nc("runtime.delete",e,t,!0),Zee=async(e,t)=>{let r=await t.getProjectArgs(e),n=s_("runtime.run_code",e),s=await(await Ws(t.client,r)).adminClient.request(n.document,n.variables);return t.ok({keptWrites:n.variables.updateDb===!0,result:s?.fz_debug_action_code})},Sk={"runtime.graphql":Qee,"runtime.run_code":Zee,"runtime.query":Wee,"runtime.aggregate":Yee,"runtime.insert":Jee,"runtime.update":zee,"runtime.delete":Xee};f();var ete=["GATEWAY","ACTION_FLOW","ACTION_FLOW_NODE","ACTION_FLOW_CONTEXT_LOG","DEPLOYMENT","TPA","TRIGGER","SQL_GENERATION","GQL","ZAI"],tte=["INFO","WARNING","ERROR"],rte=50,nte=100,bk=5,Tk=e=>`${e.toISOString().slice(0,19)}Z`,ite=e=>{if(!e)return new Date;let t=new Date(e);return Number.isNaN(t.getTime())?new Date:t},wk=(e,t)=>{if(!e)return;let r=e.map(n=>n.toUpperCase()).filter(n=>t.includes(n));return r.length>0?r:void 0},ste=async(e,t)=>{let r=await t.getProjectArgs(e),{adminToken:n}=await Ws(t.client,r),i=ite(Q(e.requestCreatedAt)),s={start:Tk(new Date(i.getTime()-bk*6e4)),end:Tk(new Date(i.getTime()+bk*6e4)),desc:!0},o=wk(Ni(e.types),ete);o&&(s.type=o);let a=wk(Ni(e.levels),tte);a&&(s.level=a);let c=Q(e.customQueryCondition);c&&(s.customQueryCondition=c);let u=Math.min(nte,tt(e.limit,rte)),l=Ft().logApiUrlTemplate.replace("{projectExId}",r.projectExId),h=((await new it(l,{headers:{authorization:`Bearer ${n}`},fetch:Qs}).request(wR,{queryCreation:s,paginator:{first:u}}))?.fetchLogsByPaginator?.edges??[]).map(g=>g?.node).filter(g=>!!g);return t.ok({entries:h})},Ok={"logs.search":ste};f();f();var ote=async()=>(await import("./corpus-XVQ4ZV2V.js")).DOCS_CORPUS,ate=3,Ik=null,cte=e=>{let t=new Map;for(let r of e)t.set(r.path,r);for(let r of e)for(let n of r.aliases??[])t.has(n)||t.set(n,r);return t},ute=e=>{let t=e.map(r=>{let n=vp(r.content),i=vp(r.title);for(let s=0;s<ate;s+=1)n.push(...i);return{ref:r,tokens:n}});return{index:bb(t),byPath:cte(e)}},Ak=async()=>(Ik??=ute(await ote()),Ik),Nk=async(e,t=10)=>{let{index:r}=await Ak();return Tb(r,e).filter(n=>n.score>0).sort((n,i)=>i.score-n.score).slice(0,Math.max(1,t)).map(n=>({path:n.ref.path,title:n.ref.title,url:n.ref.url}))},lte=e=>{let t=e.trim().replace(/\.mdx$/,"").replace(/^\/+/,"/").replace(/\/+$/,"");return t===""||t==="/"?"/":t.startsWith("/")?t:`/${t}`},Ck=async e=>(await Ak()).byPath.get(lte(e))??null;var fte=async(e,t)=>{let r=Q(e.query);if(!r)throw new Error("query is required");let n=tt(e.limit,10);return t.ok({results:await Nk(r,n)})},dte=async(e,t)=>{let r=Q(e.path);if(!r)throw new Error("path is required");let n=await Ck(r);if(!n)throw new Error(`No doc page found for path: ${r}`);return t.ok(n)},Pk={"docs.search":fte,"docs.get_page":dte};f();var pte=async(e,t)=>{let r=Q(e.query);if(!r)throw new Error("query is required");let n=e.variables&&typeof e.variables=="object"?e.variables:{};return t.ok(await t.client.request(r,n))},Rk={"platform.graphql":pte};f();var hte=async(e,t)=>{let r=await Mt(),n=r?.api?.ZTypePredefinedApi;if(!n)return t.fail(new Error("ztype predefined template API is unavailable"));let s=n.getActionFlowTemplates(Ks(r)).map(o=>({templateCodeId:o.preDefinedCodeId,displayName:o.displayName,group:o.directory,async:o.async,inputs:o.input,outputs:o.output}));return t.ok({templates:s})},xk={"actionflow.list_node_templates":hte};f();var mte=e=>{if(!e)return null;let t=e.split("?")[0]?.split("/").pop();if(!t)return null;let r=t.replace(/\.[a-z0-9]+$/i,"");return r.length>0?r:null},gte=async(e,t)=>{let n=(await t.client.request(UP)).getTabBarIcons.flatMap(i=>i?[{name:mte(i.url),exId:i.exId}]:[]);return t.ok({icons:n,note:n.length===0?"This deployment ships no preset tab-bar icons; upload one in the editor and use its exId.":"A name ending in _selected is the pressed-state partner of the icon with the same prefix; for the plain icons use the same exId for both states."})},Dk={"component.tab_bar_icons":gte};f();var Fq=He(bq(),1);f();function Bse(e){let t;try{t=new URL(e)}catch{throw new Error(`Unsupported or malformed URL: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Only http/https URLs are allowed: ${e}`);return t}async function Kse(e,t){let r=e.body?.getReader();if(!r)throw new Error(`Empty response body from ${t}`);let n=[],i=0;for(;;){let{done:s,value:o}=await r.read();if(s)break;if(i+=o.byteLength,i>10485760)throw await r.cancel(),new Error("Response exceeds size limit of 10485760 bytes");n.push(o)}return Buffer.concat(n).toString("utf8")}async function US(e){let t=e;for(let r=0;r<=5;r++){let n=Bse(t),i=await fetch(n,{redirect:"manual",signal:AbortSignal.timeout(2e4),headers:{Accept:"application/json, application/yaml, text/yaml, text/html, */*","User-Agent":"Momen-Agent-TpaImport"}});if(i.status>=300&&i.status<400){let s=i.headers.get("location");if(await i.body?.cancel(),!s)throw new Error(`Redirect without Location from ${t}`);t=new URL(s,n).toString();continue}if(!i.ok)throw await i.body?.cancel(),new Error(`HTTP ${i.status} fetching ${t}`);return{finalUrl:n.toString(),contentType:i.headers.get("content-type"),body:await Kse(i,t)}}throw new Error(`Too many redirects fetching ${e}`)}f();var Hse=/(?:href|src|url)\s*[=:]\s*["']?([^"'\s>)]+)/gi,Qse=/<(script|style|noscript|svg|iframe|canvas|template|nav|footer|aside)\b[\s\S]*?<\/\1\s*>/gi,Wse=new Set(["css","js","png","jpg","jpeg","gif","svg","ico","woff","woff2","ttf","webp","mp4","zip","pdf"]);function Tq(e,t){if(e&&e.toLowerCase().includes("html"))return!0;let r=t.trimStart();return r.startsWith("<")&&!r.startsWith("<?xml")}function wq(e){let t=e.length>4e3?e.slice(0,4e3):e;return t.includes('"openapi"')||t.includes('"swagger"')||/(^|\n)\s*openapi\s*:/.test(t)||/(^|\n)\s*swagger\s*:/.test(t)}function Oq(e,t){try{return new URL(t,e).toString()}catch{return t.startsWith("http")?t:null}}var Yse=/^https?:\/\/app\.swaggerhub\.com\/apis(?:-docs)?\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)/i;function Jse(e){let t=e.match(Yse);return t?`https://api.swaggerhub.com/apis/${t[1]}/${t[2]}/${t[3]}`:null}function Iq(e,t){let r=[],n=i=>{i&&r.length<20&&!r.includes(i)&&r.push(i)};for(let i of e.matchAll(Hse)){if(r.length>=20)break;let s=i[1],o=s.toLowerCase();if(!(o.includes("openapi")||o.includes("swagger")||(o.endsWith(".json")||o.endsWith(".yaml")||o.endsWith(".yml"))&&o.includes("api")))continue;let c=Oq(t,s);n(c&&Jse(c)),n(c)}return r}function Aq(e,t){let r=[],n;try{n=new URL(t).host}catch{return r}for(let i of e.matchAll(/<a\b[^>]*href\s*=\s*["']([^"'#]+)[^"']*["']/gi)){if(r.length>=40)break;let s;try{s=new URL(i[1],t)}catch{continue}if(s.host!==n)continue;s.hash="";let o=s.toString(),a=s.pathname.toLowerCase(),c=a.slice(a.lastIndexOf(".")+1);Wse.has(c)||o===t||r.includes(o)||r.push(o)}return r}var zse={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",copy:"\xA9"};function VS(e){return e.replace(/&#x([0-9a-f]+);/gi,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/&#(\d+);/g,(t,r)=>String.fromCodePoint(parseInt(r,10))).replace(/&([a-z]+);/gi,(t,r)=>zse[r.toLowerCase()]??t)}var Lc=e=>e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();function Nq(e,t){let r=e.replace(/<!--[\s\S]*?-->/g,"").replace(Qse,"");return r=r.replace(/<pre\b[^>]*>([\s\S]*?)<\/pre\s*>/gi,(n,i)=>`
1538
+ }`;var Gee=20,$ee=200,Bee=20,n_="id",i_=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ek=e=>Array.isArray(e)?e:[],Kee=(e,t)=>typeof e=="boolean"?e:e==null?t:String(e).toLowerCase()==="true",gk=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):t,yk=(e,t)=>{let r=e[t];if(typeof r!="string"||r.trim()==="")throw new Error(`'${t}' is required.`);return r},vk=(e,t,r)=>{let n=i_(e.where);if(Object.keys(n).length>0)return n;if(e[r]===!0)return{};throw new Error(`'where' is required and must not be empty \u2014 this ${t} runs against the live app and there is no change-everything option.`)},Xf=(e,t)=>{let r=Ek(e.fields).filter(n=>typeof n=="string"&&n.trim()!=="");return r.length>0?(r_(r,"fields"),r):t.length>0?t.slice(0,Bee):[n_]},Hee=e=>e.includes(n_)?e:[n_,...e],s_=(e,t,r=[])=>{if(e==="runtime.run_code")return{document:mk(),variables:{jsCode:yk(t,"jsCode"),args:i_(t.args),updateDb:Kee(t.updateDb,!1)},rootField:"fz_debug_action_code"};let n=yk(t,"tableName");switch(xn(n,"tableName"),e){case"runtime.query":return{document:lk(n,Xf(t,r)),variables:{where:t.where??{},limit:Math.min(gk(t.limit,Gee),$ee),offset:gk(t.offset,0),order_by:t.orderBy??null},rootField:n};case"runtime.aggregate":return{document:fk(n),variables:{where:t.where??{}},rootField:`${n}_aggregate`};case"runtime.insert":{let i=Ek(t.objects);if(i.length===0)throw new Error("'objects' must contain at least one row to insert.");if(i.some(s=>!s||typeof s!="object"||Array.isArray(s)))throw new Error("every entry in 'objects' must be an object of column values.");return{document:dk(n,Hee(Xf(t,r))),variables:{objects:i},rootField:`insert_${n}`}}case"runtime.update":{let i=vk(t,"update","allowUpdateAll"),s=i_(t.set);if(Object.keys(s).length===0)throw new Error("'set' must contain at least one column to change.");return{document:pk(n,Xf(t,r)),variables:{where:i,set:s},rootField:`update_${n}`}}case"runtime.delete":return{document:hk(n,Xf(t,r)),variables:{where:vk(t,"delete","allowDeleteAll")},rootField:`delete_${n}`};default:throw new Error(`'${e}' is not a planned runtime operation.`)}},_k=e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;let t=Object.keys(e);return t.length===1?e[t[0]]:e};async function nc(e,t,r,n){let i=await r.checkSchema(t),s=await r.getProjectArgs(t),o=Ci(t.tableName,"tableName"),[a,c]=await Promise.all([r.schemaManager.dataModel(qt(s.projectExId,s)),Ws(r.client,s)]);uk(a,o,Ni(t.fields));let u=s_(e,{...t,tableName:o},CL(a,o)),l;try{l=await c.dataClient.request(u.document,u.variables)}catch(d){throw ck(d,o,a)}return r.ok(St(n?_k(l):l,i))}var Qee=async(e,t)=>{let r=await t.checkSchema(e),n=await t.getProjectArgs(e),i=Ci(e.query,"query"),o=await(await Ws(t.client,n)).dataClient.request(i,e.variables??{});return t.ok(St(o,r))},Wee=async(e,t)=>nc("runtime.query",e,t,!1),Yee=async(e,t)=>nc("runtime.aggregate",e,t,!1),Jee=async(e,t)=>nc("runtime.insert",e,t,!0),zee=async(e,t)=>nc("runtime.update",e,t,!0),Xee=async(e,t)=>nc("runtime.delete",e,t,!0),Zee=async(e,t)=>{let r=await t.getProjectArgs(e),n=s_("runtime.run_code",e),s=await(await Ws(t.client,r)).adminClient.request(n.document,n.variables);return t.ok({keptWrites:n.variables.updateDb===!0,result:s?.fz_debug_action_code})},Sk={"runtime.graphql":Qee,"runtime.run_code":Zee,"runtime.query":Wee,"runtime.aggregate":Yee,"runtime.insert":Jee,"runtime.update":zee,"runtime.delete":Xee};f();var ete=["GATEWAY","ACTION_FLOW","ACTION_FLOW_NODE","ACTION_FLOW_CONTEXT_LOG","DEPLOYMENT","TPA","TRIGGER","SQL_GENERATION","GQL","ZAI"],tte=["INFO","WARNING","ERROR"],rte=50,nte=100,bk=5,Tk=e=>`${e.toISOString().slice(0,19)}Z`,ite=e=>{if(!e)return new Date;let t=new Date(e);return Number.isNaN(t.getTime())?new Date:t},wk=(e,t)=>{if(!e)return;let r=e.map(n=>n.toUpperCase()).filter(n=>t.includes(n));return r.length>0?r:void 0},ste=async(e,t)=>{let r=await t.getProjectArgs(e),{adminToken:n}=await Ws(t.client,r),i=ite(Q(e.requestCreatedAt)),s={start:Tk(new Date(i.getTime()-bk*6e4)),end:Tk(new Date(i.getTime()+bk*6e4)),desc:!0},o=wk(Ni(e.types),ete);o&&(s.type=o);let a=wk(Ni(e.levels),tte);a&&(s.level=a);let c=Q(e.customQueryCondition);c&&(s.customQueryCondition=c);let u=Math.min(nte,tt(e.limit,rte)),l=Ft().logApiUrlTemplate.replace("{projectExId}",r.projectExId),h=((await new it(l,{headers:{authorization:`Bearer ${n}`},fetch:Qs}).request(wR,{queryCreation:s,paginator:{first:u}}))?.fetchLogsByPaginator?.edges??[]).map(g=>g?.node).filter(g=>!!g);return t.ok({entries:h})},Ok={"logs.search":ste};f();f();var ote=async()=>(await import("./corpus-5HA6PGP5.js")).DOCS_CORPUS,ate=3,Ik=null,cte=e=>{let t=new Map;for(let r of e)t.set(r.path,r);for(let r of e)for(let n of r.aliases??[])t.has(n)||t.set(n,r);return t},ute=e=>{let t=e.map(r=>{let n=vp(r.content),i=vp(r.title);for(let s=0;s<ate;s+=1)n.push(...i);return{ref:r,tokens:n}});return{index:bb(t),byPath:cte(e)}},Ak=async()=>(Ik??=ute(await ote()),Ik),Nk=async(e,t=10)=>{let{index:r}=await Ak();return Tb(r,e).filter(n=>n.score>0).sort((n,i)=>i.score-n.score).slice(0,Math.max(1,t)).map(n=>({path:n.ref.path,title:n.ref.title,url:n.ref.url}))},lte=e=>{let t=e.trim().replace(/\.mdx$/,"").replace(/^\/+/,"/").replace(/\/+$/,"");return t===""||t==="/"?"/":t.startsWith("/")?t:`/${t}`},Ck=async e=>(await Ak()).byPath.get(lte(e))??null;var fte=async(e,t)=>{let r=Q(e.query);if(!r)throw new Error("query is required");let n=tt(e.limit,10);return t.ok({results:await Nk(r,n)})},dte=async(e,t)=>{let r=Q(e.path);if(!r)throw new Error("path is required");let n=await Ck(r);if(!n)throw new Error(`No doc page found for path: ${r}`);return t.ok(n)},Pk={"docs.search":fte,"docs.get_page":dte};f();var pte=async(e,t)=>{let r=Q(e.query);if(!r)throw new Error("query is required");let n=e.variables&&typeof e.variables=="object"?e.variables:{};return t.ok(await t.client.request(r,n))},Rk={"platform.graphql":pte};f();var hte=async(e,t)=>{let r=await Mt(),n=r?.api?.ZTypePredefinedApi;if(!n)return t.fail(new Error("ztype predefined template API is unavailable"));let s=n.getActionFlowTemplates(Ks(r)).map(o=>({templateCodeId:o.preDefinedCodeId,displayName:o.displayName,group:o.directory,async:o.async,inputs:o.input,outputs:o.output}));return t.ok({templates:s})},xk={"actionflow.list_node_templates":hte};f();var mte=e=>{if(!e)return null;let t=e.split("?")[0]?.split("/").pop();if(!t)return null;let r=t.replace(/\.[a-z0-9]+$/i,"");return r.length>0?r:null},gte=async(e,t)=>{let n=(await t.client.request(UP)).getTabBarIcons.flatMap(i=>i?[{name:mte(i.url),exId:i.exId}]:[]);return t.ok({icons:n,note:n.length===0?"This deployment ships no preset tab-bar icons; upload one in the editor and use its exId.":"A name ending in _selected is the pressed-state partner of the icon with the same prefix; for the plain icons use the same exId for both states."})},Dk={"component.tab_bar_icons":gte};f();var Fq=He(bq(),1);f();function Bse(e){let t;try{t=new URL(e)}catch{throw new Error(`Unsupported or malformed URL: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Only http/https URLs are allowed: ${e}`);return t}async function Kse(e,t){let r=e.body?.getReader();if(!r)throw new Error(`Empty response body from ${t}`);let n=[],i=0;for(;;){let{done:s,value:o}=await r.read();if(s)break;if(i+=o.byteLength,i>10485760)throw await r.cancel(),new Error("Response exceeds size limit of 10485760 bytes");n.push(o)}return Buffer.concat(n).toString("utf8")}async function US(e){let t=e;for(let r=0;r<=5;r++){let n=Bse(t),i=await fetch(n,{redirect:"manual",signal:AbortSignal.timeout(2e4),headers:{Accept:"application/json, application/yaml, text/yaml, text/html, */*","User-Agent":"Momen-Agent-TpaImport"}});if(i.status>=300&&i.status<400){let s=i.headers.get("location");if(await i.body?.cancel(),!s)throw new Error(`Redirect without Location from ${t}`);t=new URL(s,n).toString();continue}if(!i.ok)throw await i.body?.cancel(),new Error(`HTTP ${i.status} fetching ${t}`);return{finalUrl:n.toString(),contentType:i.headers.get("content-type"),body:await Kse(i,t)}}throw new Error(`Too many redirects fetching ${e}`)}f();var Hse=/(?:href|src|url)\s*[=:]\s*["']?([^"'\s>)]+)/gi,Qse=/<(script|style|noscript|svg|iframe|canvas|template|nav|footer|aside)\b[\s\S]*?<\/\1\s*>/gi,Wse=new Set(["css","js","png","jpg","jpeg","gif","svg","ico","woff","woff2","ttf","webp","mp4","zip","pdf"]);function Tq(e,t){if(e&&e.toLowerCase().includes("html"))return!0;let r=t.trimStart();return r.startsWith("<")&&!r.startsWith("<?xml")}function wq(e){let t=e.length>4e3?e.slice(0,4e3):e;return t.includes('"openapi"')||t.includes('"swagger"')||/(^|\n)\s*openapi\s*:/.test(t)||/(^|\n)\s*swagger\s*:/.test(t)}function Oq(e,t){try{return new URL(t,e).toString()}catch{return t.startsWith("http")?t:null}}var Yse=/^https?:\/\/app\.swaggerhub\.com\/apis(?:-docs)?\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)/i;function Jse(e){let t=e.match(Yse);return t?`https://api.swaggerhub.com/apis/${t[1]}/${t[2]}/${t[3]}`:null}function Iq(e,t){let r=[],n=i=>{i&&r.length<20&&!r.includes(i)&&r.push(i)};for(let i of e.matchAll(Hse)){if(r.length>=20)break;let s=i[1],o=s.toLowerCase();if(!(o.includes("openapi")||o.includes("swagger")||(o.endsWith(".json")||o.endsWith(".yaml")||o.endsWith(".yml"))&&o.includes("api")))continue;let c=Oq(t,s);n(c&&Jse(c)),n(c)}return r}function Aq(e,t){let r=[],n;try{n=new URL(t).host}catch{return r}for(let i of e.matchAll(/<a\b[^>]*href\s*=\s*["']([^"'#]+)[^"']*["']/gi)){if(r.length>=40)break;let s;try{s=new URL(i[1],t)}catch{continue}if(s.host!==n)continue;s.hash="";let o=s.toString(),a=s.pathname.toLowerCase(),c=a.slice(a.lastIndexOf(".")+1);Wse.has(c)||o===t||r.includes(o)||r.push(o)}return r}var zse={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",copy:"\xA9"};function VS(e){return e.replace(/&#x([0-9a-f]+);/gi,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/&#(\d+);/g,(t,r)=>String.fromCodePoint(parseInt(r,10))).replace(/&([a-z]+);/gi,(t,r)=>zse[r.toLowerCase()]??t)}var Lc=e=>e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();function Nq(e,t){let r=e.replace(/<!--[\s\S]*?-->/g,"").replace(Qse,"");return r=r.replace(/<pre\b[^>]*>([\s\S]*?)<\/pre\s*>/gi,(n,i)=>`
1539
1539
  \`\`\`
1540
1540
  ${VS(Xse(i))}
1541
1541
  \`\`\`
@@ -1585,7 +1585,7 @@ Ask when ambiguous. Ground every call in what you retrieved \u2014 never fabrica
1585
1585
  `);let s;try{s=await r.installFirst(qc(e))}catch(o){return{kind:"FAILED",reason:o instanceof Error?o.message:String(o)}}return{kind:"RERAN",status:await mb(r,s,t)}}async function AF(e,t=new go,r){if(!yo(r))return;let n=await e();n.status==="outdated"&&lo(n)&&await t.installFirst(qc(n))}var NF=`__MCP_UPGRADE_HANDOVER_${sce()}__`,oce=4e4,ace=3e4,cce=600*1e3,uce=2e3,lce=`${te} upgraded itself from`,fce=/^(MCP error -?\d+: )?Tool \S+ not found/,dce=/^(MCP error -?\d+: )?Input validation error/,pce=new Set(["logging/setLevel","resources/subscribe","resources/unsubscribe"]),hce=["notifications/tools/list_changed","notifications/prompts/list_changed","notifications/resources/list_changed"],CF=e=>"method"in e&&"id"in e,RF=e=>"id"in e&&!("method"in e),fp=class{constructor(t){this.options=t}onmessage;onclose;onerror;pending=new Map;initializeRequest=null;negotiatedProtocol=null;logLevelRequest=null;subscriptions=new Map;upgrade=null;relay=null;toolsRelisted=new zS;startedAt=Date.now();upgradeNoted=!1;async start(){let{inner:t}=this.options;t.onmessage=(r,n)=>this.fromHost(r,n),t.onclose=()=>this.onclose?.(),t.onerror=r=>this.onerror?.(r),await t.start()}async close(){this.relay?.close(),await this.options.inner.close()}setProtocolVersion(t){this.options.inner.setProtocolVersion?.(t)}async send(t,r){if(RF(t)){let n=this.pending.get(t.id);if(this.pending.delete(t.id),n&&this.upgrade&&JSON.stringify(t).includes(NF)){this.handOver(n);return}if(n?.method==="initialize"){let i=t.result?.protocolVersion;this.negotiatedProtocol=typeof i=="string"?i:null}n&&(t=await this.withToolHint(n,t))}await this.options.inner.send(t,r)}wrapSender(t){return async(r,n)=>{let i=await t(r,n),s=lp(i);return!s||!this.options.canUpgrade(s)?i:(this.requestUpgrade(s),{ok:!1,error:NF})}}fromHost(t,r){if(CF(t)&&t.method==="tools/list"&&this.toolsRelisted.mark(),this.relay){this.relay.send(t);return}CF(t)&&(this.remember(t),this.pending.set(t.id,t)),this.onmessage?.(t,r)}remember(t){if(t.method==="initialize")this.initializeRequest=t;else if(t.method==="logging/setLevel")this.logLevelRequest=t;else if(pce.has(t.method)){let r=String(t.params?.uri??"");t.method==="resources/subscribe"?this.subscriptions.set(r,t):this.subscriptions.delete(r)}}requestUpgrade(t){let r=this.upgrade;if(r?.kind==="RUNNING"||r?.kind==="FAILED"&&Date.now()-r.at<cce)return;let n=this.performUpgrade(t);this.upgrade={kind:"RUNNING",version:t,target:n},n.catch(i=>{let s=i instanceof Error?i.message:String(i);D.warn(`[upgrade] handover failed: ${s}`),this.upgrade={kind:"FAILED",version:t,reason:s,at:Date.now()}})}async performUpgrade(t){let r=this.initializeRequest;if(!r)throw new Error("the MCP client never initialized this server");let n=await this.options.prepare(t),i=new XS(n,this.options.launch(n),s=>this.options.inner.send(s),s=>{this.relay===i&&this.options.onRelayExit?.(s)});try{await i.initialize(r,this.negotiatedProtocol,[...this.logLevelRequest?[this.logLevelRequest]:[],...this.subscriptions.values()])}catch(s){throw i.close(),s}this.relay=i,this.toolsRelisted.reset();for(let s of hce)await this.options.inner.send({jsonrpc:"2.0",method:s});return D.info(`[upgrade] handed this session over to ${n} (was ${this.options.currentVersion})`),this.options.onRelayActive?.(),i}async handOver(t){let r=this.upgrade;if(!r){await this.options.inner.send(JS(t,"internal error: upgrade was not requested"));return}if(r.kind==="FAILED"){await this.options.inner.send(JS(t,ji(r.version,r.reason,this.host())));return}let n=await yce(r.target,this.options.waitMs??oce);if(n.kind==="DONE"){let s=this.options.currentVersion,o=n.value.version;n.value.send(t,async a=>{let c=await this.toolsRelisted.waitFor(this.reloadGraceMs()),u=this.upgradeNoted;return this.upgradeNoted=!0,c||u||JSON.stringify(a).includes(lce)?a:PF(a,gF(s,o,this.host()))});return}let i=n.kind==="TIMEOUT"?mF(r.version.current,lo(r.version)??r.version.latest):ji(r.version,n.reason,this.host());await this.options.inner.send(JS(t,i))}reloadGraceMs(){return this.options.toolReloadGraceMs??uce}async hostRelistedTools(){let t=this.startedAt+2*this.reloadGraceMs()-Date.now();return this.toolsRelisted.waitFor(Math.max(0,t))}host(){let t=this.initializeRequest?.params?.clientInfo;return hF(t)}async withToolHint(t,r){if(t.method!=="tools/call")return r;let n=mce(r);if(n===null)return r;let{upgradedFrom:i,currentVersion:s}=this.options;return fce.test(n)?gce(r,yF(String(t.params?.name??""),s,this.host(),{upgradedFrom:i,toolListReloaded:i?await this.hostRelistedTools():!1})):i&&dce.test(n)?PF(r,vF(i,s,this.host(),await this.hostRelistedTools())):r}};function mce(e){let t=e.result,r=t?.content?.[0];return t?.isError&&r?.type==="text"&&typeof r.text=="string"?r.text:null}function gce(e,t){return{jsonrpc:"2.0",id:e.id,result:{content:[{type:"text",text:t}],isError:!0}}}function PF(e,t){if(e.error)return{jsonrpc:"2.0",id:e.id,error:{...e.error,message:`${e.error.message}
1586
1586
  ${t}`}};let r=e.result;return r?.content?{jsonrpc:"2.0",id:e.id,result:{...r,content:[...r.content,{type:"text",text:t}]}}:e}function JS(e,t){return e.method==="tools/call"?{jsonrpc:"2.0",id:e.id,result:{content:[{type:"text",text:t}],isError:!0}}:{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:t}}}var zS=class{seen=!1;waiters=new Set;reset(){this.seen=!1}mark(){this.seen=!0;for(let t of this.waiters)t();this.waiters.clear()}waitFor(t){return this.seen||t<=0?Promise.resolve(this.seen):new Promise(r=>{let n=()=>{clearTimeout(i),r(!0)},i=setTimeout(()=>{this.waiters.delete(n),r(!1)},t);this.waiters.add(n)})}};function yce(e,t){return new Promise(r=>{let n=setTimeout(()=>r({kind:"TIMEOUT"}),t);e.then(i=>{clearTimeout(n),r({kind:"DONE",value:i})},i=>{clearTimeout(n),r({kind:"FAILED",reason:i instanceof Error?i.message:String(i)})})})}var XS=class{constructor(t,r,n,i){this.version=t;this.child=r;this.toHost=n;r.stdout.on("data",a=>{for(this.buffer.append(a);;){let c;try{c=this.buffer.readMessage()}catch(u){D.warn(`[upgrade] unreadable message from new version: ${String(u)}`);continue}if(!c)break;this.route(c)}}),r.stdin.on("error",()=>{});let s=!1,o=(a,c)=>{if(!s){s=!0;for(let u of this.waiters.values())u({jsonrpc:"2.0",id:"",error:{code:-32603,message:c}});this.waiters.clear(),this.closed||Promise.allSettled([...this.inflight]).then(()=>i(a))}};r.on("error",a=>o(1,`it could not start: ${a.message}`)),r.on("exit",a=>o(a??1,`it exited with ${a}`))}buffer=new uo;intercepts=new Map;inflight=new Set;waiters=new Map;sequence=0;closed=!1;send(t,r){r&&"id"in t&&t.id!==void 0&&this.intercepts.set(t.id,r),this.closed||this.child.stdin.write(cp(t))}async initialize(t,r,n){let i=await this.request(t.method,{...t.params,...r?{protocolVersion:r}:{}});if(i.error)throw new Error(`the new version did not initialize: ${i.error.message}`);let s=i.result?.protocolVersion;if(r&&s!==r)throw new Error(`the new version speaks MCP ${String(s)}, but this session uses ${r}`);this.send({jsonrpc:"2.0",method:"notifications/initialized"});for(let o of n)await this.request(o.method,o.params).catch(()=>{})}close(){this.closed||(this.closed=!0,this.child.stdin.end())}request(t,r){this.sequence+=1;let n=`handover-${this.sequence}`;return new Promise((i,s)=>{let o=setTimeout(()=>{this.waiters.delete(n),s(new Error(`the new version did not answer ${t}`))},ace);this.waiters.set(n,a=>{clearTimeout(o),i(a)}),this.send({jsonrpc:"2.0",id:n,method:t,params:r})})}route(t){if(RF(t)){let r=typeof t.id=="string"?this.waiters.get(t.id):void 0;if(r){this.waiters.delete(t.id),r(t);return}let n=this.intercepts.get(t.id);if(n){this.intercepts.delete(t.id);let i=n(t).then(s=>this.toHost(s));this.inflight.add(i),i.finally(()=>this.inflight.delete(i));return}}this.toHost(t)}};var dp=mo.toLowerCase(),DF=e=>`${dp}://project/${encodeURIComponent(e)}/schema-state`,LF=e=>`${dp}://project/${encodeURIComponent(e)}/schema-events`,kF=e=>Array.isArray(e)?String(e[0]??""):String(e??"");async function ZS(e){let t=xF.resolve(e),r=await Fc(t),n=jF(),i=async()=>{await Ct(r,{name:"daemon.pin",args:{token:n}})},s=async()=>{await Ct(r,{name:"daemon.unpin",args:{token:n}}).catch(()=>{})};await i();let o=setInterval(()=>{Ct(r,{name:"daemon.heartbeat",args:{token:n}}).catch(()=>{})},6e4);o.unref();let a=new Ab({name:te,version:"1.0.0"},{instructions:OF(),capabilities:{tools:{},prompts:{},resources:{subscribe:!0}}});yb(a);let c=new Set;a.server.setRequestHandler(Ob,_=>(c.add(_.params.uri),{})),a.server.setRequestHandler(Ib,_=>(c.delete(_.params.uri),{}));let u=process.env.MCP_HOST_SESSION_ID||Ece(),l=async(_,w)=>{if(_.agent??=a.server.getClientVersion()?.name,_.sessionId??=u,_.name==="workspace.set"&&typeof _.args?.cwd=="string"){let I=xF.resolve(_.args.cwd);if(_.args.cwd=I,I!==t){let T=r;r=await Fc(I),t=I,await Ct(T,{name:"daemon.unpin",args:{token:n}},w).catch(()=>{}),await i()}}return Ct(r,_,w)},d=new go,p=new fp({inner:new up,currentVersion:Hn(),upgradedFrom:process.env.MCP_UPGRADED_FROM||void 0,canUpgrade:_=>yo()&&lo(_)!==null,prepare:_=>d.installFirst(qc(_)),launch:_=>vce(process.execPath,[d.binPath(_),"mcp","--cwd",t],{stdio:["pipe","pipe","inherit"],env:{...process.env,MCP_HOST_SESSION_ID:u,MCP_UPGRADED_FROM:Hn()}}),onRelayActive:()=>{clearInterval(o),y.unsubscribe(),s()},onRelayExit:_=>process.exit(_)});Cb(a,p.wrapSender(l)),Rb(a,p.wrapSender(l));let h=async()=>{let _=await Ct(r,{name:"schema.status"});if(!_.ok)return[];let I=_.data?.sessions;return Array.isArray(I)?[...new Set(I.map(T=>T?.projectExId).filter(T=>typeof T=="string"))]:[]};a.registerResource("project-schema-state",new Ep(`${dp}://project/{projectExId}/schema-state`,{list:async()=>({resources:(await h()).map(_=>({uri:DF(_),name:`schema-state-${_}`,title:`Schema state ${_}`,description:"Current in-memory schema revision and stale/change notification state.",mimeType:"application/json"}))})}),{title:"Project Schema State",description:"Current in-memory schema revision and stale/change notification state.",mimeType:"application/json"},async(_,w)=>{let I=kF(w.projectExId),T=await Ct(r,{name:"schema.state",args:{projectExId:I}});return{contents:[{uri:_.href,mimeType:"application/json",text:JSON.stringify(T.ok?T.data:T,null,2)}]}}),a.registerResource("project-schema-events",new Ep(`${dp}://project/{projectExId}/schema-events`,{list:async()=>({resources:(await h()).map(_=>({uri:LF(_),name:`schema-events-${_}`,title:`Schema events ${_}`,description:"Recent semantic schema-change events observed by the daemon.",mimeType:"application/json"}))})}),{title:"Project Schema Events",description:"Recent semantic schema-change events observed by the daemon.",mimeType:"application/json"},async(_,w)=>{let I=kF(w.projectExId),T=await Ct(r,{name:"schema.events",args:{projectExId:I}});return{contents:[{uri:_.href,mimeType:"application/json",text:JSON.stringify(T.ok?T.data:T,null,2)}]}}),await a.connect(p),process.env.MCP_UPGRADED_FROM||AF(jc,d).catch(_=>{D.warn(`[upgrade] prefetch failed: ${String(_)}`)});let g=new Set,y=_F(r,async _=>{if(!_?.id||g.has(_.id))return;g.add(_.id);let w=String(_.projectExId??"");if(!w)return;let I=DF(w),T=LF(w),N=[c.has(I)?a.server.sendResourceUpdated({uri:I}):Promise.resolve(),c.has(T)?a.server.sendResourceUpdated({uri:T}):Promise.resolve()];await Promise.all([...N,a.sendLoggingMessage({level:"notice",logger:te,data:{message:"Project schema changed",projectExId:w,event:_}})])},_=>{D.warn("Daemon subscription error",_.message)}),E=!1,S=async()=>{E||(E=!0,clearInterval(o),y.unsubscribe(),await s(),await a.close())};process.on("SIGINT",()=>{S().finally(()=>process.exit(0))}),process.on("SIGTERM",()=>{S().finally(()=>process.exit(0))}),process.stdin.on("end",()=>{S().finally(()=>process.exit(0))}),process.stdin.on("close",()=>{S().finally(()=>process.exit(0))}),process.on("exit",()=>{clearInterval(o),y.unsubscribe()})}f();var _ce=/^-?\d+(\.\d+)?$/;function Sce(e){return e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")}function bce(e){if(e==="true")return!0;if(e==="false")return!1;if(_ce.test(e))return Number(e);if(Sce(e))try{return JSON.parse(e)}catch{return e}return e}function MF(e){let t=Number(e);if(Number.isNaN(t))throw new Mp("expected a number");return t}function eb(e){try{return JSON.parse(e)}catch{throw new Mp("expected valid JSON")}}function qF(e){if(typeof e!="string")return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Tce(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--"))continue;let i=n.slice(2),s,o=i.indexOf("=");if(o!==-1)s=i.slice(o+1),i=i.slice(0,o);else{let a=e[r+1];a!==void 0&&!a.startsWith("--")&&(s=a,r+=1)}s===void 0?i.startsWith("no-")?t[i.slice(3)]=!1:t[i]=!0:t[i]=bce(s)}return t}function FF(e,t,r){let n=qF(e.args);return Object.assign(n,Tce(t)),r&&(n.subcommand=r),n}function UF(e,t){let r=qF(t.args),n=e.opts();for(let i of e.options){let s=i.attributeName();e.getOptionValueSource(s)==="cli"&&(r[s]=n[s])}return r}f();function wce(e){let t=e,r=!1;for(;;)if(t instanceof Ut.ZodOptional)r=!0,t=t.unwrap();else if(t instanceof Ut.ZodNullable)t=t.unwrap();else if(t instanceof Ut.ZodDefault)t=t.removeDefault();else break;return{base:t,optional:r}}function VF(e,t){for(let[r,n]of Object.entries(t)){let{base:i,optional:s}=wce(n),o=s?"":"required",a=`${o} JSON`.trim();i instanceof Ut.ZodBoolean?(e.option(`--${r}`,o),e.option(`--no-${r}`)):i instanceof Ut.ZodNumber?e.option(`--${r} <value>`,o,MF):i instanceof Ut.ZodArray?i.element instanceof Ut.ZodString?e.option(`--${r} <values...>`,o):e.option(`--${r} <json>`,a,eb):i instanceof Ut.ZodRecord||i instanceof Ut.ZodObject||i instanceof Ut.ZodAny||i instanceof Ut.ZodUnknown?e.option(`--${r} <json>`,a,eb):e.option(`--${r} <value>`,o)}}var tb=["default"],KF=[];function Mi(e){return typeof e.cwd=="string"?BF.resolve(e.cwd):process.env.WORKSPACE_ROOT||process.cwd()}function pp(e){return e.pretty===void 0?!0:!e.pretty}async function HF(e,t,r){let n={name:e,args:t},i=Mi(r),s=r.daemon===!1?await qce(n,i):await Mce(n,i),o=lp(s);if(o){let a=await IF(o,KF);if(a.kind==="RERAN"){gb(a.status);return}a.kind==="FAILED"&&(s={...s,error:ji(o,a.reason)})}hp(s,pp(r)),s.ok||(process.exitCode=1)}async function Pce(e){let t=await Fc(Mi(e));hp({ok:!0,data:QF(t),message:"Daemon started"},pp(e))}async function Rce(e){await TF({workspaceRoot:Mi(e),idleTimeoutMs:Fce(process.env.ZED_AGENT_DAEMON_IDLE_TTL)??ap,startupFlags:tb})}async function xce(e){let r=await new Bn(Mi(e)).list();hp({ok:!0,data:r.map(QF)},pp(e))}async function Dce(e){let t=Mi(e),r=new Bn(t),n=new kr(t),i=await Hs(n,tb),s=await r.list(),o=[];for(let a of s)if(JSON.stringify(a.compatibility)===JSON.stringify(i))try{await Ct(a,{name:"daemon.stop"}),o.push(a.pid)}catch{await r.remove(a.pid)}hp({ok:!0,data:{stopped:o}},pp(e))}function GF(e,t){return e.commands.find(r=>r.name()===t)}function $F(e,t,r,n,i){let s=e;for(let c=0;c<t.length-1;c+=1)s=GF(s,t[c])??s.command(t[c]);let o=t[t.length-1];if(GF(s,o))return;let a=s.command(o).description(r);i&&VF(a,i),a.action(async(c,u)=>{let l=u.optsWithGlobals();await HF(n,UF(u,l),l)})}function Lce(e,t,r,n){$F(e,r.path.split(" "),t.description,t.command,n),r.alias&&$F(e,r.alias.split(" "),t.description,t.command,n)}function kce(){let e=Ft(),t=Object.keys(hb).join(", ");return["","Backend environment:",` Active: ${e.name} (select with ZION_ENV / MCP_ENV; known: ${t})`,` API: ${e.apiBaseUrl}`,` Auth: ${e.authEndpoint}`," Override any endpoint individually with BACKEND_API_BASE,"," BACKEND_AUTH_ENDPOINT, ZERO_API_URL_TEMPLATE, LOG_API_URL_TEMPLATE.","","Type system:",` Mode: ${qi()} (set MCP_TYPE_SYSTEM=pre or post; default pre)`," Post-only writes (enums, object/custom types) are gated unless the project"," is detected as post-refactor or MCP_TYPE_SYSTEM=post.","","Upgrades:"," When the backend stops supporting this version, the newer release is installed",` into ~/.${te}/versions and the call continues on it; later starts run it directly.`," MCP_AUTO_UPGRADE=0 turns this off and only reports the required upgrade.","","Logs:",` File: ${vb()}`,` Level: ${process.env.MCP_LOG_LEVEL??"info"} (set MCP_LOG_LEVEL; debug, or verbose)`," Verbose: MCP_LOG_LEVEL=verbose (or MCP_LOG_GQL=1) logs full GraphQL bodies + subscription events"," Rotation: 50 MB x 5 files; data older than 1 day is truncated"," Override: MCP_LOG_DIR, MCP_LOG_MAX_BYTES, MCP_LOG_MAX_FILES,"," MCP_LOG_MAX_AGE_DAYS (0 disables), MCP_LOG_FILE=off"].join(`
1587
1587
  `)}function jce(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}async function kNe(e=process.argv.slice(2)){KF=e;let t=new Kb;t.name(te).allowUnknownOption(!0).allowExcessArguments(!0).exitOverride(),t.option("--no-daemon","Run command one-shot without starting or using daemon"),t.option("--cwd <dir>","Workspace root for product config and daemon registry"),t.option("--pretty","Human-oriented output"),t.option("--args <json>","Pass arguments as JSON string"),t.command("mcp").description("Run MCP Bridge").allowUnknownOption(!0).action(async(i,s)=>{await ZS(Mi(s.optsWithGlobals()))}),t.command("version-check").description("Compare this CLI against the backend-advertised minimum supported version").action(async()=>{let i=await jc();process.stdout.write(`${ip(i)}
1588
- `),i.status==="outdated"&&(process.exitCode=1)}),t.command("tool-surface",{hidden:!0}).description("Print the MCP tools, prompts and CLI verbs this version exposes, as JSON").action(async()=>{let{collectToolSurface:i}=await import("./surface-S5OGOVQV.js");process.stdout.write(`${JSON.stringify(await i(),null,2)}
1588
+ `),i.status==="outdated"&&(process.exitCode=1)}),t.command("tool-surface",{hidden:!0}).description("Print the MCP tools, prompts and CLI verbs this version exposes, as JSON").action(async()=>{let{collectToolSurface:i}=await import("./surface-EKEYXH5K.js");process.stdout.write(`${JSON.stringify(await i(),null,2)}
1589
1589
  `)});let r=t.command("daemon").description("Daemon control"),n=[["start","Start daemon",Pce],["foreground","Run daemon in foreground",Rce],["status","Get daemon status",xce],["stop","Stop daemon",Dce]];for(let[i,s,o]of n)r.command(i).description(s).action(async(a,c)=>{await o(c.optsWithGlobals())});for(let i of Nb){if(!i.cli)continue;let s=i.cli,o=i.tool?.inputSchema;Lce(t,i,s,o)}t.argument("[parts...]","Custom agent command or MCP Bridge").action(async(i,s,o)=>{let a=o.optsWithGlobals();if(!i||i.length===0){await ZS(Mi(a));return}let c=[],u=[],l=!1;for(let d of i)!l&&d.startsWith("--")&&(l=!0),(l?u:c).push(d);await HF(c[0],FF(a,u,c[1]),a)}),t.addHelpText("afterAll",kce);try{await t.parseAsync(["node",te,...e])}catch(i){if(jce(i)){i.code==="commander.help"||i.code==="commander.helpDisplayed"||i.code==="commander.version"||(process.exitCode=1);return}throw i}}async function Mce(e,t){let r=await Fc(t);return Ct(r,e)}async function qce(e,t){let r=sp(t);try{return await r.execute(e)}finally{r.stop()}}async function Fc(e){let t=new Bn(e),r=new kr(e),n=await Hs(r,tb),i=await t.findCompatible(n);if(i)try{if((await Ct(i,{name:"daemon.ping"})).ok)return i}catch{await t.remove(i.pid)}let s=t.createRecord(n);await t.ensure(),await Cce.mkdir(BF.dirname(s.logPath),{recursive:!0});let o=Nce(s.logPath,"a"),a=Oce(process.execPath,[process.argv[1],"daemon","foreground"],{cwd:e,detached:!0,env:{...process.env,WORKSPACE_ROOT:e,ZED_AGENT_DAEMON_IDLE_TTL:process.env.ZED_AGENT_DAEMON_IDLE_TTL??String(ap)},stdio:["ignore",o,o]});Ace(o),a.unref();let c=Date.now()+1e4,u=null;for(;Date.now()<c;){await Uce(200);let l=await t.findCompatible(n);if(l)try{if((await Ct(l,{name:"daemon.ping"})).ok)return l}catch(d){u=d}}throw new Error(`Failed to start daemon${u?`: ${u.message}`:""}`)}function QF(e){let{token:t,...r}=e;return r}function hp(e,t){if(t){let r=e.ok?e.data??(e.message!==void 0?{message:e.message}:{}):{error:e.error,...e.data!==void 0?{data:e.data}:{}};process.stdout.write(`${JSON.stringify(r,null,2)}
1590
1590
  `);return}e.message&&process.stdout.write(`${e.message}
1591
1591
  `),e.data!==void 0&&process.stdout.write(`${JSON.stringify(e.data,null,2)}
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __nodeCreateRequire } from 'node:module';
2
2
  const require = __nodeCreateRequire(import.meta.url);
3
- import{g as n}from"./chunk-OHILD5KP.js";n();var e=[{path:"/",title:"/",url:"https://docs.functorz.com/",content:`import { Head } from 'nextra/components'
3
+ import{g as n}from"./chunk-WXFOSPKR.js";n();var e=[{path:"/",title:"/",url:"https://docs.functorz.com/",content:`import { Head } from 'nextra/components'
4
4
 
5
5
  <Head>
6
6
  <meta httpEquiv="refresh" content="0; url=/docs/" />