zion-mcp 2.8.2 → 2.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{chunk-V7YNFSBA.js → chunk-75A6HWF6.js} +1 -1
- package/dist/{chunk-LQXIJ6IC.js → chunk-7VVKHGGT.js} +1 -1
- package/dist/{chunk-4QGP6SS6.js → chunk-ATGTMFY5.js} +1 -1
- package/dist/{chunk-2HB5XNRD.js → chunk-EP2OX7PH.js} +11 -17
- package/dist/{chunk-PCRBAYPI.js → chunk-QTOGKZCE.js} +1 -1
- package/dist/{chunk-L3ZOUP3F.js → chunk-YUFE5SO6.js} +1 -1
- package/dist/cli-XXSHELNV.js +1433 -0
- package/dist/{corpus-UM23FYNV.js → corpus-73N3F2LB.js} +1 -1
- package/dist/{index.cjs-3U67BJYG.js → index.cjs-ERRJ7ONN.js} +1 -1
- package/dist/{json-crdt-BC5BIGDJ.js → json-crdt-DOM7HQ5E.js} +1 -1
- package/dist/{json-crdt-patch-JAVNDWYK.js → json-crdt-patch-3KSX2FWP.js} +1 -1
- package/dist/server.js +1 -1
- package/dist/{surface-JDDFP4JL.js → surface-JK45KCNT.js} +1 -1
- package/dist/{ztype-VF25BWB2.js → ztype-G7EMRCO5.js} +115 -107
- package/package.json +1 -1
- package/dist/cli-OEODBI6G.js +0 -1465
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __nodeCreateRequire } from 'node:module';
|
|
2
2
|
const require = __nodeCreateRequire(import.meta.url);
|
|
3
|
-
import{d as xo,e as Un,h as Au,i as Su}from"./chunk-L3ZOUP3F.js";import{c as N,d as Rs,e as Iu,g as u}from"./chunk-4QGP6SS6.js";var to=N(te=>{"use strict";u();Object.defineProperty(te,"__esModule",{value:!0});te.regexpCode=te.getEsmExportName=te.getProperty=te.safeStringify=te.stringify=te.strConcat=te.addCodeArg=te.str=te._=te.nil=te._Code=te.Name=te.IDENTIFIER=te._CodeOrName=void 0;var Qr=class{};te._CodeOrName=Qr;te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var In=class extends Qr{constructor(e){if(super(),!te.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};te.Name=In;var tt=class extends Qr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof In&&(n[r.str]=(n[r.str]||0)+1),n),{})}};te._Code=tt;te.nil=new tt("");function Sm(t,...e){let n=[t[0]],r=0;for(;r<e.length;)El(n,e[r]),n.push(t[++r]);return new tt(n)}te._=Sm;var yl=new tt("+");function Om(t,...e){let n=[eo(t[0])],r=0;for(;r<e.length;)n.push(yl),El(n,e[r]),n.push(yl,eo(t[++r]));return Ev(n),new tt(n)}te.str=Om;function El(t,e){e instanceof tt?t.push(...e._items):e instanceof In?t.push(e):t.push(wv(e))}te.addCodeArg=El;function Ev(t){let e=1;for(;e<t.length-1;){if(t[e]===yl){let n=Tv(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Tv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof In||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof In))return`"${t}${e.slice(1)}`}function bv(t,e){return e.emptyStr()?t:t.emptyStr()?e:Om`${t}${e}`}te.strConcat=bv;function wv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:eo(Array.isArray(t)?t.join(","):t)}function vv(t){return new tt(eo(t))}te.stringify=vv;function eo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}te.safeStringify=eo;function Iv(t){return typeof t=="string"&&te.IDENTIFIER.test(t)?new tt(`.${t}`):Sm`[${t}]`}te.getProperty=Iv;function Av(t){if(typeof t=="string"&&te.IDENTIFIER.test(t))return new tt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}te.getEsmExportName=Av;function Sv(t){return new tt(t.toString())}te.regexpCode=Sv});var wl=N(Ze=>{"use strict";u();Object.defineProperty(Ze,"__esModule",{value:!0});Ze.ValueScope=Ze.ValueScopeName=Ze.Scope=Ze.varKinds=Ze.UsedValueState=void 0;var Ge=to(),Tl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},za;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(za||(Ze.UsedValueState=za={}));Ze.varKinds={const:new Ge.Name("const"),let:new Ge.Name("let"),var:new Ge.Name("var")};var Ma=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ge.Name?e:this.name(e)}name(e){return new Ge.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ze.Scope=Ma;var Ua=class extends Ge.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ge._)`.${new Ge.Name(n)}[${r}]`}};Ze.ValueScopeName=Ua;var Ov=(0,Ge._)`\n`,bl=class extends Ma{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Ov:Ge.nil}}get(){return this._scope}name(e){return new Ua(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:a}=o,s=(r=n.key)!==null&&r!==void 0?r:n.ref,i=this._values[a];if(i){let h=i.get(s);if(h)return h}else i=this._values[a]=new Map;i.set(s,o);let l=this._scope[a]||(this._scope[a]=[]),d=l.length;return l[d]=n.ref,o.setValue(n,{property:a,itemIndex:d}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Ge._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let a=Ge.nil;for(let s in e){let i=e[s];if(!i)continue;let l=r[s]=r[s]||new Map;i.forEach(d=>{if(l.has(d))return;l.set(d,za.Started);let h=n(d);if(h){let p=this.opts.es5?Ze.varKinds.var:Ze.varKinds.const;a=(0,Ge._)`${a}${p} ${d} = ${h};${this.opts._n}`}else if(h=o?.(d))a=(0,Ge._)`${a}${h}${this.opts._n}`;else throw new Tl(d);l.set(d,za.Completed)})}return a}};Ze.ValueScope=bl});var q=N(V=>{"use strict";u();Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var X=to(),lt=wl(),Bt=to();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Bt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Bt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Bt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Bt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Bt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Bt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Bt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Bt.Name}});var Za=wl();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return Za.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return Za.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return Za.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return Za.varKinds}});V.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var Nt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},vl=class extends Nt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?lt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=ar(this.rhs,e,n)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},ja=class extends Nt{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof X.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ar(this.rhs,e,n),this}get names(){let e=this.lhs instanceof X.Name?{}:{...this.lhs.names};return Ga(e,this.rhs)}},Il=class extends ja{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Al=class extends Nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Sl=class extends Nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ol=class extends Nt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Nl=class extends Nt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=ar(this.code,e,n),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},no=class extends Nt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let a=r[o];a.optimizeNames(e,n)||(Nv(e,a.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>On(e,n.names),{})}},Pt=class extends no{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Pl=class extends no{},or=class extends Pt{};or.kind="else";var An=class t extends Pt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new or(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Nm(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=ar(this.condition,e,n),this}get names(){let e=super.names;return Ga(e,this.condition),this.else&&On(e,this.else.names),e}};An.kind="if";var Sn=class extends Pt{};Sn.kind="for";var Cl=class extends Sn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=ar(this.iteration,e,n),this}get names(){return On(super.names,this.iteration.names)}},Dl=class extends Sn{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?lt.varKinds.var:this.varKind,{name:r,from:o,to:a}=this;return`for(${n} ${r}=${o}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){let e=Ga(super.names,this.from);return Ga(e,this.to)}},Fa=class extends Sn{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=ar(this.iterable,e,n),this}get names(){return On(super.names,this.iterable.names)}},ro=class extends Pt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ro.kind="func";var oo=class extends no{render(e){return"return "+super.render(e)}};oo.kind="return";var Rl=class extends Pt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&On(e,this.catch.names),this.finally&&On(e,this.finally.names),e}},ao=class extends Pt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ao.kind="catch";var so=class extends Pt{render(e){return"finally"+super.render(e)}};so.kind="finally";var xl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
3
|
+
import{d as xo,e as Un,h as Au,i as Su}from"./chunk-YUFE5SO6.js";import{c as N,d as Rs,e as Iu,g as u}from"./chunk-ATGTMFY5.js";var to=N(te=>{"use strict";u();Object.defineProperty(te,"__esModule",{value:!0});te.regexpCode=te.getEsmExportName=te.getProperty=te.safeStringify=te.stringify=te.strConcat=te.addCodeArg=te.str=te._=te.nil=te._Code=te.Name=te.IDENTIFIER=te._CodeOrName=void 0;var Qr=class{};te._CodeOrName=Qr;te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var In=class extends Qr{constructor(e){if(super(),!te.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};te.Name=In;var tt=class extends Qr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof In&&(n[r.str]=(n[r.str]||0)+1),n),{})}};te._Code=tt;te.nil=new tt("");function Sm(t,...e){let n=[t[0]],r=0;for(;r<e.length;)El(n,e[r]),n.push(t[++r]);return new tt(n)}te._=Sm;var yl=new tt("+");function Om(t,...e){let n=[eo(t[0])],r=0;for(;r<e.length;)n.push(yl),El(n,e[r]),n.push(yl,eo(t[++r]));return Ev(n),new tt(n)}te.str=Om;function El(t,e){e instanceof tt?t.push(...e._items):e instanceof In?t.push(e):t.push(wv(e))}te.addCodeArg=El;function Ev(t){let e=1;for(;e<t.length-1;){if(t[e]===yl){let n=Tv(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Tv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof In||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof In))return`"${t}${e.slice(1)}`}function bv(t,e){return e.emptyStr()?t:t.emptyStr()?e:Om`${t}${e}`}te.strConcat=bv;function wv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:eo(Array.isArray(t)?t.join(","):t)}function vv(t){return new tt(eo(t))}te.stringify=vv;function eo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}te.safeStringify=eo;function Iv(t){return typeof t=="string"&&te.IDENTIFIER.test(t)?new tt(`.${t}`):Sm`[${t}]`}te.getProperty=Iv;function Av(t){if(typeof t=="string"&&te.IDENTIFIER.test(t))return new tt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}te.getEsmExportName=Av;function Sv(t){return new tt(t.toString())}te.regexpCode=Sv});var wl=N(Ze=>{"use strict";u();Object.defineProperty(Ze,"__esModule",{value:!0});Ze.ValueScope=Ze.ValueScopeName=Ze.Scope=Ze.varKinds=Ze.UsedValueState=void 0;var Ge=to(),Tl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},za;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(za||(Ze.UsedValueState=za={}));Ze.varKinds={const:new Ge.Name("const"),let:new Ge.Name("let"),var:new Ge.Name("var")};var Ma=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ge.Name?e:this.name(e)}name(e){return new Ge.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ze.Scope=Ma;var Ua=class extends Ge.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ge._)`.${new Ge.Name(n)}[${r}]`}};Ze.ValueScopeName=Ua;var Ov=(0,Ge._)`\n`,bl=class extends Ma{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Ov:Ge.nil}}get(){return this._scope}name(e){return new Ua(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:a}=o,s=(r=n.key)!==null&&r!==void 0?r:n.ref,i=this._values[a];if(i){let h=i.get(s);if(h)return h}else i=this._values[a]=new Map;i.set(s,o);let l=this._scope[a]||(this._scope[a]=[]),d=l.length;return l[d]=n.ref,o.setValue(n,{property:a,itemIndex:d}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Ge._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let a=Ge.nil;for(let s in e){let i=e[s];if(!i)continue;let l=r[s]=r[s]||new Map;i.forEach(d=>{if(l.has(d))return;l.set(d,za.Started);let h=n(d);if(h){let p=this.opts.es5?Ze.varKinds.var:Ze.varKinds.const;a=(0,Ge._)`${a}${p} ${d} = ${h};${this.opts._n}`}else if(h=o?.(d))a=(0,Ge._)`${a}${h}${this.opts._n}`;else throw new Tl(d);l.set(d,za.Completed)})}return a}};Ze.ValueScope=bl});var q=N(V=>{"use strict";u();Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var X=to(),lt=wl(),Bt=to();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Bt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Bt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Bt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Bt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Bt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Bt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Bt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Bt.Name}});var Za=wl();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return Za.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return Za.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return Za.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return Za.varKinds}});V.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var Nt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},vl=class extends Nt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?lt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=ar(this.rhs,e,n)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},ja=class extends Nt{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof X.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ar(this.rhs,e,n),this}get names(){let e=this.lhs instanceof X.Name?{}:{...this.lhs.names};return Ga(e,this.rhs)}},Il=class extends ja{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Al=class extends Nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Sl=class extends Nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ol=class extends Nt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Nl=class extends Nt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=ar(this.code,e,n),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},no=class extends Nt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let a=r[o];a.optimizeNames(e,n)||(Nv(e,a.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>On(e,n.names),{})}},Pt=class extends no{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Pl=class extends no{},or=class extends Pt{};or.kind="else";var An=class t extends Pt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new or(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Nm(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=ar(this.condition,e,n),this}get names(){let e=super.names;return Ga(e,this.condition),this.else&&On(e,this.else.names),e}};An.kind="if";var Sn=class extends Pt{};Sn.kind="for";var Cl=class extends Sn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=ar(this.iteration,e,n),this}get names(){return On(super.names,this.iteration.names)}},Dl=class extends Sn{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?lt.varKinds.var:this.varKind,{name:r,from:o,to:a}=this;return`for(${n} ${r}=${o}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){let e=Ga(super.names,this.from);return Ga(e,this.to)}},Fa=class extends Sn{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=ar(this.iterable,e,n),this}get names(){return On(super.names,this.iterable.names)}},ro=class extends Pt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ro.kind="func";var oo=class extends no{render(e){return"return "+super.render(e)}};oo.kind="return";var Rl=class extends Pt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&On(e,this.catch.names),this.finally&&On(e,this.finally.names),e}},ao=class extends Pt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ao.kind="catch";var so=class extends Pt{render(e){return"finally"+super.render(e)}};so.kind="finally";var xl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
4
4
|
`:""},this._extScope=e,this._scope=new lt.Scope({parent:e}),this._nodes=[new Pl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let a=this._scope.toName(n);return r!==void 0&&o&&(this._constants[a.str]=r),this._leafNode(new vl(e,a,r)),a}const(e,n,r){return this._def(lt.varKinds.const,e,n,r)}let(e,n,r){return this._def(lt.varKinds.let,e,n,r)}var(e,n,r){return this._def(lt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ja(e,n,r))}add(e,n){return this._leafNode(new Il(e,V.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==X.nil&&this._leafNode(new Nl(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,X.addCodeArg)(n,o));return n.push("}"),new X._Code(n)}if(e,n,r){if(this._blockNode(new An(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new An(e))}else(){return this._elseNode(new or)}endIf(){return this._endBlockNode(An,or)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Cl(e),n)}forRange(e,n,r,o,a=this.opts.es5?lt.varKinds.var:lt.varKinds.let){let s=this._scope.toName(e);return this._for(new Dl(a,s,n,r),()=>o(s))}forOf(e,n,r,o=lt.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=n instanceof X.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,X._)`${s}.length`,i=>{this.var(a,(0,X._)`${s}[${i}]`),r(a)})}return this._for(new Fa("of",o,a,n),()=>r(a))}forIn(e,n,r,o=this.opts.es5?lt.varKinds.var:lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,X._)`Object.keys(${n})`,r);let a=this._scope.toName(e);return this._for(new Fa("in",o,a,n),()=>r(a))}endFor(){return this._endBlockNode(Sn)}label(e){return this._leafNode(new Al(e))}break(e){return this._leafNode(new Sl(e))}return(e){let n=new oo;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(oo)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Rl;if(this._blockNode(o),this.code(e),n){let a=this.name("e");this._currNode=o.catch=new ao(a),n(a)}return r&&(this._currNode=o.finally=new so,this.code(r)),this._endBlockNode(ao,so)}throw(e){return this._leafNode(new Ol(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=X.nil,r,o){return this._blockNode(new ro(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ro)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof An))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};V.CodeGen=xl;function On(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Ga(t,e){return e instanceof X._CodeOrName?On(t,e.names):t}function ar(t,e,n){if(t instanceof X.Name)return r(t);if(!o(t))return t;return new X._Code(t._items.reduce((a,s)=>(s instanceof X.Name&&(s=r(s)),s instanceof X._Code?a.push(...s._items):a.push(s),a),[]));function r(a){let s=n[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function o(a){return a instanceof X._Code&&a._items.some(s=>s instanceof X.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Nv(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Nm(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,X._)`!${kl(t)}`}V.not=Nm;var Pv=Pm(V.operators.AND);function Cv(...t){return t.reduce(Pv)}V.and=Cv;var Dv=Pm(V.operators.OR);function Rv(...t){return t.reduce(Dv)}V.or=Rv;function Pm(t){return(e,n)=>e===X.nil?n:n===X.nil?e:(0,X._)`${kl(e)} ${t} ${kl(n)}`}function kl(t){return t instanceof X.Name?t:(0,X._)`(${t})`}});var Q=N(W=>{"use strict";u();Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var ae=q(),xv=to();function kv(t){let e={};for(let n of t)e[n]=!0;return e}W.toHash=kv;function Lv(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Rm(t,e),!xm(e,t.self.RULES.all))}W.alwaysValidSchema=Lv;function Rm(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let a in e)o[a]||$m(t,`unknown keyword: "${a}"`)}W.checkUnknownRules=Rm;function xm(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}W.schemaHasRules=xm;function $v(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}W.schemaHasRulesButRef=$v;function zv({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ae._)`${n}`}return(0,ae._)`${t}${e}${(0,ae.getProperty)(r)}`}W.schemaRefOrVal=zv;function Mv(t){return km(decodeURIComponent(t))}W.unescapeFragment=Mv;function Uv(t){return encodeURIComponent($l(t))}W.escapeFragment=Uv;function $l(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=$l;function km(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=km;function jv(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}W.eachItem=jv;function Cm({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,a,s,i)=>{let l=s===void 0?a:s instanceof ae.Name?(a instanceof ae.Name?t(o,a,s):e(o,a,s),s):a instanceof ae.Name?(e(o,s,a),a):n(a,s);return i===ae.Name&&!(l instanceof ae.Name)?r(o,l):l}}W.mergeEvaluated={props:Cm({mergeNames:(t,e,n)=>t.if((0,ae._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ae._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ae._)`${n} || {}`).code((0,ae._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ae._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ae._)`${n} || {}`),zl(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Lm}),items:Cm({mergeNames:(t,e,n)=>t.if((0,ae._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ae._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ae._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ae._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Lm(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ae._)`{}`);return e!==void 0&&zl(t,n,e),n}W.evaluatedPropsToName=Lm;function zl(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ae._)`${e}${(0,ae.getProperty)(r)}`,!0))}W.setEvaluated=zl;var Dm={};function Fv(t,e){return t.scopeValue("func",{ref:e,code:Dm[e.code]||(Dm[e.code]=new xv._Code(e.code))})}W.useFunc=Fv;var Ll;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ll||(W.Type=Ll={}));function Gv(t,e,n){if(t instanceof ae.Name){let r=e===Ll.Num;return n?r?(0,ae._)`"[" + ${t} + "]"`:(0,ae._)`"['" + ${t} + "']"`:r?(0,ae._)`"/" + ${t}`:(0,ae._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ae.getProperty)(t).toString():"/"+$l(t)}W.getErrorPath=Gv;function $m(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=$m});var Ct=N(Ml=>{"use strict";u();Object.defineProperty(Ml,"__esModule",{value:!0});var Ce=q(),Zv={data:new Ce.Name("data"),valCxt:new Ce.Name("valCxt"),instancePath:new Ce.Name("instancePath"),parentData:new Ce.Name("parentData"),parentDataProperty:new Ce.Name("parentDataProperty"),rootData:new Ce.Name("rootData"),dynamicAnchors:new Ce.Name("dynamicAnchors"),vErrors:new Ce.Name("vErrors"),errors:new Ce.Name("errors"),this:new Ce.Name("this"),self:new Ce.Name("self"),scope:new Ce.Name("scope"),json:new Ce.Name("json"),jsonPos:new Ce.Name("jsonPos"),jsonLen:new Ce.Name("jsonLen"),jsonPart:new Ce.Name("jsonPart")};Ml.default=Zv});var io=N(De=>{"use strict";u();Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var ee=q(),Ba=Q(),$e=Ct();De.keywordError={message:({keyword:t})=>(0,ee.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ee.str)`"${t}" keyword must be ${e} ($data)`:(0,ee.str)`"${t}" keyword is invalid ($data)`};function Bv(t,e=De.keywordError,n,r){let{it:o}=t,{gen:a,compositeRule:s,allErrors:i}=o,l=Um(t,e,n);r??(s||i)?zm(a,l):Mm(o,(0,ee._)`[${l}]`)}De.reportError=Bv;function qv(t,e=De.keywordError,n){let{it:r}=t,{gen:o,compositeRule:a,allErrors:s}=r,i=Um(t,e,n);zm(o,i),a||s||Mm(r,$e.default.vErrors)}De.reportExtraError=qv;function Vv(t,e){t.assign($e.default.errors,e),t.if((0,ee._)`${$e.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ee._)`${$e.default.vErrors}.length`,e),()=>t.assign($e.default.vErrors,null)))}De.resetErrorsCount=Vv;function Wv({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:a}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,$e.default.errors,i=>{t.const(s,(0,ee._)`${$e.default.vErrors}[${i}]`),t.if((0,ee._)`${s}.instancePath === undefined`,()=>t.assign((0,ee._)`${s}.instancePath`,(0,ee.strConcat)($e.default.instancePath,a.errorPath))),t.assign((0,ee._)`${s}.schemaPath`,(0,ee.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(t.assign((0,ee._)`${s}.schema`,n),t.assign((0,ee._)`${s}.data`,r))})}De.extendErrors=Wv;function zm(t,e){let n=t.const("err",e);t.if((0,ee._)`${$e.default.vErrors} === null`,()=>t.assign($e.default.vErrors,(0,ee._)`[${n}]`),(0,ee._)`${$e.default.vErrors}.push(${n})`),t.code((0,ee._)`${$e.default.errors}++`)}function Mm(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,ee._)`new ${t.ValidationError}(${e})`):(n.assign((0,ee._)`${r}.errors`,e),n.return(!1))}var Nn={keyword:new ee.Name("keyword"),schemaPath:new ee.Name("schemaPath"),params:new ee.Name("params"),propertyName:new ee.Name("propertyName"),message:new ee.Name("message"),schema:new ee.Name("schema"),parentSchema:new ee.Name("parentSchema")};function Um(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,ee._)`{}`:Hv(t,e,n)}function Hv(t,e,n={}){let{gen:r,it:o}=t,a=[Yv(o,n),Kv(t,n)];return Jv(t,e,a),r.object(...a)}function Yv({errorPath:t},{instancePath:e}){let n=e?(0,ee.str)`${t}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:t;return[$e.default.instancePath,(0,ee.strConcat)($e.default.instancePath,n)]}function Kv({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,ee.str)`${e}/${t}`;return n&&(o=(0,ee.str)`${o}${(0,Ba.getErrorPath)(n,Ba.Type.Str)}`),[Nn.schemaPath,o]}function Jv(t,{params:e,message:n},r){let{keyword:o,data:a,schemaValue:s,it:i}=t,{opts:l,propertyName:d,topSchemaRef:h,schemaPath:p}=i;r.push([Nn.keyword,o],[Nn.params,typeof e=="function"?e(t):e||(0,ee._)`{}`]),l.messages&&r.push([Nn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([Nn.schema,s],[Nn.parentSchema,(0,ee._)`${h}${p}`],[$e.default.data,a]),d&&r.push([Nn.propertyName,d])}});var Fm=N(sr=>{"use strict";u();Object.defineProperty(sr,"__esModule",{value:!0});sr.boolOrEmptySchema=sr.topBoolOrEmptySchema=void 0;var Xv=io(),Qv=q(),eI=Ct(),tI={message:"boolean schema is false"};function nI(t){let{gen:e,schema:n,validateName:r}=t;n===!1?jm(t,!1):typeof n=="object"&&n.$async===!0?e.return(eI.default.data):(e.assign((0,Qv._)`${r}.errors`,null),e.return(!0))}sr.topBoolOrEmptySchema=nI;function rI(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),jm(t)):n.var(e,!0)}sr.boolOrEmptySchema=rI;function jm(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Xv.reportError)(o,tI,void 0,e)}});var Ul=N(ir=>{"use strict";u();Object.defineProperty(ir,"__esModule",{value:!0});ir.getRules=ir.isJSONType=void 0;var oI=["string","number","integer","boolean","null","object","array"],aI=new Set(oI);function sI(t){return typeof t=="string"&&aI.has(t)}ir.isJSONType=sI;function iI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}ir.getRules=iI});var jl=N(qt=>{"use strict";u();Object.defineProperty(qt,"__esModule",{value:!0});qt.shouldUseRule=qt.shouldUseGroup=qt.schemaHasRulesForType=void 0;function cI({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Gm(t,r)}qt.schemaHasRulesForType=cI;function Gm(t,e){return e.rules.some(n=>Zm(t,n))}qt.shouldUseGroup=Gm;function Zm(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}qt.shouldUseRule=Zm});var co=N(Re=>{"use strict";u();Object.defineProperty(Re,"__esModule",{value:!0});Re.reportTypeError=Re.checkDataTypes=Re.checkDataType=Re.coerceAndCheckDataType=Re.getJSONTypes=Re.getSchemaTypes=Re.DataType=void 0;var lI=Ul(),dI=jl(),uI=io(),Z=q(),Bm=Q(),cr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(cr||(Re.DataType=cr={}));function hI(t){let e=qm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Re.getSchemaTypes=hI;function qm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(lI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Re.getJSONTypes=qm;function pI(t,e){let{gen:n,data:r,opts:o}=t,a=mI(e,o.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0,dI.schemaHasRulesForType)(t,e[0]));if(s){let i=Gl(e,r,o.strictNumbers,cr.Wrong);n.if(i,()=>{a.length?fI(t,e,a):Zl(t)})}return s}Re.coerceAndCheckDataType=pI;var Vm=new Set(["string","number","integer","boolean","null"]);function mI(t,e){return e?t.filter(n=>Vm.has(n)||e==="array"&&n==="array"):[]}function fI(t,e,n){let{gen:r,data:o,opts:a}=t,s=r.let("dataType",(0,Z._)`typeof ${o}`),i=r.let("coerced",(0,Z._)`undefined`);a.coerceTypes==="array"&&r.if((0,Z._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,Z._)`${o}[0]`).assign(s,(0,Z._)`typeof ${o}`).if(Gl(e,o,a.strictNumbers),()=>r.assign(i,o))),r.if((0,Z._)`${i} !== undefined`);for(let d of n)(Vm.has(d)||d==="array"&&a.coerceTypes==="array")&&l(d);r.else(),Zl(t),r.endIf(),r.if((0,Z._)`${i} !== undefined`,()=>{r.assign(o,i),_I(t,i)});function l(d){switch(d){case"string":r.elseIf((0,Z._)`${s} == "number" || ${s} == "boolean"`).assign(i,(0,Z._)`"" + ${o}`).elseIf((0,Z._)`${o} === null`).assign(i,(0,Z._)`""`);return;case"number":r.elseIf((0,Z._)`${s} == "boolean" || ${o} === null
|
|
5
5
|
|| (${s} == "string" && ${o} && ${o} == +${o})`).assign(i,(0,Z._)`+${o}`);return;case"integer":r.elseIf((0,Z._)`${s} === "boolean" || ${o} === null
|
|
6
6
|
|| (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(i,(0,Z._)`+${o}`);return;case"boolean":r.elseIf((0,Z._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(i,!1).elseIf((0,Z._)`${o} === "true" || ${o} === 1`).assign(i,!0);return;case"null":r.elseIf((0,Z._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(i,null);return;case"array":r.elseIf((0,Z._)`${s} === "string" || ${s} === "number"
|
|
@@ -40,7 +40,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
40
40
|
]))`;continue}}if(n.s&&r[l]==="."){o+=s?`${r[l]}\r
|
|
41
41
|
`:`[${r[l]}\r
|
|
42
42
|
]`;continue}o+=r[l],r[l]==="\\"?a=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function La(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===A.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??fe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===A.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=ka(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===A.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===A.ZodBranded&&t.keyType._def.type._def.typeName===A.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=xa(t.keyType._def,e);return{...n,propertyNames:o}}}return n}function sm(t,e){if(e.mapStrategy==="record")return La(t,e);let n=j(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||fe(e),r=j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}u();function im(t){let e=t.values,r=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),o=Array.from(new Set(r.map(a=>typeof a)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}u();function cm(t){return t.target==="openAi"?void 0:{not:fe({...t,currentPath:[...t.currentPath,"not"]})}}u();function lm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}u();u();var Xr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function um(t,e){if(e.target==="openApi3")return dm(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Xr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,a)=>{let s=Xr[a._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,a)=>{let s=typeof a._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(a._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){let o=r.filter((a,s,i)=>i.indexOf(a)===s);return{type:o.length>1?o:o[0],enum:n.reduce((a,s)=>a.includes(s._def.value)?a:[...a,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(a=>!r.includes(a))],[])};return dm(t,e)}var dm=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>j(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function hm(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Xr[t.innerType._def.typeName],nullable:!0}:{type:[Xr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}u();function pm(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",dl(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?J(n,"minimum",r.value,r.message,e):J(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),J(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?J(n,"maximum",r.value,r.message,e):J(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),J(n,"maximum",r.value,r.message,e));break;case"multipleOf":J(n,"multipleOf",r.value,r.message,e);break}return n}u();function mm(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},o=[],a=t.shape();for(let i in a){let l=a[i];if(l===void 0||l._def===void 0)continue;let d=mv(l);d&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let h=j(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});h!==void 0&&(r.properties[i]=h,d||o.push(i))}o.length&&(r.required=o);let s=pv(t,e);return s!==void 0&&(r.additionalProperties=s),r}function pv(t,e){if(t.catchall._def.typeName!=="ZodNever")return j(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function mv(t){try{return t.isOptional()}catch{return!0}}u();var fm=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return j(t.innerType._def,e);let n=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:fe(e)},n]}:fe(e)};u();var _m=(t,e)=>{if(e.pipeStrategy==="input")return j(t.in._def,e);if(e.pipeStrategy==="output")return j(t.out._def,e);let n=j(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=j(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};u();function gm(t,e){return j(t.type._def,e)}u();function ym(t,e){let r={type:"array",uniqueItems:!0,items:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&J(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&J(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}u();function Em(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>j(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:j(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>j(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}u();function Tm(t){return{not:fe(t)}}u();function bm(t){return fe(t)}u();var wm=(t,e)=>j(t.innerType._def,e);var vm=(t,e,n)=>{switch(e){case A.ZodString:return ka(t,n);case A.ZodNumber:return pm(t,n);case A.ZodObject:return mm(t,n);case A.ZodBigInt:return Jp(t,n);case A.ZodBoolean:return Xp();case A.ZodDate:return ul(t,n);case A.ZodUndefined:return Tm(n);case A.ZodNull:return lm(n);case A.ZodArray:return Kp(t,n);case A.ZodUnion:case A.ZodDiscriminatedUnion:return um(t,n);case A.ZodIntersection:return rm(t,n);case A.ZodTuple:return Em(t,n);case A.ZodRecord:return La(t,n);case A.ZodLiteral:return om(t,n);case A.ZodEnum:return nm(t);case A.ZodNativeEnum:return im(t);case A.ZodNullable:return hm(t,n);case A.ZodOptional:return fm(t,n);case A.ZodMap:return sm(t,n);case A.ZodSet:return ym(t,n);case A.ZodLazy:return()=>t.getter()._def;case A.ZodPromise:return gm(t,n);case A.ZodNaN:case A.ZodNever:return cm(n);case A.ZodEffects:return tm(t,n);case A.ZodAny:return fe(n);case A.ZodUnknown:return bm(n);case A.ZodDefault:return em(t,n);case A.ZodBranded:return xa(t,n);case A.ZodReadonly:return wm(t,n);case A.ZodCatch:return Qp(t,n);case A.ZodPipeline:return _m(t,n);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(r=>{})(e)}};function j(t,e,n=!1){let r=e.seen.get(t);if(e.override){let i=e.override?.(t,e,r,n);if(i!==Wp)return i}if(r&&!n){let i=fv(r,e);if(i!==void 0)return i}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let a=vm(t,t.typeName,e),s=typeof a=="function"?j(a(),e):a;if(s&&_v(t,e,s),e.postProcess){let i=e.postProcess(s,t,e);return o.jsonSchema=s,i}return o.jsonSchema=s,s}var fv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ra(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),fe(e)):e.$refStrategy==="seen"?fe(e):void 0}},_v=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);u();u();var ml=(t,e)=>{let n=Yp(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,h])=>({...l,[d]:j(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,d]},!0)??fe(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=j(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??fe(n),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(a.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let i=o===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:a}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function gv(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function fl(t,e){return Xe(t)?zc(t,{target:gv(e?.target),io:e?.pipeStrategy??"input"}):ml(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function _l(t){let n=Ft(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=ca(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function gl(t,e){let n=jt(t,e);if(!n.success)throw n.error;return n.data}var yv=6e4,$a=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(fa,n=>{this._oncancel(n)}),this.setNotificationHandler(ga,n=>{this._onprogress(n)}),this.setRequestHandler(_a,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ya,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new x($.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ta,async(n,r)=>{let o=async()=>{let a=n.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(a,r.sessionId);){if(i.type==="response"||i.type==="error"){let l=i.message,d=l.id,h=this._requestResolvers.get(d);if(h)if(this._requestResolvers.delete(d),i.type==="response")h(l);else{let p=l,g=new x(p.error.code,p.error.message,p.error.data);h(g)}else{let p=i.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${d}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}let s=await this._taskStore.getTask(a,r.sessionId);if(!s)throw new x($.InvalidParams,`Task not found: ${a}`);if(!Zt(s.status))return await this._waitForTaskUpdate(a,r.signal),await o();if(Zt(s.status)){let i=await this._taskStore.getTaskResult(a,r.sessionId);return this._clearTaskQueue(a),{...i,_meta:{...i._meta,[Gt]:{taskId:a}}}}return await o()};return await o()}),this.setRequestHandler(ba,async(n,r)=>{try{let{tasks:o,nextCursor:a}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:a,_meta:{}}}catch(o){throw new x($.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(va,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new x($.InvalidParams,`Task not found: ${n.params.taskId}`);if(Zt(o.status))throw new x($.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let a=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!a)throw new x($.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...a}}catch(o){throw o instanceof x?o:new x($.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,o,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:a,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),x.fromError($.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=a=>{r?.(a),this._onerror(a)};let o=this._transport?.onmessage;this._transport.onmessage=(a,s)=>{o?.(a,s),Zr(a)||$p(a)?this._onresponse(a):Kc(a)?this._onrequest(a,s):Lp(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=x.fromError($.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,a=e.params?._meta?.[Gt]?.taskId;if(r===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:$.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:h,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(h).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let i=Rp(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,d={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};a&&(p.relatedTask={taskId:a}),await this.notification(h,p)},sendRequest:async(h,p,g)=>{if(s.signal.aborted)throw new x($.ConnectionClosed,"Request was cancelled");let f={...g,relatedRequestId:e.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});let m=f.relatedTask?.taskId??a;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(h,p,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,d)).then(async h=>{if(s.signal.aborted)return;let p={result:h,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async h=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:$.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,o=Number(n),a=this._progressHandlers.get(o);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(l);return}a(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Zr(e))r(e);else{let s=new x(e.error.code,e.error.message,e.error.data);r(s)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let a=!1;if(Zr(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let i=s.task;typeof i.taskId=="string"&&(a=!0,this._taskProgressTokens.set(i.taskId,n))}}if(a||this._progressHandlers.delete(n),Zr(e))o(e);else{let s=x.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(s){yield{type:"error",error:s instanceof x?s:new x($.InternalError,String(s))}}return}let a;try{let s=await this.request(e,er,r);if(s.task)a=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new x($.InternalError,"Task creation did not return a task");for(;;){let i=await this.getTask({taskId:a},r);if(yield{type:"taskStatus",task:i},Zt(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)}:i.status==="failed"?yield{type:"error",error:new x($.InternalError,`Task ${a} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new x($.InternalError,`Task ${a} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)};return}let l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,l)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof x?s:new x($.InternalError,String(s))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s,task:i,relatedTask:l}=r??{};return new Promise((d,h)=>{let p=I=>{h(I)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(I){p(I);return}r?.signal?.throwIfAborted();let g=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:g};r?.onprogress&&(this._progressHandlers.set(g,r.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:g}}),i&&(f.params={...f.params,task:i}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Gt]:l}});let m=I=>{this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(I)}},{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`)));let S=I instanceof x?I:new x($.RequestTimeout,String(I));h(S)};this._responseHandlers.set(g,I=>{if(!r?.signal?.aborted){if(I instanceof Error)return h(I);try{let S=jt(n,I.result);S.success?d(S.data):h(S.error)}catch(S){h(S)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});let y=r?.timeout??yv,T=()=>m(x.fromError($.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(g,y,r?.maxTotalTimeout,T,r?.resetTimeoutOnProgress??!1);let w=l?.taskId;if(w){let I=S=>{let D=this._responseHandlers.get(g);D?D(S):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,I),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(g),h(S)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s}).catch(I=>{this._cleanupTimeout(g),h(I)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Ea,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},wa,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Mp,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Gt]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Gt]:n.relatedTask}}}),this._transport?.send(i,n).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gt]:n.relatedTask}}}),await this._transport.send(s,n)}setRequestHandler(e,n){let r=_l(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,a)=>{let s=gl(e,o);return Promise.resolve(n(s,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=_l(e);this._notificationHandlers.set(r,o=>{let a=gl(e,o);return Promise.resolve(n(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&Kc(o.message)){let a=o.message.id,s=this._requestResolvers.get(a);s?(s(new x($.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,a)=>{if(n.aborted){a(new x($.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(s),a(new x($.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let a=await r.getTask(o,n);if(!a)throw new x($.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(o,a,s)=>{await r.storeTaskResult(o,a,s,n);let i=await r.getTask(o,n);if(i){let l=Hr.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Zt(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,a,s)=>{let i=await r.getTask(o,n);if(!i)throw new x($.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Zt(i.status))throw new x($.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,a,s,n);let l=await r.getTask(o,n);if(l){let d=Hr.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Zt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}};function Im(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Am(t,e){let n={...t};for(let r in e){let o=r,a=e[o];if(a===void 0)continue;let s=n[o];Im(s)&&Im(a)?n[o]={...s,...a}:n[o]=a}return n}u();var gg=Iu(ru(),1),yg=Iu(_g(),1);function bP(){let t=new gg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,yg.default)(t),t}var gs=class{constructor(e){this._ajv=e??bP()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};u();var ys=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],a=Array.isArray(o.content)?o.content:[o.content],s=a.some(h=>h.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=i?Array.isArray(i.content)?i.content:[i.content]:[],d=l.some(h=>h.type==="tool_use");if(s){if(a.some(h=>h.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let h=new Set(l.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(a.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(h.size!==p.size||![...h].every(g=>p.has(g)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Jr,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let a=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},rr,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};u();function Eg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Tg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Es=class extends $a{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Kr.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let a=this._loggingLevels.get(o);return a?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new gs,this.setRequestHandler(Qc,r=>this._oninitialize(r)),this.setNotificationHandler(el,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(il,async(r,o)=>{let a=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=r.params,i=Kr.safeParse(s);return i.success&&this._loggingLevels.set(a,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ys(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Am(this._capabilities,e)}setRequestHandler(e,n){let o=Ft(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let a;if(Xe(o)){let i=o;a=i._zod?.def?.value??i.value}else{let i=o;a=i._def?.value??i.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let i=async(l,d)=>{let h=jt(nr,l);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new x($.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=h.data,g=await Promise.resolve(n(l,d));if(p.task){let m=jt(er,g);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new x($.InvalidParams,`Invalid task creation result: ${y}`)}return m.data}let f=jt(Ca,g);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new x($.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Tg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Eg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Pp.includes(n)?n:Hc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ma)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],a=o.some(d=>d.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],l=i.some(d=>d.type==="tool_use");if(a){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(i.filter(p=>p.type==="tool_use").map(p=>p.id)),h=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==h.size||![...d].every(p=>h.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},cl,n):this.request({method:"sampling/createMessage",params:e},Jr,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},rr,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:o},rr,n);if(a.action==="accept"&&a.content&&o.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(a.content);if(!i.valid)throw new x($.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){throw s instanceof x?s:new x($.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return a}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},ll,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};u();var wg=Symbol.for("mcp.completable");function uu(t){return!!t&&typeof t=="object"&&wg in t}function vg(t){return t[wg]?.complete}var bg;(function(t){t.Completable="McpCompletable"})(bg||(bg={}));u();var Ts=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,n,r){if(e.length>n)throw new Error(`${r} exceeds maximum length of ${n} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let n=[],r="",o=0,a=0;for(;o<e.length;)if(e[o]==="{"){r&&(n.push(r),r="");let s=e.indexOf("}",o);if(s===-1)throw new Error("Unclosed template expression");if(a++,a>1e4)throw new Error("Template contains too many expressions (max 10000)");let i=e.slice(o+1,s),l=this.getOperator(i),d=i.includes("*"),h=this.getNames(i),p=h[0];for(let g of h)t.validateLength(g,1e6,"Variable name");n.push({name:p,operator:l,names:h,exploded:d}),o=s+1}else r+=e[o],o++;return r&&n.push(r),n}getOperator(e){return["+","#",".","/","?","&"].find(r=>e.startsWith(r))||""}getNames(e){let n=this.getOperator(e);return e.slice(n.length).split(",").map(r=>r.replace("*","").trim()).filter(r=>r.length>0)}encodeValue(e,n){return t.validateLength(e,1e6,"Variable value"),n==="+"||n==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,n){if(e.operator==="?"||e.operator==="&"){let s=e.names.map(l=>{let d=n[l];if(d===void 0)return"";let h=Array.isArray(d)?d.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(d.toString(),e.operator);return`${l}=${h}`}).filter(l=>l.length>0);return s.length===0?"":(e.operator==="?"?"?":"&")+s.join("&")}if(e.names.length>1){let s=e.names.map(i=>n[i]).filter(i=>i!==void 0);return s.length===0?"":s.map(i=>Array.isArray(i)?i[0]:i).join(",")}let r=n[e.name];if(r===void 0)return"";let a=(Array.isArray(r)?r:[r]).map(s=>this.encodeValue(s,e.operator));switch(e.operator){case"":return a.join(",");case"+":return a.join(",");case"#":return"#"+a.join(",");case".":return"."+a.join(".");case"/":return"/"+a.join("/");default:return a.join(",")}}expand(e){let n="",r=!1;for(let o of this.parts){if(typeof o=="string"){n+=o;continue}let a=this.expandPart(o,e);a&&((o.operator==="?"||o.operator==="&")&&r?n+=a.replace("?","&"):n+=a,(o.operator==="?"||o.operator==="&")&&(r=!0))}return n}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let n=[];for(let a of e.names)t.validateLength(a,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let a=0;a<e.names.length;a++){let s=e.names[a],i=a===0?"\\"+e.operator:"&";n.push({pattern:i+this.escapeRegExp(s)+"=([^&]+)",name:s})}return n}let r,o=e.name;switch(e.operator){case"":r=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":r="(.+)";break;case".":r="\\.([^/,]+)";break;case"/":r="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:r="([^/]+)"}return n.push({pattern:r,name:o}),n}match(e){t.validateLength(e,1e6,"URI");let n="^",r=[];for(let i of this.parts)if(typeof i=="string")n+=this.escapeRegExp(i);else{let l=this.partToRegExp(i);for(let{pattern:d,name:h}of l)n+=d,r.push({name:h,exploded:i.exploded})}n+="$",t.validateLength(n,1e6,"Generated regex pattern");let o=new RegExp(n),a=e.match(o);if(!a)return null;let s={};for(let i=0;i<r.length;i++){let{name:l,exploded:d}=r[i],h=a[i+1],p=l.replace("*","");d&&h.includes(",")?s[p]=h.split(","):s[p]=h}return s}};u();var wP=/^[A-Za-z0-9._-]{1,128}$/;function vP(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!wP.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,a)=>a.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function IP(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function hu(t){let e=vP(t);return IP(t,e.warnings),e.isValid}u();var bs=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}};u();var Ig=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Es(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new bs(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Pa)),this.server.assertCanSetRequestHandler(Xt(nr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Pa,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Xn(n.inputSchema);return o?fl(o,{strictUnions:!0,pipeStrategy:"input"}):AP})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Xn(n.outputSchema);o&&(r.outputSchema=fl(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(nr,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new x($.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new x($.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,a=r.execution?.taskSupport,s="createTask"in r.handler;if((a==="required"||a==="optional")&&!s)throw new x($.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!o)throw new x($.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(r,e,n);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),l=await this.executeToolHandler(r,i,n);return o||await this.validateToolOutput(r,l,e.params.name),l}catch(r){if(r instanceof x&&r.code===$.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let a=Xn(e.inputSchema)??e.inputSchema,s=await sa(a,n);if(!s.success){let i="error"in s?s.error:"Unknown error",l=ia(i);throw new x($.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${l}`)}return s.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new x($.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Xn(e.outputSchema),a=await sa(o,n.structuredContent);if(!a.success){let s="error"in a?a.error:"Unknown error",i=ia(s);throw new x($.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let s={...r,taskStore:r.taskStore};if(e.inputSchema){let i=o;return await Promise.resolve(i.createTask(n,s))}else{let i=o;return await Promise.resolve(i.createTask(s))}}if(e.inputSchema){let s=o;return await Promise.resolve(s(n,r))}else{let s=o;return await Promise.resolve(s(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),a=e.handler,s={...r,taskStore:r.taskStore},i=o?await Promise.resolve(a.createTask(o,s)):await Promise.resolve(a.createTask(s)),l=i.task.taskId,d=i.task,h=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(g=>setTimeout(g,h));let p=await r.taskStore.getTask(l);if(!p)throw new x($.InternalError,`Task ${l} not found during polling`);d=p}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Xt(Da)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Da,async e=>{switch(e.params.ref.type){case"ref/prompt":return Bp(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return qp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new x($.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new x($.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new x($.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Po;let a=Ft(r.argsSchema)?.[e.params.argument.name];if(!uu(a))return Po;let s=vg(a);if(!s)return Po;let i=await s(e.params.argument.value,e.params.context);return Og(i)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Po;throw new x($.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Po;let a=await o(e.params.argument.value,e.params.context);return Og(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Ia)),this.server.assertCanSetRequestHandler(Xt(Aa)),this.server.assertCanSetRequestHandler(Xt(Sa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ia,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([a,s])=>s.enabled).map(([a,s])=>({uri:a,name:s.name,...s.metadata})),o=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let s=await a.resourceTemplate.listCallback(n);for(let i of s.resources)o.push({...a.metadata,...i})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Aa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Sa,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new x($.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let a of Object.values(this._registeredResourceTemplates)){let s=a.resourceTemplate.uriTemplate.match(r.toString());if(s)return a.readCallback(r,s,n)}throw new x($.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Oa)),this.server.assertCanSetRequestHandler(Xt(Na)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oa,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?SP(n.argsSchema):void 0}))})),this.server.setRequestHandler(Na,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new x($.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new x($.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Xn(r.argsSchema),a=await sa(o,e.params.arguments);if(!a.success){let l="error"in a?a.error:"Unknown error",d=ia(l);throw new x($.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let s=a.data,i=r.callback;return await Promise.resolve(i(s,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let a=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,void 0,n,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,n,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let a=this._createRegisteredResource(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,n,r,o,a){let s={name:e,title:n,metadata:o,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],i.uri&&(this._registeredResources[i.uri]=s)),typeof i.name<"u"&&(s.name=i.name),typeof i.title<"u"&&(s.title=i.title),typeof i.metadata<"u"&&(s.metadata=i.metadata),typeof i.callback<"u"&&(s.readCallback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=s,s}_createRegisteredResourceTemplate(e,n,r,o,a){let s={resourceTemplate:r,title:n,metadata:o,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=s)),typeof d.title<"u"&&(s.title=d.title),typeof d.template<"u"&&(s.resourceTemplate=d.template),typeof d.metadata<"u"&&(s.metadata=d.metadata),typeof d.callback<"u"&&(s.readCallback=d.callback),typeof d.enabled<"u"&&(s.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let i=r.uriTemplate.variableNames;return Array.isArray(i)&&i.some(d=>!!r.completeCallback(d))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,n,r,o,a){let s={title:n,description:r,argsSchema:o===void 0?void 0:vn(o),callback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=s)),typeof i.title<"u"&&(s.title=i.title),typeof i.description<"u"&&(s.description=i.description),typeof i.argsSchema<"u"&&(s.argsSchema=vn(i.argsSchema)),typeof i.callback<"u"&&(s.callback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,o&&Object.values(o).some(l=>{let d=l instanceof Ue?l._def?.innerType:l;return uu(d)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,n,r,o,a,s,i,l,d){hu(e);let h={title:n,description:r,inputSchema:Sg(o),outputSchema:Sg(a),annotations:s,execution:i,_meta:l,handler:d,enabled:!0,disable:()=>h.update({enabled:!1}),enable:()=>h.update({enabled:!0}),remove:()=>h.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&hu(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=h)),typeof p.title<"u"&&(h.title=p.title),typeof p.description<"u"&&(h.description=p.description),typeof p.paramsSchema<"u"&&(h.inputSchema=vn(p.paramsSchema)),typeof p.outputSchema<"u"&&(h.outputSchema=vn(p.outputSchema)),typeof p.callback<"u"&&(h.handler=p.callback),typeof p.annotations<"u"&&(h.annotations=p.annotations),typeof p._meta<"u"&&(h._meta=p._meta),typeof p.enabled<"u"&&(h.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=h,this.setToolRequestHandlers(),this.sendToolListChanged(),h}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,a,s;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let l=n[0];if(pu(l))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!pu(n[0])&&(s=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=n.shift()}}let i=n[0];return this._createRegisteredTool(e,void 0,r,o,a,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:a,inputSchema:s,outputSchema:i,annotations:l,_meta:d}=n;return this._createRegisteredTool(e,o,a,s,i,l,{taskSupport:"forbidden"},d,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let a=n[0],s=this._createRegisteredPrompt(e,void 0,r,o,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:a,argsSchema:s}=n,i=this._createRegisteredPrompt(e,o,a,s,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Ag=class{constructor(e,n){this._callbacks=n,this._uriTemplate=typeof e=="string"?new Ts(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},AP={type:"object",properties:{}};function Ng(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Pg(t){return"_def"in t||"_zod"in t||Ng(t)}function pu(t){return typeof t!="object"||t===null||Pg(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ng)}function Sg(t){if(t){if(pu(t))return vn(t);if(!Pg(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function SP(t){let e=Ft(t);return e?Object.entries(e).map(([n,r])=>{let o=ap(r),a=sp(r);return{name:n,description:o,required:!a}}):[]}function Xt(t){let n=Ft(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=ca(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Og(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Po={completion:{values:[],hasMore:!1}};u();u();u();u();u();import{readFileSync as LP}from"node:fs";import{dirname as $P,join as zP}from"node:path";import{fileURLToPath as MP}from"node:url";u();var be,Co=null;function ws(){return(Co===null||Co.byteLength===0)&&(Co=new Uint8Array(be.memory.buffer)),Co}var vs=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&vs.decode();var OP=2146435072,mu=0;function NP(t,e){return mu+=e,mu>=OP&&(vs=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}},vs.decode(),mu=e),vs.decode(ws().subarray(t,t+e))}function fu(t,e){return t=t>>>0,NP(t,e)}function _u(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return`${t}`;if(e=="string")return`"${t}"`;if(e=="symbol"){let o=t.description;return o==null?"Symbol":`Symbol(${o})`}if(e=="function"){let o=t.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(t)){let o=t.length,a="[";o>0&&(a+=_u(t[0]));for(let s=1;s<o;s++)a+=", "+_u(t[s]);return a+="]",a}let n=/\[object ([^\]]+)\]/.exec(toString.call(t)),r;if(n&&n.length>1)r=n[1];else return toString.call(t);if(r=="Object")try{return"Object("+JSON.stringify(t)+")"}catch{return"Object"}return t instanceof Error?`${t.name}: ${t.message}
|
|
43
|
-
${t.stack}`:r}var As=0,Is=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},PP=typeof Is.encodeInto=="function"?function(t,e){return Is.encodeInto(t,e)}:function(t,e){let n=Is.encode(t);return e.set(n),{read:t.length,written:n.length}};function Cg(t,e,n){if(n===void 0){let i=Is.encode(t),l=e(i.length,1)>>>0;return ws().subarray(l,l+i.length).set(i),As=i.length,l}let r=t.length,o=e(r,1)>>>0,a=ws(),s=0;for(;s<r;s++){let i=t.charCodeAt(s);if(i>127)break;a[o+s]=i}if(s!==r){s!==0&&(t=t.slice(s)),o=n(o,r,r=s+t.length*3,1)>>>0;let i=ws().subarray(o+s,o+r),l=PP(t,i);s+=l.written,o=n(o,r,s,1)>>>0}return As=s,o}var Ln=null;function gu(){return(Ln===null||Ln.buffer.detached===!0||Ln.buffer.detached===void 0&&Ln.buffer!==be.memory.buffer)&&(Ln=new DataView(be.memory.buffer)),Ln}function CP(t){return t==null}function DP(t,e){t=t>>>0;let n=gu(),r=[];for(let o=t;o<t+4*e;o+=4)r.push(be.__wbindgen_export_2.get(n.getUint32(o,!0)));return be.__externref_drop_slice(t,e),r}function Dg(t,e){let n=Cg(t,be.__wbindgen_malloc,be.__wbindgen_realloc),r=As,o=be.cut(n,r,CP(e)?16777215:e?1:0);var a=DP(o[0],o[1]).slice();return be.__wbindgen_free(o[0],o[1]*4,4),a}var RP=new Set(["basic","cors","default"]);async function xP(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.ok&&RP.has(t.type)&&t.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function Rg(){let t={};return t.wbg={},t.wbg.__wbg_Error_0497d5bdba9362e5=function(e,n){return Error(fu(e,n))},t.wbg.__wbg_new_07b483f72211fd66=function(){return new Object},t.wbg.__wbg_set_3f1d0b984ed272ed=function(e,n,r){e[n]=r},t.wbg.__wbindgen_bigint_from_u64=function(e){return BigInt.asUintN(64,e)},t.wbg.__wbindgen_debug_string=function(e,n){let r=_u(n),o=Cg(r,be.__wbindgen_malloc,be.__wbindgen_realloc),a=As;gu().setInt32(e+4,a,!0),gu().setInt32(e+0,o,!0)},t.wbg.__wbindgen_init_externref_table=function(){let e=be.__wbindgen_export_2,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,!0),e.set(n+3,!1)},t.wbg.__wbindgen_number_new=function(e){return e},t.wbg.__wbindgen_string_new=function(e,n){return fu(e,n)},t.wbg.__wbindgen_throw=function(e,n){throw new Error(fu(e,n))},t}function xg(t,e){return be=t.exports,kP.__wbindgen_wasm_module=e,Ln=null,Co=null,be.__wbindgen_start(),be}function kg(t){if(be!==void 0)return be;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module:t}=t:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let e=Rg();t instanceof WebAssembly.Module||(t=new WebAssembly.Module(t));let n=new WebAssembly.Instance(t,e);return xg(n,t)}async function kP(t){if(be!==void 0)return be;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module_or_path:t}=t:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof t>"u"&&(t=new URL("jieba_rs_wasm_bg.wasm",import.meta.url));let e=Rg();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:r}=await xP(await t,e);return xg(n,r)}var Lg=!1,$g=(t,e)=>{if(!Lg){let n=zP($P(MP(import.meta.url)),"jieba-engine.wasm");kg({module:LP(n)}),Lg=!0}return Dg(t,e)};var UP=new Set(["a","an","and","are","as","at","be","but","by","for","if","in","into","is","it","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"]),jP=/[a-z0-9]+/g,FP=t=>{let e=t.toLowerCase().replace(/'s\b/g,""),n=[];for(let r of e.matchAll(jP)){let o=r[0];UP.has(o)||n.push(BP(o))}return n},GP=/[㐀-鿿豈--ヿ가-]|[a-z0-9]/i,ZP=t=>$g(t.toLowerCase(),!0).filter(e=>GP.test(e)),Eu=t=>{switch(Un){case"ZION":return ZP(t);case"MOMEN":return FP(t);default:throw new Error(`[analyzer] unknown PRODUCT '${Un}'`)}},$n=(t,e)=>{let n=t[e];return n==="a"||n==="e"||n==="i"||n==="o"||n==="u"?!1:n==="y"?e===0?!0:!$n(t,e-1):!0},Qt=t=>{let e=0,n=!1;for(let r=0;r<t.length;r+=1){let o=!$n(t,r);n&&!o&&(e+=1),n=o}return e},yu=t=>{for(let e=0;e<t.length;e+=1)if(!$n(t,e))return!0;return!1},zg=t=>{let e=t.length;return e>=2&&t[e-1]===t[e-2]&&$n(t,e-1)},Mg=t=>{let e=t.length;if(e<3||!$n(t,e-1)||$n(t,e-2)||!$n(t,e-3))return!1;let n=t[e-1];return n!=="w"&&n!=="x"&&n!=="y"},Ss=(t,e,n)=>t.slice(0,t.length-e.length)+n;function BP(t){let e=t;if(e.length<=2)return e;e.endsWith("sses")?e=Ss(e,"sses","ss"):e.endsWith("ies")?e=Ss(e,"ies","i"):e.endsWith("ss")||e.endsWith("s")&&(e=e.slice(0,-1));let n=!1;e.endsWith("eed")?Qt(e.slice(0,-3))>0&&(e=e.slice(0,-1)):e.endsWith("ed")&&yu(e.slice(0,-2))?(e=e.slice(0,-2),n=!0):e.endsWith("ing")&&yu(e.slice(0,-3))&&(e=e.slice(0,-3),n=!0),n&&(e.endsWith("at")||e.endsWith("bl")||e.endsWith("iz")?e+="e":zg(e)&&!/[lsz]$/.test(e)?e=e.slice(0,-1):Qt(e)===1&&Mg(e)&&(e+="e")),e.endsWith("y")&&yu(e.slice(0,-1))&&(e=`${e.slice(0,-1)}i`);let r=[["ational","ate"],["tional","tion"],["enci","ence"],["anci","ance"],["izer","ize"],["bli","ble"],["alli","al"],["entli","ent"],["eli","e"],["ousli","ous"],["ization","ize"],["ation","ate"],["ator","ate"],["alism","al"],["iveness","ive"],["fulness","ful"],["ousness","ous"],["aliti","al"],["iviti","ive"],["biliti","ble"],["logi","log"]];for(let[i,l]of r)if(e.endsWith(i)){Qt(e.slice(0,e.length-i.length))>0&&(e=Ss(e,i,l));break}let o=[["icate","ic"],["ative",""],["alize","al"],["iciti","ic"],["ical","ic"],["ful",""],["ness",""]];for(let[i,l]of o)if(e.endsWith(i)){Qt(e.slice(0,e.length-i.length))>0&&(e=Ss(e,i,l));break}let a=["al","ance","ence","er","ic","able","ible","ant","ement","ment","ent","ou","ism","ate","iti","ous","ive","ize"],s=!1;for(let i of a)if(e.endsWith(i)){let l=e.slice(0,e.length-i.length);Qt(l)>1&&(e=l),s=!0;break}if(!s&&e.endsWith("ion")){let i=e.slice(0,-3);Qt(i)>1&&/[st]$/.test(i)&&(e=i)}if(e.endsWith("e")){let i=e.slice(0,-1),l=Qt(i);(l>1||l===1&&!Mg(i))&&(e=i)}return Qt(e)>1&&zg(e)&&e.endsWith("l")&&(e=e.slice(0,-1)),e}u();var Ug=1.5,jg=.75,qP=t=>{let e=[],n=new Map,r=0;for(let{ref:o,tokens:a}of t){let s=new Map;for(let i of a)s.set(i,(s.get(i)??0)+1);for(let i of s.keys())n.set(i,(n.get(i)??0)+1);e.push({ref:o,tf:s,length:a.length}),r+=a.length}return{docs:e,df:n,avgdl:e.length>0?r/e.length:0}},VP=(t,e)=>{let n=[...new Set(Eu(e))],r=t.docs.length;return n.length===0||r===0?[]:t.docs.map(o=>{let a=0;for(let s of n){let i=o.tf.get(s);if(!i)continue;let l=t.df.get(s)??0,d=Math.log(1+(r-l+.5)/(l+.5)),h=i+Ug*(1-jg+jg*o.length/(t.avgdl||1));a+=d*(i*(Ug+1)/h)}return{ref:o.ref,score:a}})};u();var wr={actionflow:"## Actionflow Domain Knowledge\nActionflows are server-side workflows for business logic. They run entirely on the server; the frontend triggers them via \"Request \u2013 Actionflow\" component actions.\n\n### When to Use an Actionflow\nDo not create an Actionflow merely to proxy CRUD. Simple single-table CRUD should run directly from the frontend when table, column, and row permissions fully express the authorization policy. Reserve Actionflows for genuinely server-side, multi-step, transactional, or orchestrated operations: cross-table atomicity, trusted calculations or secrets, loops, AI steps, third-party calls, schedules, webhooks, and database triggers. If data permissions cannot express the authorization rule, enforce it server-side here. A condition on its own is not a reason to build a flow: a check that only decides what the UI does belongs in the frontend, and only a condition that must be guaranteed rather than merely evaluated has to run here, where the client cannot bypass it. That includes authorization checks \u2014 if the rule is already expressed in table, column, and row permissions, the frontend may hold the condition, because permissions are enforced on every request and nothing the client sends can bypass them. Wrapping such a check in a flow adds a hop and a second place for the rule to drift, without making it any harder to circumvent.\n\n### Execution Modes\nSynchronous: all nodes in one synchronous Actionflow invocation execute inside a single database transaction; the caller blocks for the result, and any node error rolls back every DB write from that invocation. Asynchronous: the caller gets a task handle instead of blocking and retrieves the result later \u2014 the flow still computes and returns its declared output; only the failing node's DB writes roll back; required for AI agents and video generation.\n\nEvery flow has a `timeout` in seconds for the whole run, not per node: 30 s by default for a synchronous flow and 120 s for an asynchronous one, whose clock keeps running through Delay and AI waits. Set it on ADD_ACTION_FLOWS or UPDATE_ACTION_FLOW: at least 1, and at most 60 while the flow is synchronous \u2014 a job that needs longer belongs in an asynchronous flow. GET_ALL_ACTION_FLOWS_INFO and GET_ACTION_FLOW_DETAIL report the timeout in force, default included. When it runs out the flow is cut off inside whatever node is running (a query, custom code, an API call) and fails with a timeout error; a synchronous flow's DB writes roll back. Switching a flow whose timeout is above 60 s to synchronous is refused unless the same UPDATE_ACTION_FLOW call lowers `timeout`.\n\n### Triggers\nWhat fires a flow. Four kinds: Manual (a UI action \u2014 no config), scheduled (cron), database-change event, and webhook. Scheduled and database-change triggers are tool-managed: inspect with `GET_ALL_SCHEDULED_TRIGGERS_INFO` / `GET_ALL_DB_TRIGGERS_INFO`, create with `ADD_SCHEDULED_TRIGGERS` (a Quartz cron \u2014 set a future `endInstant` or it never fires) and `ADD_DB_TRIGGERS` (a table + INSERT/UPDATE/DELETE), each pointing at a flow id from `GET_ALL_ACTION_FLOWS_INFO` (update/delete variants too). Manual triggers need no setup; webhook triggers are managed by the separate `webhook` plugin (`ADD_CALLBACK_TRIGGERS`) \u2014 load it to add or edit an incoming HTTP webhook that fires a flow.\n\n### Node Types\nWhat can be added at a position is the add-node menu there: read it with BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at that same `afterNodeId` and pass that entry's `node` to ADD_ACTION_FLOW_NODE \u2014 the entry already carries every default for that position, and its config fields are yours to override; its `type` and `templateCodeId` name the menu entry, so never assemble those yourself, and an entry disabled there is refused with the same reason. The menu also carries the deployment's **preset integration nodes** (the `TEMPLATE_CODE` entries \u2014 the current user's ID / WeChat OpenID / Access Token, file/media conversion to Zion native types, SMS, and video/AI generation), whose set varies by deployment. There is no built-in `CURRENT_USER` / `FILES` / `SMS` node type; do not pass those to `ADD_ACTION_FLOW_NODE`.\n\n### AI Conversation Nodes\nAI conversation nodes are valid only in asynchronous Actionflows.\n\n`AI_CREATE_CONVERSATION` creates a new conversation and runs its first turn. Bind the Agent's declared inputs; Start has no free-form message field because the first user message comes from the Agent's configured prompt. When the node completes, `id` is the conversation ID and `data` is the Agent result. For plain output, `data` is text; for structured output, it has the Agent's declared output type. `id` and `data` are the stable fields. Inspect the node's data-binding options for feature-dependent reasoning and media outputs.\n\n`AI_SEND_MESSAGE` continues an existing conversation. Continue returns the same `id` and `data` shape as Start. Bind `conversationId` to the `id` returned by Start, then bind the new message. Continue uses the Agent configuration stored by Start; selecting another Agent on Continue does not switch the conversation. Use the same `configId` as Start so validation and output typing remain correct.\n\n`AI_STOP_RESPONSE` cancels only the response currently being generated. It preserves the conversation, which may later be continued. `AI_DELETE_CONVERSATION` permanently deletes the conversation and its messages. Stop and Delete have no node output.\n\nUse the target node's data-binding options to select the preceding Start or Continue node's `id`; the event's `taskId` is not a conversation ID.\n\nStart and Continue are wait points: the Actionflow does not proceed to the next node until the AI response finishes. A Stop node placed after Start or Continue therefore cannot stop that response.\n\n**Current runtime limitation:** There is currently no safe cancellation path for a response launched by an Actionflow. Do not use Stop for a response launched by an Actionflow. Stop acts only while the stored status is `IN_PROGRESS`; once it is `STREAMING`, Stop does not cancel the response. If Stop reaches an in-progress response, canceling leaves the AI child task processing, so the source Actionflow never resumes.\n\n### Choosing How to Express Logic: nodes \u2192 formulas \u2192 code\nThree tiers, in order of preference:\n1. **Visual nodes** for orchestration \u2014 query / branch / iterate / write / call (Database, Condition, Loop, Set Variable, Call API, Run Actionflow). They take part in the flow's transaction, surface individually in logs and the edit-time error collector, and stay user-editable.\n2. **Formula bindings** for value-level computation. A node value \u2014 a Set Variable value, a mutation column, a condition predicate \u2014 can be a FORMULA binding built with the bindings plugin, and formulas cover far more than people expect: text and regex (extract / match / replace, substring, split, concat), math, date/time arithmetic and formatting, array aggregation / mapping / filtering, JSON value access, and type casts. Prefer a formula over code whenever you are computing a single value.\n3. **Run Code** only for genuinely procedural logic that neither a node nor a formula operator expresses \u2014 e.g. cryptographic hashing / signature building, multi-step algorithms with intermediate state, or assembling / parsing a complex nested payload. Keep it small and fed by node inputs; never collapse a whole flow into one Run Code node.\n\n### Variables\nDeclared at flow level, accessible by all nodes, assigned with \"Set Variable\" node.\n\n### Inputs & Outputs\nInspect a flow first with `GET_ALL_ACTION_FLOWS_INFO` / `GET_ACTION_FLOW_DETAIL` (unless its detail is already provided in your context). Declare typed **input params** with `ADD_ACTION_FLOW_INPUT_PARAMS`; set each param's type to a value copied verbatim from `GET_ACTION_FLOW_SELECTABLE_TYPES` (never hand-build the type string). Every input param, variable, output field and code-node input/output name is an identifier: letters, digits and underscores only, never starting with a digit. The editor enforces the same rule on a manual rename, so a name that breaks it is one the user cannot repair in the UI; put user-facing wording in a displayName or description instead.\n\nA flow returns a **single typed output value**: set its type with `SET_ACTION_FLOW_OUTPUT`\n(type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`) and clear it with\n`CLEAR_ACTION_FLOW_OUTPUT`; bind the value afterwards at the output's schema path.\n\n### Building & Editing a Flow\nCreate flows with `ADD_ACTION_FLOWS` (each seeds an empty FLOW_START \u2192 FLOW_END), then read node and structure ids from `GET_ACTION_FLOW_DETAIL` before editing. See what can be added after a node with `BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS` at that same position, then add an entry's `node` with `ADD_ACTION_FLOW_NODE`; reorder with `MOVE_ACTION_FLOW_NODES`, remove with `DELETE_ACTION_FLOW_NODES`, and branch a Condition node with `ADD_ACTION_FLOW_BRANCH_ITEM`. When a flow has grown a run of nodes that reads as one step, or the same run is wanted in another flow, extract it with `EXTRACT_ACTION_FLOW_NODES` instead of rebuilding it: the run becomes a new flow with the inputs and output it needs, and a Run Actionflow node calling it stays in place. Every node's displayName should state its business intent ('Insert generation request', 'Decrement like count') rather than the node-type default \u2014 it is optional, and a name left off becomes that default, so omit it only when no better name fits. Edit a node's name or type-scalar config with `UPDATE_ACTION_FLOW_NODE`, but set its data bindings (values, conditions, data sources, mutation fields) with the bindings plugin at the node's schema path \u2014 never inline. A node's schema path is NEVER hand-built: copy it from `ADD_ACTION_FLOW_NODE`'s result or `GET_ACTION_FLOW_DETAIL`'s nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments to reach a binding site inside the node. The key names vary by node type \u2014 an AI node's input arg is `.../allNodes/{j}/inputArgs/<argKey>`, a code node's is `.../allNodes/{j}/inputs/{index}/value`, a mutation column is `.../allNodes/{j}/mutation/object/<columnName>` \u2014 copy the exact keys from `GET_ACTION_FLOW_CONTEXT_INFO`'s currentNode structure, never guess them. Declare flow variables with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` and assign them in a Set Variable node with `ADD_GLOBAL_VARIABLES_NODE_TARGETS`. A Run Code node's `args.<name>` input slots are managed with `ADD_CUSTOM_CODE_NODE_INPUT` (rename/delete variants); its result type is declared with `SET_CUSTOM_CODE_NODE_OUTPUT_TYPE` so downstream nodes can bind to it; fill the code body with `CREATE_CONST_BINDING`. An update or delete Database node is seeded with an always-true filter that matches **every** row \u2014 narrow it with the bindings plugin's request filters before syncing, or the write hits the whole table. A workspace API node's request parameters are pre-seeded on the node when the API is selected \u2014 read the node back and bind ONLY the parameter slots it shows under `event/inputs/<param>`. NEVER invent input keys the read-back does not show: the runtime and editor ignore them.\n\n### Condition Branches\nCondition branches use their left-to-right editor order. At runtime, only the first branch whose condition is true has its branch body executed; branches to its right are not entered. Put an `Always` branch last when fallback behavior is required\u2014an earlier `Always` branch shadows every branch to its right. Do not rely on the no-match behavior; provide an explicit fallback whenever the flow must choose a branch. Only `MUTUAL_EXCLUSION` is supported. `MUTUAL_TOLERANCE` may still appear in generated argument schemas, but tolerance branches are not implemented and fail at runtime. Always set a Condition node's `conditionType` to `MUTUAL_EXCLUSION`.\n\n### Node Input Visibility (Scope)\nWhat a node can bind to is not \"any earlier node\": ztype limits it to the nodes **visible** from that site \u2014 the ones on its straight path back from FLOW_START. The data binding options tree returned with every binding response (its \"Actionflow data\" branch) already applies this rule and is the authoritative list of reachable node outputs; if a node is absent there it is out of scope, so never hand-build a path to reach it.\n\nLoops and Condition branches are **one-way scopes**. From *inside* a block, a node sees the outer scope, the flow inputs, and \u2014 in a Loop \u2014 the current item; but from *outside* the block (any node after the loop's end or after a branch merge) the block's inner nodes are invisible, and sibling branches never see one another. A value produced inside one branch or one loop iteration therefore CANNOT be bound directly by a later node \u2014 it will not appear in that node's options tree.\n\nTo carry a branch- or loop-dependent value past the block, use a **flow variable** \u2014 the only output that crosses a scope boundary. Declare it once with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` (type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`), assign it *inside* the branch or loop body with a Set Variable node (`ADD_GLOBAL_VARIABLES_NODE_TARGETS`), then read the variable from any later node. Idioms: choose a value by branch \u2014 assign the SAME variable in every branch, then read it after the merge; capture or accumulate across a Loop \u2014 assign the variable inside the loop body, then read it after the loop's end. A branch that never assigns the variable leaves its prior value, so set a sensible default before the branch when every path must yield one.\n\n### Concurrency\nConcurrent invocations of the same flow interleave between nodes; sync-mode ACID rolls back on error but does NOT serialize flows (read committed). Query-a-row, branch, then write based on that read is a race: concurrent calls all act on the same stale read. Where the platform can express the check inside the write, prefer that: put row-local guards in the mutation node's own filter (update where stock >= qty; delete where the key pair matches) and branch on the write's affected rows; use an update node's increment/decrement mode for counters; for insert-if-absent or toggle semantics use a unique constraint (the only DB-enforced constraint kind today) with `insert ... on_conflict do nothing` and branch on affected_rows \u2014 that idiom is only expressible in a Run Code node, which makes it a legitimate Run Code use. Invariants none of these can express (cross-row rules, aggregates) have no atomic form yet; check-then-write is the accepted fallback there.\n\n### Error Handling\nSynchronous: all DB changes roll back on error. Asynchronous: only the failing node's DB changes roll back.\n\n### Versioning\nEach save creates a new version. \"Sync Backend\" required after editing for changes to take effect in production.\n\n### JavaScript Sandbox (Run Code node)\nCustom Code Blocks run in a synchronous GraalJS server sandbox. No async/await, no require(), no browser APIs. All platform interactions go through the global `context` object: context.getArg(key) \u2014 retrieve flow input context.setResult(val) \u2014 pass this node's single result downstream context.runGql(opName, gql, vars, permission) \u2014 execute DB operations context.callThirdPartyApi(apiId, params) \u2014 invoke a workspace API by its apiId (the method name is historical; this project has no third-party API configs) context.callActionFlow(flowId, ver, args) \u2014 run a sub-flow synchronously context.createActionFlowTask(flowId, ver, args) \u2014 trigger a sub-flow async context.getSsoUserInfo() \u2014 get authenticated user profile context.uploadMedia(url, headers) \u2014 stream remote image to asset server context.log(message) \u2014 emit to Log Service\n\n`runGql` takes FOUR arguments and the first one is the operation NAME, not the document: `runGql(\"GetWords\", \"query GetWords { theme_word(where: {...}) { word } }\", {}, {role: \"admin\"})`. The name must match the one declared in the document. `vars` is a JS object (not a JSON string) and `permission` is `{role: \"<role name>\"}` with an optional `sessionVariable` map. Passing the document first is the mistake that costs an afternoon: the arity error, then a String-coercion error naming a type you did not pass, then \"permission should have field role\" are all the same misalignment reported one argument at a time.\n\nIt returns the `data` object directly \u2014 `r.theme_word`, never `r.data.theme_word` \u2014 and it THROWS on a GraphQL error rather than returning an `errors` array, so there is no envelope to branch on. Do not write defensive code for a response shape you have not seen.\n\nThe list above is the methods you will reach for, not the whole API. The complete Context API reference \u2014 every method with its parameters and return shape \u2014 is the \"Develop with Run Code\" developer page: find it with `docs.search`, and read it rather than inferring a signature from an error message. Search by title; the page's path is not the same across products.",agent:`Zion is a powerful no-code development platform that enables developers to build and deploy web, mobile, and WeChat Mini Program (\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F) applications. It integrates a visual drag-and-drop design canvas, an enterprise-grade relational database engine (PostgreSQL), and an event-driven backend logic execution pipeline.
|
|
43
|
+
${t.stack}`:r}var As=0,Is=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},PP=typeof Is.encodeInto=="function"?function(t,e){return Is.encodeInto(t,e)}:function(t,e){let n=Is.encode(t);return e.set(n),{read:t.length,written:n.length}};function Cg(t,e,n){if(n===void 0){let i=Is.encode(t),l=e(i.length,1)>>>0;return ws().subarray(l,l+i.length).set(i),As=i.length,l}let r=t.length,o=e(r,1)>>>0,a=ws(),s=0;for(;s<r;s++){let i=t.charCodeAt(s);if(i>127)break;a[o+s]=i}if(s!==r){s!==0&&(t=t.slice(s)),o=n(o,r,r=s+t.length*3,1)>>>0;let i=ws().subarray(o+s,o+r),l=PP(t,i);s+=l.written,o=n(o,r,s,1)>>>0}return As=s,o}var Ln=null;function gu(){return(Ln===null||Ln.buffer.detached===!0||Ln.buffer.detached===void 0&&Ln.buffer!==be.memory.buffer)&&(Ln=new DataView(be.memory.buffer)),Ln}function CP(t){return t==null}function DP(t,e){t=t>>>0;let n=gu(),r=[];for(let o=t;o<t+4*e;o+=4)r.push(be.__wbindgen_export_2.get(n.getUint32(o,!0)));return be.__externref_drop_slice(t,e),r}function Dg(t,e){let n=Cg(t,be.__wbindgen_malloc,be.__wbindgen_realloc),r=As,o=be.cut(n,r,CP(e)?16777215:e?1:0);var a=DP(o[0],o[1]).slice();return be.__wbindgen_free(o[0],o[1]*4,4),a}var RP=new Set(["basic","cors","default"]);async function xP(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.ok&&RP.has(t.type)&&t.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function Rg(){let t={};return t.wbg={},t.wbg.__wbg_Error_0497d5bdba9362e5=function(e,n){return Error(fu(e,n))},t.wbg.__wbg_new_07b483f72211fd66=function(){return new Object},t.wbg.__wbg_set_3f1d0b984ed272ed=function(e,n,r){e[n]=r},t.wbg.__wbindgen_bigint_from_u64=function(e){return BigInt.asUintN(64,e)},t.wbg.__wbindgen_debug_string=function(e,n){let r=_u(n),o=Cg(r,be.__wbindgen_malloc,be.__wbindgen_realloc),a=As;gu().setInt32(e+4,a,!0),gu().setInt32(e+0,o,!0)},t.wbg.__wbindgen_init_externref_table=function(){let e=be.__wbindgen_export_2,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,!0),e.set(n+3,!1)},t.wbg.__wbindgen_number_new=function(e){return e},t.wbg.__wbindgen_string_new=function(e,n){return fu(e,n)},t.wbg.__wbindgen_throw=function(e,n){throw new Error(fu(e,n))},t}function xg(t,e){return be=t.exports,kP.__wbindgen_wasm_module=e,Ln=null,Co=null,be.__wbindgen_start(),be}function kg(t){if(be!==void 0)return be;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module:t}=t:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let e=Rg();t instanceof WebAssembly.Module||(t=new WebAssembly.Module(t));let n=new WebAssembly.Instance(t,e);return xg(n,t)}async function kP(t){if(be!==void 0)return be;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module_or_path:t}=t:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof t>"u"&&(t=new URL("jieba_rs_wasm_bg.wasm",import.meta.url));let e=Rg();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:r}=await xP(await t,e);return xg(n,r)}var Lg=!1,$g=(t,e)=>{if(!Lg){let n=zP($P(MP(import.meta.url)),"jieba-engine.wasm");kg({module:LP(n)}),Lg=!0}return Dg(t,e)};var UP=new Set(["a","an","and","are","as","at","be","but","by","for","if","in","into","is","it","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"]),jP=/[a-z0-9]+/g,FP=t=>{let e=t.toLowerCase().replace(/'s\b/g,""),n=[];for(let r of e.matchAll(jP)){let o=r[0];UP.has(o)||n.push(BP(o))}return n},GP=/[㐀-鿿豈--ヿ가-]|[a-z0-9]/i,ZP=t=>$g(t.toLowerCase(),!0).filter(e=>GP.test(e)),Eu=t=>{switch(Un){case"ZION":return ZP(t);case"MOMEN":return FP(t);default:throw new Error(`[analyzer] unknown PRODUCT '${Un}'`)}},$n=(t,e)=>{let n=t[e];return n==="a"||n==="e"||n==="i"||n==="o"||n==="u"?!1:n==="y"?e===0?!0:!$n(t,e-1):!0},Qt=t=>{let e=0,n=!1;for(let r=0;r<t.length;r+=1){let o=!$n(t,r);n&&!o&&(e+=1),n=o}return e},yu=t=>{for(let e=0;e<t.length;e+=1)if(!$n(t,e))return!0;return!1},zg=t=>{let e=t.length;return e>=2&&t[e-1]===t[e-2]&&$n(t,e-1)},Mg=t=>{let e=t.length;if(e<3||!$n(t,e-1)||$n(t,e-2)||!$n(t,e-3))return!1;let n=t[e-1];return n!=="w"&&n!=="x"&&n!=="y"},Ss=(t,e,n)=>t.slice(0,t.length-e.length)+n;function BP(t){let e=t;if(e.length<=2)return e;e.endsWith("sses")?e=Ss(e,"sses","ss"):e.endsWith("ies")?e=Ss(e,"ies","i"):e.endsWith("ss")||e.endsWith("s")&&(e=e.slice(0,-1));let n=!1;e.endsWith("eed")?Qt(e.slice(0,-3))>0&&(e=e.slice(0,-1)):e.endsWith("ed")&&yu(e.slice(0,-2))?(e=e.slice(0,-2),n=!0):e.endsWith("ing")&&yu(e.slice(0,-3))&&(e=e.slice(0,-3),n=!0),n&&(e.endsWith("at")||e.endsWith("bl")||e.endsWith("iz")?e+="e":zg(e)&&!/[lsz]$/.test(e)?e=e.slice(0,-1):Qt(e)===1&&Mg(e)&&(e+="e")),e.endsWith("y")&&yu(e.slice(0,-1))&&(e=`${e.slice(0,-1)}i`);let r=[["ational","ate"],["tional","tion"],["enci","ence"],["anci","ance"],["izer","ize"],["bli","ble"],["alli","al"],["entli","ent"],["eli","e"],["ousli","ous"],["ization","ize"],["ation","ate"],["ator","ate"],["alism","al"],["iveness","ive"],["fulness","ful"],["ousness","ous"],["aliti","al"],["iviti","ive"],["biliti","ble"],["logi","log"]];for(let[i,l]of r)if(e.endsWith(i)){Qt(e.slice(0,e.length-i.length))>0&&(e=Ss(e,i,l));break}let o=[["icate","ic"],["ative",""],["alize","al"],["iciti","ic"],["ical","ic"],["ful",""],["ness",""]];for(let[i,l]of o)if(e.endsWith(i)){Qt(e.slice(0,e.length-i.length))>0&&(e=Ss(e,i,l));break}let a=["al","ance","ence","er","ic","able","ible","ant","ement","ment","ent","ou","ism","ate","iti","ous","ive","ize"],s=!1;for(let i of a)if(e.endsWith(i)){let l=e.slice(0,e.length-i.length);Qt(l)>1&&(e=l),s=!0;break}if(!s&&e.endsWith("ion")){let i=e.slice(0,-3);Qt(i)>1&&/[st]$/.test(i)&&(e=i)}if(e.endsWith("e")){let i=e.slice(0,-1),l=Qt(i);(l>1||l===1&&!Mg(i))&&(e=i)}return Qt(e)>1&&zg(e)&&e.endsWith("l")&&(e=e.slice(0,-1)),e}u();var Ug=1.5,jg=.75,qP=t=>{let e=[],n=new Map,r=0;for(let{ref:o,tokens:a}of t){let s=new Map;for(let i of a)s.set(i,(s.get(i)??0)+1);for(let i of s.keys())n.set(i,(n.get(i)??0)+1);e.push({ref:o,tf:s,length:a.length}),r+=a.length}return{docs:e,df:n,avgdl:e.length>0?r/e.length:0}},VP=(t,e)=>{let n=[...new Set(Eu(e))],r=t.docs.length;return n.length===0||r===0?[]:t.docs.map(o=>{let a=0;for(let s of n){let i=o.tf.get(s);if(!i)continue;let l=t.df.get(s)??0,d=Math.log(1+(r-l+.5)/(l+.5)),h=i+Ug*(1-jg+jg*o.length/(t.avgdl||1));a+=d*(i*(Ug+1)/h)}return{ref:o.ref,score:a}})};u();var wr={actionflow:"## Actionflow Domain Knowledge\nActionflows are server-side workflows for business logic. They run entirely on the server; the frontend triggers them via \"Request \u2013 Actionflow\" component actions.\n\n### When to Use an Actionflow\nDo not create an Actionflow merely to proxy CRUD. Simple single-table CRUD should run directly from the frontend when table, column, and row permissions fully express the authorization policy. Reserve Actionflows for genuinely server-side, multi-step, transactional, or orchestrated operations: cross-table atomicity, trusted calculations or secrets, loops, AI steps, third-party calls, schedules, webhooks, and database triggers. If data permissions cannot express the authorization rule, enforce it server-side here. A condition on its own is not a reason to build a flow: a check that only decides what the UI does belongs in the frontend, and only a condition that must be guaranteed rather than merely evaluated has to run here, where the client cannot bypass it. That includes authorization checks \u2014 if the rule is already expressed in table, column, and row permissions, the frontend may hold the condition, because permissions are enforced on every request and nothing the client sends can bypass them. Wrapping such a check in a flow adds a hop and a second place for the rule to drift, without making it any harder to circumvent.\n\n### Execution Modes\nSynchronous: all nodes in one synchronous Actionflow invocation execute inside a single database transaction; the caller blocks for the result, and any node error rolls back every DB write from that invocation. Asynchronous: the caller gets a task handle instead of blocking and retrieves the result later \u2014 the flow still computes and returns its declared output; only the failing node's DB writes roll back; required for AI agents and video generation.\n\nEvery flow has a `timeout` in seconds for the whole run, not per node: 30 s by default for a synchronous flow and 120 s for an asynchronous one, whose clock stops while a Delay node waits but keeps running through AI waits. Set it on ADD_ACTION_FLOWS or UPDATE_ACTION_FLOW: at least 1, and at most 60 while the flow is synchronous \u2014 a job that needs longer belongs in an asynchronous flow. GET_ALL_ACTION_FLOWS_INFO and GET_ACTION_FLOW_DETAIL report the timeout in force, default included. When it runs out the flow is cut off inside whatever node is running (a query, custom code, an API call) and fails with a timeout error; a synchronous flow's DB writes roll back. Switching a flow whose timeout is above 60 s to synchronous is refused unless the same UPDATE_ACTION_FLOW call lowers `timeout`.\n\n### Triggers\nWhat fires a flow. Four kinds: Manual (a UI action \u2014 no config), scheduled (cron), database-change event, and webhook. Scheduled and database-change triggers are tool-managed: inspect with `GET_ALL_SCHEDULED_TRIGGERS_INFO` / `GET_ALL_DB_TRIGGERS_INFO`, create with `ADD_SCHEDULED_TRIGGERS` (a Quartz cron \u2014 set a future `endInstant` or it never fires) and `ADD_DB_TRIGGERS` (a table + INSERT/UPDATE/DELETE), each pointing at a flow id from `GET_ALL_ACTION_FLOWS_INFO` (update/delete variants too). Manual triggers need no setup; webhook triggers are managed by the separate `webhook` plugin (`ADD_CALLBACK_TRIGGERS`) \u2014 load it to add or edit an incoming HTTP webhook that fires a flow.\n\n### Node Types\nWhat can be added at a position is the add-node menu there: read it with BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at that same `afterNodeId` and pass that entry's `node` to ADD_ACTION_FLOW_NODE \u2014 the entry already carries every default for that position, and its config fields are yours to override; its `type` and `templateCodeId` name the menu entry, so never assemble those yourself, and an entry disabled there is refused with the same reason. The menu also carries the deployment's **preset integration nodes** (the `TEMPLATE_CODE` entries \u2014 the current user's ID / WeChat OpenID / Access Token, file/media conversion to Zion native types, SMS, and video/AI generation), whose set varies by deployment. There is no built-in `CURRENT_USER` / `FILES` / `SMS` node type; do not pass those to `ADD_ACTION_FLOW_NODE`.\n\n### AI Conversation Nodes\nAI conversation nodes are valid only in asynchronous Actionflows.\n\n`AI_CREATE_CONVERSATION` creates a new conversation and runs its first turn. Bind the Agent's declared inputs; Start has no free-form message field because the first user message comes from the Agent's configured prompt. When the node completes, `id` is the conversation ID and `data` is the Agent result. For plain output, `data` is text; for structured output, it has the Agent's declared output type. `id` and `data` are the stable fields. Inspect the node's data-binding options for feature-dependent reasoning and media outputs.\n\n`AI_SEND_MESSAGE` continues an existing conversation. Continue returns the same `id` and `data` shape as Start. Bind `conversationId` to the `id` returned by Start, then bind the new message. Continue uses the Agent configuration stored by Start; selecting another Agent on Continue does not switch the conversation. Use the same `configId` as Start so validation and output typing remain correct.\n\n`AI_STOP_RESPONSE` cancels only the response currently being generated. It preserves the conversation, which may later be continued. `AI_DELETE_CONVERSATION` permanently deletes the conversation and its messages. Stop and Delete have no node output.\n\nUse the target node's data-binding options to select the preceding Start or Continue node's `id`; the event's `taskId` is not a conversation ID.\n\nStart and Continue are wait points: the Actionflow does not proceed to the next node until the AI response finishes. A Stop node placed after Start or Continue therefore cannot stop that response.\n\n**Current runtime limitation:** There is currently no safe cancellation path for a response launched by an Actionflow. Do not use Stop for a response launched by an Actionflow. Stop acts only while the stored status is `IN_PROGRESS`; once it is `STREAMING`, Stop does not cancel the response. If Stop reaches an in-progress response, canceling leaves the AI child task processing, so the source Actionflow never resumes.\n\n### Choosing How to Express Logic: nodes \u2192 formulas \u2192 code\nThree tiers, in order of preference:\n1. **Visual nodes** for orchestration \u2014 query / branch / iterate / write / call (Database, Condition, Loop, Set Variable, Call API, Run Actionflow). They take part in the flow's transaction, surface individually in logs and the edit-time error collector, and stay user-editable.\n2. **Formula bindings** for value-level computation. A node value \u2014 a Set Variable value, a mutation column, a condition predicate \u2014 can be a FORMULA binding built with the bindings plugin, and formulas cover far more than people expect: text and regex (extract / match / replace, substring, split, concat), math, date/time arithmetic and formatting, array aggregation / mapping / filtering, JSON value access, and type casts. Prefer a formula over code whenever you are computing a single value.\n3. **Run Code** only for genuinely procedural logic that neither a node nor a formula operator expresses \u2014 e.g. cryptographic hashing / signature building, multi-step algorithms with intermediate state, or assembling / parsing a complex nested payload. Keep it small and fed by node inputs; never collapse a whole flow into one Run Code node.\n\n### Variables\nDeclared at flow level, accessible by all nodes, assigned with \"Set Variable\" node.\n\n### Inputs & Outputs\nInspect a flow first with `GET_ALL_ACTION_FLOWS_INFO` / `GET_ACTION_FLOW_DETAIL` (unless its detail is already provided in your context). Declare typed **input params** with `ADD_ACTION_FLOW_INPUT_PARAMS`; set each param's type to a value copied verbatim from `GET_ACTION_FLOW_SELECTABLE_TYPES` (never hand-build the type string). Every input param, variable, output field and code-node input/output name is an identifier: letters, digits and underscores only, never starting with a digit. The editor enforces the same rule on a manual rename, so a name that breaks it is one the user cannot repair in the UI; put user-facing wording in a displayName or description instead.\n\nA flow returns a **single typed output value**: set its type with `SET_ACTION_FLOW_OUTPUT`\n(type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`) and clear it with\n`CLEAR_ACTION_FLOW_OUTPUT`; bind the value afterwards at the output's schema path.\n\n### Building & Editing a Flow\nCreate flows with `ADD_ACTION_FLOWS` (each seeds an empty FLOW_START \u2192 FLOW_END), then read node and structure ids from `GET_ACTION_FLOW_DETAIL` before editing. See what can be added after a node with `BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS` at that same position, then add an entry's `node` with `ADD_ACTION_FLOW_NODE`; reorder with `MOVE_ACTION_FLOW_NODES`, remove with `DELETE_ACTION_FLOW_NODES`, and branch a Condition node with `ADD_ACTION_FLOW_BRANCH_ITEM`. When a flow has grown a run of nodes that reads as one step, or the same run is wanted in another flow, extract it with `EXTRACT_ACTION_FLOW_NODES` instead of rebuilding it: the run becomes a new flow with the inputs and output it needs, and a Run Actionflow node calling it stays in place. Every node's displayName should state its business intent ('Insert generation request', 'Decrement like count') rather than the node-type default \u2014 it is optional, and a name left off becomes that default, so omit it only when no better name fits. Edit a node's name or type-scalar config with `UPDATE_ACTION_FLOW_NODE`, but set its data bindings (values, conditions, data sources, mutation fields) with the bindings plugin at the node's schema path \u2014 never inline. A node's schema path is NEVER hand-built: copy it from `ADD_ACTION_FLOW_NODE`'s result or `GET_ACTION_FLOW_DETAIL`'s nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments to reach a binding site inside the node. The key names vary by node type \u2014 an AI node's input arg is `.../allNodes/{j}/inputArgs/<argKey>`, a code node's is `.../allNodes/{j}/inputs/{index}/value`, a mutation column is `.../allNodes/{j}/mutation/object/<columnName>` \u2014 copy the exact keys from `GET_ACTION_FLOW_CONTEXT_INFO`'s currentNode structure, never guess them. Declare flow variables with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` and assign them in a Set Variable node with `ADD_GLOBAL_VARIABLES_NODE_TARGETS`. A Run Code node's `args.<name>` input slots are managed with `ADD_CUSTOM_CODE_NODE_INPUT` (rename/delete variants); its result type is declared with `SET_CUSTOM_CODE_NODE_OUTPUT_TYPE` so downstream nodes can bind to it; fill the code body with `CREATE_CONST_BINDING`. An update or delete Database node is seeded with an always-true filter that matches **every** row \u2014 narrow it with the bindings plugin's request filters before syncing, or the write hits the whole table. A workspace API node's request parameters are pre-seeded on the node when the API is selected \u2014 read the node back and bind ONLY the parameter slots it shows under `event/inputs/<param>`. NEVER invent input keys the read-back does not show: the runtime and editor ignore them.\n\n### Condition Branches\nCondition branches use their left-to-right editor order. At runtime, only the first branch whose condition is true has its branch body executed; branches to its right are not entered. Put an `Always` branch last when fallback behavior is required\u2014an earlier `Always` branch shadows every branch to its right. Do not rely on the no-match behavior; provide an explicit fallback whenever the flow must choose a branch. Only `MUTUAL_EXCLUSION` is supported. `MUTUAL_TOLERANCE` may still appear in generated argument schemas, but tolerance branches are not implemented and fail at runtime. Always set a Condition node's `conditionType` to `MUTUAL_EXCLUSION`.\n\n### Node Input Visibility (Scope)\nWhat a node can bind to is not \"any earlier node\": ztype limits it to the nodes **visible** from that site \u2014 the ones on its straight path back from FLOW_START. The data binding options tree returned with every binding response (its \"Actionflow data\" branch) already applies this rule and is the authoritative list of reachable node outputs; if a node is absent there it is out of scope, so never hand-build a path to reach it.\n\nLoops and Condition branches are **one-way scopes**. From *inside* a block, a node sees the outer scope, the flow inputs, and \u2014 in a Loop \u2014 the current item; but from *outside* the block (any node after the loop's end or after a branch merge) the block's inner nodes are invisible, and sibling branches never see one another. A value produced inside one branch or one loop iteration therefore CANNOT be bound directly by a later node \u2014 it will not appear in that node's options tree.\n\nTo carry a branch- or loop-dependent value past the block, use a **flow variable** \u2014 the only output that crosses a scope boundary. Declare it once with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` (type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`), assign it *inside* the branch or loop body with a Set Variable node (`ADD_GLOBAL_VARIABLES_NODE_TARGETS`), then read the variable from any later node. Idioms: choose a value by branch \u2014 assign the SAME variable in every branch, then read it after the merge; capture or accumulate across a Loop \u2014 assign the variable inside the loop body, then read it after the loop's end. A branch that never assigns the variable leaves its prior value, so set a sensible default before the branch when every path must yield one.\n\n### Concurrency\nConcurrent invocations of the same flow interleave between nodes; sync-mode ACID rolls back on error but does NOT serialize flows (read committed). Query-a-row, branch, then write based on that read is a race: concurrent calls all act on the same stale read. Where the platform can express the check inside the write, prefer that: put row-local guards in the mutation node's own filter (update where stock >= qty; delete where the key pair matches) and branch on the write's affected rows; use an update node's increment/decrement mode for counters; for insert-if-absent or toggle semantics use a unique constraint (the only DB-enforced constraint kind today) with `insert ... on_conflict do nothing` and branch on affected_rows \u2014 that idiom is only expressible in a Run Code node, which makes it a legitimate Run Code use. Invariants none of these can express (cross-row rules, aggregates) have no atomic form yet; check-then-write is the accepted fallback there.\n\n### Error Handling\nSynchronous: all DB changes roll back on error. Asynchronous: only the failing node's DB changes roll back.\n\n### Versioning\nEach save creates a new version. \"Sync Backend\" required after editing for changes to take effect in production.\n\n### JavaScript Sandbox (Run Code node)\nCustom Code Blocks run in a synchronous GraalJS server sandbox. No async/await, no require(), no browser APIs. All platform interactions go through the global `context` object: context.getArg(key) \u2014 retrieve flow input context.setResult(val) \u2014 pass this node's single result downstream context.runGql(opName, gql, vars, permission) \u2014 execute DB operations context.callThirdPartyApi(apiId, params) \u2014 invoke a workspace API by its apiId (the method name is historical; this project has no third-party API configs) context.callActionFlow(flowId, ver, args) \u2014 run a sub-flow synchronously context.createActionFlowTask(flowId, ver, args) \u2014 trigger a sub-flow async context.getSsoUserInfo() \u2014 get authenticated user profile context.uploadMedia(url, headers) \u2014 stream remote image to asset server context.log(message) \u2014 emit to Log Service\n\n`runGql` takes FOUR arguments and the first one is the operation NAME, not the document: `runGql(\"GetWords\", \"query GetWords { theme_word(where: {...}) { word } }\", {}, {role: \"admin\"})`. The name must match the one declared in the document. `vars` is a JS object (not a JSON string) and `permission` is `{role: \"<role name>\"}` with an optional `sessionVariable` map. Passing the document first is the mistake that costs an afternoon: the arity error, then a String-coercion error naming a type you did not pass, then \"permission should have field role\" are all the same misalignment reported one argument at a time.\n\nIt returns the `data` object directly \u2014 `r.theme_word`, never `r.data.theme_word` \u2014 and it THROWS on a GraphQL error rather than returning an `errors` array, so there is no envelope to branch on. Do not write defensive code for a response shape you have not seen.\n\nThe list above is the methods you will reach for, not the whole API. The complete Context API reference \u2014 every method with its parameters and return shape \u2014 is the \"Develop with Run Code\" developer page: find it with `docs.search`, and read it rather than inferring a signature from an error message. Search by title; the page's path is not the same across products.",agent:`Zion is a powerful no-code development platform that enables developers to build and deploy web, mobile, and WeChat Mini Program (\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F) applications. It integrates a visual drag-and-drop design canvas, an enterprise-grade relational database engine (PostgreSQL), and an event-driven backend logic execution pipeline.
|
|
44
44
|
|
|
45
45
|
This overview details the structural design, data engines, execution pipelines, and safety requirements of the platform.
|
|
46
46
|
|
|
@@ -232,7 +232,7 @@ The mini program publish flow is distinct from web/mobile:
|
|
|
232
232
|
* Email/password
|
|
233
233
|
|
|
234
234
|
### Timezone & Locale
|
|
235
|
-
Product default timezone: **Asia/Shanghai** (UTC+08:00). A project can override it; the zone actually in effect is \`timezone\` in GET_PROJECT_OVERVIEW. Default UI language: Simplified Chinese (zh-CN).`,api:"## API Integration Domain Knowledge\nAn API integration is a saved external HTTP endpoint the project can use as a data source. APIs are organized into **workspaces**: a workspace groups related endpoints and holds shared **constants** (e.g. a base URL or API key) the endpoints reference, so credentials live in one place. The action-flow \"Call API\" node invokes these workspace APIs.\n\n### Anatomy\n- **Workspace**: a named group with a description and a set of `constants`.\n- **API**: an HTTP `method` + URL under a workspace, with request **parameters** (path / query / header / body), typed **response configs** (the result shape downstream binds from), and declared **input variables** (the values a caller supplies).\n\n### Workflow\nList with `GET_ALL_API_WORKSPACES` / `GET_ALL_APIS_INFO`, then `GET_API_DETAIL` to read an API's `apiId`, `workspaceId`, and parameter / response `uniqueId`s before editing \u2014 never fabricate them. Build top-down: `ADD_API_WORKSPACES` \u2192 `ADD_API_WORKSPACE_CONSTANTS` (put API keys / base URLs here, never inline) \u2192 `ADD_APIS` (each under a `workspaceId`) \u2192 `ADD_API_PARAMETERS`, `ADD_API_RESPONSE_CONFIGS`, `ADD_API_INPUT_VARIABLES`. Editing creates a new version; \"Sync Backend\" is required for changes to take effect in production.\n\n### Timeout\nEach API has a request `timeout` in seconds, 1 to 60, 30 when never set; ADD_APIS and UPDATE_API set it and GET_API_DETAIL reports it. Called from an action flow, the request is also cut off when the flow's own timeout runs out, whichever comes first, so raising an API's timeout helps only if the calling flow's timeout leaves room for it.\n\n### Request Bodies\nA body-carrying method needs a body FORMAT, and `SET_API_CONTENT_TYPE` is what sets it \u2014 `UPDATE_API` has no content-type argument and will reject one. `application/json` seeds an empty object type that belongs to this API; `GET_API_DETAIL` reports it as `bodyType`, and you describe it with the 'type' plugin's `ADD_TYPE_DEFINITION_FIELDS`. The two form formats take their fields from `ADD_API_PARAMETERS` instead. Every such switch DISCARDS the body that was there, so pick the format before filling it in \u2014 and never cycle the method away and back to force a reset, which throws the body parameters away with it.\n\nA media field, or an object field carried as a JSON string, cannot travel over HTTP as itself: it needs a conversion, and a media field left without one leaves the API incomplete. `GET_API_CODEC_OPTIONS` says which slots need one and what each allows; `SET_API_CODECS` applies it and `DELETE_API_CODECS` removes it.\n\n### Response Shapes\nA response config's type is what downstream reads the result through, and only an object type puts that result's fields where a binding can see and pick them. A JSON response still yields values \u2014 through the get-value-from-JSON formula \u2014 but the key path is a string you have to already know and spell by hand, nothing in the project lists what the payload holds, and a key that does not match it comes back empty rather than erroring; a text response does not even reach that formula. So whenever the endpoint documents what it returns \u2014 and it usually does \u2014 give the response a shape: `ADD_API_RESPONSE_CONFIGS` / `UPDATE_API_RESPONSE_CONFIGS` with `seedObjectType: true` mint an object type owned by this API and echo its `responseTypeId`, which you then describe with the 'type' plugin's `ADD_TYPE_DEFINITION_FIELDS`, exactly as you do a JSON request body. Add `arrayLevel: 1` where the endpoint returns a list of that shape. Reach for the JSON type only when the body's shape genuinely varies from call to call, and for text only when the response is not JSON at all (a 204 with no content, a plain-text body).\n\n### Types\nEvery `type` argument here is picked, not written: call `GET_API_SELECTABLE_TYPES` for the slot being filled and copy a returned `typeIdentifier` verbatim. A private object type belongs to the one feature that owns it and is never offered to another, so to reuse a shape some other feature owns, publish it with `COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC` and select the public copy. This API's own JSON body type is the exception \u2014 it is already this API's, so describe it in place with `ADD_TYPE_DEFINITION_FIELDS`. Lists are not enumerated \u2014 the nesting has no end \u2014 so a list response or input variable is a returned identifier plus `arrayLevel: 1`; the URL, header and form-body parameters hold one value, take no `arrayLevel`, and accept no list at all.",bindings:"## Data Binding Domain Knowledge\nData binding connects data sources to UI components for display or interaction.\n\n### Concepts\nSchema path: array of keys/indices locating a bindable node in the project JSON schema. Data binding options tree: hierarchical tree of all available data for a given schema path. Never hand-build a schema path for an action-flow node: copy it from the actionflow plugin's add_node result or get_flow_detail's nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments for the binding site inside the node. The binding-site key names VARY BY NODE TYPE (an AI node's input arg lives under inputArgs/<argKey>, a code node's under inputs/<index>/value, a mutation column under mutation/object/<columnName>) \u2014 copy the exact keys from the currentNode structure returned by get_context_info; never guess them.\nType metadata in read results uses exact typeIdentifier values such as `s:p:string` and `u:e:<enumId>`; copy those values verbatim.\n\n### Binding Kinds\nOPTION: bind to an existing path in the data binding options tree. pathInHierarchicalMenu must be the EXACT complete path, and menu labels are locale-dependent display names (a project may render them in Chinese or English) \u2014 so a label can NEVER be guessed. Before the first option binding at a schema path whose tree you have not seen, read it with `BROWSE_DATA_BINDING_OPTIONS` (CRITICAL: Do NOT call `get_options_tree` if the tree is already provided in the context above); afterwards every binding response attaches the refreshed tree for its op's path. Copy every label verbatim from that tree \u2014 never invent, translate, or shorten a label \u2014 and include every intermediate menu level. If the tree root is a named context (e.g., \"List Context\"), include it as the first element. CONST_VALUE: set a literal constant (e.g., \"Submit\", 0, false). FORMULA: compute a value with an operator (text / math / time / array / enum / geography / json groups); discover the available operators before building one. CONDITIONAL: choose the value by branch \u2014 define the branches, then build each branch's predicate.\n\n### Priority\n1. Prefer OPTION (live data) over CONST_VALUE.\n2. No suitable option? Use CONST_VALUE with a reasonable inferred constant.\n3. Component purpose unclear? Skip binding.\n4. A list NESTED INSIDE another list binds from the ancestor's item data, not from a table, so the relational linkage survives. This is about nesting only \u2014 a top-level list binds straight to the table it shows, and prefers that over consuming someone else's page query unless the result set is genuinely shared.\n5. Bind ONLY what the task requires: in an update/insert node's object leave every other column untouched \u2014 never fill it with a Null option or a placeholder constant (Null on a required column breaks the flow at runtime).\n6. Never seed a typed site with a throwaway constant \"for now\" and upgrade later \u2014 bind the real value directly; a constant re-types nothing but still wastes a round.\n\n### Iterative Refinement\nPer-op errors are returned keyed by index. Successful bindings have already landed. On rejection, fix ONLY the failing entries by index and re-call.\n\n### Data Sources Available in Zion\nDatabase tables (with filters/sorting/limits), page data sources, page variables, global variables, page parameters, logged-in user, list/component item data, Actionflow inputs/outputs, formula results.\nThis is the product-wide catalog, NOT what is bindable at any given site \u2014 each site exposes only a subset. NEVER assume a category is available: the options tree for the site is authoritative, so read it with `BROWSE_DATA_BINDING_OPTIONS` first and bind only categories it actually lists. If one (e.g. formula data) is absent for that path, it is not valid there \u2014 do not attempt it. (Action flows run strictly on the backend, so page data sources never apply inside a flow node.)\n\n### Request Filters (where / sort)\nA database-query data source \u2014 a list/component request, or an action-flow query / update / delete node \u2014 carries **request filters**. FIRST call `GET_REQUEST_FILTER_CONTEXT` with the request's (or owning node's) schema path: it returns the table's selectable columns (with the `pathComponents` and `allowedOperators` to use) and the filter entries' `whereSchemaPath` / `sortConfigsSchemaPath`. Copy those paths and column `pathComponents` verbatim \u2014 never hand-build them. Queries and component requests carry a LIST of conditional filters (where + sort groups, each gated by its own condition, always including a system Default filter). An action-flow update/delete node instead carries ONE bare where (`supportsConditionalFilters: false` in the context result) \u2014 edit it via the single entry's `whereSchemaPath` with the where-condition tools only; the filter-group and sort tools do not apply, and insert nodes have no request filter at all.\nTo change a numeric column RELATIVE to its current value (stock, counters, balances), set the column's write mode with `SET_UPDATE_COLUMN_ARITHMETIC` and bind only the DELTA as the column's value \u2014 the database applies it atomically. Never query the current value, compute in a formula, and set it back: that read-modify-write loses concurrent updates. Idiom \u2014 decrease field_a by x: mode 'decrement' on field_a, value x, and a where guard `field_a > x` (or `>= x` when draining to zero is allowed) so the update changes nothing when the stored value is insufficient. That rule generalizes to every mutation this plugin configures \u2014 frontend component mutation events and action-flow nodes alike: when a write's correctness depends on current row state, put the check in the mutation's own where filter and let follow-ups branch on its affected rows, instead of querying first and writing on the stale read (concurrent users race it). Insert-if-absent semantics additionally need a unique constraint \u2014 the only DB-enforced constraint kind today (see the database plugin).\n- Filter groups: `ADD_REQUEST_CONDITIONAL_FILTER` / `UPDATE_REQUEST_CONDITIONAL_FILTER` / `DELETE_REQUEST_CONDITIONAL_FILTER` / `REORDER_REQUEST_CONDITIONAL_FILTERS`. The Default filter cannot be renamed or deleted.\n- Where conditions: `ADD_REQUEST_FILTER_CONDITION` (column + operator), then fill its comparison value with a binding (OPTION / CONST_VALUE) at the condition's `value` path; shape the expression with `NEST_REQUEST_FILTER_CONDITION`, `TOGGLE_REQUEST_FILTER_CONDITION_AND_OR`, `TOGGLE_REQUEST_FILTER_CONDITION_NOT`, `UPDATE_REQUEST_FILTER_CONDITION_OPERATOR`, `DELETE_REQUEST_FILTER_CONDITION`.\n- Sort: `ADD_REQUEST_SORT_CONFIG` / `UPDATE_REQUEST_SORT_CONFIG` / `DELETE_REQUEST_SORT_CONFIG` / `REORDER_REQUEST_SORT_CONFIGS`.\n\n### Composing text from fragments and variables\nFor any `s:p:string` value that mixes literal fragments with variables \u2014 AI prompt templates, titles, labels, messages \u2014 do NOT build a stringConcat formula. Build the template at the same schema path with operation CONCAT: `CREATE_CONST_BINDING` for a literal fragment, `CREATE_OPTION_BINDING` for a variable. Each CONCAT appends to the end, so the final order is exactly the order you emit entries \u2014 within a call and across consecutive binding calls in the same turn. Emit them in final reading order, interleaving literals and variables \u2014 e.g. const_value \"Hello \", option user, const_value \", order \", option orderId, const_value \" total \", option amount. Never emit all literals then all variables (that puts every label before every variable), and two literal CONCATs in a row merge into one fragment. This produces the same inline template the editor's text fields produce and stays editable there. Reserve formulas for real computation (math, time, regex, arrays) \u2014 never for simple text templating.\nA number, boolean, date, time, datetime or color bound into a `s:p:string` slot is converted for display automatically, so bind the option straight to the slot \u2014 never wrap it in `toText` or any other conversion operator. Only structured values (lists, objects, media) genuinely need one. `BROWSE_DATA_BINDING_OPTIONS` marks an option with `*` only when the target really cannot take it; an unmarked option needs no conversion step.\n\n### Formula & Conditional Bindings\nA FORMULA or CONDITIONAL value is built in several steps at the value's schema path, not in a single call.\n- Formula: call `GET_FORMULA_OPERATORS` at the path, then `CREATE_FORMULA_BINDING` with an operator copied verbatim (the wire token, e.g. `-` not SUBTRACT; operation REPLACE). If the operator needs scalar config (e.g. distance unit, rounding mode), read its shape with `GET_FORMULA_CONFIG_OPTIONS` and pass it or apply it later with `SET_FORMULA_CONFIG`. The create result returns `operandSchemaPaths` \u2014 fill each operand with an OPTION / CONST_VALUE binding at its returned path, copied verbatim; never derive an operand path yourself. A `timezone` operand (e.g. on FORMAT_DATE_TIME) is optional: unbound, the project's default zone applies, so bind it only when the user asks for a specific zone or the viewer's own.\n- Conditional: `CREATE_CONDITIONAL_BINDING` (seed branches with initialBranchNames; operation REPLACE), add more with `INSERT_CONDITIONAL_DATA`. For each branch, build its predicate with `INSERT_CONDITION_BOOL_EXP`, choose the comparison via `GET_EXPRESSION_CONDITION_OPERATORS` + `UPDATE_EXPRESSION_CONDITION_OPERATOR`, fill both operands with OPTION / CONST_VALUE bindings, and shape the expression with `NEST_CONDITION_BOOL_EXP`, `TOGGLE_CONDITION_BOOL_EXP_AND_OR`, `TOGGLE_CONDITION_BOOL_EXP_NOT`, `DELETE_CONDITION_BOOL_EXP`; then bind the branch's resulting value. The first branch whose predicate is true wins \u2014 order them with `REORDER_CONDITIONAL_DATA`.\n- There is no string is-empty operator (`_is_empty` accepts lists only, and `\"\"` is not null): test text emptiness as `stringLength(x) > 0` via a formula binding on the operand.\n\n### Page links\nThe global page-link option binds a getPageUrl function binding with no target page, so the link points nowhere until you call `SET_FUNCTION_BINDING_PAGE_URL_TARGET` at the same schema path with the target page's id. Fill each parameter it returns under argSchemaPaths with an OPTION / CONST_VALUE binding at that path, copied verbatim.\n\n### Lists composed item by item\nTo give a list slot a literal list, bind the Custom > Array option at its schema path, then append items with `ADD_CUSTOM_ARRAY_BINDING_ITEMS` \u2014 a binding at an item index that does not exist yet is rejected, so an empty custom array can only grow through that tool. Fill each item it returns under itemSchemaPaths with an OPTION / CONST_VALUE binding, copied verbatim. For a list of lists, each item is a custom array of its own: call `ADD_CUSTOM_ARRAY_BINDING_ITEMS` again at the item's path. Remove items with `DELETE_CUSTOM_ARRAY_BINDING_ITEMS`.",component:"## Component Domain Knowledge\nThe UI is a tree of components organized into pages.\n\n### Identity & Tree Rules\nEvery component has an immutable id and a displayName. Reads return both; write tools verify the {id, displayName} pair and reject a mismatch \u2014 re-read, then retry. A container's children order IS the visual order. A component can never be moved into its own subtree.\n\n### Categories\nLayout (container \u2014 can hold other components via `children`):\n- PAGE: root of each page; created without a parent and registered as a new page.\n- LAYOUT_VIEW: generic Flexbox container; the most common container.\n- MODAL: popup/dialog container; created without a parent, opened/closed via events.\n\nSpecial (complex \u2014 children live in built-in slots seeded at creation and mutated only via the slot tools, never via ADD_COMPONENT / MOVE_COMPONENTS):\n- LIST: repeating list; its \"cell\" slot renders once per data row (optional header/footer).\n- TAB_VIEW: tabbed interface; one child view per tab in tabList.\n- SELECT_VIEW: built-in normal/selected state views.\n- CONDITIONAL_VIEW: one built-in view per condition branch.\n- MAP: optional \"marker\" slot taking a MAP_MARKER.\n\nLeaf/Business (cannot have children): BUTTON, TEXT, IMAGE, VIDEO, LOTTIE, RICH_TEXT, TEXT_INPUT, NUMBER_INPUT, VIDEO_PICKER, FILE_PICKER, SWITCH, MAP_MARKER, CALENDAR, HORIZONTAL_LINE, SHEET, HTML, RICH_TEXT_EDITOR, MIX_IMAGE_PICKER, DATE_TIME_PICKER, DATA_SELECTOR, PROGRESS_BAR. MAP_MARKER can only be placed inside MAP. `GET_SELECTABLE_COMPONENT_TYPES` returns the full creatable catalog with each type's slot fields.\n\n### Hierarchy Rules\nEvery component except PAGE and MODAL must have a Layout Component as its parent. Prefer relative positioning; use absolute/fixed only when truly necessary.\n\n### Layout\nZion uses Flexbox. Layout containers configure: direction (row/column), justify-content (start, space-between, space-evenly, space-around), gap, wrap, overflow (scroll/visible/hidden).\n\n### Responsive Breakpoints\nPhone: 0\u2013767 px (375 px panel) | Tablet: 768\u20131279 px (820 px panel) | Desktop: 1280\u20131920 px (1440 px panel). Desktop is the primary breakpoint and the one every read and write defaults to. A narrower breakpoint stores only its differences from desktop, so a field it does not override renders the desktop value at that width \u2014 an app built without touching phone is not unstyled there, it is desktop-sized there, which is how a 600 px card ends up running off a 375 px screen. Nothing fails: the schema is valid, the error center stays clean, and the only symptom is what the user sees on a phone. Read what phone actually resolves to by passing `breakpoint` to `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO`; the read names which fields that breakpoint overrides and which it inherits. Fix one by resending that field with the `breakpoint` param to `UPDATE_COMPONENT_STYLE` \u2014 usually flexDirection 'column' on rows, and widths in % or fill rather than px; the phone breakpoint in the editor shows the result. Resending a value unchanged at a breakpoint pins it there and stops it following desktop, so override only what has to differ.\n\n### Reading the Component Tree\nIds are opaque: copy them verbatim from these read tools and never modify them. A page id (from `GET_ALL_ROOTS_INFO`) is not a component id, and breakpoint keys (phone/tablet/desktop) are tool parameters, never part of an id \u2014 passing something like `<pageId>-desktop` as a component target fails with \"target component not found\".\n\n### Building & Editing the Component Tree\nConstruction workflow: read the target container, pick types with `GET_SELECTABLE_COMPONENT_TYPES`, edit `GET_COMPONENT_TEMPLATE` output and submit it via `ADD_COMPONENT`, then use the ids it echoes instead of re-reading.\nContainer sizing: a LAYOUT_VIEW hugs its content, so a container created WITH its children inside is sized by them and needs no height of its own; an empty one keeps a small minimum height so it stays visible and droppable, and filling it makes that minimum irrelevant. Give a container an explicit height only when you want a fixed-size box or a scroll viewport \u2014 a fixed height its content outgrows clips that content invisibly, and a fixed width crops text mid-word. `UPDATE_COMPONENT_STYLE` merges, so a size you do not name keeps its old value.\nWidth/height `fill` means \"grow along the flex main axis\", so it only makes sense on the axis the parent lays out along: `width: fill` in a row, `height: fill` in a column. On the other axis it would unset the size and let the child shrink to its content, so it is applied as '100%' instead and the result says so. There is no `stretch` alignment to fall back on \u2014 in Zion a component declares its own size rather than having its container negotiate one.\nA row of cards is sized one axis at a time. Along the row, give every child `fill`, or fr shares \u2014 `65fr` and `35fr` \u2014 when the split is deliberate; never percentages, because fr divides what is left after the gap and the padding while `65%` + `35%` claims the whole width and the gap then pushes it over, wrapping or clipping the last column. Across the row, give every child the SAME `minHeight` so they bottom out together: a real `height` would clip the card whose content grows past it, and with no `stretch` to fall back on a shared floor is as close to equal-height cards as this system gets \u2014 a card whose content clears the floor still grows alone, so pick a floor that clears the tallest copy you expect. Set `minWidth` on a child only where that column has a genuine floor: it, not `flexWrap`, is what makes a row break into 2+1 once the container is narrower than the floors plus the gaps. Size the children this way and the container needs nothing beyond `flexDirection`, `gap` and its own width \u2014 `justifyContent` and `alignItems` have no free space left to distribute, so reaching for them to fix a ragged row means the children are the wrong size.\nWhen a sentence reports as clipped horizontally, it is nearly always `textWrap` false (see Typography below): widening the box, or setting `overflowX`, does not make the text reflow.\nA TEXT_INPUT collecting a password needs `password: true` via `UPDATE_COMPONENT_PROPERTIES`; a \"Password\" placeholder alone does not mask anything.\n\n### A Look Is Decided, Not Defaulted\nA request that names no visual direction \u2014 \"a task tracker\", \"a booking page\" \u2014 is not a request for no styling: the platform's creation defaults are what produce the grey-box build the user then has to describe their way out of. The subject is where a non-generic direction comes from \u2014 what this app is, who opens it, the one job it does, and the palette, typeface and type roles that reading implies \u2014 and it is the only input no other project shares: a shift-handover tool for night-shift nurses and a portfolio for a ceramicist should not resolve to the same screen. Written into the theme (next section), that direction holds every screen built out of it together. A direction the user states \u2014 a brand colour, \"dark\", \"playful\", a screenshot \u2014 replaces your own everywhere. What fails is splitting the difference: a stated direction on the first two screens and your own default on the rest reads worse than either applied throughout, because inconsistency looks like a bug rather than a choice.\n\n### The Theme Is The Design System\nEvery style value that has a theme category is sent as that variable's referenceValue, `$$<id>`, never as a literal: colours (backgroundColor, textColor, borderColor, gradient stops, shadow.color) from colour variables, padding/margin/gap from spacings, borderRadius from radii, fontSize, fontWeight and fontFamily from their own categories, and a whole shadow as `shadow: {variable: '$$<id>'}`. The id resolves against the field's category, so `$$md` under padding is the spacing md and under borderRadius the radius md. A literal renders the same today and is pinned to the component it was written on; a reference follows the theme. That difference is the whole point: \"make it rounder\", \"a different font\", \"warmer\" is then a few `UPDATE_THEME_VARIABLES` edits that every screen follows, instead of a sweep that touches every component and still misses some. Only lineHeight, letterSpacing, borderWidth, opacity and sizes have no category and stay literal.\nThat is the default, not a rule over the user:\n- A value the user gives for one component (\"make this button 13px\", \"this banner #ff6600\") is written as that literal on that component \u2014 not rounded to the nearest variable, not turned into a new variable, and not applied by retuning a variable every screen shares. When it is unclear whether they mean this component or the whole app, ask.\n- Change only what the request touches. Existing literals stay literal unless the user asks for the restyle; do not convert them on the side.\n- Add a variable only for a value several components share, never for a one-off.\n`GET_THEME_INFO` shows what the theme holds. A theme already carries colour roles (Primary, Secondary, Tertiary, Text_primary, Text_secondary, Background, Surface, Border, Success, Alert, Error), font sizes h1 through caption that already shrink per breakpoint, weights 100\u2013900, radii sm\u2013full, spacings xs\u2013xl3 and shadows xs\u2013xl2 \u2014 and no font family. Retune those values to the direction you decided rather than working around them, and add a variable only for a role the theme lacks. When the user later asks for a different look, change the variables, not the components.\nOn a web client a font size, radius or spacing variable holds one value per breakpoint (`{desktop, tablet, phone}`). When one has to differ on phone \u2014 an h1 at 28 on desktop and 24 on phone \u2014 set that on the variable, not as a breakpoint override of fontSize, padding, gap or borderRadius on the components that reference it: an override replaces the reference at that width, so the component stops following the theme there.\n\n### The Palette Is Named Before It Is Spent\nGive a new colour variable a palette level (the theme plugin explains which), not a hex, so it recolours with the rest. A working set is roughly eight roles, named by ROLE, not by colour \u2014 \"surface\", not \"light-grey\":\n- Four neutrals, not two: the page ground, a surface lifted off it, a border a step darker again, and a hairline/divider weaker than the border. Two neutrals is the single most common cause of a flat screen \u2014 with only \"background\" and \"border\" available, every card, input, header and divider ends up drawn with the same one, and nothing separates from anything.\n- Two inks: primary for content, muted for secondary text and labels. Do NOT make muted text by dropping `opacity` on a TEXT \u2014 opacity fades the whole component including anything it contains, and it composites against whatever is behind it, so the same \"muted\" reads differently on a card than on the page. Muted is a colour.\n- One accent, and one status colour (danger) if the app writes data.\nSpend the accent only on the primary action and the active/selected state. The moment it also appears on a heading, an icon and a border, nothing on the screen is being pointed at.\n\n### A Text Role Is Three Values Sent Together\nThe theme has font sizes and font weights but no line height and no combined text style, so a role \u2014 page title, section heading, body, label, caption, rarely more than five \u2014 is a pairing you keep yourself: a size variable, a weight variable and a lineHeight, sent together every time. Asking for a heading means all three; a heading size at body weight is two roles blended. lineHeight is absolute px and does not follow the size: roughly 1.2\xD7 the size for headings, 1.5\xD7 for body copy, and without it anything above the default crops or overlaps. The display sizes shrink on phone while the lineHeight you sent at the main breakpoint does not, so give a heading role a phone lineHeight as well. For the same reason, changing a font size variable does not move the lineHeight of the text that uses it: in the same turn, re-send lineHeight (and the phone lineHeight) on every TEXT and BUTTON of that role, or the larger text crops and overlaps.\n\n### Typography Carries Most Of The Impression\nThe type is the largest coloured area on almost every screen, so it decides the character of the page before any accent does.\n- Typeface is a real choice: the default (DM Sans on web, pingFang SC on mobile) is the face every other project ships with. Add it as a FONT_FAMILIES variable and reference it as fontFamily on every TEXT, BUTTON and TEXT_INPUT \u2014 then switching the face later is one edit. `GET_THEME_INFO` lists the families this client offers under offeredFontFamilies, and only those have font files; any other name renders as the system fallback. One family is a complete answer; two only when clearly distinct in role (a display face and a text face), never two sans faces that differ slightly. If the copy is Chinese, the BODY face has to be a CJK one, not just the headline: a Latin family carries no Chinese glyphs, so every Chinese character falls back to whatever the device has. A display face carries a headline and nothing longer.\n- Hierarchy comes from weight and space as much as from size. Three text roles that differ only in size read as one undifferentiated block; a heading at 600\u2013700 against body at 400 separates at a glance even when the sizes are close.\n- `letterSpacing` is in PIXELS, not em, and goes NEGATIVE on large display type \u2014 roughly -0.5px at a 28\u201332px page title, -1px or beyond as the size grows \u2014 because a face designed at body size is too loose when set large. Body text wants 0. A fractional value like -0.02 changes nothing visible, so sending one and then reporting the tracking as tightened is a false claim. It goes slightly POSITIVE only on small uppercase labels, which are themselves worth avoiding (see below).\n- Set `maxWidth` on any TEXT holding a paragraph. Unbounded body text stretches to the container and a 1200px-wide line is unreadable regardless of how well it is styled; hold it near 60\u201370 characters, which at body size is roughly 600\u2013680px. A capped column keeps hugging the left edge until its PARENT centres it \u2014 in a column parent (a PAGE's default) that is `alignItems: 'center'`. This is the most-skipped and most-visible typographic fix in a wide desktop layout.\n- Body text needs `textWrap: true` \u2014 false pins it to one line and ellipsises it at the box edge however wide the sentence is. `lineClamp` on top when it must stop after N lines.\n\n### Depth Is One Decision, Applied Once\nThe failure mode is shadow everywhere rather than shadow used well.\n- A card lifts off the page with EITHER a hairline border OR a soft shadow, not both. Pick one for the whole app.\n- Elevation is at most two levels \u2014 resting surface, and the raised thing (modal, dropdown, the one hero card) \u2014 so reference two of the theme's shadow variables and no more. A third level means the second is not doing its job.\n- A real shadow is large, soft and nearly transparent, and offset downward only \u2014 light comes from above: `blur` well above `offsetY`, a colour at low alpha. If the theme's shadows do not read that way, retune those variables rather than drawing a shadow on one component.\n- `inset: true` is for the pressed state of a button and for a well an input sits in. It is the only correct way to make something look recessed rather than raised.\n- `backdropBlur` belongs on overlay chrome that sits over content \u2014 a sticky header, a modal scrim. On an ordinary card it costs paint and buys nothing, since there is nothing behind it to blur.\n- `borderRadiusCorners` exists for the cases a single radius cannot express: a segmented control, a sheet rounded only at the top, a cell at the end of a row. Reach for it there and nowhere else.\n- Radius is hierarchy. If the card, the input, the badge and the button all carry the same radius variable, the screen has told the user nothing about what is what.\n\n### Space Is The Cheapest Thing That Reads As Finished\nThe common failure is far too little of it, and it is not a matter of taste \u2014 the numbers are knowable. On desktop, section padding starts at 64px vertical and goes up, not down; card padding at 20\u201324px; the page gutter at least two spacing steps above the in-card gap, so a card reads as sitting on the page rather than pasted onto it. When a screen feels cramped, the fix is almost always more space AROUND the groups, not less space inside them. Proximity is the actual signal: things that belong together sit closer to each other than to anything else, and if a label is equidistant from its own field and the next one, the layout has lost the reader regardless of how the label is styled.\n\n### The Look That Reads As Generated\nNone of these is forbidden \u2014 each is right for some brief \u2014 but they are what gets reached for when nothing has been decided, so they appear regardless of subject. Where the user asked for one, give it to them. Where they left the axis free, spend the freedom elsewhere:\n- Cream page (near #F4F1EA) with a high-contrast serif display and a terracotta/clay accent (near #D97757).\n- Near-black page with one acid-green or vermilion accent.\n- Every surface on the same radius under the same soft grey shadow, whatever its role.\n- A tracked-out ALL-CAPS eyebrow label above every heading.\n- Meta strings joined with middle dots ('A \xB7 B \xB7 C'); '\u2192' appended to button text.\n- One word in a heading coloured or bolded to add interest.\n- Numbered markers (01 / 02 / 03) on content that is not actually a sequence.\n- A gradient used as decoration on a surface that has no reason to be gradient. A gradient is legitimate as the subject of a hero, or to keep text legible over an image; as a wash behind ordinary cards it is the clearest single tell.\n\n### Every Interactive Thing Answers The Cursor\n`UPDATE_COMPONENT_STYLE` takes `variant: 'hover'`, and a build that never sends it is a build where nothing on screen responds to the mouse. That, more than any colour choice, is what makes a page feel like a mockup rather than an application. A hover state on buttons, clickable cards and list rows \u2014 a surface a step lighter or darker is enough \u2014 costs one extra call per component type, not per component, because the same few shapes repeat. A LAYOUT_VIEW with an ON_CLICK handler still shows an arrow cursor until it gets `cursor: 'pointer'`, so the user has no way to know it is a target. Where a SELECT_VIEW or a TAB_VIEW has a selected state, style it. The default selected state is not a design decision, and \"the active tab looks like the inactive ones\" is a bug the user will report in different words.\n\n### Three Things Can Be Conditional \u2014 Pick The Smallest One\nWhen a screen has two modes, do NOT reach for a conditional container first. Ask what actually differs between the modes, and make only that conditional:\n- Conditional DATA (`CREATE_CONDITIONAL_BINDING`) when only VALUES differ \u2014 a label, a title, a placeholder, a colour. One component, one conditional binding whose branches are keyed off the deciding value. This is the default answer.\n- Conditional ACTION when only BEHAVIOR differs \u2014 one button that submits, signs in or signs up depending on the mode. One button, one handler that branches.\n- Conditional VIEW (CONDITIONAL_VIEW) only when the STRUCTURE differs \u2014 different fields, different counts of children. Branches do NOT share children, so anything you put in a branch is duplicated in every other branch. If the two modes share a form, keep the shared form OUTSIDE the CONDITIONAL_VIEW and put only the differing part inside it. Its branch conditions start always-true, so the first branch shows until you narrow them; make the mode a page variable the conditions read and change it with SET_VARIABLE_DATA.\nA \"switchable signup / login\" is therefore conditional data plus a conditional action over ONE shared form \u2014 not two branches each holding a copy of the same fields. Wrapping shared UI in branches is the classic wrong answer: it looks right and silently doubles the tree.\nTAB_VIEW is a different question entirely: use it only when the tab strip itself is the affordance the user should see and click. It renders tab chrome you cannot remove.\nBoth TAB_VIEW and CONDITIONAL_VIEW take `preserveStateOnSwitch`, and it is the same mechanism in both: true keeps every case alive, so a scrolled list, a half-filled input or a loaded query survives switching away and back; false tears the inactive case down and rebuilds it from scratch. Both are created with it ON. Turn it off only when stale state would be wrong (a form that must reset), and remember the cost: every case stays mounted.\n\n### Components That Display a Field of Their Data\nDATA_SELECTOR, SELECT_VIEW and LIST name one field of their data source: `displayDataField` (the value the user sees) and `cellKeyDataField` (the row identity). Binding the dataSource is not enough \u2014 a DATA_SELECTOR or SELECT_VIEW whose data source resolves to a list of objects is invalid until its displayDataField is set. Set it with `UPDATE_COMPONENT_PROPERTIES`, passing the field's plain NAME as a string; the full field reference is resolved for you, so never hand-assemble one. The candidates appear as selectableDataFields in `GET_COMPONENT_INFO` once the dataSource is bound \u2014 so the order is always: create \u2192 bind dataSource \u2192 read the component \u2192 name the field.\n\n### Page Data: Queries, Variables & Inputs\nPages have NO separate query list \u2014 a page query IS a read-only page variable whose dataSource is a database query. It is for data more than one component reads, or a filter the page owns centrally; a single list showing one filtered table binds that table itself (see Data Bindings below) and needs nothing here:\n- `ADD_COMPONENT_QUERY` attaches a table query to a PAGE or MODAL (limit 1 = single row, >1 = list). Components consume it through data bindings (bindings plugin) at the echoed dataSourceSchemaPath; narrow filters and sorting with the request-filter tools at that same path. The result also reports rolesWithoutSelect: those roles see no rows until they are granted SELECT with the permission plugin's table-permission tool. Tune with `UPDATE_COMPONENT_QUERY` \u2014 which also sets or clears the row limit of the query a LIST, SELECT_VIEW, DATA_SELECTOR or SHEET owns; remove queries and variables alike with `DELETE_COMPONENT_VARIABLES`.\n- Page-local mutable state: `ADD_COMPONENT_VARIABLES`, with each typeIdentifier picked from `GET_COMPONENT_VARIABLE_SELECTABLE_TYPES` \u2014 never hand-assembled. A new variable starts with no value, so give it an initial one at the `defaultValueSchemaPath` the result echoes whenever anything reads it: conditional cases, branch conditions and SET_VARIABLE_DATA values all test the variable against specific values, and none of them match an empty variable. The page then loads with every dependent case unmatched \u2014 blank labels, the fallback branch showing \u2014 and a toggle whose new value is itself conditional on the old one cannot recover, because it has nothing to match either.\n- Page parameters: `ADD_COMPONENT_INPUTS` / `UPDATE_COMPONENT_INPUT` / `DELETE_COMPONENT_INPUTS`. WEB pages take URL query/path params; WECHAT/MOBILE pages and MODALs take general inputs. Navigation and show-modal call sites pass one value per input.\n- `SET_INITIAL_PAGE_ID` sets the app's home page for the current client.\n\n### Data Bindings on Components\n`GET_COMPONENT_BINDABLE_PROPERTIES` lists every place a component can be bound \u2014 always start there and copy the paths verbatim, never hand-assemble a binding path. It returns two sections: `properties`, the component's own slots, each with its ready-to-use schemaPath, expected type, current binding and scope; and `actionSlots`, the parameter slots of the actions already wired to its events, chained success/failure branches included. `ADD_COMPONENT_ACTIONS` echoes an action's slots when it creates it \u2014 bind them in the same turn when you can, and use `actionSlots` to find them again in any later turn. Fill the echoed paths with the bindings plugin's tools: `BROWSE_DATA_BINDING_OPTIONS` + `CREATE_OPTION_BINDING` for dataSource slots and other dynamic values, `CREATE_CONST_BINDING` for literals. A LIST, SELECT_VIEW or DATA_SELECTOR can take its dataSource either way, and the options tree offers both in one answer: the tables under 'Table', and any page query under 'Context > Current page > Data source'. **Prefer the table** \u2014 a component that owns its data source is filtered, sorted and retyped in one place, and `GET_REQUEST_FILTER_CONTEXT` narrows it at the component's own path. Reach for a page query (`ADD_COMPONENT_QUERY` first) only when the SAME result set is genuinely shared \u2014 two components reading one query, or a filter the page tunes centrally. One component, one filtered list is not a sharing case: adding a page variable there buys nothing and leaves a second thing to keep in step. Inside a list cell (scope \"list-cell:<listId>\") the options tree additionally offers the current list item's fields under 'item-data' \u2014 bind cell children to those instead of re-querying the table.\n\n### Editing Protocol\n- One read of a container covers both adding children to it and editing its own configuration, so `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO` on the same component is one call wasted. After a conflict, re-read and retry.\n- Wiring behavior: `GET_COMPONENT_SELECTABLE_EVENTS`, then `GET_SELECTABLE_COMPONENT_ACTIONS` for what that event accepts, then `ADD_COMPONENT_ACTIONS`. Anything a specific kind returns beyond its bindableSchemaPaths arrives under that handler's `details`.\n- Pick the kind from `GET_SELECTABLE_COMPONENT_ACTIONS` and take its parameter shape from `ADD_COMPONENT_ACTIONS`'s parameter schema (fetch it first if it was left out as \"schema on request\"), which is the only complete list of the kinds and their fields \u2014 the editor offers far more than the handful named below, including SHOW_TOAST, OPEN_EXTERNAL_LINK, SET_CLIPBOARD, DOWNLOAD_FILE, CALL_PHONE, the payment kinds and the animation kinds. Do not conclude an interaction is impossible because it is not discussed here; the selectable list and the schema decide that. What follows is only the judgment the schema cannot carry.\n- ALERT_DIALOG is the runtime's own confirm box \u2014 a title, a message and two buttons it draws itself, with no MODAL to build or lay out. Use it for \"are you sure?\"; use SHOW_MODAL when the dialog needs your own components in it. Chain what confirming does onto ALERT_DIALOG's ON_CONFIRM branch, or the buttons do nothing.\n- Building a MODAL does not make it reachable. Without a SHOW_MODAL action pointing at it, nothing opens it, and the modal you just laid out is dead UI the user cannot reach.\n- An action that produces a RESULT \u2014 GET_LOCATION, UPLOAD_FILE, GENERATE_QR_CODE and the other result-bearing kinds \u2014 can only keep it through assignToVariable, a writable page variable created with `ADD_COMPONENT_VARIABLES` on the page the component sits on. Their success branches cannot see the result, so an action without assignToVariable runs and throws its answer away. Create the variable first.\n- SIGN_UP and USER_LOGIN are separate actions, and the password slot on a SIGN_UP decides what the account can sign in with later: leave it unbound and the account has no password, so a USER_LOGIN with credentialType PASSWORD can never succeed for anyone who signed up there. Build the pair together, or sign in with VERIFICATION_CODE.\n- A WeChat mini-program signs its user in by itself. The client is created with a silent WeChat login in its own app-did-load configuration, which the editor will not let anyone delete, so whoever opens the app is already signed in, and the account is created there too. Do NOT build a sign-in or sign-up screen there and do NOT wire a login action: USER_LOGIN offers no WeChat mode at all, the silent login belongs to that configuration alone, and SIGN_IN / SIGN_UP / SIGN_OUT are absent from the mini-program's selectable actions. When the app needs the user's phone number, use OBTAIN_PHONE_NUMBER.\n- MUTATION writes the database without an action flow. rolesWithoutPermission in its result is report-only \u2014 grant the table permission with the permission plugin or the write is denied at runtime, which looks like a silent no-op to the user. rowScope CURRENT_ITEM is valid only inside a LIST cell; refreshOnSuccess is preferable to a separate REFRESH.\n- CONDITIONAL is how ONE event does different things in different cases: branches in evaluation order, first match wins, each branch narrowed at the echoed conditionSchemaPath and filled by a further `ADD_COMPONENT_ACTIONS` carrying that branch's conditionalBranchId. Leave the last branch always-true as the else. Without it every action on the event fires on every click \u2014 ON_SUCCESS / ON_FAILURE branch on whether a call worked, never on a data condition. Do NOT reach for an action flow to get branching: a flow's BRANCH node runs on the server and cannot navigate, toast or open a modal, so frontend branching belongs here. This decides what HAPPENS; a CONDITIONAL_VIEW decides what is DISPLAYED.\n- There is no per-component conditional visibility \u2014 an ordinary component has no data-driven show/hide flag. To make content appear only when a condition holds, wrap it in a CONDITIONAL_VIEW container and gate the branch with the bindings plugin's condition tools.\n\n### Motion Is One Moment, Not A Coat Of Paint\nZion has animation as ACTIONS, not style fields, so they are attached with `ADD_COMPONENT_ACTIONS` like any other handler: ANIMATION_FADE_EFFECT and ANIMATION_SLIDE_EFFECT (APPEAR / DISAPPEAR, eight directions, a distance defaulting to 150px), ANIMATION_SCALE_EFFECT, ANIMATION_COMMON_EMPHASIS (BOUNCE / PULSE / BLINK), ANIMATION_FLIP_EMPHASIS, and ANIMATION_SCROLLING_INTERACTION. Each takes delay, and the emphasis kinds take repeat or loop.\nThe rules are hard ones, and breaking them shows up as a project error rather than a subtle defect: exactly ONE animation per event, and only on onClick, onHover or onScrollIntoPage \u2014 the runtime reads the last effect it finds on the event and ignores any attached elsewhere. ANIMATION_SCROLLING_INTERACTION is the exception and goes ONLY on onPageScroll, which carries nothing else at all, because the curve is driven by scroll distance. None of them take attachTo and none take bindings, so they cannot be chained onto a success branch.\nSpend motion the way you spend the accent. Movement that answers what a person just did \u2014 a press, an open, a confirm \u2014 is worth it, because it shows what changed. Movement that merely announces that content exists is the generated-page tell: a fade-and-slide on every section as it scrolls into view reads as a template, and it reads that way precisely because it is the first thing reached for. One orchestrated moment on the screen that matters beats an effect on every card, and a screen with no animation at all is a perfectly good answer \u2014 far better than one where everything twitches. The emphasis kinds earn their place on something genuinely needing attention, never as decoration, and BLINK almost never earns it.\n\n### Reading A Screenshot\nOnly the editor's canvas shows what the user will see, and canvas screenshots are not reachable from here: the user has to open the screen in the editor. `schema validate` knows only about invalid schema. What it shows is worth reading against: one clear focal point rather than everything at the same weight; related things closer together than unrelated ones; at least three levels of text that differ in weight, not only size; gutters where things would otherwise touch an edge, and lines under ~70 characters; the accent only on the primary action and the active state; something that responds to hover; colour, spacing, radius, type and shadow values that are theme references, so a restyle reaches them. Report only what you actually changed. Every claim about appearance \u2014 a heading looks larger, a selected state looks different, spacing was tightened \u2014 must correspond to an `UPDATE_COMPONENT_STYLE` (or creation-time style) call you made in this session. If a requested look was not achievable with the available tools, say which part you skipped and why; do not describe the component's built-in default styling as if you had applied it. A user who is told the work is done stops checking.",database:`## Database Domain Knowledge
|
|
235
|
+
Product default timezone: **Asia/Shanghai** (UTC+08:00). A project can override it; the zone actually in effect is \`timezone\` in GET_PROJECT_OVERVIEW. Default UI language: Simplified Chinese (zh-CN).`,api:"## API Integration Domain Knowledge\nAn API integration is a saved external HTTP endpoint the project can use as a data source. APIs are organized into **workspaces**: a workspace groups related endpoints and holds shared **constants** (e.g. a base URL or API key) the endpoints reference, so credentials live in one place. The action-flow \"Call API\" node invokes these workspace APIs.\n\n### Anatomy\n- **Workspace**: a named group with a description and a set of `constants`.\n- **API**: an HTTP `method` + URL under a workspace, with request **parameters** (path / query / header / body), typed **response configs** (the result shape downstream binds from), and declared **input variables** (the values a caller supplies).\n\n### Workflow\nList with `GET_ALL_API_WORKSPACES` / `GET_ALL_APIS_INFO`, then `GET_API_DETAIL` to read an API's `apiId`, `workspaceId`, and parameter / response `uniqueId`s before editing \u2014 never fabricate them. Build top-down: `ADD_API_WORKSPACES` \u2192 `ADD_API_WORKSPACE_CONSTANTS` (put API keys / base URLs here, never inline) \u2192 `ADD_APIS` (each under a `workspaceId`) \u2192 `ADD_API_PARAMETERS`, `ADD_API_RESPONSE_CONFIGS`, `ADD_API_INPUT_VARIABLES`. Editing creates a new version; \"Sync Backend\" is required for changes to take effect in production.\n\n### Timeout\nEach API has a request `timeout` in seconds, 1 to 60, 30 when never set; ADD_APIS and UPDATE_API set it and GET_API_DETAIL reports it. Called from an action flow, the request is also cut off when the flow's own timeout runs out, whichever comes first, so raising an API's timeout helps only if the calling flow's timeout leaves room for it.\n\n### Request Bodies\nA body-carrying method needs a body FORMAT, and `SET_API_CONTENT_TYPE` is what sets it \u2014 `UPDATE_API` has no content-type argument and will reject one. `application/json` seeds an empty object type that belongs to this API; `GET_API_DETAIL` reports it as `bodyType`, and you describe it with the 'type' plugin's `ADD_TYPE_DEFINITION_FIELDS`. The two form formats take their fields from `ADD_API_PARAMETERS` instead. Every such switch DISCARDS the body that was there, so pick the format before filling it in \u2014 and never cycle the method away and back to force a reset, which throws the body parameters away with it.\n\nA media field, or an object field carried as a JSON string, cannot travel over HTTP as itself: it needs a conversion, and a media field left without one leaves the API incomplete. `GET_API_CODEC_OPTIONS` says which slots need one and what each allows; `SET_API_CODECS` applies it and `DELETE_API_CODECS` removes it.\n\n### Response Shapes\nA response config's type is what downstream reads the result through, and only an object type puts that result's fields where a binding can see and pick them. A JSON response still yields values \u2014 through the get-value-from-JSON formula \u2014 but the key path is a string you have to already know and spell by hand, nothing in the project lists what the payload holds, and a key that does not match it comes back empty rather than erroring; a text response does not even reach that formula. So whenever the endpoint documents what it returns \u2014 and it usually does \u2014 give the response a shape: `ADD_API_RESPONSE_CONFIGS` / `UPDATE_API_RESPONSE_CONFIGS` with `seedObjectType: true` mint an object type owned by this API and echo its `responseTypeId`, which you then describe with the 'type' plugin's `ADD_TYPE_DEFINITION_FIELDS`, exactly as you do a JSON request body. Add `arrayLevel: 1` where the endpoint returns a list of that shape. Reach for the JSON type only when the body's shape genuinely varies from call to call, and for text only when the response is not JSON at all (a 204 with no content, a plain-text body).\n\n### Types\nEvery `type` argument here is picked, not written: call `GET_API_SELECTABLE_TYPES` for the slot being filled and copy a returned `typeIdentifier` verbatim. A private object type belongs to the one feature that owns it and is never offered to another, so to reuse a shape some other feature owns, publish it with `COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC` and select the public copy. This API's own JSON body type is the exception \u2014 it is already this API's, so describe it in place with `ADD_TYPE_DEFINITION_FIELDS`. Lists are not enumerated \u2014 the nesting has no end \u2014 so a list response or input variable is a returned identifier plus `arrayLevel: 1`; the URL, header and form-body parameters hold one value, take no `arrayLevel`, and accept no list at all.",bindings:"## Data Binding Domain Knowledge\nData binding connects data sources to UI components for display or interaction.\n\n### Concepts\nSchema path: array of keys/indices locating a bindable node in the project JSON schema. Data binding options tree: hierarchical tree of all available data for a given schema path. Never hand-build a schema path for an action-flow node: copy it from the actionflow plugin's add_node result or get_flow_detail's nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments for the binding site inside the node. The binding-site key names VARY BY NODE TYPE (an AI node's input arg lives under inputArgs/<argKey>, a code node's under inputs/<index>/value, a mutation column under mutation/object/<columnName>) \u2014 copy the exact keys from the currentNode structure returned by get_context_info; never guess them.\nType metadata in read results uses exact typeIdentifier values such as `s:p:string` and `u:e:<enumId>`; copy those values verbatim.\n\n### Binding Kinds\nOPTION: bind to an existing path in the data binding options tree. pathInHierarchicalMenu must be the EXACT complete path, and menu labels are locale-dependent display names (a project may render them in Chinese or English) \u2014 so a label can NEVER be guessed. Before the first option binding at a schema path whose tree you have not seen, read it with `BROWSE_DATA_BINDING_OPTIONS` (CRITICAL: Do NOT call `get_options_tree` if the tree is already provided in the context above); afterwards every binding response attaches the refreshed tree for its op's path. Copy every label verbatim from that tree \u2014 never invent, translate, or shorten a label \u2014 and include every intermediate menu level. If the tree root is a named context (e.g., \"List Context\"), include it as the first element. CONST_VALUE: set a literal constant (e.g., \"Submit\", 0, false). FORMULA: compute a value with an operator (text / math / time / array / enum / geography / json groups); discover the available operators before building one. CONDITIONAL: choose the value by branch \u2014 define the branches, then build each branch's predicate.\n\n### Priority\n1. Prefer OPTION (live data) over CONST_VALUE.\n2. No suitable option? Use CONST_VALUE with a reasonable inferred constant.\n3. Component purpose unclear? Skip binding.\n4. A list NESTED INSIDE another list binds from the ancestor's item data, not from a table, so the relational linkage survives. This is about nesting only \u2014 a top-level list binds straight to the table it shows, and prefers that over consuming someone else's page query unless the result set is genuinely shared.\n5. Bind ONLY what the task requires: in an update/insert node's object leave every other column untouched \u2014 never fill it with a Null option or a placeholder constant (Null on a required column breaks the flow at runtime).\n6. Never seed a typed site with a throwaway constant \"for now\" and upgrade later \u2014 bind the real value directly; a constant re-types nothing but still wastes a round.\n\n### Iterative Refinement\nPer-op errors are returned keyed by index. Successful bindings have already landed. On rejection, fix ONLY the failing entries by index and re-call.\n\n### Data Sources Available in Zion\nDatabase tables (with filters/sorting/limits), page data sources, page variables, global variables, page parameters, logged-in user, list/component item data, Actionflow inputs/outputs, formula results.\nThis is the product-wide catalog, NOT what is bindable at any given site \u2014 each site exposes only a subset. NEVER assume a category is available: the options tree for the site is authoritative, so read it with `BROWSE_DATA_BINDING_OPTIONS` first and bind only categories it actually lists. If one (e.g. formula data) is absent for that path, it is not valid there \u2014 do not attempt it. (Action flows run strictly on the backend, so page data sources never apply inside a flow node.)\n\n### Request Filters (where / sort)\nA database-query data source \u2014 a list/component request, or an action-flow query / update / delete node \u2014 carries **request filters**. FIRST call `GET_REQUEST_FILTER_CONTEXT` with the request's (or owning node's) schema path: it returns the table's selectable columns (with the `pathComponents` and `allowedOperators` to use) and the filter entries' `whereSchemaPath` / `sortConfigsSchemaPath`. Copy those paths and column `pathComponents` verbatim \u2014 never hand-build them. Queries and component requests carry a LIST of conditional filters (where + sort groups, each gated by its own condition, always including a system Default filter). An action-flow update/delete node instead carries ONE bare where (`supportsConditionalFilters: false` in the context result) \u2014 edit it via the single entry's `whereSchemaPath` with the where-condition tools only; the filter-group and sort tools do not apply, and insert nodes have no request filter at all.\nTo change a numeric column RELATIVE to its current value (stock, counters, balances), set the column's write mode with `SET_UPDATE_COLUMN_ARITHMETIC` and bind only the DELTA as the column's value \u2014 the database applies it atomically. Never query the current value, compute in a formula, and set it back: that read-modify-write loses concurrent updates. Idiom \u2014 decrease field_a by x: mode 'decrement' on field_a, value x, and a where guard `field_a > x` (or `>= x` when draining to zero is allowed) so the update changes nothing when the stored value is insufficient. That rule generalizes to every mutation this plugin configures \u2014 frontend component mutation events and action-flow nodes alike: when a write's correctness depends on current row state, put the check in the mutation's own where filter and let follow-ups branch on its affected rows, instead of querying first and writing on the stale read (concurrent users race it). Insert-if-absent semantics additionally need a unique constraint \u2014 the only DB-enforced constraint kind today (see the database plugin).\n- Filter groups: `ADD_REQUEST_CONDITIONAL_FILTER` / `UPDATE_REQUEST_CONDITIONAL_FILTER` / `DELETE_REQUEST_CONDITIONAL_FILTER` / `REORDER_REQUEST_CONDITIONAL_FILTERS`. The Default filter cannot be renamed or deleted.\n- Where conditions: `ADD_REQUEST_FILTER_CONDITION` (column + operator), then fill its comparison value with a binding (OPTION / CONST_VALUE) at the condition's `value` path; shape the expression with `NEST_REQUEST_FILTER_CONDITION`, `TOGGLE_REQUEST_FILTER_CONDITION_AND_OR`, `TOGGLE_REQUEST_FILTER_CONDITION_NOT`, `UPDATE_REQUEST_FILTER_CONDITION_OPERATOR`, `DELETE_REQUEST_FILTER_CONDITION`.\n- Sort: `ADD_REQUEST_SORT_CONFIG` / `UPDATE_REQUEST_SORT_CONFIG` / `DELETE_REQUEST_SORT_CONFIG` / `REORDER_REQUEST_SORT_CONFIGS`.\n\n### Composing text from fragments and variables\nFor any `s:p:string` value that mixes literal fragments with variables \u2014 AI prompt templates, titles, labels, messages \u2014 do NOT build a stringConcat formula. Build the template at the same schema path with operation CONCAT: `CREATE_CONST_BINDING` for a literal fragment, `CREATE_OPTION_BINDING` for a variable. Each CONCAT appends to the end, so the final order is exactly the order you emit entries \u2014 within a call and across consecutive binding calls in the same turn. Emit them in final reading order, interleaving literals and variables \u2014 e.g. const_value \"Hello \", option user, const_value \", order \", option orderId, const_value \" total \", option amount. Never emit all literals then all variables (that puts every label before every variable), and two literal CONCATs in a row merge into one fragment. This produces the same inline template the editor's text fields produce and stays editable there. Reserve formulas for real computation (math, time, regex, arrays) \u2014 never for simple text templating.\nA number, boolean, date, time, datetime or color bound into a `s:p:string` slot is converted for display automatically, so bind the option straight to the slot \u2014 never wrap it in `toText` or any other conversion operator. Only structured values (lists, objects, media) genuinely need one. `BROWSE_DATA_BINDING_OPTIONS` marks an option with `*` only when the target really cannot take it; an unmarked option needs no conversion step.\n\n### Formula & Conditional Bindings\nA FORMULA or CONDITIONAL value is built in several steps at the value's schema path, not in a single call.\n- Formula: call `GET_FORMULA_OPERATORS` at the path, then `CREATE_FORMULA_BINDING` with an operator copied verbatim (the wire token, e.g. `-` not SUBTRACT; operation REPLACE). If the operator needs scalar config (e.g. distance unit, rounding mode), read its shape with `GET_FORMULA_CONFIG_OPTIONS` and pass it or apply it later with `SET_FORMULA_CONFIG`. The create result returns `operandSchemaPaths` \u2014 fill each operand with an OPTION / CONST_VALUE binding at its returned path, copied verbatim; never derive an operand path yourself. A `timezone` operand (e.g. on FORMAT_DATE_TIME) is optional: unbound, the project's default zone applies, so bind it only when the user asks for a specific zone or the viewer's own.\n- Conditional: `CREATE_CONDITIONAL_BINDING` (seed branches with initialBranchNames; operation REPLACE), add more with `INSERT_CONDITIONAL_DATA`. For each branch, build its predicate with `INSERT_CONDITION_BOOL_EXP`, choose the comparison via `GET_EXPRESSION_CONDITION_OPERATORS` + `UPDATE_EXPRESSION_CONDITION_OPERATOR`, fill both operands with OPTION / CONST_VALUE bindings, and shape the expression with `NEST_CONDITION_BOOL_EXP`, `TOGGLE_CONDITION_BOOL_EXP_AND_OR`, `TOGGLE_CONDITION_BOOL_EXP_NOT`, `DELETE_CONDITION_BOOL_EXP`; then bind the branch's resulting value. The first branch whose predicate is true wins \u2014 order them with `REORDER_CONDITIONAL_DATA`.\n- There is no string is-empty operator (`_is_empty` accepts lists only, and `\"\"` is not null): test text emptiness as `stringLength(x) > 0` via a formula binding on the operand.\n\n### Page links\nThe global page-link option binds a getPageUrl function binding with no target page, so the link points nowhere until you call `SET_FUNCTION_BINDING_PAGE_URL_TARGET` at the same schema path with the target page's id. Fill each parameter it returns under argSchemaPaths with an OPTION / CONST_VALUE binding at that path, copied verbatim.\n\n### Lists composed item by item\nTo give a list slot a literal list, bind the Custom > Array option at its schema path, then append items with `ADD_CUSTOM_ARRAY_BINDING_ITEMS` \u2014 a binding at an item index that does not exist yet is rejected, so an empty custom array can only grow through that tool. Fill each item it returns under itemSchemaPaths with an OPTION / CONST_VALUE binding, copied verbatim. For a list of lists, each item is a custom array of its own: call `ADD_CUSTOM_ARRAY_BINDING_ITEMS` again at the item's path. Remove items with `DELETE_CUSTOM_ARRAY_BINDING_ITEMS`.",component:"## Component Domain Knowledge\nThe UI is a tree of components organized into pages.\n\n### Identity & Tree Rules\nEvery component has an immutable id and a displayName. Reads return both; write tools verify the {id, displayName} pair and reject a mismatch \u2014 re-read, then retry. A container's children order IS the visual order. A component can never be moved into its own subtree.\n\n### Categories\nLayout (container \u2014 can hold other components via `children`):\n- PAGE: root of each page; created without a parent and registered as a new page.\n- LAYOUT_VIEW: generic Flexbox container; the most common container.\n- MODAL: popup/dialog container; created without a parent, opened/closed via events.\n\nSpecial (complex \u2014 children live in built-in slots seeded at creation and mutated only via the slot tools, never via ADD_COMPONENT / MOVE_COMPONENTS):\n- LIST: repeating list; its \"cell\" slot renders once per data row (optional header/footer).\n- TAB_VIEW: tabbed interface; one child view per tab in tabList.\n- SELECT_VIEW: built-in normal/selected state views.\n- CONDITIONAL_VIEW: one built-in view per condition branch.\n- MAP: optional \"marker\" slot taking a MAP_MARKER.\n\nLeaf/Business (cannot have children): BUTTON, TEXT, IMAGE, VIDEO, LOTTIE, RICH_TEXT, TEXT_INPUT, NUMBER_INPUT, VIDEO_PICKER, FILE_PICKER, SWITCH, MAP_MARKER, CALENDAR, HORIZONTAL_LINE, SHEET, HTML, RICH_TEXT_EDITOR, MIX_IMAGE_PICKER, DATE_TIME_PICKER, DATA_SELECTOR, PROGRESS_BAR. MAP_MARKER can only be placed inside MAP. `GET_SELECTABLE_COMPONENT_TYPES` returns the full creatable catalog with each type's slot fields.\n\n### Hierarchy Rules\nEvery component except PAGE and MODAL must have a Layout Component as its parent. Prefer relative positioning; use absolute/fixed only when truly necessary.\n\n### Layout\nZion uses Flexbox. Layout containers configure: direction (row/column), justify-content (start, space-between, space-evenly, space-around), gap, wrap, overflow (scroll/visible/hidden).\n\n### Responsive Breakpoints\nPhone: 0\u2013767 px (375 px panel) | Tablet: 768\u20131279 px (820 px panel) | Desktop: 1280\u20131920 px (1440 px panel). Desktop is the primary breakpoint and the one every read and write defaults to. A narrower breakpoint stores only its differences from desktop, so a field it does not override renders the desktop value at that width \u2014 an app built without touching phone is not unstyled there, it is desktop-sized there, which is how a 600 px card ends up running off a 375 px screen. The schema and the error center do not show this; a read with `breakpoint` or a phone capture does, so look at phone when you build or restyle a layout the user will open on one, not after every edit. Read what phone actually resolves to by passing `breakpoint` to `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO`; the read names which fields that breakpoint overrides and which it inherits. Fix one by resending that field with the `breakpoint` param to `UPDATE_COMPONENT_STYLE` \u2014 usually flexDirection 'column' on rows, and widths in % or fill rather than px; the phone breakpoint in the editor shows the result. Resending a value unchanged at a breakpoint pins it there and stops it following desktop, so override only what has to differ.\n\n### Reading the Component Tree\nIds are opaque: copy them verbatim from these read tools and never modify them. A page id (from `GET_ALL_ROOTS_INFO`) is not a component id, and breakpoint keys (phone/tablet/desktop) are tool parameters, never part of an id \u2014 passing something like `<pageId>-desktop` as a component target fails with \"target component not found\".\n\n### Building & Editing the Component Tree\nConstruction workflow: read the target container, pick types with `GET_SELECTABLE_COMPONENT_TYPES`, edit `GET_COMPONENT_TEMPLATE` output and submit it via `ADD_COMPONENT`, then use the ids it echoes instead of re-reading.\nContainer sizing: a LAYOUT_VIEW hugs its content, so a container created WITH its children inside is sized by them and needs no height of its own; an empty one keeps a small minimum height so it stays visible and droppable, and filling it makes that minimum irrelevant. Give a container an explicit height only when you want a fixed-size box or a scroll viewport \u2014 a fixed height its content outgrows clips that content invisibly, and a fixed width crops text mid-word. `UPDATE_COMPONENT_STYLE` merges, so a size you do not name keeps its old value.\nWidth/height `fill` means \"grow along the flex main axis\", so it only makes sense on the axis the parent lays out along: `width: fill` in a row, `height: fill` in a column. On the other axis it would unset the size and let the child shrink to its content, so it is applied as '100%' instead and the result says so. There is no `stretch` alignment to fall back on \u2014 in Zion a component declares its own size rather than having its container negotiate one.\nA row of cards is sized one axis at a time. Along the row, give every child `fill`, or fr shares \u2014 `65fr` and `35fr` \u2014 when the split is deliberate; never percentages, because fr divides what is left after the gap and the padding while `65%` + `35%` claims the whole width and the gap then pushes it over, wrapping or clipping the last column. Across the row, give every child the SAME `minHeight` so they bottom out together: a real `height` would clip the card whose content grows past it, and with no `stretch` to fall back on a shared floor is as close to equal-height cards as this system gets \u2014 a card whose content clears the floor still grows alone, so pick a floor that clears the tallest copy you expect. Set `minWidth` on a child only where that column has a genuine floor: it, not `flexWrap`, is what makes a row break into 2+1 once the container is narrower than the floors plus the gaps. Size the children this way and the container needs nothing beyond `flexDirection`, `gap` and its own width \u2014 `justifyContent` and `alignItems` have no free space left to distribute, so reaching for them to fix a ragged row means the children are the wrong size.\nWhen a sentence reports as clipped horizontally, it is nearly always `textWrap` false (see Typography below): widening the box, or setting `overflowX`, does not make the text reflow.\nA TEXT_INPUT collecting a password needs `password: true` via `UPDATE_COMPONENT_PROPERTIES`; a \"Password\" placeholder alone does not mask anything.\n\n### A Look Is Decided, Not Defaulted\nA request that names no visual direction \u2014 \"a task tracker\", \"a booking page\" \u2014 is not a request for no styling: the platform's creation defaults are what produce the grey-box build the user then has to describe their way out of. The subject is where a non-generic direction comes from \u2014 what this app is, who opens it, the one job it does, and the palette, typeface and type roles that reading implies \u2014 and it is the only input no other project shares: a shift-handover tool for night-shift nurses and a portfolio for a ceramicist should not resolve to the same screen. Written into the theme (next section), that direction holds every screen built out of it together. A direction the user states \u2014 a brand colour, \"dark\", \"playful\", a screenshot \u2014 replaces your own everywhere. What fails is splitting the difference: a stated direction on the first two screens and your own default on the rest reads worse than either applied throughout, because inconsistency looks like a bug rather than a choice.\n\n### The Theme Is The Design System\nEvery style value that has a theme category is sent as that variable's referenceValue, `$$<id>`, never as a literal: colours (backgroundColor, textColor, borderColor, gradient stops, shadow.color) from colour variables, padding/margin/gap from spacings, borderRadius from radii, fontSize, fontWeight and fontFamily from their own categories, and a whole shadow as `shadow: {variable: '$$<id>'}`. The id resolves against the field's category, so `$$md` under padding is the spacing md and under borderRadius the radius md. A literal renders the same today and is pinned to the component it was written on; a reference follows the theme. That difference is the whole point: \"make it rounder\", \"a different font\", \"warmer\" is then a few `UPDATE_THEME_VARIABLES` edits that every screen follows, instead of a sweep that touches every component and still misses some. Only lineHeight, letterSpacing, borderWidth, opacity and sizes have no category and stay literal.\nThat is the default, not a rule over the user:\n- A value the user gives for one component (\"make this button 13px\", \"this banner #ff6600\") is written as that literal on that component \u2014 not rounded to the nearest variable, not turned into a new variable, and not applied by retuning a variable every screen shares. When it is unclear whether they mean this component or the whole app, ask.\n- Change only what the request touches. Existing literals stay literal unless the user asks for the restyle; do not convert them on the side.\n- Add a variable only for a value several components share, never for a one-off.\n`GET_THEME_INFO` shows what the theme holds. A theme already carries colour roles (Primary, Secondary, Tertiary, Text_primary, Text_secondary, Background, Surface, Border, Success, Alert, Error), font sizes h1 through caption that already shrink per breakpoint, weights 100\u2013900, radii sm\u2013full, spacings xs\u2013xl3 and shadows xs\u2013xl2 \u2014 and no font family. Retune those values to the direction you decided rather than working around them, and add a variable only for a role the theme lacks. When the user later asks for a different look, change the variables, not the components.\nOn a web client a font size, radius or spacing variable holds one value per breakpoint (`{desktop, tablet, phone}`). When one has to differ on phone \u2014 an h1 at 28 on desktop and 24 on phone \u2014 set that on the variable, not as a breakpoint override of fontSize, padding, gap or borderRadius on the components that reference it: an override replaces the reference at that width, so the component stops following the theme there.\n\n### The Palette Is Named Before It Is Spent\nGive a new colour variable a palette level (the theme plugin explains which), not a hex, so it recolours with the rest. A working set is roughly eight roles, named by ROLE, not by colour \u2014 \"surface\", not \"light-grey\":\n- Four neutrals, not two: the page ground, a surface lifted off it, a border a step darker again, and a hairline/divider weaker than the border. Two neutrals is the single most common cause of a flat screen \u2014 with only \"background\" and \"border\" available, every card, input, header and divider ends up drawn with the same one, and nothing separates from anything.\n- Two inks: primary for content, muted for secondary text and labels. Do NOT make muted text by dropping `opacity` on a TEXT \u2014 opacity fades the whole component including anything it contains, and it composites against whatever is behind it, so the same \"muted\" reads differently on a card than on the page. Muted is a colour.\n- One accent, and one status colour (danger) if the app writes data.\nSpend the accent only on the primary action and the active/selected state. The moment it also appears on a heading, an icon and a border, nothing on the screen is being pointed at.\n\n### A Text Role Is Three Values Sent Together\nThe theme has font sizes and font weights but no line height and no combined text style, so a role \u2014 page title, section heading, body, label, caption, rarely more than five \u2014 is a pairing you keep yourself: a size variable, a weight variable and a lineHeight, sent together every time. Asking for a heading means all three; a heading size at body weight is two roles blended. lineHeight is absolute px and does not follow the size: roughly 1.2\xD7 the size for headings, 1.5\xD7 for body copy, and without it anything above the default crops or overlaps. The display sizes shrink on phone while the lineHeight you sent at the main breakpoint does not, so give a heading role a phone lineHeight as well. For the same reason, changing a font size variable does not move the lineHeight of the text that uses it: in the same turn, re-send lineHeight (and the phone lineHeight) on every TEXT and BUTTON of that role, or the larger text crops and overlaps.\n\n### Typography Carries Most Of The Impression\nThe type is the largest coloured area on almost every screen, so it decides the character of the page before any accent does.\n- Typeface is a real choice: the default (DM Sans on web, pingFang SC on mobile) is the face every other project ships with. Add it as a FONT_FAMILIES variable and reference it as fontFamily on every TEXT, BUTTON and TEXT_INPUT \u2014 then switching the face later is one edit. If the theme already has a FONT_FAMILIES variable, reference it rather than adding another; a project that predates theme font variables lists its faces in styleScaleFontFamilies. `GET_THEME_INFO` lists the families this client offers under offeredFontFamilies, and only those have font files; any other name renders as the system fallback. One family is a complete answer; two only when clearly distinct in role (a display face and a text face), never two sans faces that differ slightly. If the copy is Chinese, the BODY face has to be a CJK one, not just the headline: a Latin family carries no Chinese glyphs, so every Chinese character falls back to whatever the device has. A display face carries a headline and nothing longer.\n- Hierarchy comes from weight and space as much as from size. Three text roles that differ only in size read as one undifferentiated block; a heading at 600\u2013700 against body at 400 separates at a glance even when the sizes are close.\n- `letterSpacing` is in PIXELS, not em, and goes NEGATIVE on large display type \u2014 roughly -0.5px at a 28\u201332px page title, -1px or beyond as the size grows \u2014 because a face designed at body size is too loose when set large. Body text wants 0. A fractional value like -0.02 changes nothing visible, so sending one and then reporting the tracking as tightened is a false claim. It goes slightly POSITIVE only on small uppercase labels, which are themselves worth avoiding (see below).\n- Set `maxWidth` on any TEXT holding a paragraph. Unbounded body text stretches to the container and a 1200px-wide line is unreadable regardless of how well it is styled; hold it near 60\u201370 characters, which at body size is roughly 600\u2013680px. A capped column keeps hugging the left edge until its PARENT centres it \u2014 in a column parent (a PAGE's default) that is `alignItems: 'center'`. This is the most-skipped and most-visible typographic fix in a wide desktop layout.\n- Body text needs `textWrap: true` \u2014 false pins it to one line and ellipsises it at the box edge however wide the sentence is. `lineClamp` on top when it must stop after N lines.\n\n### Depth Is One Decision, Applied Once\nThe failure mode is shadow everywhere rather than shadow used well.\n- A card lifts off the page with EITHER a hairline border OR a soft shadow, not both. Pick one for the whole app.\n- Elevation is at most two levels \u2014 resting surface, and the raised thing (modal, dropdown, the one hero card) \u2014 so reference two of the theme's shadow variables and no more. A third level means the second is not doing its job.\n- A real shadow is large, soft and nearly transparent, and offset downward only \u2014 light comes from above: `blur` well above `offsetY`, a colour at low alpha. If the theme's shadows do not read that way, retune those variables rather than drawing a shadow on one component.\n- `inset: true` is for the pressed state of a button and for a well an input sits in. It is the only correct way to make something look recessed rather than raised.\n- `backdropBlur` belongs on overlay chrome that sits over content \u2014 a sticky header, a modal scrim. On an ordinary card it costs paint and buys nothing, since there is nothing behind it to blur.\n- `borderRadiusCorners` exists for the cases a single radius cannot express: a segmented control, a sheet rounded only at the top, a cell at the end of a row. Reach for it there and nowhere else.\n- Radius is hierarchy. If the card, the input, the badge and the button all carry the same radius variable, the screen has told the user nothing about what is what.\n\n### Space Is The Cheapest Thing That Reads As Finished\nThe common failure is far too little of it, and it is not a matter of taste \u2014 the numbers are knowable. On desktop, section padding starts at 64px vertical and goes up, not down; card padding at 20\u201324px; the page gutter at least two spacing steps above the in-card gap, so a card reads as sitting on the page rather than pasted onto it. When a screen feels cramped, the fix is almost always more space AROUND the groups, not less space inside them. Proximity is the actual signal: things that belong together sit closer to each other than to anything else, and if a label is equidistant from its own field and the next one, the layout has lost the reader regardless of how the label is styled.\n\n### The Look That Reads As Generated\nNone of these is forbidden \u2014 each is right for some brief \u2014 but they are what gets reached for when nothing has been decided, so they appear regardless of subject. Where the user asked for one, give it to them. Where they left the axis free, spend the freedom elsewhere:\n- Cream page (near #F4F1EA) with a high-contrast serif display and a terracotta/clay accent (near #D97757).\n- Near-black page with one acid-green or vermilion accent.\n- Every surface on the same radius under the same soft grey shadow, whatever its role.\n- A tracked-out ALL-CAPS eyebrow label above every heading.\n- Meta strings joined with middle dots ('A \xB7 B \xB7 C'); '\u2192' appended to button text.\n- One word in a heading coloured or bolded to add interest.\n- Numbered markers (01 / 02 / 03) on content that is not actually a sequence.\n- A gradient used as decoration on a surface that has no reason to be gradient. A gradient is legitimate as the subject of a hero, or to keep text legible over an image; as a wash behind ordinary cards it is the clearest single tell.\n\n### Every Interactive Thing Answers The Cursor\n`UPDATE_COMPONENT_STYLE` takes `variant: 'hover'`, and a build that never sends it is a build where nothing on screen responds to the mouse. That, more than any colour choice, is what makes a page feel like a mockup rather than an application. A hover state on buttons, clickable cards and list rows \u2014 a surface a step lighter or darker is enough \u2014 costs one extra call per component type, not per component, because the same few shapes repeat. A LAYOUT_VIEW with an ON_CLICK handler still shows an arrow cursor until it gets `cursor: 'pointer'`, so the user has no way to know it is a target. Where a SELECT_VIEW or a TAB_VIEW has a selected state, style it. The default selected state is not a design decision, and \"the active tab looks like the inactive ones\" is a bug the user will report in different words.\n\n### Three Things Can Be Conditional \u2014 Pick The Smallest One\nWhen a screen has two modes, do NOT reach for a conditional container first. Ask what actually differs between the modes, and make only that conditional:\n- Conditional DATA (`CREATE_CONDITIONAL_BINDING`) when only VALUES differ \u2014 a label, a title, a placeholder, a colour. One component, one conditional binding whose branches are keyed off the deciding value. This is the default answer.\n- Conditional ACTION when only BEHAVIOR differs \u2014 one button that submits, signs in or signs up depending on the mode. One button, one handler that branches.\n- Conditional VIEW (CONDITIONAL_VIEW) only when the STRUCTURE differs \u2014 different fields, different counts of children. Branches do NOT share children, so anything you put in a branch is duplicated in every other branch. If the two modes share a form, keep the shared form OUTSIDE the CONDITIONAL_VIEW and put only the differing part inside it. Its branch conditions start always-true, so the first branch shows until you narrow them; make the mode a page variable the conditions read and change it with SET_VARIABLE_DATA.\nA \"switchable signup / login\" is therefore conditional data plus a conditional action over ONE shared form \u2014 not two branches each holding a copy of the same fields. Wrapping shared UI in branches is the classic wrong answer: it looks right and silently doubles the tree.\nTAB_VIEW is a different question entirely: use it only when the tab strip itself is the affordance the user should see and click. It renders tab chrome you cannot remove.\nBoth TAB_VIEW and CONDITIONAL_VIEW take `preserveStateOnSwitch`, and it is the same mechanism in both: true keeps every case alive, so a scrolled list, a half-filled input or a loaded query survives switching away and back; false tears the inactive case down and rebuilds it from scratch. Both are created with it ON. Turn it off only when stale state would be wrong (a form that must reset), and remember the cost: every case stays mounted.\n\n### Components That Display a Field of Their Data\nDATA_SELECTOR, SELECT_VIEW and LIST name one field of their data source: `displayDataField` (the value the user sees) and `cellKeyDataField` (the row identity). Binding the dataSource is not enough \u2014 a DATA_SELECTOR or SELECT_VIEW whose data source resolves to a list of objects is invalid until its displayDataField is set. Set it with `UPDATE_COMPONENT_PROPERTIES`, passing the field's plain NAME as a string; the full field reference is resolved for you, so never hand-assemble one. The candidates appear as selectableDataFields in `GET_COMPONENT_INFO` once the dataSource is bound \u2014 so the order is always: create \u2192 bind dataSource \u2192 read the component \u2192 name the field.\n\n### Page Data: Queries, Variables & Inputs\nPages have NO separate query list \u2014 a page query IS a read-only page variable whose dataSource is a database query. It is for data more than one component reads, or a filter the page owns centrally; a single list showing one filtered table binds that table itself (see Data Bindings below) and needs nothing here:\n- `ADD_COMPONENT_QUERY` attaches a table query to a PAGE or MODAL (limit 1 = single row, >1 = list). Components consume it through data bindings (bindings plugin) at the echoed dataSourceSchemaPath; narrow filters and sorting with the request-filter tools at that same path. The result also reports rolesWithoutSelect: those roles see no rows until they are granted SELECT with the permission plugin's table-permission tool. Tune with `UPDATE_COMPONENT_QUERY` \u2014 which also sets or clears the row limit of the query a LIST, SELECT_VIEW, DATA_SELECTOR or SHEET owns; remove queries and variables alike with `DELETE_COMPONENT_VARIABLES`.\n- Page-local mutable state: `ADD_COMPONENT_VARIABLES`, with each typeIdentifier picked from `GET_COMPONENT_VARIABLE_SELECTABLE_TYPES` \u2014 never hand-assembled. A new variable starts with no value, so give it an initial one at the `defaultValueSchemaPath` the result echoes whenever anything reads it: conditional cases, branch conditions and SET_VARIABLE_DATA values all test the variable against specific values, and none of them match an empty variable. The page then loads with every dependent case unmatched \u2014 blank labels, the fallback branch showing \u2014 and a toggle whose new value is itself conditional on the old one cannot recover, because it has nothing to match either.\n- Page parameters: `ADD_COMPONENT_INPUTS` / `UPDATE_COMPONENT_INPUT` / `DELETE_COMPONENT_INPUTS`. WEB pages take URL query/path params; WECHAT/MOBILE pages and MODALs take general inputs. Navigation and show-modal call sites pass one value per input.\n- `SET_INITIAL_PAGE_ID` sets the app's home page for the current client.\n\n### Data Bindings on Components\n`GET_COMPONENT_BINDABLE_PROPERTIES` lists every place a component can be bound \u2014 always start there and copy the paths verbatim, never hand-assemble a binding path. It returns two sections: `properties`, the component's own slots, each with its ready-to-use schemaPath, expected type, current binding and scope; and `actionSlots`, the parameter slots of the actions already wired to its events, chained success/failure branches included. `ADD_COMPONENT_ACTIONS` echoes an action's slots when it creates it \u2014 bind them in the same turn when you can, and use `actionSlots` to find them again in any later turn. Fill the echoed paths with the bindings plugin's tools: `BROWSE_DATA_BINDING_OPTIONS` + `CREATE_OPTION_BINDING` for dataSource slots and other dynamic values, `CREATE_CONST_BINDING` for literals. A LIST, SELECT_VIEW or DATA_SELECTOR can take its dataSource either way, and the options tree offers both in one answer: the tables under 'Table', and any page query under 'Context > Current page > Data source'. **Prefer the table** \u2014 a component that owns its data source is filtered, sorted and retyped in one place, and `GET_REQUEST_FILTER_CONTEXT` narrows it at the component's own path. Reach for a page query (`ADD_COMPONENT_QUERY` first) only when the SAME result set is genuinely shared \u2014 two components reading one query, or a filter the page tunes centrally. One component, one filtered list is not a sharing case: adding a page variable there buys nothing and leaves a second thing to keep in step. Inside a list cell (scope \"list-cell:<listId>\") the options tree additionally offers the current list item's fields under 'item-data' \u2014 bind cell children to those instead of re-querying the table.\n\n### Editing Protocol\n- One read of a container covers both adding children to it and editing its own configuration, so `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO` on the same component is one call wasted. After a conflict, re-read and retry.\n- Wiring behavior: `GET_COMPONENT_SELECTABLE_EVENTS`, then `GET_SELECTABLE_COMPONENT_ACTIONS` for what that event accepts, then `ADD_COMPONENT_ACTIONS`. Anything a specific kind returns beyond its bindableSchemaPaths arrives under that handler's `details`.\n- Pick the kind from `GET_SELECTABLE_COMPONENT_ACTIONS` and take its parameter shape from `ADD_COMPONENT_ACTIONS`'s parameter schema (fetch it first if it was left out as \"schema on request\"), which is the only complete list of the kinds and their fields \u2014 the editor offers far more than the handful named below, including SHOW_TOAST, OPEN_EXTERNAL_LINK, SET_CLIPBOARD, DOWNLOAD_FILE, CALL_PHONE, the payment kinds and the animation kinds. Do not conclude an interaction is impossible because it is not discussed here; the selectable list and the schema decide that. What follows is only the judgment the schema cannot carry.\n- ALERT_DIALOG is the runtime's own confirm box \u2014 a title, a message and two buttons it draws itself, with no MODAL to build or lay out. Use it for \"are you sure?\"; use SHOW_MODAL when the dialog needs your own components in it. Chain what confirming does onto ALERT_DIALOG's ON_CONFIRM branch, or the buttons do nothing.\n- Building a MODAL does not make it reachable. Without a SHOW_MODAL action pointing at it, nothing opens it, and the modal you just laid out is dead UI the user cannot reach.\n- An action that produces a RESULT \u2014 GET_LOCATION, UPLOAD_FILE, GENERATE_QR_CODE and the other result-bearing kinds \u2014 can only keep it through assignToVariable, a writable page variable created with `ADD_COMPONENT_VARIABLES` on the page the component sits on. Their success branches cannot see the result, so an action without assignToVariable runs and throws its answer away. Create the variable first.\n- SIGN_UP and USER_LOGIN are separate actions, and the password slot on a SIGN_UP decides what the account can sign in with later: leave it unbound and the account has no password, so a USER_LOGIN with credentialType PASSWORD can never succeed for anyone who signed up there. Build the pair together, or sign in with VERIFICATION_CODE.\n- A WeChat mini-program signs its user in by itself. The client is created with a silent WeChat login in its own app-did-load configuration, which the editor will not let anyone delete, so whoever opens the app is already signed in, and the account is created there too. Do NOT build a sign-in or sign-up screen there and do NOT wire a login action: USER_LOGIN offers no WeChat mode at all, the silent login belongs to that configuration alone, and SIGN_IN / SIGN_UP / SIGN_OUT are absent from the mini-program's selectable actions. When the app needs the user's phone number, use OBTAIN_PHONE_NUMBER.\n- MUTATION writes the database without an action flow. rolesWithoutPermission in its result is report-only \u2014 grant the table permission with the permission plugin or the write is denied at runtime, which looks like a silent no-op to the user. rowScope CURRENT_ITEM is valid only inside a LIST cell; refreshOnSuccess is preferable to a separate REFRESH.\n- CONDITIONAL is how ONE event does different things in different cases: branches in evaluation order, first match wins, each branch narrowed at the echoed conditionSchemaPath and filled by a further `ADD_COMPONENT_ACTIONS` carrying that branch's conditionalBranchId. Leave the last branch always-true as the else. Without it every action on the event fires on every click \u2014 ON_SUCCESS / ON_FAILURE branch on whether a call worked, never on a data condition. Do NOT reach for an action flow to get branching: a flow's BRANCH node runs on the server and cannot navigate, toast or open a modal, so frontend branching belongs here. This decides what HAPPENS; a CONDITIONAL_VIEW decides what is DISPLAYED.\n- There is no per-component conditional visibility \u2014 an ordinary component has no data-driven show/hide flag. To make content appear only when a condition holds, wrap it in a CONDITIONAL_VIEW container and gate the branch with the bindings plugin's condition tools.\n\n### Motion Is One Moment, Not A Coat Of Paint\nZion has animation as ACTIONS, not style fields, so they are attached with `ADD_COMPONENT_ACTIONS` like any other handler: ANIMATION_FADE_EFFECT and ANIMATION_SLIDE_EFFECT (APPEAR / DISAPPEAR, eight directions, a distance defaulting to 150px), ANIMATION_SCALE_EFFECT, ANIMATION_COMMON_EMPHASIS (BOUNCE / PULSE / BLINK), ANIMATION_FLIP_EMPHASIS, and ANIMATION_SCROLLING_INTERACTION. Each takes delay, and the emphasis kinds take repeat or loop.\nThe rules are hard ones, and breaking them shows up as a project error rather than a subtle defect: exactly ONE animation per event, and only on onClick, onHover or onScrollIntoPage \u2014 the runtime reads the last effect it finds on the event and ignores any attached elsewhere. ANIMATION_SCROLLING_INTERACTION is the exception and goes ONLY on onPageScroll, which carries nothing else at all, because the curve is driven by scroll distance. None of them take attachTo and none take bindings, so they cannot be chained onto a success branch.\nSpend motion the way you spend the accent. Movement that answers what a person just did \u2014 a press, an open, a confirm \u2014 is worth it, because it shows what changed. Movement that merely announces that content exists is the generated-page tell: a fade-and-slide on every section as it scrolls into view reads as a template, and it reads that way precisely because it is the first thing reached for. One orchestrated moment on the screen that matters beats an effect on every card, and a screen with no animation at all is a perfectly good answer \u2014 far better than one where everything twitches. The emphasis kinds earn their place on something genuinely needing attention, never as decoration, and BLINK almost never earns it.\n\n### Reading A Screenshot\nOnly the editor's canvas shows what the user will see, and canvas screenshots are not reachable from here; `schema validate` knows only about invalid schema. When the request calls for seeing the screen \u2014 you built a screen the user will judge, or they asked about its look \u2014 ask the user to open it in the editor; a change that only adds or rewires something on an existing screen does not need that. What it shows is worth reading against: one clear focal point rather than everything at the same weight; related things closer together than unrelated ones; at least three levels of text that differ in weight, not only size; gutters where things would otherwise touch an edge, and lines under ~70 characters; the accent only on the primary action and the active state; something that responds to hover; colour, spacing, radius, type and shadow values that are theme references, so a restyle reaches them. Report only what you actually changed. Every claim about appearance \u2014 a heading looks larger, a selected state looks different, spacing was tightened \u2014 must correspond to an `UPDATE_COMPONENT_STYLE` (or creation-time style) call you made in this session. If a requested look was not achievable with the available tools, say which part you skipped and why; do not describe the component's built-in default styling as if you had applied it. A user who is told the work is done stops checking.",database:`## Database Domain Knowledge
|
|
236
236
|
Zion uses PostgreSQL. Data model changes require "Sync Backend" to take effect online.
|
|
237
237
|
|
|
238
238
|
### Capabilities & Limitations
|
|
@@ -325,7 +325,7 @@ A sync redeploys the whole backend and takes anywhere from tens of seconds to a
|
|
|
325
325
|
### Reading the result
|
|
326
326
|
- SYNCED \u2014 the saved schema is live on the runtime.
|
|
327
327
|
- FAILED \u2014 the deployment pipeline rejected the schema. Something in the project is invalid; find it (the component plugin's project-error list and the logs plugin's DEPLOYMENT entries are the two places it shows up), fix it, and sync again. Repeating the sync unchanged fails the same way.
|
|
328
|
-
- IN_PROGRESS \u2014 the pipeline was still running when the wait expired. Nothing is wrong
|
|
328
|
+
- IN_PROGRESS \u2014 the pipeline was still running when the wait expired. Nothing is wrong, and it finishes on its own, so tell the user it is deploying. Call project sync-backend again only when your next step needs the deployed backend, such as a test against the runtime: waiting otherwise costs the user time and changes nothing.
|
|
329
329
|
- NOT_STARTED \u2014 nothing was deployed. The usual cause is the user dismissing the save confirmation the editor raises when the project changed elsewhere; tell them rather than retrying in a loop.
|
|
330
330
|
|
|
331
331
|
### One backend, every client app
|
|
@@ -379,7 +379,7 @@ A themed project keeps its colours and sizes in one place and components referen
|
|
|
379
379
|
A variable's referenceValue is \`$$\` followed by its id, in every category, and that is what UPDATE_COMPONENT_STYLE takes: colours, spacings, radii, font sizes, weights and families on the field of that class, a shadow as \`shadow: {variable}\`. Only a component holding a reference follows when the variable changes, which is what turns a restyle into a few edits here. There is no line-height category, so a text role is a size and a weight variable paired by name, with the line height sent as px alongside.
|
|
380
380
|
|
|
381
381
|
## Font families
|
|
382
|
-
The theme starts with none, so text renders in the platform default until one is added and referenced. GET_THEME_INFO lists the families this client offers (offeredFontFamilies); a FONT_FAMILIES value
|
|
382
|
+
The theme starts with none, so text renders in the platform default until one is added and referenced. GET_THEME_INFO lists the families this client offers (offeredFontFamilies); a FONT_FAMILIES value must name one of them \u2014 send its \`value\`; a \`localeEn\`/\`localeZh\` display name is stored as that value \u2014 and anything else is rejected. Read the existing fontFamilies variables first and reference one when it fits instead of adding a duplicate. A project that predates theme font variables lists the faces it already uses in styleScaleFontFamilies; follow those unless the user asks for a different face.
|
|
383
383
|
|
|
384
384
|
## Editing
|
|
385
385
|
ADD_THEME_VARIABLES returns each new variable's id, which is what component bindings reference. UPDATE_THEME_VARIABLES is incremental \u2014 omitted fields keep their current value. DELETE_THEME_VARIABLES refuses preset variables: their ids carry semantics the palette algorithm and existing bindings depend on, and a component left bound to a deleted variable falls back to no value, so check usages first.
|
|
@@ -685,7 +685,7 @@ getImageListByIds(imageIds:_int8){ id exId url urlInfo{ urlExpireAt } } \u2014 e
|
|
|
685
685
|
getImageListByExIds(imageExIds:[String]) \u2014 then rewrite each src. Cache by urlExpireAt and
|
|
686
686
|
never write a resolved URL back into the column. Writing is the mirror image: upload through
|
|
687
687
|
the two-step above, then emit src="fz_image_<imageId>". An external URL left in the body is
|
|
688
|
-
stored verbatim and leaves the picture depending on a host nobody here controls.`};u();function Gg(t){let e=wr[t];if(!e)throw new Error(`No guide available for '${t}'.`);return e}var ye={projectExId:c.string().optional().describe("The project to act on. Defaults to the project set by set_current_project."),appExId:c.string().nullable().optional().describe(
|
|
688
|
+
stored verbatim and leaves the picture depending on a host nobody here controls.`};u();function Gg(t){let e=wr[t];if(!e)throw new Error(`No guide available for '${t}'.`);return e}var ye={projectExId:c.string().optional().describe("The project to act on. Defaults to the project set by set_current_project."),appExId:c.string().nullable().optional().describe("A client app INSIDE the project (web / WeChat mini program / mobile) \u2014 never the project's own exId. Leave unset for the project's current client, pinned by create_project / set_current_project: that session holds the client's pages and the project's backend, which is what UI work needs. Pass null for the project's own document alone \u2014 its backend. Other values come from project metadata \u2192 apps[], entries whose appExId is non-null (the null entry is the project itself). A session reaches one client; a sibling client's pages live in another document, so re-pin to work on it."),appVersionExId:c.string().nullable().optional().describe("A specific version of the app named by appExId. Leave unset for the current version.")},Os=t=>({content:[{type:"text",text:t.ok?t.message??JSON.stringify(t.data??{},null,2):JSON.stringify({error:t.error??"Unknown error",data:t.data},null,2)}],isError:!t.ok}),Do=(t,e,n,r,o)=>{t.registerTool(e,{description:n,inputSchema:r},o)},Zg=(t,e,n)=>{for(let r of e)Do(t,r.name,r.description,r.inputSchema??{},async(o,a)=>Os(await n({name:r.command,args:o},a.signal)))},Bg=(t,e,n)=>{for(let r of e){let{ops:o}=r,a={op:c.enum(Object.keys(o)),...r.inputSchema??{}};Do(t,r.name,r.description,a,async(s,i)=>{let{op:l,...d}=s;return Os(await n({name:o[String(l)],args:d},i.signal))})}};var WP=t=>({content:[{type:"text",text:t}],isError:!1});var qg=(t,e,n)=>{for(let r of e){let o={...ye,op:c.enum(r.ops),args:c.record(c.any()).optional()};Do(t,r.name,r.description,o,async(a,s)=>{let{op:i,projectExId:l,appExId:d,appVersionExId:h,args:p}=a;return Os(await n({name:"schema.ztype_tool_calls",args:{projectExId:l,appExId:d,appVersionExId:h,toolCalls:[{toolCallId:`${r.name}-${String(i)}-${Date.now()}`,name:String(i),args:p??{}}]}},s?.signal))})}},Vg=t=>{let e=Object.keys(wr);Do(t,"guide","Load the domain guide for a backend capability \u2014 the rules, conventions, and gotchas for a plugin area (database, type, bindings, actionflow, api, zai, component, permissions, payments, logs, agent). Call before editing an unfamiliar area, or when a meta-tool call is rejected.",{plugin:c.enum(e)},async n=>WP(Gg(String(n.plugin))))},Wg=(t,e)=>{Do(t,"agent_command","Advanced escape hatch for directly invoking an internal agent command.",{name:c.string(),args:c.record(c.any()).optional()},async(n,r)=>Os(await e({name:String(n.name),args:n.args??{}},r.signal)))};u();var Ns=[{name:"schema_action_menu",tier:"catalog",description:"\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=GET_SELECTABLE_COMPONENT_ACTIONS \u2014 The frontend actions attachable to a component event, as the same category tree the editor's action picker shows \u2014 already filtered to this client's platform, what this product ships, the project's configured authentication, and what the event accepts. A few actions belong to one product only, so an absence can mean that rather than a missing capability. Each leaf carries the `eventType` it resolved to here (a leaf like SIGN_IN becomes whichever login the project configured) and the `path` to address it. A leaf's `kind` is what you send to ADD_COMPONENT_ACTIONS to attach it. A leaf with no `kind` cannot be attached by that tool at all \u2014 say so and let the user add it in the editor, rather than attaching some other action that looks close. `kind` is necessary but not sufficient: several leaves share one kind (SIGN_IN and SIGN_OUT are both USER_LOGIN, and each sign-in method is that same kind under a different identifier), so send the leaf's `itemArgs` verbatim in the same item alongside `kind` \u2014 a kind sent without them is a valid call for the OTHER action and is not refused. A leaf's `alternativeKinds` are further kinds the same leaf builds, as the editor's own panel switches between them (SET_VARIABLE writes a page or modal variable with SET_VARIABLE_DATA, or a client variable with SET_GLOBAL_DATA). Where a kind still cannot express the leaf you picked the write says so; follow that error instead of substituting a different action.",ops:{GET_SELECTABLE_COMPONENT_ACTIONS:"GET_SELECTABLE_COMPONENT_ACTIONS"},inputSchema:{componentId:c.string().optional(),eventType:c.string().optional()}},{name:"schema_actionflow",tier:"core",description:`Action flows \u2014 flow-level (addressed by actionFlowId). Discover types via op=SELECTABLE_TYPES and ids via op=GET_DETAIL. AI nodes require isAsync=true.
|
|
689
689
|
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
690
690
|
- op=ADD \u2014 Result echoes each new flow's id.
|
|
691
691
|
- op=ADD_GLOBAL_VARS \u2014 Result echoes each new variable's minted key. These are the flow's own variables, visible inside it only; a variable the client's pages share is ADD_CLIENT_VARIABLES.
|
|
@@ -812,11 +812,11 @@ Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
|
812
812
|
- op=SET_OPERATOR \u2014 Set the comparison operator of the condition at the schema path. This is where a condition starts, whether INSERT_CONDITION_BOOL_EXP just added it or the slot was already an always-true condition (an emptied condition tree's leaf). The condition becomes an expression condition with an empty target binding \u2014 fill its target/value via the CREATE_*_BINDING tools; unary operators (is-null / is-true / is-empty variants) drop the value.`,ops:{DELETE_TERM:"DELETE_CONDITION_BOOL_EXP",DUPLICATE_CONDITION:"DUPLICATE_CONDITION",LIST_OPERATORS:"GET_EXPRESSION_CONDITION_OPERATORS",INSERT_TERM:"INSERT_CONDITION_BOOL_EXP",NEST:"NEST_CONDITION_BOOL_EXP",SET_CONSTANT:"SET_CONSTANT_CONDITION",SET_OS_TYPE:"SET_OS_TYPE_CONDITION",SET_WECHAT_PERMISSION:"SET_WECHAT_PERMISSION_CONDITION",TOGGLE_AND_OR:"TOGGLE_CONDITION_BOOL_EXP_AND_OR",TOGGLE_NOT:"TOGGLE_CONDITION_BOOL_EXP_NOT",SET_OPERATOR:"UPDATE_EXPRESSION_CONDITION_OPERATOR"},inputSchema:{operator:c.string().optional(),osType:c.enum(["IOS","ANDROID","MAC","WINDOWS","DEVTOOLS"]).optional(),permission:c.enum(["USER_INFO","USER_LOCATION","WE_RUN","RECORD","WRITE_PHOTOS_ALBUM","CAMERA"]).optional(),schemaPath:c.array(c.any()).optional(),sourceSchemaPath:c.array(c.any()).optional(),type:c.enum(["ALWAYS","NEVER"]).optional()}},{name:"schema_conditional_branch",tier:"core",description:`Manage branches of a conditional binding (schemaPath). Build each branch predicate with schema_condition_expr.
|
|
813
813
|
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
814
814
|
- op=DELETE \u2014 Delete one branch of the conditional binding at the schema path.
|
|
815
|
-
- op=INSERT \u2014 Insert a new branch into the conditional binding at the schema path. Result echoes the new branch's id.
|
|
815
|
+
- op=INSERT \u2014 Insert a new branch into the conditional binding at the schema path. Result echoes the new branch's id and the schema paths of its condition and value slots.
|
|
816
816
|
- op=REORDER \u2014 Reorder the branches (= evaluation order) of the conditional binding at the schema path.
|
|
817
817
|
- op=UPDATE \u2014 Replace fields (condition / value / name) of one branch of the conditional binding at the schema path.`,ops:{DELETE:"DELETE_CONDITIONAL_DATA",INSERT:"INSERT_CONDITIONAL_DATA",REORDER:"REORDER_CONDITIONAL_DATA",UPDATE:"UPDATE_CONDITIONAL_DATA"},inputSchema:{afterId:c.string().optional(),conditionData:c.record(c.any()).optional(),id:c.string().optional(),reorderedIds:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional()}},{name:"schema_create_binding",tier:"core",description:`Create a data binding at a binding location (schemaPath). op=OPTION uses a pathInHierarchicalMenu from schema_binding_inspect; op=FORMULA an operator from FORMULA_OPERATORS. operation defaults to REPLACE (CONCAT to append).
|
|
818
818
|
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
819
|
-
- op=CONDITIONAL \u2014 Replace the binding at the schema path with a conditional binding: ordered branches of condition + value, evaluated in order \u2014 the first branch whose condition holds supplies the value. Branches start always-true with empty values: manage them with the *_CONDITIONAL_DATA tools, narrow conditions via the condition tools, fill values via the CREATE_*_BINDING tools. Result echoes the branch
|
|
819
|
+
- op=CONDITIONAL \u2014 Replace the binding at the schema path with a conditional binding: ordered branches of condition + value, evaluated in order \u2014 the first branch whose condition holds supplies the value. Branches start always-true with empty values: manage them with the *_CONDITIONAL_DATA tools, narrow conditions via the condition tools, fill values via the CREATE_*_BINDING tools. Result echoes the conditional binding's own schema path (the *_CONDITIONAL_DATA tools take it) and each branch's id and the schema paths of its condition and value slots.
|
|
820
820
|
- op=CONST \u2014 Bind a literal constant value at the schema path.
|
|
821
821
|
- op=FORMULA \u2014 Bind a computed formula at the schema path \u2014 pick \`operator\` from GET_FORMULA_OPERATORS, then fill the formula's argument slots via further CREATE_*_BINDING calls at their paths.
|
|
822
822
|
- op=OPTION \u2014 Bind a dynamic value (variable / column / node output \u2026) at the schema path, picked from the BROWSE_DATA_BINDING_OPTIONS tree.
|
|
@@ -832,7 +832,7 @@ Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
|
832
832
|
- op=GET_PAYMENT_CONFIGS \u2014 The project's payment configs, and for each one the checkout products a payment action on it can use. Both fields such an action carries come from here: \`id\` is its configId, and \`usableProductsOnThisClient\` \u2014 the products the merchant enabled that this client can also run \u2014 is what its paymentProduct has to be one of. An empty one means this config cannot back a payment action on this client at all, whatever it enables. \`legacyPaymentModel\` true means the project is on the legacy payment model: there is nothing to point at and a payment action takes neither field.
|
|
833
833
|
- op=GET_PAYMENT_CONFIG_DETAIL (req: configId) [payment-config only]
|
|
834
834
|
- op=SET_PAYMENT_CALLBACK_ACTION \u2014 Bind or unbind the action flow that runs for one payment event kind on a payment callback. The callback has to be a PAYMENT_CALLBACK whose id comes from GET_PAYMENT_CONFIG_DETAIL's callbackIds; read it with GET_CALLBACK_DETAIL first \u2014 the lock engine requires that read. Omit actionFlowId to unbind that event kind. Input args are seeded empty \u2014 fill them with the binding tools at the returned inputArgsSchemaPath. [payment-config only]
|
|
835
|
-
- op=UPDATE_PAYMENT_CONFIGS \u2014 Incrementally update payment configs by id; omitted fields are left unchanged. Read each config with GET_PAYMENT_CONFIG_DETAIL first \u2014 the lock engine requires that read. Secret credential fields take a secret config id from GET_ALL_SECRET_CONFIGS \u2014 an empty string clears the binding. A config's provider cannot be changed. [payment-config only]`,ops:{ACTIVATE_PAYMENT:"ACTIVATE_PAYMENT",ADD_PAYMENT_CONFIGS:"ADD_PAYMENT_CONFIGS",DELETE_PAYMENT_CONFIGS:"DELETE_PAYMENT_CONFIGS",GET_PAYMENT_CONFIGS:"GET_PAYMENT_CONFIGS",GET_PAYMENT_CONFIG_DETAIL:"GET_PAYMENT_CONFIG_DETAIL",SET_PAYMENT_CALLBACK_ACTION:"SET_PAYMENT_CALLBACK_ACTION",UPDATE_PAYMENT_CONFIGS:"UPDATE_PAYMENT_CONFIGS"},inputSchema:{actionFlowId:c.string().optional(),callbackId:c.string().optional(),configId:c.string().optional(),configIds:c.array(c.any()).optional(),eventKind:c.enum(["PAYMENT_COMPLETED","REFUND_COMPLETED","SUBSCRIPTION_STATUS_CHANGED","SUBSCRIPTION_INVOICE_CREATED","VIRTUAL_PAYMENT_COMPLETED","VIRTUAL_REFUND_COMPLETED"]).optional(),items:c.array(c.any()).optional(),orderTableDisplayName:c.string().optional(),paymentType:c.enum(["STRIPE","AIRWALLEX","ALIPAY","WECHAT"]).optional()}},{name:"schema_permission",tier:"catalog",description:`
|
|
835
|
+
- op=UPDATE_PAYMENT_CONFIGS \u2014 Incrementally update payment configs by id; omitted fields are left unchanged. Read each config with GET_PAYMENT_CONFIG_DETAIL first \u2014 the lock engine requires that read. Secret credential fields take a secret config id from GET_ALL_SECRET_CONFIGS \u2014 an empty string clears the binding. A config's provider cannot be changed. [payment-config only]`,ops:{ACTIVATE_PAYMENT:"ACTIVATE_PAYMENT",ADD_PAYMENT_CONFIGS:"ADD_PAYMENT_CONFIGS",DELETE_PAYMENT_CONFIGS:"DELETE_PAYMENT_CONFIGS",GET_PAYMENT_CONFIGS:"GET_PAYMENT_CONFIGS",GET_PAYMENT_CONFIG_DETAIL:"GET_PAYMENT_CONFIG_DETAIL",SET_PAYMENT_CALLBACK_ACTION:"SET_PAYMENT_CALLBACK_ACTION",UPDATE_PAYMENT_CONFIGS:"UPDATE_PAYMENT_CONFIGS"},inputSchema:{actionFlowId:c.string().optional(),callbackId:c.string().optional(),configId:c.string().optional(),configIds:c.array(c.any()).optional(),eventKind:c.enum(["PAYMENT_COMPLETED","REFUND_COMPLETED","SUBSCRIPTION_STATUS_CHANGED","SUBSCRIPTION_INVOICE_CREATED","VIRTUAL_PAYMENT_COMPLETED","VIRTUAL_REFUND_COMPLETED"]).optional(),items:c.array(c.any()).optional(),orderTableDisplayName:c.string().optional(),paymentType:c.enum(["STRIPE","AIRWALLEX","ALIPAY","WECHAT","WECHAT_VIRTUAL"]).optional()}},{name:"schema_permission",tier:"catalog",description:`
|
|
836
836
|
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
837
837
|
- op=ACTIVATE_ROLE_PERMISSION \u2014 Activate RBAC by seeding the predefined Logged-in User and Anonymous User roles with their default grants. Requires Sync Backend afterward to affect the deployed backend. Result echoes the seeded roles.
|
|
838
838
|
- op=ADD_ROLES \u2014 Create custom roles with the editor's defaults (minimal grants \u2014 extend them with the UPDATE_ROLE_*_PERMISSION tools). Call ACTIVATE_ROLE_PERMISSION first when GET_ALL_ROLES_INFO reports that RBAC is not activated. Result echoes each new role's name and predefined flag.
|
|
@@ -872,13 +872,7 @@ Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
|
872
872
|
- op=REORDER_TABLE_FIELDS \u2014 Reorder the fields of one table as the editor lists them. The order is editor state kept outside the table, so it exists only after the type-system refactor.
|
|
873
873
|
- op=UPDATE_FIELDS_AND_RELATIONS \u2014 Edit existing fields and relations in place: a field's display name, required flag and default value; a relation's display name on either side. Changing a field's type is not available here: the type is fixed once the field has been deployed to the backend, and only the editor can tell whether it has \u2014 to use a different type, delete the field with DELETE_FIELDS_AND_RELATIONS and add it again with ADD_FIELDS_AND_RELATIONS. A field's api name is minted at creation and never changes, and a relation's type or tables can only be changed by deleting it and adding a new one.
|
|
874
874
|
- op=UPDATE_TABLES (req: items)
|
|
875
|
-
- op=UPDATE_EXTENSION \u2014 Switch an existing embedding index to another model. The embedding model is the only part of an extension that can be reconfigured \u2014 the indexed field and the hidden columns backing it are fixed once the index exists.`,ops:{ADD_CONSTRAINTS:"ADD_CONSTRAINTS",ADD_DATABASE_INDEX:"ADD_DATABASE_INDEX",ADD_FIELDS_RELATIONS:"ADD_FIELDS_AND_RELATIONS",ADD_TABLES:"ADD_TABLES",ADD_EXTENSION:"ADD_TABLE_EXTENSION",DELETE_CONSTRAINTS:"DELETE_CONSTRAINTS",DELETE_DATABASE_INDEX:"DELETE_DATABASE_INDEX",DELETE_FIELDS_RELATIONS:"DELETE_FIELDS_AND_RELATIONS",DELETE_TABLES:"DELETE_TABLES",DELETE_EXTENSION:"DELETE_TABLE_EXTENSION",LIST_NAMES:"GET_ALL_TABLE_DISPLAY_NAMES",LIST_EMBEDDING_MODELS:"GET_AVAILABLE_EMBEDDING_MODELS",GET_INFOS:"GET_TABLES_INFO",SELECTABLE_TYPES:"GET_TABLE_FIELD_SELECTABLE_TYPES",REORDER_CONSTRAINTS:"REORDER_CONSTRAINTS",REORDER_TABLES:"REORDER_TABLES",REORDER_TABLE_FIELDS:"REORDER_TABLE_FIELDS",UPDATE_FIELDS_AND_RELATIONS:"UPDATE_FIELDS_AND_RELATIONS",UPDATE_TABLES:"UPDATE_TABLES",UPDATE_EXTENSION:"UPDATE_TABLE_EXTENSION"},inputSchema:{b:c.number().optional(),constraints:c.array(c.any()).optional(),customEmbeddingId:c.string().optional(),fieldDisplayName:c.string().optional(),fieldDisplayNames:c.array(c.any()).optional(),fields:c.array(c.any()).optional(),indexType:c.enum(["BM25"]).optional(),items:c.array(c.any()).optional(),k1:c.number().optional(),relationFieldDisplayNamesInSourceTable:c.array(c.any()).optional(),relations:c.array(c.any()).optional(),reorderedConstraintNames:c.array(c.any()).optional(),reorderedFieldDisplayNames:c.array(c.any()).optional(),reorderedTableDisplayNames:c.array(c.any()).optional(),showApiName:c.boolean().optional(),tableDisplayName:c.string().optional(),tableDisplayNames:c.array(c.any()).optional(),textConfig:c.enum(["SIMPLE","AFRIKAANS","ARABIC","ARMENIAN","BASQUE","CATALAN","DANISH","DUTCH","ENGLISH","ESTONIAN","FINNISH","FRENCH","GERMAN","GREEK","HINDI","HUNGARIAN","INDONESIAN","IRISH","ITALIAN","LITHUANIAN","NEPALI","NORWEGIAN","PORTUGUESE","ROMANIAN","RUSSIAN","SERBIAN","SPANISH","SWEDISH","TAMIL","TURKISH","YIDDISH","BULGARIAN","CROATIAN","CZECH","LATVIAN","PERSIAN","POLISH","SLOVAK","SLOVENIAN","UKRAINIAN","CHINESE","JAPANESE","KOREAN","THAI"]).optional()}},{name:"schema_theme",tier:"catalog",description:`
|
|
876
|
-
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
877
|
-
- op=ADD_THEME_VARIABLES \u2014 Adds theme variables. Result echoes each new variable's id, which is what component bindings reference. A FONT_FAMILIES value must be one of the font families the target client offers: only those have font files to load, so any other name would render as the system fallback. A value outside the list is rejected with the list itself.
|
|
878
|
-
- op=DELETE_THEME_VARIABLES \u2014 Deletes theme variables. Preset variables are rejected: their ids carry semantics that bindings and the theme algorithm depend on. A variable still in use is rejected until onReferences says what becomes of its uses.
|
|
879
|
-
- op=GET_THEME_INFO \u2014 Reports the client's whole theme: every variable in all eight categories (id, displayName, isPreset and its value under the default theme), the scrollbar style, and the font families this client offers, which are the only values FONT_FAMILIES accepts. Each palette also lists its 12 derived levels, level 1 lightest to level 12 darkest, so a colour variable can be pinned to a level by sight. Read this before editing \u2014 the add/update tools take a value in the category's own shape, and this is where to copy that shape from.
|
|
880
|
-
- op=SET_SCROLLBAR_STYLE \u2014 Sets the scrollbar appearance for the default theme (incremental). Web only \u2014 other clients draw the scrollbar with the OS and ignore this.
|
|
881
|
-
- op=UPDATE_THEME_VARIABLES \u2014 Renames a theme variable and/or replaces its value under the default theme (incremental \u2014 omitted fields keep their current value). A FONT_FAMILIES value must be one of the font families the target client offers; a value outside the list is rejected with the list itself.`,ops:{ADD_THEME_VARIABLES:"ADD_THEME_VARIABLES",DELETE_THEME_VARIABLES:"DELETE_THEME_VARIABLES",GET_THEME_INFO:"GET_THEME_INFO",SET_SCROLLBAR_STYLE:"SET_SCROLLBAR_STYLE",UPDATE_THEME_VARIABLES:"UPDATE_THEME_VARIABLES"},inputSchema:{colorMode:c.enum(["light","dark"]).optional(),items:c.array(c.any()).optional(),themeId:c.string().optional(),thumbColor:c.any().optional(),thumbHoverColor:c.any().optional(),thumbRadius:c.number().optional(),thumbWidth:c.number().optional(),trackColor:c.any().optional(),visible:c.boolean().optional()}},{name:"schema_trigger",tier:"catalog",description:`
|
|
875
|
+
- op=UPDATE_EXTENSION \u2014 Switch an existing embedding index to another model. The embedding model is the only part of an extension that can be reconfigured \u2014 the indexed field and the hidden columns backing it are fixed once the index exists.`,ops:{ADD_CONSTRAINTS:"ADD_CONSTRAINTS",ADD_DATABASE_INDEX:"ADD_DATABASE_INDEX",ADD_FIELDS_RELATIONS:"ADD_FIELDS_AND_RELATIONS",ADD_TABLES:"ADD_TABLES",ADD_EXTENSION:"ADD_TABLE_EXTENSION",DELETE_CONSTRAINTS:"DELETE_CONSTRAINTS",DELETE_DATABASE_INDEX:"DELETE_DATABASE_INDEX",DELETE_FIELDS_RELATIONS:"DELETE_FIELDS_AND_RELATIONS",DELETE_TABLES:"DELETE_TABLES",DELETE_EXTENSION:"DELETE_TABLE_EXTENSION",LIST_NAMES:"GET_ALL_TABLE_DISPLAY_NAMES",LIST_EMBEDDING_MODELS:"GET_AVAILABLE_EMBEDDING_MODELS",GET_INFOS:"GET_TABLES_INFO",SELECTABLE_TYPES:"GET_TABLE_FIELD_SELECTABLE_TYPES",REORDER_CONSTRAINTS:"REORDER_CONSTRAINTS",REORDER_TABLES:"REORDER_TABLES",REORDER_TABLE_FIELDS:"REORDER_TABLE_FIELDS",UPDATE_FIELDS_AND_RELATIONS:"UPDATE_FIELDS_AND_RELATIONS",UPDATE_TABLES:"UPDATE_TABLES",UPDATE_EXTENSION:"UPDATE_TABLE_EXTENSION"},inputSchema:{b:c.number().optional(),constraints:c.array(c.any()).optional(),customEmbeddingId:c.string().optional(),fieldDisplayName:c.string().optional(),fieldDisplayNames:c.array(c.any()).optional(),fields:c.array(c.any()).optional(),indexType:c.enum(["BM25"]).optional(),items:c.array(c.any()).optional(),k1:c.number().optional(),relationFieldDisplayNamesInSourceTable:c.array(c.any()).optional(),relations:c.array(c.any()).optional(),reorderedConstraintNames:c.array(c.any()).optional(),reorderedFieldDisplayNames:c.array(c.any()).optional(),reorderedTableDisplayNames:c.array(c.any()).optional(),showApiName:c.boolean().optional(),tableDisplayName:c.string().optional(),tableDisplayNames:c.array(c.any()).optional(),textConfig:c.enum(["SIMPLE","AFRIKAANS","ARABIC","ARMENIAN","BASQUE","CATALAN","DANISH","DUTCH","ENGLISH","ESTONIAN","FINNISH","FRENCH","GERMAN","GREEK","HINDI","HUNGARIAN","INDONESIAN","IRISH","ITALIAN","LITHUANIAN","NEPALI","NORWEGIAN","PORTUGUESE","ROMANIAN","RUSSIAN","SERBIAN","SPANISH","SWEDISH","TAMIL","TURKISH","YIDDISH","BULGARIAN","CROATIAN","CZECH","LATVIAN","PERSIAN","POLISH","SLOVAK","SLOVENIAN","UKRAINIAN","CHINESE","JAPANESE","KOREAN","THAI"]).optional()}},{name:"schema_theme",tier:"catalog",description:"\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=ADD_THEME_VARIABLES \u2014 Adds theme variables. Result echoes each new variable's id, which is what component bindings reference. A FONT_FAMILIES value must name one of `offeredFontFamilies` in GET_THEME_INFO \u2014 send its `value`; a `localeEn`/`localeZh` display name is stored as that value. Only those have font files to load; any other name is rejected with the list itself.\n- op=DELETE_THEME_VARIABLES \u2014 Deletes theme variables. Preset variables are rejected: their ids carry semantics that bindings and the theme algorithm depend on. A variable still in use is rejected until onReferences says what becomes of its uses.\n- op=GET_THEME_INFO \u2014 Reports the client's whole theme: every variable in all eight categories (id, displayName, isPreset and its value under the default theme), the scrollbar style, and the font families this client offers. Each palette also lists its 12 derived levels, level 1 lightest to level 12 darkest, so a colour variable can be pinned to a level by sight. Read this before editing \u2014 the add/update tools take a value in the category's own shape, and this is where to copy that shape from. `offeredFontFamilies` lists every family this client can load; a FONT_FAMILIES value must name one of them \u2014 send its `value`; a `localeEn`/`localeZh` display name is stored as that value. `styleScaleFontFamilies` lists the faces an older project already uses in its style scale. Prefer an existing FONT_FAMILIES variable or one of those faces over adding a new family.\n- op=SET_SCROLLBAR_STYLE \u2014 Sets the scrollbar appearance for the default theme (incremental). Web only \u2014 other clients draw the scrollbar with the OS and ignore this.\n- op=UPDATE_THEME_VARIABLES \u2014 Renames a theme variable and/or replaces its value under the default theme (incremental \u2014 omitted fields keep their current value). A FONT_FAMILIES value must name one of `offeredFontFamilies` in GET_THEME_INFO \u2014 send its `value`; a `localeEn`/`localeZh` display name is stored as that value. A value outside the list is rejected with the list itself.",ops:{ADD_THEME_VARIABLES:"ADD_THEME_VARIABLES",DELETE_THEME_VARIABLES:"DELETE_THEME_VARIABLES",GET_THEME_INFO:"GET_THEME_INFO",SET_SCROLLBAR_STYLE:"SET_SCROLLBAR_STYLE",UPDATE_THEME_VARIABLES:"UPDATE_THEME_VARIABLES"},inputSchema:{colorMode:c.enum(["light","dark"]).optional(),items:c.array(c.any()).optional(),themeId:c.string().optional(),thumbColor:c.any().optional(),thumbHoverColor:c.any().optional(),thumbRadius:c.number().optional(),thumbWidth:c.number().optional(),trackColor:c.any().optional(),visible:c.boolean().optional()}},{name:"schema_trigger",tier:"catalog",description:`
|
|
882
876
|
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
883
877
|
- op=ADD_DB_TRIGGERS \u2014 Result echoes each new trigger's id.
|
|
884
878
|
- op=ADD_SCHEDULED_TRIGGERS \u2014 Result echoes each new trigger's id.
|
|
@@ -949,7 +943,7 @@ Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
|
949
943
|
- op=UPDATE_ZAI_CONFIG_INPUT_ARGS (req: configId, items)
|
|
950
944
|
- op=UPDATE_ZAI_CONFIG_OUTPUT (req: configId)
|
|
951
945
|
- op=UPDATE_ZAI_CONFIG_TOOL (req: configId, toolId)
|
|
952
|
-
- op=UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS (req: configId, toolId)`,ops:{ADD_ZAI_CONFIGS:"ADD_ZAI_CONFIGS",ADD_ZAI_CONFIG_API_CONTEXTS:"ADD_ZAI_CONFIG_API_CONTEXTS",ADD_ZAI_CONFIG_DB_CONTEXTS:"ADD_ZAI_CONFIG_DB_CONTEXTS",ADD_ZAI_CONFIG_INPUT_ARGS:"ADD_ZAI_CONFIG_INPUT_ARGS",ADD_ZAI_CONFIG_TOOLS:"ADD_ZAI_CONFIG_TOOLS",DELETE_ZAI_CONFIGS:"DELETE_ZAI_CONFIGS",DELETE_ZAI_CONFIG_API_CONTEXTS:"DELETE_ZAI_CONFIG_API_CONTEXTS",DELETE_ZAI_CONFIG_DB_CONTEXTS:"DELETE_ZAI_CONFIG_DB_CONTEXTS",DELETE_ZAI_CONFIG_INPUT_ARGS:"DELETE_ZAI_CONFIG_INPUT_ARGS",DELETE_ZAI_CONFIG_TOOLS:"DELETE_ZAI_CONFIG_TOOLS",DUPLICATE_ZAI_CONFIG:"DUPLICATE_ZAI_CONFIG",GET_ALL_ZAI_CONFIGS_INFO:"GET_ALL_ZAI_CONFIGS_INFO",GET_ZAI_CONFIG_DETAIL:"GET_ZAI_CONFIG_DETAIL",GET_ZAI_CONFIG_SELECTABLE_TYPES:"GET_ZAI_CONFIG_SELECTABLE_TYPES",GET_ZAI_MODEL_OPTIONS:"GET_ZAI_MODEL_OPTIONS",UPDATE_ZAI_CONFIG:"UPDATE_ZAI_CONFIG",UPDATE_ZAI_CONFIG_API_CONTEXT:"UPDATE_ZAI_CONFIG_API_CONTEXT",UPDATE_ZAI_CONFIG_DB_CONTEXT:"UPDATE_ZAI_CONFIG_DB_CONTEXT",UPDATE_ZAI_CONFIG_INPUT_ARGS:"UPDATE_ZAI_CONFIG_INPUT_ARGS",UPDATE_ZAI_CONFIG_OUTPUT:"UPDATE_ZAI_CONFIG_OUTPUT",UPDATE_ZAI_CONFIG_TOOL:"UPDATE_ZAI_CONFIG_TOOL",UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS:"UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS"},inputSchema:{addRelations:c.array(c.any()).optional(),apiId:c.string().optional(),apiIds:c.array(c.any()).optional(),argKeys:c.array(c.any()).optional(),arrayLevel:c.number().optional(),clearLimit:c.boolean().optional(),columns:c.array(c.any()).optional(),configId:c.string().optional(),configIds:c.array(c.any()).optional(),customModelIdentifier:c.record(c.any()).optional(),description:c.string().optional(),enable:c.boolean().optional(),ignoreNullValuesFromContext:c.boolean().optional(),imageInputQuality:c.enum(["LOW","HIGH"]).optional(),inputDescriptionConfigs:c.record(c.any()).optional(),isStreaming:c.boolean().optional(),isStructured:c.boolean().optional(),items:c.array(c.any()).optional(),limit:c.number().optional(),maxRound:c.number().optional(),maxTokenSize:c.number().optional(),name:c.string().optional(),outputDescriptionConfig:c.record(c.any()).optional(),outputType:c.string().optional(),relationPath:c.array(c.any()).optional(),removeRelations:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional(),selectedFieldsByType:c.record(c.any()).optional(),slot:c.enum(["INPUT","OUTPUT"]).optional(),sourceZAiConfigId:c.string().optional(),tableDisplayName:c.string().optional(),tableDisplayNames:c.array(c.any()).optional(),temperature:c.number().optional(),toolId:c.string().optional(),toolIds:c.array(c.any()).optional()}}],NU={ADD_VIEWS:"DATA_MODEL_VIEW_2610",ANALYZE_VIEW_SQL:"DATA_MODEL_VIEW_2610",DELETE_VIEWS:"DATA_MODEL_VIEW_2610",GET_VIEWS_INFO:"DATA_MODEL_VIEW_2610",GET_VIEW_PERMISSION:"DATA_MODEL_VIEW_2610",UPDATE_ROLE_VIEW_PERMISSION:"DATA_MODEL_VIEW_2610",UPDATE_VIEWS:"DATA_MODEL_VIEW_2610"};var HP={"actionflow.list_node_templates":{description:"List the preset action-flow integration nodes (the TEMPLATE_CODE catalog \u2014 e.g. SMS, video/AI generation) for planning: each template\u2019s templateCodeId, displayName, group, async flag, and input/output param types. To add one, read schema_actionflow_node op=BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at the position and pass that entry\u2019s `node` to op=ADD_NODE. A TEMPLATE_CODE node already in the schema carries one of these templateCodeIds; never rewrite it to an id from anywhere else.",tool:{name:"list_actionflow_node_templates"},cli:{path:"actionflow list-node-templates"}},"component.tab_bar_icons":{description:"The preset tab-bar icons this deployment ships, as name and media exId \u2014 home, cart, chat, profile and the rest. A tab that is shown needs an icon for both its normal and its selected state or the project reports an error, and the exIds are hashids of media rows that cannot be derived from an icon\u2019s name, so take them from here before schema_tab_bar op=UPDATE_TAB_BAR_ITEMS \u2014 that tool rejects a value that could not be an exId rather than letting the mini-program build fail over a file it cannot find. To use an icon that is not in the list, upload it in the editor and use the exId it is stored under.",tool:{name:"get_tab_bar_icons"},cli:{path:"component tab-bar-icons"}},"workspace.set":{description:"Set the workspace root for local credentials, daemon registry, and project context.",tool:{name:"set_current_working_directory",inputSchema:{cwd:c.string()}}},"auth.login":{description:"Start browser login and save credentials.",cli:{path:"login"}},"auth.logout":{description:"Delete local credentials and unload schema sessions.",cli:{path:"logout"}},"auth.whoami":{description:"Show the currently authenticated account token payload.",cli:{path:"whoami"}},"auth.reauth":{description:"Delete credentials and start login again.",cli:{path:"reauth"}},"account.profile":{description:"Fetch current account and organization/project-space metadata used for project creation.",tool:{name:"get_account_profile"},cli:{path:"account profile",alias:"account me"}},"projects.search":{description:"List/search projects with pagination.",tool:{name:"get_projects",inputSchema:{projectName:c.string().optional(),cursor:c.string().nullable().optional(),limit:c.number().optional()}},cli:{path:"projects search"}},"projects.list":{description:"List projects.",cli:{path:"projects list"}},"project.create":{description:"Create a new blank project. Defaults to the current account organization and waits for the project to appear in search. Pass useRefactoredComponent to override the component model.",tool:{name:"create_project",inputSchema:{projectName:c.string(),templateExId:c.string().nullable().optional(),platform:c.string().nullable().optional(),projectSpaceType:c.string().optional(),organizationExId:c.string().optional(),category:c.string().nullable().optional(),forBeginnerGuide:c.boolean().optional(),useRefactoredComponent:c.boolean().optional(),wait:c.boolean().optional(),timeoutMs:c.number().optional()}},cli:{path:"project create"}},"project.set_current":{description:"Set the default project context by external id.",tool:{name:"set_current_project",inputSchema:{projectExId:c.string()}},cli:{path:"project set-current"}},"project.get_current":{description:"Get the current project context.",tool:{name:"get_current_project"},cli:{path:"project current",alias:"project get-current"}},"project.detail":{description:"Fetch the Zed project/app detail payload, including app list, project config, latest schema metadata, and deployment info.",cli:{path:"project detail"}},"project.metadata":{description:"Fetch a lean project summary: identity, platforms, publish/deploy state (incl. hasUndeployedChanges), configured integrations, plan, capabilities, and RPS. Pass raw=true for the full unshaped payload.",cli:{path:"project metadata",alias:"project inspect"}},"project.resources":{description:"Fetch project resource consumption, plan/capability limits, RPS stats, and optional resource history.",cli:{path:"project resources"}},"project.rename":{description:"Rename a project.",tool:{name:"rename_project",inputSchema:{...ye,projectName:c.string()}},cli:{path:"project rename"}},"project.rename_app":{description:"Rename an app inside a project.",tool:{name:"rename_project_app",inputSchema:{projectExId:c.string(),appExId:c.string(),appName:c.string()}},cli:{path:"project rename-app"}},"project.delete":{description:"Delete a project. IRREVERSIBLE: requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve. Set MCP_HITL=off to fall back to the confirmProjectExId/force text gate in headless automation.",tool:{name:"delete_project",inputSchema:{projectExId:c.string(),confirmProjectExId:c.string().optional(),force:c.boolean().optional()}},cli:{path:"project delete"}},"project.reset":{description:"Reset a project. IRREVERSIBLE: requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve. Set MCP_HITL=off to fall back to the confirmProjectExId/force text gate in headless automation.",tool:{name:"reset_project",inputSchema:{projectExId:c.string(),confirmProjectExId:c.string().optional(),force:c.boolean().optional(),languageType:c.string().optional()}},cli:{path:"project reset"}},"project.sync_backend":{description:"Save the schema and deploy/sync the project runtime backend. Returns ztype diagnostics and blocks on backend validation errors by default.",tool:{name:"sync_backend",inputSchema:{...ye,buildTarget:c.string().optional(),validateMultiClient:c.boolean().optional(),allowValidationErrors:c.boolean().optional()}},cli:{path:"project sync-backend",alias:"project deploy-backend"}},"schema.load":{description:"Load a project's CRDT schema into the daemon's in-memory headless schema session.",cli:{path:"schema load"}},"schema.reload":{description:"Force reload a project schema session from the backend CRDT model and patch log.",cli:{path:"schema reload"}},"schema.status":{description:"Show daemon schema sessions and TTL state.",tool:{name:"schema_status"},cli:{path:"schema status"}},"schema.state":{description:"Read the daemon's schema revision, stale state, and latest semantic schema-change event for a project.",cli:{path:"schema state"}},"schema.events":{description:"Read recent semantic schema-change events observed by the daemon for a project.",cli:{path:"schema events"}},"schema.sync":{description:"Catch up schema CRDT patches from the backend for the loaded project session.",cli:{path:"schema sync"}},"schema.snapshot":{description:"Return the data model of the loaded schema (tables, relations, enum types). Pass full=true for the entire raw ZSchema document (UI tree + all server configs), which is much larger.",cli:{path:"schema snapshot"}},"schema.validate":{description:"Run ztype validation/type checks against the loaded schema and return stable/beta/backend diagnostics.",cli:{path:"schema validate",alias:"schema type-check"}},"bridge.flow_definition":{description:"Resolve an action flow to the definition the debug mutation takes, plus its terminal end node. Derived from the draft CRDT, so it answers with no editor tab attached.",cli:{path:"bridge flow-definition"}},"bridge.trigger_bindings":{description:"List database and scheduled trigger bindings with their flow names, table names and enabled state, derived from the draft CRDT.",cli:{path:"bridge trigger-bindings"}},"bridge.deploy_status":{description:"Compare the draft schema against the last deployed server schema and report which of the eleven server areas differ. Unlike project.inspect this diffs content against the *draft*, so unsaved edits count as pending changes.",cli:{path:"bridge deploy-status"}},"bridge.project_errors":{description:"List the project validation errors and warnings in the shape the editor reports them, newest ztype run, capped by limit. Same union and order as the editor panel.",cli:{path:"bridge project-errors"}},"bridge.sync_backend":{description:"Save the draft schema, deploy the backend and wait for the pipeline, reporting the outcome in the shape the editor reports it. A deploy already running is waited for, not restarted.",cli:{path:"bridge sync-backend"}},"bridge.clipped_components":{description:"Measure which components on a page render clipped (content larger than their box), in the shape the editor reports. Renders the canvas in a headless browser owned by the daemon, after it has applied the latest schema patch.",cli:{path:"bridge clipped-components"}},"bridge.capture_canvas":{description:"Screenshot a page or component as the editor canvas renders it and store it as the agent session's media. Same headless renderer and patch wait as bridge clipped-components.",cli:{path:"bridge capture-canvas"}},"schema.ztype_tool_calls":{description:"Run ztype Copilot tool calls against the loaded schema as one atomic batch: either every call lands or none does, and `applied` reports which. A batch ztype rejects, or whose patch trips validation, reports errors with errorCode/failedIndex and applies nothing \u2014 pass force to apply over a DEPENDENCY_CONFLICT. Use schema_undo to revert the last change.",tool:{name:"ztype_tool_calls",inputSchema:{...ye,toolCalls:c.array(c.record(c.any())),verbose:c.boolean().optional(),readState:c.record(c.any()).optional(),force:c.boolean().optional()}},cli:{path:"schema tool-call",alias:"schema tool-calls"}},"schema.undo":{description:"Undo the most recent schema change made in this session by applying a reverse CRDT patch. Refuses if a concurrent edit touched the same path. Pairs with schema_redo.",tool:{name:"schema_undo",inputSchema:{...ye}},cli:{path:"schema undo"}},"schema.redo":{description:"Re-apply the schema change most recently undone via schema_undo in this session.",tool:{name:"schema_redo",inputSchema:{...ye}},cli:{path:"schema redo"}},"secret.save_value":{description:"Prompt the user (native GUI dialog) to set a secret's plaintext value, store it, and attach the handle so the secret reports hasValue:true. Provide secretId (an existing secret) OR displayName (create a new one). The value is typed into the dialog and never passes through this tool call or the model. Requires a desktop session (fails on headless/SSH/CI).",tool:{name:"save_secret_value",inputSchema:{...ye,secretId:c.string().optional(),displayName:c.string().optional(),description:c.string().optional()}},cli:{path:"secret save-value"}},"runtime.graphql":{description:"Run a raw GraphQL operation against the deployed project's runtime backend (the auto-generated data/actionflow/AI API), as admin.",tool:{name:"runtime_graphql",inputSchema:{...ye,query:c.string(),variables:c.record(c.any()).optional()}},cli:{path:"runtime graphql"}},"runtime.run_code":{description:"Execute a JavaScript snippet in the deployed project's Run Code sandbox and return its result. Database writes are reverted unless updateDb is true, so this is the cheap way to check what a Run Code node will actually return before wiring it into a flow. Runs on the admin surface, as admin.",tool:{name:"runtime_run_code",inputSchema:{...ye,jsCode:c.string(),args:c.record(c.any()).optional(),updateDb:c.boolean().optional()}},cli:{path:"runtime run-code"}},"runtime.query":{description:"Query rows from a deployed project's runtime table.",cli:{path:"runtime query"}},"runtime.aggregate":{description:"Count rows matching a filter in a deployed project's runtime table \u2014 the cheapest assertion available.",cli:{path:"runtime aggregate"}},"runtime.insert":{description:"Insert one or more rows into a deployed project's runtime table.",cli:{path:"runtime insert"}},"runtime.update":{description:"Update rows in a deployed project's runtime table.",cli:{path:"runtime update"}},"runtime.delete":{description:"Delete rows from a deployed project's runtime table. Requires where unless allowDeleteAll=true.",cli:{path:"runtime delete"}},"logs.search":{description:`Fetch recent runtime logs from the project's log endpoint. Window is \xB15 minutes around requestCreatedAt (ISO-8601, defaults to now). types: GATEWAY, ACTION_FLOW, ACTION_FLOW_NODE, ACTION_FLOW_CONTEXT_LOG, DEPLOYMENT, TPA, TRIGGER, SQL_GENERATION, GQL, ZAI. levels: INFO, WARNING, ERROR. customQueryCondition is an Elasticsearch condition (e.g. 'traceId: "abc-123"').`,tool:{name:"search_logs",inputSchema:{...ye,requestCreatedAt:c.string().optional(),types:c.array(c.string()).optional(),levels:c.array(c.string()).optional(),customQueryCondition:c.string().optional(),limit:c.number().optional()}},cli:{path:"logs search"}},"docs.search":{description:"Full-text search the bundled product documentation. Returns the best-matching pages as { path, title, url }, where url is the public HTTPS docs link you can cite. Use docs.get_page with a returned path to read a page.",tool:{name:"search_docs",inputSchema:{query:c.string(),limit:c.number().optional()}},cli:{path:"docs search"}},"docs.get_page":{description:'Fetch a documentation page as markdown by its path (as returned by docs.search, e.g. "/02_design/01_layout_concepts").',tool:{name:"get_doc_page",inputSchema:{path:c.string()}},cli:{path:"docs get-page"}},"platform.graphql":{description:"Guarded raw GraphQL passthrough to the platform backend (projects, accounts, publishing \u2014 the editor/meta API, not the deployed runtime).",tool:{name:"platform_graphql",inputSchema:{query:c.string(),variables:c.record(c.any()).optional()}},cli:{path:"platform graphql"}},"web.fetch_doc":{description:"Fetch a web page or spec by URL for reading. Returns the page content (HTML converted to Markdown; long pages are windowed \u2014 pass `offset` with the same url to keep reading, guided by `totalLength`/`truncated`), same-site `pageLinks` to explore the documentation further, and any OpenAPI/Swagger `specLinks` found. Explore iteratively by fetching returned links, within a budget of 15 fetches per session (`fetchesRemaining`). Build the endpoints you read about with the api schema ops.",tool:{name:"fetch_api_doc",inputSchema:{url:c.string(),offset:c.number().optional()}},cli:{path:"web fetch-doc"}},"site.deploy":{description:"Deploy a built frontend directory (e.g. ./dist) to the project\u2019s hosted static site and return the live url. Scans the directory, declares the manifest, uploads every asset to object storage, and switches the site over in one call \u2014 the agent never handles checksums or upload urls itself. `target` is BETA (default) or PROD; a PROD deploy takes the site live and requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve, and `force` does NOT approve it. Set MCP_HITL=off to fall back to the confirmProjectExId text gate in headless automation. An interrupted run resumes automatically when the directory is unchanged; pass `force` to discard it and start over. `dryRun` reports what would be uploaded without creating a deployment. The total size must fit the project\u2019s remaining object storage, and the directory must contain an index.html.",tool:{name:"deploy_static_site",inputSchema:{...ye,dir:c.string(),target:c.string().optional(),dryRun:c.boolean().optional(),force:c.boolean().optional(),concurrency:c.number().optional(),confirmProjectExId:c.string().optional()}},cli:{path:"site deploy"}},"site.status":{description:"Report the project\u2019s static site: the currently live deployment (with its url) and any upload still in progress. Use to find the site url, or to see whether an interrupted deploy is still resumable.",tool:{name:"get_static_site_status",inputSchema:{...ye,target:c.string().optional()}},cli:{path:"site status"}},"site.abort":{description:"Abandon an in-progress static site upload and delete whatever it already uploaded. Targets the current in-progress deployment unless `deploymentExId` names one. The live site is untouched.",tool:{name:"abort_static_site_deployment",inputSchema:{...ye,target:c.string().optional(),deploymentExId:c.string().optional()}},cli:{path:"site abort"}},"wechat.deploy":{description:"Upload a locally-developed WeChat mini program source tree (the directory holding app.json) to the project and start the server-side build that commits it to WeChat as the \u4F53\u9A8C\u7248 (trial version). Scans the directory, declares the manifest, uploads every file to object storage, and hands off to the build job in one call \u2014 the agent never handles checksums or upload urls itself. By default it then WAITS for the build and returns the trial version number plus the path of the trial QR code image it saved (`wait: false` returns as soon as the build starts; `timeoutSeconds` bounds the wait). Requires the project to have granted Zion third-party platform authorization. An interrupted run resumes automatically when the directory is unchanged; pass `force` to discard it and start over. `dryRun` reports what would be uploaded without creating a deployment. This does NOT submit for audit or release \u2014 it only produces a trial version to verify; submitting it for review and releasing it are done by the user in the editor, not from here.",tool:{name:"deploy_wechat_source_code",inputSchema:{...ye,dir:c.string(),dryRun:c.boolean().optional(),force:c.boolean().optional(),wait:c.boolean().optional(),timeoutSeconds:c.number().optional(),qrOut:c.string().optional(),concurrency:c.number().optional()}},cli:{path:"wechat deploy"}},"wechat.status":{description:"Report the project\u2019s WeChat mini program source upload: any upload still in progress and any build already running (with its deploymentRecordExId and start time). Use to poll a build after `wechat deploy`, or to see whether an interrupted upload is still resumable.",tool:{name:"get_wechat_source_code_status",inputSchema:{...ye}},cli:{path:"wechat status"}},"wechat.abort":{description:"Abandon an in-progress WeChat mini program source upload and delete whatever it already uploaded. Targets the current in-progress deployment unless `deploymentExId` names one. A deployment that already reached BUILDING cannot be aborted.",tool:{name:"abort_wechat_source_code_deployment",inputSchema:{...ye,deploymentExId:c.string().optional()}},cli:{path:"wechat abort"}},"wechat.qrcode":{description:"Save the WeChat trial version (\u4F53\u9A8C\u7248) QR code of the project\u2019s mini program to a local image file and return its path, along with the trial version number and the time it was committed. The QR code is written to disk rather than returned inline because it is a JPEG. Available once a `wechat deploy` build has succeeded; scanning it opens the trial version on a phone whose WeChat id is bound as a tester.",tool:{name:"get_wechat_trial_qrcode",inputSchema:{...ye,out:c.string().optional()}},cli:{path:"wechat qrcode"}}},Hg=Object.entries(HP).map(([t,e])=>({command:t,...e})),Yg=[{name:"schema_session",description:"Schema session lifecycle for the loaded project. op: LOAD (warm the in-memory CRDT session) | RELOAD (force reload from backend) | SYNC (catch up patches) | SNAPSHOT (return the data model: tables, relations, enum types; pass full=true for the entire raw document) | VALIDATE (ztype type checks, stable/beta/backend diagnostics). Edits do not go live until sync_backend.",ops:{LOAD:"schema.load",RELOAD:"schema.reload",SYNC:"schema.sync",SNAPSHOT:"schema.snapshot",VALIDATE:"schema.validate"},inputSchema:{...ye,full:c.boolean().optional()}},{name:"schema_observe",description:"Read the daemon's schema change-state for a project. op: STATE (revision, stale flag, latest change event) | EVENTS (recent semantic schema-change events; afterEventId/limit paginate).",ops:{STATE:"schema.state",EVENTS:"schema.events"},inputSchema:{projectExId:c.string().optional(),afterEventId:c.string().nullable().optional(),limit:c.number().optional()}},{name:"auth",description:"Authentication. op: LOGIN (browser login + save credentials) | LOGOUT (delete credentials, unload sessions) | WHOAMI (show authenticated account token payload) | REAUTH (delete credentials and log in again).",ops:{LOGIN:"auth.login",LOGOUT:"auth.logout",WHOAMI:"auth.whoami",REAUTH:"auth.reauth"}},{name:"project_inspect",description:"Inspect a project. op: DETAIL (app list, project config, latest schema metadata, deployment) | METADATA (plan/capability, deployment, app list, schema metadata, RPS summary) | RESOURCES (resource consumption, plan limits, RPS, optional history). includeSecrets applies to DETAIL/METADATA; refresh/resourceType/nonRealTimeDisplayedResourceTypes apply to RESOURCES.",ops:{DETAIL:"project.detail",METADATA:"project.metadata",RESOURCES:"project.resources"},inputSchema:{...ye,includeSecrets:c.boolean().optional(),refresh:c.boolean().optional(),resourceType:c.string().optional(),nonRealTimeDisplayedResourceTypes:c.array(c.string()).optional()}}];u();u();var YP={schema_table:"database",schema_view:"database",schema_common:"database",schema_overview:"database",schema_type:"type",schema_binding_inspect:"bindings",schema_create_binding:"bindings",schema_conditional_branch:"bindings",schema_custom_array_binding:"bindings",schema_condition_expr:"bindings",schema_request_filter:"bindings",schema_actionflow:"actionflow",schema_actionflow_node:"actionflow",schema_trigger:"actionflow",schema_api:"api",schema_component:"component",schema_action_menu:"component",schema_theme:"component",schema_tab_bar:"component",schema_client_variables:"component",schema_verification_code_config:"component",schema_permission:"permissions",schema_secret:"secret",schema_zai_config:"zai",schema_callback:"webhook",schema_payment:"payments"},Kg=t=>YP[t]??"UNMAPPED",KP={database:'Edit the data model \u2014 tables, columns, relations, unique constraints, display names. op is a schema ToolName from the enum; args is its payload. Call guide {plugin:"database"} first for the rules and per-op arg shapes.',type:'Edit enums and object/custom type definitions. op is a schema ToolName; args is its payload. Call guide {plugin:"type"} for the rules and arg shapes.',bindings:'Create and edit data bindings \u2014 option/const/formula/conditional bindings, boolean condition expressions, and request filters (where + sort), all addressed by schemaPath. op is a schema ToolName; args is its payload. Call guide {plugin:"bindings"} for the rules and arg shapes.',actionflow:'Edit server-side action flows \u2014 flows, nodes, branches, I/O, global variables, and triggers (scheduled / database-change). op is a schema ToolName; args is its payload. Call guide {plugin:"actionflow"} for the rules and arg shapes.',api:'Edit the API-integration library \u2014 workspaces, APIs, request parameters, response configs, input variables, and workspace constants. op is a schema ToolName; args is its payload. Call guide {plugin:"api"} for the rules and arg shapes.',secret:'Register, update, and delete project secrets (API keys and tokens) by handle \u2014 never their plaintext. op is a schema ToolName; args is its payload. Call guide {plugin:"secret"} for the rules and arg shapes.',zai:'Edit ZAI AI-agent configs \u2014 agents, input args, and model settings. op is a schema ToolName; args is its payload. Call guide {plugin:"zai"} for the rules and arg shapes.',component:`Build and edit the UI \u2014 pages, containers, components, slots, properties, styles and responsive breakpoints, plus the design system (color themes, style scale), the client's app-wide variables, and custom verification-code delivery channels. op is a schema ToolName; args is its payload. Call guide {plugin:"component"} first for the tree rules, component templates, and per-op arg shapes.`,permissions:'Edit roles and their table, API, action-flow, AI, and payment permissions. op is a schema ToolName; args is its payload. Call guide {plugin:"permissions"} for the rules and arg shapes.',webhook:'Edit incoming HTTP triggers (webhooks, called callbacks in the schema) \u2014 the bound action flow, request and response body shapes, body codecs, and the provider protocol. op is a schema ToolName; args is its payload. Call guide {plugin:"webhook"} for the rules and arg shapes.',payments:'Design and wire up payments: pick the model the project uses (legacy activation or payment configs), configure providers and credentials, and bind the callback fulfillment flows. op is a schema ToolName; args is its payload. Call guide {plugin:"payments"} for the rules and arg shapes.'},Jg=(()=>{let t=new Map;for(let e of Ns){let n=Kg(e.name);if(n==="UNMAPPED")continue;let r=t.get(n)??new Set;for(let o of Object.values(e.ops))r.add(o);t.set(n,r)}return[...t.entries()].map(([e,n])=>({name:e,description:KP[e]??`Edit ${e}.`,ops:[...n].sort()})).sort((e,n)=>e.name.localeCompare(n.name))})(),zU=Ns.filter(t=>Kg(t.name)==="UNMAPPED").map(t=>t.name);function JP(){let t=[];for(let e of Hg){if(!e.tool)continue;let{name:n,aliases:r,inputSchema:o}=e.tool;t.push({name:n,description:e.description,command:e.command,inputSchema:o});for(let a of r??[])t.push({name:a.name,description:a.description??e.description,command:e.command,inputSchema:o})}return t}function ZU(t,e){Zg(t,JP(),e),Bg(t,Yg,e),qg(t,Jg,e),Vg(t),Wg(t,e)}u();u();var XP={productName:"Zion",utcOffset:"+08:00",accountTable:"\u5E10\u6237(\u8D26\u6237)",paymentTables:"\u652F\u4ED8, \u5468\u671F\u6027\u652F\u4ED8, \u9000\u6B3E",aiTables:"\u4F1A\u8BDD, \u6D88\u606F, \u5DE5\u5177\u4F7F\u7528\u8BB0\u5F55, \u6D88\u606F\u5185\u5BB9",displayNameRule:'user-visible; use the natural Chinese name as the displayName and derive the English snake_case apiName from it (e.g. displayName "\u7528\u6237\u540D" \u2192 apiName "user_name").',enumDisplayNameRule:'use a natural Chinese phrase (enum displayName "\u8BA2\u5355\u72B6\u6001", option displayName "\u5F85\u5904\u7406"); the enum id and option values stay English.',runtimeGraphqlUrl:t=>jn().zeroApiUrlTemplate.replace("{projectExId}",t)},QP={productName:"Momen",utcOffset:"+00:00",accountTable:"account",paymentTables:"payment_record, recurring_payment, refund",aiTables:"conversation, message, tool_usage_record, message_content",displayNameRule:'user-visible; prefer it IDENTICAL to the apiName (e.g. apiName "first_name" \u2192 displayName "first_name").',enumDisplayNameRule:'keep it close to the name/value itself (enum displayName \u2248 the enum name, e.g. "OrderStatus"; an option displayName \u2248 its value, e.g. "PENDING").',runtimeGraphqlUrl:t=>jn().zeroApiUrlTemplate.replace("{projectExId}",t)},Ps=()=>{switch(Un){case"MOMEN":return QP;case"ZION":return XP;default:throw new Error(`[product-context] unknown PRODUCT '${Un}'`)}};u();function Xg({brand:t,zeroApiUrl:e}){let n=e.replace(/^http:/,"ws:").replace(/^https:/,"wss:").replace("/api/graphql-v2","/api/graphql-subscription");return{brand:t,zeroApiUrl:e,zeroSubscriptionUrl:n}}function Qg(t){let e=t.brand==="Zion"?"Zion apps conventionally sign up / log in by phone number (SMS code); email and username work too.":"Momen apps conventionally sign up / log in by email; phone (SMS code) and username work too.";return`## App-user authentication (for the frontend you generate)
|
|
946
|
+
- op=UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS (req: configId, toolId)`,ops:{ADD_ZAI_CONFIGS:"ADD_ZAI_CONFIGS",ADD_ZAI_CONFIG_API_CONTEXTS:"ADD_ZAI_CONFIG_API_CONTEXTS",ADD_ZAI_CONFIG_DB_CONTEXTS:"ADD_ZAI_CONFIG_DB_CONTEXTS",ADD_ZAI_CONFIG_INPUT_ARGS:"ADD_ZAI_CONFIG_INPUT_ARGS",ADD_ZAI_CONFIG_TOOLS:"ADD_ZAI_CONFIG_TOOLS",DELETE_ZAI_CONFIGS:"DELETE_ZAI_CONFIGS",DELETE_ZAI_CONFIG_API_CONTEXTS:"DELETE_ZAI_CONFIG_API_CONTEXTS",DELETE_ZAI_CONFIG_DB_CONTEXTS:"DELETE_ZAI_CONFIG_DB_CONTEXTS",DELETE_ZAI_CONFIG_INPUT_ARGS:"DELETE_ZAI_CONFIG_INPUT_ARGS",DELETE_ZAI_CONFIG_TOOLS:"DELETE_ZAI_CONFIG_TOOLS",DUPLICATE_ZAI_CONFIG:"DUPLICATE_ZAI_CONFIG",GET_ALL_ZAI_CONFIGS_INFO:"GET_ALL_ZAI_CONFIGS_INFO",GET_ZAI_CONFIG_DETAIL:"GET_ZAI_CONFIG_DETAIL",GET_ZAI_CONFIG_SELECTABLE_TYPES:"GET_ZAI_CONFIG_SELECTABLE_TYPES",GET_ZAI_MODEL_OPTIONS:"GET_ZAI_MODEL_OPTIONS",UPDATE_ZAI_CONFIG:"UPDATE_ZAI_CONFIG",UPDATE_ZAI_CONFIG_API_CONTEXT:"UPDATE_ZAI_CONFIG_API_CONTEXT",UPDATE_ZAI_CONFIG_DB_CONTEXT:"UPDATE_ZAI_CONFIG_DB_CONTEXT",UPDATE_ZAI_CONFIG_INPUT_ARGS:"UPDATE_ZAI_CONFIG_INPUT_ARGS",UPDATE_ZAI_CONFIG_OUTPUT:"UPDATE_ZAI_CONFIG_OUTPUT",UPDATE_ZAI_CONFIG_TOOL:"UPDATE_ZAI_CONFIG_TOOL",UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS:"UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS"},inputSchema:{addRelations:c.array(c.any()).optional(),apiId:c.string().optional(),apiIds:c.array(c.any()).optional(),argKeys:c.array(c.any()).optional(),arrayLevel:c.number().optional(),clearLimit:c.boolean().optional(),columns:c.array(c.any()).optional(),configId:c.string().optional(),configIds:c.array(c.any()).optional(),customModelIdentifier:c.record(c.any()).optional(),description:c.string().optional(),enable:c.boolean().optional(),ignoreNullValuesFromContext:c.boolean().optional(),imageInputQuality:c.enum(["LOW","HIGH"]).optional(),inputDescriptionConfigs:c.record(c.any()).optional(),isStreaming:c.boolean().optional(),isStructured:c.boolean().optional(),items:c.array(c.any()).optional(),limit:c.number().optional(),maxRound:c.number().optional(),maxTokenSize:c.number().optional(),name:c.string().optional(),outputDescriptionConfig:c.record(c.any()).optional(),outputType:c.string().optional(),relationPath:c.array(c.any()).optional(),removeRelations:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional(),selectedFieldsByType:c.record(c.any()).optional(),slot:c.enum(["INPUT","OUTPUT"]).optional(),sourceZAiConfigId:c.string().optional(),tableDisplayName:c.string().optional(),tableDisplayNames:c.array(c.any()).optional(),temperature:c.number().optional(),toolId:c.string().optional(),toolIds:c.array(c.any()).optional()}}],NU={ADD_VIEWS:"DATA_MODEL_VIEW_2610",ANALYZE_VIEW_SQL:"DATA_MODEL_VIEW_2610",DELETE_VIEWS:"DATA_MODEL_VIEW_2610",GET_VIEWS_INFO:"DATA_MODEL_VIEW_2610",GET_VIEW_PERMISSION:"DATA_MODEL_VIEW_2610",UPDATE_ROLE_VIEW_PERMISSION:"DATA_MODEL_VIEW_2610",UPDATE_VIEWS:"DATA_MODEL_VIEW_2610"};var HP={"actionflow.list_node_templates":{description:"List the preset action-flow integration nodes (the TEMPLATE_CODE catalog \u2014 e.g. SMS, video/AI generation) for planning: each template\u2019s templateCodeId, displayName, group, async flag, and input/output param types. To add one, read schema_actionflow_node op=BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at the position and pass that entry\u2019s `node` to op=ADD_NODE. A TEMPLATE_CODE node already in the schema carries one of these templateCodeIds; never rewrite it to an id from anywhere else.",tool:{name:"list_actionflow_node_templates"},cli:{path:"actionflow list-node-templates"}},"component.tab_bar_icons":{description:"The preset tab-bar icons this deployment ships, as name and media exId \u2014 home, cart, chat, profile and the rest. A tab that is shown needs an icon for both its normal and its selected state or the project reports an error, and the exIds are hashids of media rows that cannot be derived from an icon\u2019s name, so take them from here before schema_tab_bar op=UPDATE_TAB_BAR_ITEMS \u2014 that tool rejects a value that could not be an exId rather than letting the mini-program build fail over a file it cannot find. To use an icon that is not in the list, upload it in the editor and use the exId it is stored under.",tool:{name:"get_tab_bar_icons"},cli:{path:"component tab-bar-icons"}},"workspace.set":{description:"Set the workspace root for local credentials, daemon registry, and project context.",tool:{name:"set_current_working_directory",inputSchema:{cwd:c.string()}}},"auth.login":{description:"Start browser login and save credentials.",cli:{path:"login"}},"auth.logout":{description:"Delete local credentials and unload schema sessions.",cli:{path:"logout"}},"auth.whoami":{description:"Show the currently authenticated account token payload.",cli:{path:"whoami"}},"auth.reauth":{description:"Delete credentials and start login again.",cli:{path:"reauth"}},"account.profile":{description:"Fetch current account and organization/project-space metadata used for project creation.",tool:{name:"get_account_profile"},cli:{path:"account profile",alias:"account me"}},"projects.search":{description:"List/search projects with pagination.",tool:{name:"get_projects",inputSchema:{projectName:c.string().optional(),cursor:c.string().nullable().optional(),limit:c.number().optional()}},cli:{path:"projects search"}},"projects.list":{description:"List projects.",cli:{path:"projects list"}},"project.create":{description:"Create a new blank project in the current account organization and wait for it to appear in search. A project is a backend plus at most one client app, named by appType \u2014 pick it with the user: the free plan pays for one client. WEB, WECHAT_MINI_PROGRAM (Zion only) and MOBILE (iOS) each create a client this project hosts: build its pages with these tools, or deploy your own build to a WEB client with site deploy. BACKEND_ONLY creates no client, for a front end hosted elsewhere that calls the project's generated GraphQL API. These tools cannot add a client to an existing project, and a second one is a paid client slot bought in the console, so pick the client the user wants now. It comes back as builtInApp, already current, so UI calls need no appExId.",tool:{name:"create_project",inputSchema:{projectName:c.string(),appType:c.enum(["WEB","WECHAT_MINI_PROGRAM","MOBILE","BACKEND_ONLY"]),appName:c.string().optional(),projectSpaceType:c.string().optional(),organizationExId:c.string().optional(),category:c.string().nullable().optional(),wait:c.boolean().optional(),timeoutMs:c.number().optional()}},cli:{path:"project create"}},"project.set_current":{description:"Set the project every later call defaults to. With no appExId it also makes that project\u2019s only client current (the client session holds its pages and the project backend both), and a project with no client defaults to its backend document. A project with several clients is refused, listing them, and leaves the current project as it was: pages belong to one client, so pass appExId to name it \u2014 or appExId: null to address the backend alone.",tool:{name:"set_current_project",inputSchema:{projectExId:c.string(),appExId:c.string().nullable().optional()}},cli:{path:"project set-current"}},"project.get_current":{description:"Get the current project context: the pinned project and the client app calls default to (appExId null means they address the project\u2019s own backend document).",tool:{name:"get_current_project"},cli:{path:"project current",alias:"project get-current"}},"project.detail":{description:"Fetch the project's detail payload: app list, project config, the backend document's latest schema metadata, and deployment info. Answers for the project itself, not for the current client \u2014 pass appExId to get one client app's own detail instead.",cli:{path:"project detail"}},"project.metadata":{description:"Fetch a lean project summary: identity, platforms, publish/deploy state (incl. hasUndeployedChanges), configured integrations, plan, capabilities, and RPS. Pass raw=true for the full unshaped payload. Deploy state belongs to the project's backend document, so naming a client with appExId leaves it out.",cli:{path:"project metadata",alias:"project inspect"}},"project.resources":{description:"Fetch project resource consumption, plan/capability limits, RPS stats, and optional resource history.",cli:{path:"project resources"}},"project.rename":{description:"Rename a project.",tool:{name:"rename_project",inputSchema:{...ye,projectName:c.string()}},cli:{path:"project rename"}},"project.rename_app":{description:"Rename an app inside a project.",tool:{name:"rename_project_app",inputSchema:{projectExId:c.string(),appExId:c.string(),appName:c.string()}},cli:{path:"project rename-app"}},"project.delete":{description:"Delete a project. IRREVERSIBLE: requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve. Set MCP_HITL=off to fall back to the confirmProjectExId/force text gate in headless automation.",tool:{name:"delete_project",inputSchema:{projectExId:c.string(),confirmProjectExId:c.string().optional(),force:c.boolean().optional()}},cli:{path:"project delete"}},"project.reset":{description:"Reset a project. IRREVERSIBLE: requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve. Set MCP_HITL=off to fall back to the confirmProjectExId/force text gate in headless automation.",tool:{name:"reset_project",inputSchema:{projectExId:c.string(),confirmProjectExId:c.string().optional(),force:c.boolean().optional(),languageType:c.string().optional()}},cli:{path:"project reset"}},"project.sync_backend":{description:"Save the schema and deploy/sync the project runtime backend. Returns ztype diagnostics and blocks on backend validation errors by default.",tool:{name:"sync_backend",inputSchema:{...ye,buildTarget:c.string().optional(),validateMultiClient:c.boolean().optional(),allowValidationErrors:c.boolean().optional()}},cli:{path:"project sync-backend",alias:"project deploy-backend"}},"schema.load":{description:"Load a project's CRDT schema into the daemon's in-memory headless schema session.",cli:{path:"schema load"}},"schema.reload":{description:"Force reload a project schema session from the backend CRDT model and patch log.",cli:{path:"schema reload"}},"schema.status":{description:"Show daemon schema sessions and TTL state.",tool:{name:"schema_status"},cli:{path:"schema status"}},"schema.state":{description:"Read the daemon's schema revision, stale state, and latest semantic schema-change event for a project.",cli:{path:"schema state"}},"schema.events":{description:"Read recent semantic schema-change events observed by the daemon for a project.",cli:{path:"schema events"}},"schema.sync":{description:"Catch up schema CRDT patches from the backend for the loaded project session.",cli:{path:"schema sync"}},"schema.snapshot":{description:"Return the data model of the loaded schema (tables, relations, enum types). Pass full=true for the entire raw ZSchema document (UI tree + all server configs), which is much larger.",cli:{path:"schema snapshot"}},"schema.validate":{description:"Run ztype validation/type checks against the loaded schema and return stable/beta/backend diagnostics.",cli:{path:"schema validate",alias:"schema type-check"}},"bridge.flow_definition":{description:"Resolve an action flow to the definition the debug mutation takes, plus its terminal end node. Derived from the draft CRDT, so it answers with no editor tab attached.",cli:{path:"bridge flow-definition"}},"bridge.trigger_bindings":{description:"List database and scheduled trigger bindings with their flow names, table names and enabled state, derived from the draft CRDT.",cli:{path:"bridge trigger-bindings"}},"bridge.deploy_status":{description:"Compare the draft schema against the last deployed server schema and report which of the eleven server areas differ. Unlike project.inspect this diffs content against the *draft*, so unsaved edits count as pending changes.",cli:{path:"bridge deploy-status"}},"bridge.project_errors":{description:"List the project validation errors and warnings in the shape the editor reports them, newest ztype run, capped by limit. Same union and order as the editor panel.",cli:{path:"bridge project-errors"}},"bridge.sync_backend":{description:"Save the draft schema, deploy the backend and wait for the pipeline, reporting the outcome in the shape the editor reports it. A deploy already running is waited for, not restarted.",cli:{path:"bridge sync-backend"}},"bridge.clipped_components":{description:"Measure which components on a page render clipped (content larger than their box), in the shape the editor reports. Renders the canvas in a headless browser owned by the daemon, after it has applied the latest schema patch.",cli:{path:"bridge clipped-components"}},"bridge.capture_canvas":{description:"Screenshot a page or component as the editor canvas renders it and store it as the agent session's media. Same headless renderer and patch wait as bridge clipped-components.",cli:{path:"bridge capture-canvas"}},"schema.ztype_tool_calls":{description:"Run ztype Copilot tool calls against the loaded schema as one atomic batch: either every call lands or none does, and `applied` reports which. A batch ztype rejects, or whose patch trips validation, reports errors with errorCode/failedIndex and applies nothing \u2014 pass force to apply over a DEPENDENCY_CONFLICT. Use schema_undo to revert the last change.",tool:{name:"ztype_tool_calls",inputSchema:{...ye,toolCalls:c.array(c.record(c.any())),verbose:c.boolean().optional(),readState:c.record(c.any()).optional(),force:c.boolean().optional()}},cli:{path:"schema tool-call",alias:"schema tool-calls"}},"schema.undo":{description:"Undo the most recent schema change made in this session by applying a reverse CRDT patch. Refuses if a concurrent edit touched the same path. Pairs with schema_redo.",tool:{name:"schema_undo",inputSchema:{...ye}},cli:{path:"schema undo"}},"schema.redo":{description:"Re-apply the schema change most recently undone via schema_undo in this session.",tool:{name:"schema_redo",inputSchema:{...ye}},cli:{path:"schema redo"}},"secret.save_value":{description:"Prompt the user (native GUI dialog) to set a secret's plaintext value, store it, and attach the handle so the secret reports hasValue:true. Provide secretId (an existing secret) OR displayName (create a new one). The value is typed into the dialog and never passes through this tool call or the model. Requires a desktop session (fails on headless/SSH/CI).",tool:{name:"save_secret_value",inputSchema:{...ye,secretId:c.string().optional(),displayName:c.string().optional(),description:c.string().optional()}},cli:{path:"secret save-value"}},"runtime.graphql":{description:"Run a raw GraphQL operation against the deployed project's runtime backend (the auto-generated data/actionflow/AI API), as admin.",tool:{name:"runtime_graphql",inputSchema:{...ye,query:c.string(),variables:c.record(c.any()).optional()}},cli:{path:"runtime graphql"}},"runtime.run_code":{description:"Execute a JavaScript snippet in the deployed project's Run Code sandbox and return its result. Database writes are reverted unless updateDb is true, so this is the cheap way to check what a Run Code node will actually return before wiring it into a flow. Runs on the admin surface, as admin.",tool:{name:"runtime_run_code",inputSchema:{...ye,jsCode:c.string(),args:c.record(c.any()).optional(),updateDb:c.boolean().optional()}},cli:{path:"runtime run-code"}},"runtime.query":{description:"Query rows from a deployed project's runtime table.",cli:{path:"runtime query"}},"runtime.aggregate":{description:"Count rows matching a filter in a deployed project's runtime table \u2014 the cheapest assertion available.",cli:{path:"runtime aggregate"}},"runtime.insert":{description:"Insert one or more rows into a deployed project's runtime table.",cli:{path:"runtime insert"}},"runtime.update":{description:"Update rows in a deployed project's runtime table.",cli:{path:"runtime update"}},"runtime.delete":{description:"Delete rows from a deployed project's runtime table. Requires where unless allowDeleteAll=true.",cli:{path:"runtime delete"}},"logs.search":{description:`Fetch recent runtime logs from the project's log endpoint. Window is \xB15 minutes around requestCreatedAt (ISO-8601, defaults to now). types: GATEWAY, ACTION_FLOW, ACTION_FLOW_NODE, ACTION_FLOW_CONTEXT_LOG, DEPLOYMENT, TPA, TRIGGER, SQL_GENERATION, GQL, ZAI. levels: INFO, WARNING, ERROR. customQueryCondition is an Elasticsearch condition (e.g. 'traceId: "abc-123"').`,tool:{name:"search_logs",inputSchema:{...ye,requestCreatedAt:c.string().optional(),types:c.array(c.string()).optional(),levels:c.array(c.string()).optional(),customQueryCondition:c.string().optional(),limit:c.number().optional()}},cli:{path:"logs search"}},"docs.search":{description:"Full-text search the bundled product documentation. Returns the best-matching pages as { path, title, url }, where url is the public HTTPS docs link you can cite. Use docs.get_page with a returned path to read a page.",tool:{name:"search_docs",inputSchema:{query:c.string(),limit:c.number().optional()}},cli:{path:"docs search"}},"docs.get_page":{description:'Fetch a documentation page as markdown by its path (as returned by docs.search, e.g. "/02_design/01_layout_concepts").',tool:{name:"get_doc_page",inputSchema:{path:c.string()}},cli:{path:"docs get-page"}},"platform.graphql":{description:"Guarded raw GraphQL passthrough to the platform backend (projects, accounts, publishing \u2014 the editor/meta API, not the deployed runtime).",tool:{name:"platform_graphql",inputSchema:{query:c.string(),variables:c.record(c.any()).optional()}},cli:{path:"platform graphql"}},"web.fetch_doc":{description:"Fetch a web page or spec by URL for reading. Returns the page content (HTML converted to Markdown; long pages are windowed \u2014 pass `offset` with the same url to keep reading, guided by `totalLength`/`truncated`), same-site `pageLinks` to explore the documentation further, and any OpenAPI/Swagger `specLinks` found. Explore iteratively by fetching returned links, within a budget of 15 fetches per session (`fetchesRemaining`). Build the endpoints you read about with the api schema ops.",tool:{name:"fetch_api_doc",inputSchema:{url:c.string(),offset:c.number().optional()}},cli:{path:"web fetch-doc"}},"site.deploy":{description:"Deploy a built frontend directory (e.g. ./dist) to the project\u2019s hosted static site and return the live url. Scans the directory, declares the manifest, uploads every asset to object storage, and switches the site over in one call \u2014 the agent never handles checksums or upload urls itself. `target` is BETA (default) or PROD; a PROD deploy takes the site live and requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve, and `force` does NOT approve it. Set MCP_HITL=off to fall back to the confirmProjectExId text gate in headless automation. An interrupted run resumes automatically when the directory is unchanged; pass `force` to discard it and start over. `dryRun` reports what would be uploaded without creating a deployment. The total size must fit the project\u2019s remaining object storage, and the directory must contain an index.html.",tool:{name:"deploy_static_site",inputSchema:{...ye,dir:c.string(),target:c.string().optional(),dryRun:c.boolean().optional(),force:c.boolean().optional(),concurrency:c.number().optional(),confirmProjectExId:c.string().optional()}},cli:{path:"site deploy"}},"site.status":{description:"Report the project\u2019s static site: the currently live deployment (with its url) and any upload still in progress. Use to find the site url, or to see whether an interrupted deploy is still resumable.",tool:{name:"get_static_site_status",inputSchema:{...ye,target:c.string().optional()}},cli:{path:"site status"}},"site.abort":{description:"Abandon an in-progress static site upload and delete whatever it already uploaded. Targets the current in-progress deployment unless `deploymentExId` names one. The live site is untouched.",tool:{name:"abort_static_site_deployment",inputSchema:{...ye,target:c.string().optional(),deploymentExId:c.string().optional()}},cli:{path:"site abort"}},"wechat.deploy":{description:"Upload a locally-developed WeChat mini program source tree (the directory holding app.json) to the project and start the server-side build that commits it to WeChat as the \u4F53\u9A8C\u7248 (trial version). Scans the directory, declares the manifest, uploads every file to object storage, and hands off to the build job in one call \u2014 the agent never handles checksums or upload urls itself. By default it then WAITS for the build and returns the trial version number plus the path of the trial QR code image it saved (`wait: false` returns as soon as the build starts; `timeoutSeconds` bounds the wait). Requires the project to have granted Zion third-party platform authorization. An interrupted run resumes automatically when the directory is unchanged; pass `force` to discard it and start over. `dryRun` reports what would be uploaded without creating a deployment. This does NOT submit for audit or release \u2014 it only produces a trial version to verify; submitting it for review and releasing it are done by the user in the editor, not from here.",tool:{name:"deploy_wechat_source_code",inputSchema:{...ye,dir:c.string(),dryRun:c.boolean().optional(),force:c.boolean().optional(),wait:c.boolean().optional(),timeoutSeconds:c.number().optional(),qrOut:c.string().optional(),concurrency:c.number().optional()}},cli:{path:"wechat deploy"}},"wechat.status":{description:"Report the project\u2019s WeChat mini program source upload: any upload still in progress and any build already running (with its deploymentRecordExId and start time). Use to poll a build after `wechat deploy`, or to see whether an interrupted upload is still resumable.",tool:{name:"get_wechat_source_code_status",inputSchema:{...ye}},cli:{path:"wechat status"}},"wechat.abort":{description:"Abandon an in-progress WeChat mini program source upload and delete whatever it already uploaded. Targets the current in-progress deployment unless `deploymentExId` names one. A deployment that already reached BUILDING cannot be aborted.",tool:{name:"abort_wechat_source_code_deployment",inputSchema:{...ye,deploymentExId:c.string().optional()}},cli:{path:"wechat abort"}},"wechat.qrcode":{description:"Save the WeChat trial version (\u4F53\u9A8C\u7248) QR code of the project\u2019s mini program to a local image file and return its path, along with the trial version number and the time it was committed. The QR code is written to disk rather than returned inline because it is a JPEG. Available once a `wechat deploy` build has succeeded; scanning it opens the trial version on a phone whose WeChat id is bound as a tester.",tool:{name:"get_wechat_trial_qrcode",inputSchema:{...ye,out:c.string().optional()}},cli:{path:"wechat qrcode"}}},Hg=Object.entries(HP).map(([t,e])=>({command:t,...e})),Yg=[{name:"schema_session",description:"Schema session lifecycle for the loaded project. op: LOAD (warm the in-memory CRDT session) | RELOAD (force reload from backend) | SYNC (catch up patches) | SNAPSHOT (return the data model: tables, relations, enum types; pass full=true for the entire raw document) | VALIDATE (ztype type checks, stable/beta/backend diagnostics). Edits do not go live until sync_backend.",ops:{LOAD:"schema.load",RELOAD:"schema.reload",SYNC:"schema.sync",SNAPSHOT:"schema.snapshot",VALIDATE:"schema.validate"},inputSchema:{...ye,full:c.boolean().optional()}},{name:"schema_observe",description:"Read the daemon's schema change-state for a project. op: STATE (revision, stale flag, latest change event) | EVENTS (recent semantic schema-change events; afterEventId/limit paginate).",ops:{STATE:"schema.state",EVENTS:"schema.events"},inputSchema:{projectExId:c.string().optional(),afterEventId:c.string().nullable().optional(),limit:c.number().optional()}},{name:"auth",description:"Authentication. op: LOGIN (browser login + save credentials) | LOGOUT (delete credentials, unload sessions) | WHOAMI (show authenticated account token payload) | REAUTH (delete credentials and log in again).",ops:{LOGIN:"auth.login",LOGOUT:"auth.logout",WHOAMI:"auth.whoami",REAUTH:"auth.reauth"}},{name:"project_inspect",description:"Inspect a project. op: DETAIL (app list, project config, latest schema metadata, deployment) | METADATA (plan/capability, deployment, app list, schema metadata, RPS summary) | RESOURCES (resource consumption, plan limits, RPS, optional history). includeSecrets applies to DETAIL/METADATA; refresh/resourceType/nonRealTimeDisplayedResourceTypes apply to RESOURCES.",ops:{DETAIL:"project.detail",METADATA:"project.metadata",RESOURCES:"project.resources"},inputSchema:{...ye,includeSecrets:c.boolean().optional(),refresh:c.boolean().optional(),resourceType:c.string().optional(),nonRealTimeDisplayedResourceTypes:c.array(c.string()).optional()}}];u();u();var YP={schema_table:"database",schema_view:"database",schema_common:"database",schema_overview:"database",schema_type:"type",schema_binding_inspect:"bindings",schema_create_binding:"bindings",schema_conditional_branch:"bindings",schema_custom_array_binding:"bindings",schema_condition_expr:"bindings",schema_request_filter:"bindings",schema_actionflow:"actionflow",schema_actionflow_node:"actionflow",schema_trigger:"actionflow",schema_api:"api",schema_component:"component",schema_action_menu:"component",schema_theme:"component",schema_tab_bar:"component",schema_client_variables:"component",schema_verification_code_config:"component",schema_permission:"permissions",schema_secret:"secret",schema_zai_config:"zai",schema_callback:"webhook",schema_payment:"payments"},Kg=t=>YP[t]??"UNMAPPED",KP={database:'Edit the data model \u2014 tables, columns, relations, unique constraints, display names. op is a schema ToolName from the enum; args is its payload. Call guide {plugin:"database"} first for the rules and per-op arg shapes.',type:'Edit enums and object/custom type definitions. op is a schema ToolName; args is its payload. Call guide {plugin:"type"} for the rules and arg shapes.',bindings:'Create and edit data bindings \u2014 option/const/formula/conditional bindings, boolean condition expressions, and request filters (where + sort), all addressed by schemaPath. op is a schema ToolName; args is its payload. Call guide {plugin:"bindings"} for the rules and arg shapes.',actionflow:'Edit server-side action flows \u2014 flows, nodes, branches, I/O, global variables, and triggers (scheduled / database-change). op is a schema ToolName; args is its payload. Call guide {plugin:"actionflow"} for the rules and arg shapes.',api:'Edit the API-integration library \u2014 workspaces, APIs, request parameters, response configs, input variables, and workspace constants. op is a schema ToolName; args is its payload. Call guide {plugin:"api"} for the rules and arg shapes.',secret:'Register, update, and delete project secrets (API keys and tokens) by handle \u2014 never their plaintext. op is a schema ToolName; args is its payload. Call guide {plugin:"secret"} for the rules and arg shapes.',zai:'Edit ZAI AI-agent configs \u2014 agents, input args, and model settings. op is a schema ToolName; args is its payload. Call guide {plugin:"zai"} for the rules and arg shapes.',component:`Build and edit the UI \u2014 pages, containers, components, slots, properties, styles and responsive breakpoints, plus the design system (color themes, style scale), the client's app-wide variables, and custom verification-code delivery channels. op is a schema ToolName; args is its payload. Call guide {plugin:"component"} first for the tree rules, component templates, and per-op arg shapes.`,permissions:'Edit roles and their table, API, action-flow, AI, and payment permissions. op is a schema ToolName; args is its payload. Call guide {plugin:"permissions"} for the rules and arg shapes.',webhook:'Edit incoming HTTP triggers (webhooks, called callbacks in the schema) \u2014 the bound action flow, request and response body shapes, body codecs, and the provider protocol. op is a schema ToolName; args is its payload. Call guide {plugin:"webhook"} for the rules and arg shapes.',payments:'Design and wire up payments: pick the model the project uses (legacy activation or payment configs), configure providers and credentials, and bind the callback fulfillment flows. op is a schema ToolName; args is its payload. Call guide {plugin:"payments"} for the rules and arg shapes.'},Jg=(()=>{let t=new Map;for(let e of Ns){let n=Kg(e.name);if(n==="UNMAPPED")continue;let r=t.get(n)??new Set;for(let o of Object.values(e.ops))r.add(o);t.set(n,r)}return[...t.entries()].map(([e,n])=>({name:e,description:KP[e]??`Edit ${e}.`,ops:[...n].sort()})).sort((e,n)=>e.name.localeCompare(n.name))})(),zU=Ns.filter(t=>Kg(t.name)==="UNMAPPED").map(t=>t.name);function JP(){let t=[];for(let e of Hg){if(!e.tool)continue;let{name:n,aliases:r,inputSchema:o}=e.tool;t.push({name:n,description:e.description,command:e.command,inputSchema:o});for(let a of r??[])t.push({name:a.name,description:a.description??e.description,command:e.command,inputSchema:o})}return t}function ZU(t,e){Zg(t,JP(),e),Bg(t,Yg,e),qg(t,Jg,e),Vg(t),Wg(t,e)}u();u();var XP={productName:"Zion",utcOffset:"+08:00",accountTable:"\u5E10\u6237(\u8D26\u6237)",paymentTables:"\u652F\u4ED8, \u5468\u671F\u6027\u652F\u4ED8, \u9000\u6B3E",aiTables:"\u4F1A\u8BDD, \u6D88\u606F, \u5DE5\u5177\u4F7F\u7528\u8BB0\u5F55, \u6D88\u606F\u5185\u5BB9",displayNameRule:'user-visible; use the natural Chinese name as the displayName and derive the English snake_case apiName from it (e.g. displayName "\u7528\u6237\u540D" \u2192 apiName "user_name").',enumDisplayNameRule:'use a natural Chinese phrase (enum displayName "\u8BA2\u5355\u72B6\u6001", option displayName "\u5F85\u5904\u7406"); the enum id and option values stay English.',runtimeGraphqlUrl:t=>jn().zeroApiUrlTemplate.replace("{projectExId}",t)},QP={productName:"Momen",utcOffset:"+00:00",accountTable:"account",paymentTables:"payment_record, recurring_payment, refund",aiTables:"conversation, message, tool_usage_record, message_content",displayNameRule:'user-visible; prefer it IDENTICAL to the apiName (e.g. apiName "first_name" \u2192 displayName "first_name").',enumDisplayNameRule:'keep it close to the name/value itself (enum displayName \u2248 the enum name, e.g. "OrderStatus"; an option displayName \u2248 its value, e.g. "PENDING").',runtimeGraphqlUrl:t=>jn().zeroApiUrlTemplate.replace("{projectExId}",t)},Ps=()=>{switch(Un){case"MOMEN":return QP;case"ZION":return XP;default:throw new Error(`[product-context] unknown PRODUCT '${Un}'`)}};u();function Xg({brand:t,zeroApiUrl:e}){let n=e.replace(/^http:/,"ws:").replace(/^https:/,"wss:").replace("/api/graphql-v2","/api/graphql-subscription");return{brand:t,zeroApiUrl:e,zeroSubscriptionUrl:n}}function Qg(t){let e=t.brand==="Zion"?"Zion apps conventionally sign up / log in by phone number (SMS code); email and username work too.":"Momen apps conventionally sign up / log in by email; phone (SMS code) and username work too.";return`## App-user authentication (for the frontend you generate)
|
|
953
947
|
The deployed app's end-users obtain a JWT by logging in / registering against the same GraphQL API;
|
|
954
948
|
unauthenticated requests fall back to the anonymous role. Distinct from the developer \`login\` that
|
|
955
949
|
authenticates THIS CLI to ${t.brand}. ${e}
|