siyuan-sisyphus 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.cjs +66 -60
  2. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var tm=Object.defineProperty;var om=(e,t,o)=>t in e?tm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var se=(e,t,o)=>om(e,typeof t!="symbol"?t+"":t,o);const H=require("node:fs"),go=require("node:os"),U=require("node:path"),nm=require("node:readline"),rm=require("node:url");var ir=typeof document<"u"?document.currentScript:null;function sm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function am(e,t){var o=e;t.slice(0,-1).forEach(function(r){o=o[r]||{}});var n=t[t.length-1];return n in o}function Ya(e){return typeof e=="number"||/^0x[0-9a-f]+$/i.test(e)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function Wa(e,t){return t==="constructor"&&typeof e[t]=="function"||t==="__proto__"}var im=function(e,t){t||(t={});var o={bools:{},strings:{},unknownFn:null};typeof t.unknown=="function"&&(o.unknownFn=t.unknown),typeof t.boolean=="boolean"&&t.boolean?o.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach(function(T){o.bools[T]=!0});var n={};function r(T){return n[T].some(function(A){return o.bools[A]})}Object.keys(t.alias||{}).forEach(function(T){n[T]=[].concat(t.alias[T]),n[T].forEach(function(A){n[A]=[T].concat(n[T].filter(function(O){return A!==O}))})}),[].concat(t.string).filter(Boolean).forEach(function(T){o.strings[T]=!0,n[T]&&[].concat(n[T]).forEach(function(A){o.strings[A]=!0})});var s=t.default||{},a={_:[]};function i(T,A){return o.allBools&&/^--[^=]+$/.test(A)||o.strings[T]||o.bools[T]||n[T]}function c(T,A,O){for(var C=T,L=0;L<A.length-1;L++){var Z=A[L];if(Wa(C,Z))return;C[Z]===void 0&&(C[Z]={}),(C[Z]===Object.prototype||C[Z]===Number.prototype||C[Z]===String.prototype)&&(C[Z]={}),C[Z]===Array.prototype&&(C[Z]=[]),C=C[Z]}var _e=A[A.length-1];Wa(C,_e)||((C===Object.prototype||C===Number.prototype||C===String.prototype)&&(C={}),C===Array.prototype&&(C=[]),C[_e]===void 0||o.bools[_e]||typeof C[_e]=="boolean"?C[_e]=O:Array.isArray(C[_e])?C[_e].push(O):C[_e]=[C[_e],O])}function l(T,A,O){if(!(O&&o.unknownFn&&!i(T,O)&&o.unknownFn(O)===!1)){var C=!o.strings[T]&&Ya(A)?Number(A):A;c(a,T.split("."),C),(n[T]||[]).forEach(function(L){c(a,L.split("."),C)})}}Object.keys(o.bools).forEach(function(T){l(T,s[T]===void 0?!1:s[T])});var u=[];e.indexOf("--")!==-1&&(u=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var p=0;p<e.length;p++){var f=e[p],h,g;if(/^--.+=/.test(f)){var b=f.match(/^--([^=]+)=([\s\S]*)$/);h=b[1];var _=b[2];o.bools[h]&&(_=_!=="false"),l(h,_,f)}else if(/^--no-.+/.test(f))h=f.match(/^--no-(.+)/)[1],l(h,!1,f);else if(/^--.+/.test(f))h=f.match(/^--(.+)/)[1],g=e[p+1],g!==void 0&&!/^(-|--)[^-]/.test(g)&&!o.bools[h]&&!o.allBools&&(!n[h]||!r(h))?(l(h,g,f),p+=1):/^(true|false)$/.test(g)?(l(h,g==="true",f),p+=1):l(h,o.strings[h]?"":!0,f);else if(/^-[^-]+/.test(f)){for(var w=f.slice(1,-1).split(""),P=!1,D=0;D<w.length;D++){if(g=f.slice(D+2),g==="-"){l(w[D],g,f);continue}if(/[A-Za-z]/.test(w[D])&&g[0]==="="){l(w[D],g.slice(1),f),P=!0;break}if(/[A-Za-z]/.test(w[D])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(g)){l(w[D],g,f),P=!0;break}if(w[D+1]&&w[D+1].match(/\W/)){l(w[D],f.slice(D+2),f),P=!0;break}else l(w[D],o.strings[w[D]]?"":!0,f)}h=f.slice(-1)[0],!P&&h!=="-"&&(e[p+1]&&!/^(-|--)[^-]/.test(e[p+1])&&!o.bools[h]&&(!n[h]||!r(h))?(l(h,e[p+1],f),p+=1):e[p+1]&&/^(true|false)$/.test(e[p+1])?(l(h,e[p+1]==="true",f),p+=1):l(h,o.strings[h]?"":!0,f))}else if((!o.unknownFn||o.unknownFn(f)!==!1)&&a._.push(o.strings._||!Ya(f)?f:Number(f)),t.stopEarly){a._.push.apply(a._,e.slice(p+1));break}}return Object.keys(s).forEach(function(T){am(a,T.split("."))||(c(a,T.split("."),s[T]),(n[T]||[]).forEach(function(A){c(a,A.split("."),s[T])}))}),t["--"]?a["--"]=u.slice():u.forEach(function(T){a._.push(T)}),a};const Tc=sm(im),$="siyuan-sisyphus",cm="sisyphus",lm=`${$} — Direct command-line control for SiYuan Note
2
+ "use strict";var rm=Object.defineProperty;var sm=(e,t,o)=>t in e?rm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var ee=(e,t,o)=>sm(e,typeof t!="symbol"?t+"":t,o);const H=require("node:fs"),yo=require("node:os"),U=require("node:path"),am=require("node:readline"),im=require("node:url");var pr=typeof document<"u"?document.currentScript:null;function cm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function lm(e,t){var o=e;t.slice(0,-1).forEach(function(r){o=o[r]||{}});var n=t[t.length-1];return n in o}function Ga(e){return typeof e=="number"||/^0x[0-9a-f]+$/i.test(e)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function Ka(e,t){return t==="constructor"&&typeof e[t]=="function"||t==="__proto__"}var um=function(e,t){t||(t={});var o={bools:{},strings:{},unknownFn:null};typeof t.unknown=="function"&&(o.unknownFn=t.unknown),typeof t.boolean=="boolean"&&t.boolean?o.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach(function(A){o.bools[A]=!0});var n={};function r(A){return n[A].some(function(T){return o.bools[T]})}Object.keys(t.alias||{}).forEach(function(A){n[A]=[].concat(t.alias[A]),n[A].forEach(function(T){n[T]=[A].concat(n[A].filter(function(O){return T!==O}))})}),[].concat(t.string).filter(Boolean).forEach(function(A){o.strings[A]=!0,n[A]&&[].concat(n[A]).forEach(function(T){o.strings[T]=!0})});var s=t.default||{},a={_:[]};function i(A,T){return o.allBools&&/^--[^=]+$/.test(T)||o.strings[A]||o.bools[A]||n[A]}function c(A,T,O){for(var E=A,B=0;B<T.length-1;B++){var Z=T[B];if(Ka(E,Z))return;E[Z]===void 0&&(E[Z]={}),(E[Z]===Object.prototype||E[Z]===Number.prototype||E[Z]===String.prototype)&&(E[Z]={}),E[Z]===Array.prototype&&(E[Z]=[]),E=E[Z]}var _e=T[T.length-1];Ka(E,_e)||((E===Object.prototype||E===Number.prototype||E===String.prototype)&&(E={}),E===Array.prototype&&(E=[]),E[_e]===void 0||o.bools[_e]||typeof E[_e]=="boolean"?E[_e]=O:Array.isArray(E[_e])?E[_e].push(O):E[_e]=[E[_e],O])}function l(A,T,O){if(!(O&&o.unknownFn&&!i(A,O)&&o.unknownFn(O)===!1)){var E=!o.strings[A]&&Ga(T)?Number(T):T;c(a,A.split("."),E),(n[A]||[]).forEach(function(B){c(a,B.split("."),E)})}}Object.keys(o.bools).forEach(function(A){l(A,s[A]===void 0?!1:s[A])});var u=[];e.indexOf("--")!==-1&&(u=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var p=0;p<e.length;p++){var f=e[p],h,g;if(/^--.+=/.test(f)){var b=f.match(/^--([^=]+)=([\s\S]*)$/);h=b[1];var _=b[2];o.bools[h]&&(_=_!=="false"),l(h,_,f)}else if(/^--no-.+/.test(f))h=f.match(/^--no-(.+)/)[1],l(h,!1,f);else if(/^--.+/.test(f))h=f.match(/^--(.+)/)[1],g=e[p+1],g!==void 0&&!/^(-|--)[^-]/.test(g)&&!o.bools[h]&&!o.allBools&&(!n[h]||!r(h))?(l(h,g,f),p+=1):/^(true|false)$/.test(g)?(l(h,g==="true",f),p+=1):l(h,o.strings[h]?"":!0,f);else if(/^-[^-]+/.test(f)){for(var w=f.slice(1,-1).split(""),P=!1,D=0;D<w.length;D++){if(g=f.slice(D+2),g==="-"){l(w[D],g,f);continue}if(/[A-Za-z]/.test(w[D])&&g[0]==="="){l(w[D],g.slice(1),f),P=!0;break}if(/[A-Za-z]/.test(w[D])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(g)){l(w[D],g,f),P=!0;break}if(w[D+1]&&w[D+1].match(/\W/)){l(w[D],f.slice(D+2),f),P=!0;break}else l(w[D],o.strings[w[D]]?"":!0,f)}h=f.slice(-1)[0],!P&&h!=="-"&&(e[p+1]&&!/^(-|--)[^-]/.test(e[p+1])&&!o.bools[h]&&(!n[h]||!r(h))?(l(h,e[p+1],f),p+=1):e[p+1]&&/^(true|false)$/.test(e[p+1])?(l(h,e[p+1]==="true",f),p+=1):l(h,o.strings[h]?"":!0,f))}else if((!o.unknownFn||o.unknownFn(f)!==!1)&&a._.push(o.strings._||!Ga(f)?f:Number(f)),t.stopEarly){a._.push.apply(a._,e.slice(p+1));break}}return Object.keys(s).forEach(function(A){lm(a,A.split("."))||(c(a,A.split("."),s[A]),(n[A]||[]).forEach(function(T){c(a,T.split("."),s[A])}))}),t["--"]?a["--"]=u.slice():u.forEach(function(A){a._.push(A)}),a};const Cc=cm(um),$="siyuan-sisyphus",dm="sisyphus",pm=`${$} — Direct command-line control for SiYuan Note
3
3
 
4
4
  Agent bootstrap:
5
5
  If you are an AI model or coding agent, run \`${$} skill install\`
@@ -22,7 +22,7 @@ Tools:
22
22
  fs, notebook, document, block, av, file, search, tag, system, flashcard, extension, mascot
23
23
 
24
24
  Alias:
25
- ${cm} Same CLI, shorter command name
25
+ ${dm} Same CLI, shorter command name
26
26
 
27
27
  Global options:
28
28
  --config <file> Load config from <file> instead of ~/.siyuan-sisyphus/config.json
@@ -70,22 +70,28 @@ Flag naming:
70
70
  fs mv /Notebook/Old /Notebook/New.
71
71
  Boolean flags: use --flag, --flag=false, or --no-flag.
72
72
  For complex object/array values, use --<key>-json '<json>'.
73
- `,Pc=["json","debug","help","version"],Ec=["config","profile","url","token","bundle"];function um(e){const t=Tc(e,{boolean:Pc,string:Ec,alias:{h:"help",v:"version"},stopEarly:!1});if(t.help)return cr("show-help");if(t.version)return cr("version");const o=t._,n=o[0];if(n==="init")return{command:"init",rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(n==="list")return{command:"list",tool:typeof o[1]=="string"?o[1]:void 0,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(n==="help")return{command:"help",tool:typeof o[1]=="string"?o[1]:void 0,action:typeof o[2]=="string"?o[2]:void 0,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(n==="config"){const a=typeof o[1]=="string"?o[1]:void 0;if(!a||!["list","get","set","use"].includes(a))throw new Error(`Missing or invalid config action. Try "${$} config list", "${$} config get [name]", "${$} config set <name> --url <url>", or "${$} config use <name>".`);return{command:"config",configAction:a,configName:typeof o[2]=="string"?o[2]:void 0,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug}}if(n==="skill"){const a=typeof o[1]=="string"?o[1]:void 0;if(!a||!["list","read","install","uninstall"].includes(a))throw new Error(`Missing or invalid skill action. Try "${$} skill list", "${$} skill read [name]", "${$} skill install", or "${$} skill uninstall".`);const i=t.bundle||"cli";if(!["cli","mcp","all"].includes(i))throw new Error('Invalid skill bundle. Use "cli", "mcp", or "all".');return{command:"skill",skillAction:a,skillName:typeof o[2]=="string"?o[2]:void 0,bundle:i,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,target:typeof t.target=="string"?t.target:void 0,local:!!t.local,dryRun:!!t["dry-run"],json:!!t.json,debug:!!t.debug}}if(typeof n!="string"||!n)return cr("show-help");const r=typeof o[1]=="string"?o[1]:void 0;if(!r)throw new Error(`Missing action for tool "${n}". Try "${$} help ${n}".`);const s=dm(e);return{command:"dispatch",tool:n,action:r,rest:s,configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug}}function cr(e){return{command:e,rest:[],json:!1,debug:!1}}function dm(e){const t=[];let o=0;for(let n=0;n<e.length;n++){const r=e[n];if(!r.startsWith("-")){if(o++,o<=2)continue;t.push(r);continue}const s=r.indexOf("="),a=s===-1?r.replace(/^-+/,""):r.slice(r.startsWith("--")?2:1,s),i=a.startsWith("no-")?a.slice(3):a;if(Ec.includes(i)){s===-1&&n++;continue}Pc.includes(i)||i==="h"||i==="v"||t.push(r)}return t}function pm(){return lm}const xt="default",bs="http://127.0.0.1:6806";function ws(){return U.join(go.homedir(),".siyuan-sisyphus","config.json")}function fm(){return U.join(go.homedir(),".siyuan-mcp","config.json")}function Cc(e){return e??ws()}function no(e){const t=ym(e);if(!H.existsSync(t))return{};try{const o=H.readFileSync(t,"utf8"),n=JSON.parse(o);if(!n||typeof n!="object")return{};const r=n,s=bm(r.profiles);return{apiUrl:typeof r.apiUrl=="string"?r.apiUrl:void 0,token:typeof r.token=="string"?r.token:void 0,currentProfile:typeof r.currentProfile=="string"?r.currentProfile:void 0,profiles:s}}catch(o){const n=o instanceof Error?o.message:String(o);throw new Error(`[siyuan-sisyphus] Failed to load config at ${t}: ${n}`)}}function ht(e){const t=wm(e.profiles);if(Object.keys(t).length>0){const r=typeof e.currentProfile=="string"&&e.currentProfile?e.currentProfile:Ga(t);return{currentProfile:t[r]?r:Ga(t),profiles:t}}const o=typeof e.apiUrl=="string"&&e.apiUrl?e.apiUrl:bs,n=typeof e.token=="string"?e.token:"";return{currentProfile:xt,profiles:{[xt]:{apiUrl:o,token:n}}}}function hm(e,t={}){const o=ht(e),n=t.profile||o.currentProfile||xt,r=o.profiles[n];if(t.profile&&!r)throw new Error(`Unknown profile "${t.profile}". Available profiles: ${Object.keys(o.profiles).join(", ")||xt}.`);const s=r??o.profiles[o.currentProfile]??o.profiles[xt]??{},a=t.cliUrl||process.env.SIYUAN_API_URL||s.apiUrl||bs,i=t.cliToken||process.env.SIYUAN_TOKEN||s.token||"";return{apiUrl:a,token:i,profileName:n}}function mm(e){process.env.SIYUAN_API_URL=e.apiUrl,e.token?process.env.SIYUAN_TOKEN=e.token:delete process.env.SIYUAN_TOKEN}function ks(e,t){const o=Cc(t),n=U.dirname(o);return H.existsSync(n)||H.mkdirSync(n,{recursive:!0,mode:448}),H.writeFileSync(o,JSON.stringify(e,null,2)+`
74
- `,{mode:384}),o}function Rc(e,t,o,n={}){const r=ht(e),s=r.profiles[t]??{},a={currentProfile:n.makeCurrent?t:r.currentProfile,profiles:{...r.profiles,[t]:{apiUrl:o.apiUrl??s.apiUrl??bs,token:o.token??s.token??""}}};return a.profiles[a.currentProfile]||(a.currentProfile=t),a}function gm(e,t){const o=ht(e);if(!o.profiles[t])throw new Error(`Unknown profile "${t}".`);return{...o,currentProfile:t}}function ym(e){if(e)return e;const t=ws();if(H.existsSync(t))return t;const o=fm();return H.existsSync(o)?o:t}function bm(e){if(!e||typeof e!="object")return;const t={};for(const[o,n]of Object.entries(e)){if(!n||typeof n!="object")continue;const r=n,s=typeof r.apiUrl=="string"?r.apiUrl:void 0,a=typeof r.token=="string"?r.token:void 0;!s&&a===void 0||(t[o]={apiUrl:s,token:a})}return Object.keys(t).length>0?t:void 0}function wm(e){if(!e)return{};const t={};for(const[o,n]of Object.entries(e)){if(!o)continue;const r=typeof(n==null?void 0:n.apiUrl)=="string"&&n.apiUrl?n.apiUrl:void 0,s=typeof(n==null?void 0:n.token)=="string"?n.token:void 0;!r&&s===void 0||(t[o]={apiUrl:r,token:s})}return t}function Ga(e){return Object.keys(e)[0]??xt}function xc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oc(e){return xc(e)?typeof e.tool=="string"&&(Array.isArray(e.commonActions)||Array.isArray(e.advancedActions))&&e.action===void 0:!1}function Nc(e){return xc(e)?typeof e.tool=="string"&&typeof e.action=="string"&&(e.example!==void 0||Array.isArray(e.examples)||Array.isArray(e.shapes)):!1}const km=new Set(["action","as","only","optional","required","requires","mode"]);function qt(e,t){return t==="cli"?`--${vo(e)}`:e}function $c(e,t,o={},n){{const r=Object.entries(o).filter(([,s])=>s!==void 0).map(([s,a])=>Pm(s,a));return[$,e,vo(t),...r].join(" ").trim()}}function fe(e,t){if(!e)return e;let o=e;return o=o.replace(/siyuan:\/\/help\/action\/([a-z_]+)\/([a-z_]+)/g,(n,r,s)=>`${$} ${r} ${vo(s)}`),o=o.replace(/siyuan:\/\/help\/tool-overview/g,`${$} list`),o=o.replace(/siyuan:\/\/help\/examples/g,`${$} help <tool> <action>`),o=o.replace(/siyuan:\/\/help\/ai-layout-guide/g,`${$} help document create`),o=o.replace(/\b([a-z]+)\(action=["”“]([a-z_]+)["”“](?:,\s*([^)]*))?\)/g,(n,r,s,a)=>{const i=Am(a);if(s==="help"){const c=typeof i.topic=="string"?zc(i.topic).trim():"";return c?`${$} help ${r} ${vo(c)}`:`${$} help ${r}`}return $c(r,s,i)}),o=o.replace(/\b([A-Za-z][A-Za-z0-9_]*)(\s*\+\s*[A-Za-z][A-Za-z0-9_]*)+\b/g,n=>Sm(n,"+")),o=o.replace(/\brequires:\s*([A-Za-z][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z][A-Za-z0-9_]*)*)/g,(n,r)=>`requires: ${r.split(/\s*,\s*/).map(s=>qt(s,"cli")).join(", ")}`),/^[A-Za-z][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z][A-Za-z0-9_]*)+$/.test(o)?o.split(/\s*,\s*/).map(n=>qt(n,"cli")).join(", "):o==="action only"?"command only":o}function Mc(e,t){if(!Ve(e))return e;if(Nc(e)){const o={...e};return typeof o.hint=="string"&&(o.hint=fe(o.hint)),Array.isArray(o.shapes)&&(o.shapes=o.shapes.map(n=>typeof n=="string"?fe(n):n)),o.requiredFields=Im(o.requiredFields,t),o.example=_s(o.tool,o.action,o.example),Array.isArray(o.examples)&&(o.examples=o.examples.map(n=>vm(o.tool,o.action,n))),Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?fe(n):n)),typeof o.fullDocResource=="string"&&(o.fullDocResource=`${$} help ${o.tool} ${vo(String(o.action))}`),o}if(Oc(e)){const o={...e};return Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?fe(n):n)),Ve(o.actionSummaries)&&(o.actionSummaries=Object.fromEntries(Object.entries(o.actionSummaries).map(([n,r])=>[n,typeof r=="string"?fe(r):r]))),Ve(o.actions)&&(o.actions=Object.fromEntries(Object.entries(o.actions).map(([n,r])=>!Ve(r)||typeof r.hint!="string"?[n,r]:[n,{...r,hint:fe(r.hint)}]))),typeof o.detailsHint=="string"&&(o.detailsHint=fe(o.detailsHint)),Array.isArray(o.helpResources)&&(o.helpResources=o.helpResources.map(n=>typeof n=="string"?fe(n):n)),o}if(Ve(e.error)){const o=e.error;return{...e,error:{...o,...typeof o.hint=="string"?{hint:fe(o.hint)}:{},...typeof o.details=="string"?{details:fe(o.details)}:{}}}}return _m(e)}function _m(e,t){const o={...e};for(const n of["hint","detailsHint"])typeof o[n]=="string"&&(o[n]=fe(o[n]));for(const n of["guidance","hints"])Array.isArray(o[n])&&(o[n]=o[n].map(r=>typeof r=="string"?fe(r):r));return o}function _s(e,t,o,n){if(typeof e!="string"||typeof t!="string")return o;if(Array.isArray(o))return o.map(s=>_s(e,t,s));if(!Ve(o))return typeof o=="string"?fe(o):o;const r={...o};return delete r.action,$c(e,t,r)}function vm(e,t,o,n){if(!Ve(o))return o;const r={...o};return typeof r.description=="string"&&(r.description=fe(r.description)),r.mcp=_s(e,t,r.mcp),r}function Im(e,t){return Array.isArray(e)&&e.every(o=>typeof o=="string")?e.map(o=>qt(o,t)):Array.isArray(e)?e.map(o=>Array.isArray(o)?o.map(n=>typeof n=="string"?qt(n,t):n):o):e}function Sm(e,t){const o=/\s*\+\s*/,n=e.split(o);return n.some(r=>!Dm(r))?e:n.map(r=>qt(r,"cli")).join(` ${t} `)}function Dm(e){const t=e.trim();return!t||km.has(t.toLowerCase())?!1:/^[A-Za-z][A-Za-z0-9_]*$/.test(t)}function Am(e){if(!e)return{};const t={};for(const o of Tm(e,",")){const n=o.trim();if(!n)continue;const r=n.indexOf("=");if(r<=0)continue;const s=n.slice(0,r).trim(),a=n.slice(r+1).trim();s&&(t[s]=zc(a))}return t}function Tm(e,t){const o=[];let n="",r=!1,s=!1,a=!1,i=0,c=0,l=0;for(const u of e){if(u==="'"&&!s&&!a){r=!r,n+=u;continue}if(u==='"'&&!r&&!a){s=!s,n+=u;continue}if((u==="“"||u==="”")&&!r&&!s){a=!a,n+=u;continue}if(!r&&!s&&!a&&(u==="["&&i++,u==="]"&&(i=Math.max(0,i-1)),u==="{"&&c++,u==="}"&&(c=Math.max(0,c-1)),u==="("&&l++,u===")"&&(l=Math.max(0,l-1)),u===t&&i===0&&c===0&&l===0)){o.push(n),n="";continue}n+=u}return n&&o.push(n),o}function Pm(e,t){const o=qt(e,"cli");return Array.isArray(t)||Ve(t)?`${o}-json '${JSON.stringify(t)}'`:typeof t=="boolean"?`${o} ${t?"true":"false"}`:typeof t=="number"?`${o} ${t}`:`${o} ${Em(String(t))}`}function Em(e){return e==="..."||/^<[^>]+>$/.test(e)||/^(true|false|null|-?\d+(\.\d+)?)$/i.test(e)||/^[A-Za-z0-9_./:-]+$/.test(e)?e:JSON.stringify(e)}function zc(e){return e.replace(/^["“”']/,"").replace(/["“”']$/,"")}function vo(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const re={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m",bold:"\x1B[1m"},Fc=["id","name","title","path","hpath","notebook","box","rootID","blockID","docID","avID","deckID","cardID","status","version","count","total","page","pageCount"],Cm=new Map(Fc.map((e,t)=>[e,t]));function Rm(e){return!!e.isTTY}function Ue(e,t,o){return Rm(e)?`${t}${o}${re.reset}`:o}function qc(e){switch(e){case"success":return re.green+re.bold;case"warning":return re.yellow+re.bold;case"error":return re.red+re.bold;case"muted":return re.dim;case"info":default:return re.cyan+re.bold}}function ne(e,t=""){e.write(t.endsWith(`
73
+ `,Ec=["json","debug","help","version"],Rc=["config","profile","url","token","bundle"];function fm(e){const t=Cc(e,{boolean:Ec,string:Rc,alias:{h:"help",v:"version"},stopEarly:!1});if(t.help)return fr("show-help");if(t.version)return fr("version");const o=t._,n=o[0];if(n==="init")return{command:"init",rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(n==="list")return{command:"list",tool:typeof o[1]=="string"?o[1]:void 0,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(n==="help")return{command:"help",tool:typeof o[1]=="string"?o[1]:void 0,action:typeof o[2]=="string"?o[2]:void 0,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(n==="config"){const a=typeof o[1]=="string"?o[1]:void 0;if(!a||!["list","get","set","use"].includes(a))throw new Error(`Missing or invalid config action. Try "${$} config list", "${$} config get [name]", "${$} config set <name> --url <url>", or "${$} config use <name>".`);return{command:"config",configAction:a,configName:typeof o[2]=="string"?o[2]:void 0,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug}}if(n==="skill"){const a=typeof o[1]=="string"?o[1]:void 0;if(!a||!["list","read","install","uninstall"].includes(a))throw new Error(`Missing or invalid skill action. Try "${$} skill list", "${$} skill read [name]", "${$} skill install", or "${$} skill uninstall".`);const i=t.bundle||"cli";if(!["cli","mcp","all"].includes(i))throw new Error('Invalid skill bundle. Use "cli", "mcp", or "all".');return{command:"skill",skillAction:a,skillName:typeof o[2]=="string"?o[2]:void 0,bundle:i,rest:[],configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,target:typeof t.target=="string"?t.target:void 0,local:!!t.local,dryRun:!!t["dry-run"],json:!!t.json,debug:!!t.debug}}if(typeof n!="string"||!n)return fr("show-help");const r=typeof o[1]=="string"?o[1]:void 0;if(!r)throw new Error(`Missing action for tool "${n}". Try "${$} help ${n}".`);const s=hm(e);return{command:"dispatch",tool:n,action:r,rest:s,configPath:t.config||void 0,profile:t.profile||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug}}function fr(e){return{command:e,rest:[],json:!1,debug:!1}}function hm(e){const t=[];let o=0;for(let n=0;n<e.length;n++){const r=e[n];if(!r.startsWith("-")){if(o++,o<=2)continue;t.push(r);continue}const s=r.indexOf("="),a=s===-1?r.replace(/^-+/,""):r.slice(r.startsWith("--")?2:1,s),i=a.startsWith("no-")?a.slice(3):a;if(Rc.includes(i)){s===-1&&n++;continue}Ec.includes(i)||i==="h"||i==="v"||t.push(r)}return t}function mm(){return pm}const Ot="default",ks="http://127.0.0.1:6806";function _s(){return U.join(yo.homedir(),".siyuan-sisyphus","config.json")}function gm(){return U.join(yo.homedir(),".siyuan-mcp","config.json")}function xc(e){return e??_s()}function ro(e){const t=km(e);if(!H.existsSync(t))return{};try{const o=H.readFileSync(t,"utf8"),n=JSON.parse(o);if(!n||typeof n!="object")return{};const r=n,s=_m(r.profiles);return{apiUrl:typeof r.apiUrl=="string"?r.apiUrl:void 0,token:typeof r.token=="string"?r.token:void 0,currentProfile:typeof r.currentProfile=="string"?r.currentProfile:void 0,profiles:s}}catch(o){const n=o instanceof Error?o.message:String(o);throw new Error(`[siyuan-sisyphus] Failed to load config at ${t}: ${n}`)}}function ht(e){const t=vm(e.profiles);if(Object.keys(t).length>0){const r=typeof e.currentProfile=="string"&&e.currentProfile?e.currentProfile:Ja(t);return{currentProfile:t[r]?r:Ja(t),profiles:t}}const o=typeof e.apiUrl=="string"&&e.apiUrl?e.apiUrl:ks,n=typeof e.token=="string"?e.token:"";return{currentProfile:Ot,profiles:{[Ot]:{apiUrl:o,token:n}}}}function ym(e,t={}){const o=ht(e),n=t.profile||o.currentProfile||Ot,r=o.profiles[n];if(t.profile&&!r)throw new Error(`Unknown profile "${t.profile}". Available profiles: ${Object.keys(o.profiles).join(", ")||Ot}.`);const s=r??o.profiles[o.currentProfile]??o.profiles[Ot]??{},a=t.cliUrl||process.env.SIYUAN_API_URL||s.apiUrl||ks,i=t.cliToken||process.env.SIYUAN_TOKEN||s.token||"";return{apiUrl:a,token:i,profileName:n}}function bm(e){process.env.SIYUAN_API_URL=e.apiUrl,e.token?process.env.SIYUAN_TOKEN=e.token:delete process.env.SIYUAN_TOKEN}function vs(e,t){const o=xc(t),n=U.dirname(o);return H.existsSync(n)||H.mkdirSync(n,{recursive:!0,mode:448}),H.writeFileSync(o,JSON.stringify(e,null,2)+`
74
+ `,{mode:384}),o}function Oc(e,t,o,n={}){const r=ht(e),s=r.profiles[t]??{},a={currentProfile:n.makeCurrent?t:r.currentProfile,profiles:{...r.profiles,[t]:{apiUrl:o.apiUrl??s.apiUrl??ks,token:o.token??s.token??""}}};return a.profiles[a.currentProfile]||(a.currentProfile=t),a}function wm(e,t){const o=ht(e);if(!o.profiles[t])throw new Error(`Unknown profile "${t}".`);return{...o,currentProfile:t}}function km(e){if(e)return e;const t=_s();if(H.existsSync(t))return t;const o=gm();return H.existsSync(o)?o:t}function _m(e){if(!e||typeof e!="object")return;const t={};for(const[o,n]of Object.entries(e)){if(!n||typeof n!="object")continue;const r=n,s=typeof r.apiUrl=="string"?r.apiUrl:void 0,a=typeof r.token=="string"?r.token:void 0;!s&&a===void 0||(t[o]={apiUrl:s,token:a})}return Object.keys(t).length>0?t:void 0}function vm(e){if(!e)return{};const t={};for(const[o,n]of Object.entries(e)){if(!o)continue;const r=typeof(n==null?void 0:n.apiUrl)=="string"&&n.apiUrl?n.apiUrl:void 0,s=typeof(n==null?void 0:n.token)=="string"?n.token:void 0;!r&&s===void 0||(t[o]={apiUrl:r,token:s})}return t}function Ja(e){return Object.keys(e)[0]??Ot}function Nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $c(e){return Nc(e)?typeof e.tool=="string"&&(Array.isArray(e.commonActions)||Array.isArray(e.advancedActions))&&e.action===void 0:!1}function Mc(e){return Nc(e)?typeof e.tool=="string"&&typeof e.action=="string"&&(e.example!==void 0||Array.isArray(e.examples)||Array.isArray(e.shapes)):!1}const Im=new Set(["action","as","only","optional","required","requires","mode"]);function Lt(e,t){return t==="cli"?`--${So(e)}`:e}function zc(e,t,o={},n){{const r=Object.entries(o).filter(([,s])=>s!==void 0).map(([s,a])=>Rm(s,a));return[$,e,So(t),...r].join(" ").trim()}}function fe(e,t){if(!e)return e;let o=e;return o=o.replace(/siyuan:\/\/help\/action\/([a-z_]+)\/([a-z_]+)/g,(n,r,s)=>`${$} ${r} ${So(s)}`),o=o.replace(/siyuan:\/\/help\/tool-overview/g,`${$} list`),o=o.replace(/siyuan:\/\/help\/examples/g,`${$} help <tool> <action>`),o=o.replace(/siyuan:\/\/help\/ai-layout-guide/g,`${$} help document create`),o=o.replace(/\b([a-z]+)\(action=["”“]([a-z_]+)["”“](?:,\s*([^)]*))?\)/g,(n,r,s,a)=>{const i=Cm(a);if(s==="help"){const c=typeof i.topic=="string"?qc(i.topic).trim():"";return c?`${$} help ${r} ${So(c)}`:`${$} help ${r}`}return zc(r,s,i)}),o=o.replace(/\b([A-Za-z][A-Za-z0-9_]*)(\s*\+\s*[A-Za-z][A-Za-z0-9_]*)+\b/g,n=>Am(n,"+")),o=o.replace(/\brequires:\s*([A-Za-z][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z][A-Za-z0-9_]*)*)/g,(n,r)=>`requires: ${r.split(/\s*,\s*/).map(s=>Lt(s,"cli")).join(", ")}`),/^[A-Za-z][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z][A-Za-z0-9_]*)+$/.test(o)?o.split(/\s*,\s*/).map(n=>Lt(n,"cli")).join(", "):o==="action only"?"command only":o}function Fc(e,t){if(!Ve(e))return e;if(Mc(e)){const o={...e};return typeof o.hint=="string"&&(o.hint=fe(o.hint)),Array.isArray(o.shapes)&&(o.shapes=o.shapes.map(n=>typeof n=="string"?fe(n):n)),o.requiredFields=Tm(o.requiredFields,t),o.example=Is(o.tool,o.action,o.example),Array.isArray(o.examples)&&(o.examples=o.examples.map(n=>Dm(o.tool,o.action,n))),Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?fe(n):n)),typeof o.fullDocResource=="string"&&(o.fullDocResource=`${$} help ${o.tool} ${So(String(o.action))}`),o}if($c(e)){const o={...e};return Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?fe(n):n)),Ve(o.actionSummaries)&&(o.actionSummaries=Object.fromEntries(Object.entries(o.actionSummaries).map(([n,r])=>[n,typeof r=="string"?fe(r):r]))),Ve(o.actions)&&(o.actions=Object.fromEntries(Object.entries(o.actions).map(([n,r])=>!Ve(r)||typeof r.hint!="string"?[n,r]:[n,{...r,hint:fe(r.hint)}]))),typeof o.detailsHint=="string"&&(o.detailsHint=fe(o.detailsHint)),Array.isArray(o.helpResources)&&(o.helpResources=o.helpResources.map(n=>typeof n=="string"?fe(n):n)),o}if(Ve(e.error)){const o=e.error;return{...e,error:{...o,...typeof o.hint=="string"?{hint:fe(o.hint)}:{},...typeof o.details=="string"?{details:fe(o.details)}:{}}}}return Sm(e)}function Sm(e,t){const o={...e};for(const n of["hint","detailsHint"])typeof o[n]=="string"&&(o[n]=fe(o[n]));for(const n of["guidance","hints"])Array.isArray(o[n])&&(o[n]=o[n].map(r=>typeof r=="string"?fe(r):r));return o}function Is(e,t,o,n){if(typeof e!="string"||typeof t!="string")return o;if(Array.isArray(o))return o.map(s=>Is(e,t,s));if(!Ve(o))return typeof o=="string"?fe(o):o;const r={...o};return delete r.action,zc(e,t,r)}function Dm(e,t,o,n){if(!Ve(o))return o;const r={...o};return typeof r.description=="string"&&(r.description=fe(r.description)),r.mcp=Is(e,t,r.mcp),r}function Tm(e,t){return Array.isArray(e)&&e.every(o=>typeof o=="string")?e.map(o=>Lt(o,t)):Array.isArray(e)?e.map(o=>Array.isArray(o)?o.map(n=>typeof n=="string"?Lt(n,t):n):o):e}function Am(e,t){const o=/\s*\+\s*/,n=e.split(o);return n.some(r=>!Pm(r))?e:n.map(r=>Lt(r,"cli")).join(` ${t} `)}function Pm(e){const t=e.trim();return!t||Im.has(t.toLowerCase())?!1:/^[A-Za-z][A-Za-z0-9_]*$/.test(t)}function Cm(e){if(!e)return{};const t={};for(const o of Em(e,",")){const n=o.trim();if(!n)continue;const r=n.indexOf("=");if(r<=0)continue;const s=n.slice(0,r).trim(),a=n.slice(r+1).trim();s&&(t[s]=qc(a))}return t}function Em(e,t){const o=[];let n="",r=!1,s=!1,a=!1,i=0,c=0,l=0;for(const u of e){if(u==="'"&&!s&&!a){r=!r,n+=u;continue}if(u==='"'&&!r&&!a){s=!s,n+=u;continue}if((u==="“"||u==="”")&&!r&&!s){a=!a,n+=u;continue}if(!r&&!s&&!a&&(u==="["&&i++,u==="]"&&(i=Math.max(0,i-1)),u==="{"&&c++,u==="}"&&(c=Math.max(0,c-1)),u==="("&&l++,u===")"&&(l=Math.max(0,l-1)),u===t&&i===0&&c===0&&l===0)){o.push(n),n="";continue}n+=u}return n&&o.push(n),o}function Rm(e,t){const o=Lt(e,"cli");return Array.isArray(t)||Ve(t)?`${o}-json '${JSON.stringify(t)}'`:typeof t=="boolean"?`${o} ${t?"true":"false"}`:typeof t=="number"?`${o} ${t}`:`${o} ${xm(String(t))}`}function xm(e){return e==="..."||/^<[^>]+>$/.test(e)||/^(true|false|null|-?\d+(\.\d+)?)$/i.test(e)||/^[A-Za-z0-9_./:-]+$/.test(e)?e:JSON.stringify(e)}function qc(e){return e.replace(/^["“”']/,"").replace(/["“”']$/,"")}function So(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const se={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m",bold:"\x1B[1m"},Lc=["id","name","title","path","hpath","notebook","box","rootID","blockID","docID","avID","deckID","cardID","status","version","count","total","page","pageCount"],Om=new Map(Lc.map((e,t)=>[e,t]));function Nm(e){return!!e.isTTY}function Ue(e,t,o){return Nm(e)?`${t}${o}${se.reset}`:o}function Bc(e){switch(e){case"success":return se.green+se.bold;case"warning":return se.yellow+se.bold;case"error":return se.red+se.bold;case"muted":return se.dim;case"info":default:return se.cyan+se.bold}}function re(e,t=""){e.write(t.endsWith(`
75
75
  `)?t:`${t}
76
- `)}function Je(e,t=process.stdout){ne(t,Ue(t,re.bold,e))}function ge(e,t,o=process.stdout){const n=e==="success"?"✓":e==="warning"?"!":e==="error"?"✗":"•";ne(o,Ue(o,qc(e),`${n} ${t}`))}function Ka(e,t=process.stdout){ne(t,Ue(t,re.dim,e))}function oe(e,t=process.stdout){ne(t),ne(t,Ue(t,re.cyan+re.bold,e))}function Pe(e,t=process.stdout,o="info"){for(const n of e)ne(t,`${Ue(t,qc(o)," •")} ${n}`)}function Me(e,t=process.stdout){if(e.length===0)return;const o=e.map(r=>gn(r.key)),n=Math.max(...o.map(r=>r.length));for(let r=0;r<e.length;r++){const s=o[r].padEnd(n);ne(t,` ${Ue(t,re.bold,`${s}:`)} ${yn(e[r].value)}`)}}function ve(e,t,o=process.stdout){ne(o,`${Ue(o,re.dim+re.bold,`${e}:`)} ${t}`)}function Ye(e,t={}){const o=process.stderr,n=fe(e instanceof Error?e.message:String(e));ge("error",n,o),t.exitHint&&ve("Hint",fe(t.exitHint),o),t.debug&&e instanceof Error&&e.stack&&ne(o,e.stack)}function Io(e,t){var r;const o=((r=e.content[0])==null?void 0:r.text)??"";let n;try{n=o?JSON.parse(o):null}catch{return process.stdout.write(o),o.endsWith(`
76
+ `)}function Je(e,t=process.stdout){re(t,Ue(t,se.bold,e))}function ge(e,t,o=process.stdout){const n=e==="success"?"✓":e==="warning"?"!":e==="error"?"✗":"•";re(o,Ue(o,Bc(e),`${n} ${t}`))}function Qa(e,t=process.stdout){re(t,Ue(t,se.dim,e))}function ne(e,t=process.stdout){re(t),re(t,Ue(t,se.cyan+se.bold,e))}function Pe(e,t=process.stdout,o="info"){for(const n of e)re(t,`${Ue(t,Bc(o)," •")} ${n}`)}function Me(e,t=process.stdout){if(e.length===0)return;const o=e.map(r=>_n(r.key)),n=Math.max(...o.map(r=>r.length));for(let r=0;r<e.length;r++){const s=o[r].padEnd(n);re(t,` ${Ue(t,se.bold,`${s}:`)} ${vn(e[r].value)}`)}}function ve(e,t,o=process.stdout){re(o,`${Ue(o,se.dim+se.bold,`${e}:`)} ${t}`)}function Ye(e,t={}){const o=process.stderr,n=fe(e instanceof Error?e.message:String(e));ge("error",n,o),t.exitHint&&ve("Hint",fe(t.exitHint),o),t.debug&&e instanceof Error&&e.stack&&re(o,e.stack)}function Do(e,t){var r;const o=((r=e.content[0])==null?void 0:r.text)??"";let n;try{n=o?JSON.parse(o):null}catch{return process.stdout.write(o),o.endsWith(`
77
77
  `)||process.stdout.write(`
78
- `),e.isError?1:0}return n=Mc(n,"cli"),t.json?xm(n,e.isError):e.isError?(Om(n),1):(Nm(n),0)}function Ja(e){var n;if(e.isError)return null;const t=((n=e.content[0])==null?void 0:n.text)??"";let o;try{o=t?JSON.parse(t):null}catch{return null}return o=Mc(o,"cli"),!qe(o)||!Array.isArray(o.data)||typeof o.total!="number"||typeof o.page!="number"||typeof o.pageCount!="number"?null:{page:o.page,pageCount:o.pageCount,hasNextPage:typeof o.hasNextPage=="boolean"?o.hasNextPage:o.page<o.pageCount}}function xm(e,t){return process.stdout.write(JSON.stringify(e)+`
79
- `),t?1:0}function Om(e){const t=process.stderr;if(qe(e)&&qe(e.error)){const o=e.error,n=typeof o.type=="string"?o.type:"error",r=typeof o.message=="string"?o.message:"Unknown error";if(ge("error",`[${n}] ${r}`,t),Array.isArray(o.fields)){const s=o.fields.filter(qe).map(a=>{const i=typeof a.path=="string"&&a.path?a.path:"(field)",c=typeof a.message=="string"?a.message:"Invalid value";return`${Ue(t,re.yellow+re.bold,i)} — ${c}`});s.length>0&&(oe("Fields",t),Pe(s,t,"warning"))}typeof o.hint=="string"&&o.hint&&(oe("Hint",t),ne(t,` ${o.hint}`)),typeof o.details=="string"&&o.details&&(oe("Details",t),ne(t,Mn(o.details,2)));return}ge("error",`Error: ${mt(e)}`,t)}function Nm(e){const t=process.stdout;if(typeof e=="string"){t.write(e),e.endsWith(`
78
+ `),e.isError?1:0}return n=Fc(n,"cli"),t.json?$m(n,e.isError):e.isError?(Mm(n),1):(zm(n),0)}function Xa(e){var n;if(e.isError)return null;const t=((n=e.content[0])==null?void 0:n.text)??"";let o;try{o=t?JSON.parse(t):null}catch{return null}return o=Fc(o,"cli"),!qe(o)||!Array.isArray(o.data)||typeof o.total!="number"||typeof o.page!="number"||typeof o.pageCount!="number"?null:{page:o.page,pageCount:o.pageCount,hasNextPage:typeof o.hasNextPage=="boolean"?o.hasNextPage:o.page<o.pageCount}}function $m(e,t){return process.stdout.write(JSON.stringify(e)+`
79
+ `),t?1:0}function Mm(e){const t=process.stderr;if(qe(e)&&qe(e.error)){const o=e.error,n=typeof o.type=="string"?o.type:"error",r=typeof o.message=="string"?o.message:"Unknown error";if(ge("error",`[${n}] ${r}`,t),Array.isArray(o.fields)){const s=o.fields.filter(qe).map(a=>{const i=typeof a.path=="string"&&a.path?a.path:"(field)",c=typeof a.message=="string"?a.message:"Invalid value";return`${Ue(t,se.yellow+se.bold,i)} — ${c}`});s.length>0&&(ne("Fields",t),Pe(s,t,"warning"))}typeof o.hint=="string"&&o.hint&&(ne("Hint",t),re(t,` ${o.hint}`)),typeof o.details=="string"&&o.details&&(ne("Details",t),re(t,Bn(o.details,2)));return}ge("error",`Error: ${mt(e)}`,t)}function zm(e){const t=process.stdout;if(typeof e=="string"){t.write(e),e.endsWith(`
80
80
  `)||t.write(`
81
- `);return}if(e==null){ge("success","Done",t);return}if(Array.isArray(e)){ge("info",`${e.length} item${e.length===1?"":"s"}`,t),vs(e,"Items",t);return}if(!qe(e)){ne(t,mt(e));return}const o=e;if(Oc(o)){Fm(o,t);return}if(Nc(o)){qm(o,t);return}const n=o;if(Array.isArray(n.data)&&typeof n.total=="number"&&typeof n.page=="number"){$m(o,t);return}Mm(o,t)}function $m(e,t){const o=Array.isArray(e.data)?e.data:[],n=typeof e.total=="number"?e.total:o.length,r=typeof e.page=="number"?e.page:1,s=typeof e.pageCount=="number"?e.pageCount:"?",a=typeof e.pageSize=="number"?e.pageSize:void 0;ge("success",`${o.length} of ${n} items · page ${r}/${s}`,t),Me([...a!==void 0?[{key:"pageSize",value:a}]:[],...typeof e.hasNextPage=="boolean"?[{key:"hasNextPage",value:e.hasNextPage}]:[]],t),vs(o,"Items",t,{maxItems:o.length}),e.hasNextPage&&(oe("Next Step",t),ve("Tip","More pages are available. In a TTY, press Enter/n for next page, or re-run with `--page <n>`.",t))}function Mm(e,t){const o=e.success===!0,n=typeof e.message=="string"?e.message:void 0,r=Object.entries(e).filter(([c])=>c!=="success");o?ge("success",n??"Success",t):n&&ge("info",n,t);const s=Bc(r,new Set(n?["message"]:[]));s.length>0&&Me(s,t);const a=new Set(s.map(c=>c.key));n&&a.add("message");const i=r.filter(([c])=>!a.has(c));if(i.length===0){!o&&!n&&s.length===0&&ne(t,mt(e));return}for(const[c,l]of i)zm(c,l,t)}function zm(e,t,o){if(t!==void 0){if(Array.isArray(t)){vs(t,gn(e),o);return}if(oe(gn(e),o),qe(t)){const n=Lm(t);if(n.length>0&&n.length===Object.keys(t).length){Me(n,o);return}ne(o,Mn(mt(t),2));return}ne(o,` ${yn(t)}`)}}function vs(e,t,o,n={}){if(e.length===0){oe(t,o),Ka(" No items.",o);return}oe(t,o);const r=n.maxItems??10,s=e.slice(0,r);for(const a of s){const i=Um(a);if(i){ne(o,` • ${i}`);continue}ne(o,Mn(mt(a),2))}e.length>s.length&&Ka(` … ${e.length-s.length} more item(s) not shown. Use --json for full output.`,o)}function Fm(e,t){const o=typeof e.tool=="string"?e.tool:"tool";Je(`${o} tool`,t);const n=At(e.guidance);n.length>0&&(oe("Guidance",t),Pe(n,t)),Qa("Common Actions",At(e.commonActions),e.actionSummaries,t),Qa("Advanced Actions",At(e.advancedActions),e.actionSummaries,t);const r=At(e.requiresConfirmation);r.length>0&&(oe("Confirmation",t),Pe(r.map(s=>`${s} requires explicit confirmation.`),t,"warning")),typeof e.detailsHint=="string"&&e.detailsHint&&(oe("Next Step",t),ve("Tip",e.detailsHint,t))}function qm(e,t){const o=typeof e.tool=="string"?e.tool:"tool",n=typeof e.action=="string"?e.action:"help";Je(`${o} ${n}`,t),typeof e.hint=="string"&&e.hint&&ge("info",e.hint,t);const r=At(e.shapes);r.length>0&&(oe("Accepted Shapes",t),Pe(r,t));const s=jm(e.requiredFields);s.length>0&&(oe("Required Fields",t),Pe(s,t));const a=Array.isArray(e.examples)?e.examples:[];a.length>0?(oe("Examples",t),Bm(a,t)):e.example!==void 0&&(oe("Example",t),Pr(e.example,t));const i=At(e.guidance);i.length>0&&(oe("Guidance",t),Pe(i,t)),e.requiresConfirmation===!0&&(oe("Safety",t),Pe(["This action requires explicit confirmation."],t,"warning")),typeof e.fullDocResource=="string"&&e.fullDocResource&&(oe("Reference",t),ve("Resource",e.fullDocResource,t))}function Qa(e,t,o,n){if(t.length===0)return;const r=qe(o)?o:{};oe(e,n),Pe(t.map(s=>{const a=typeof r[s]=="string"?String(r[s]):"";return a?`${s} — ${a}`:s}),n)}function Pr(e,t){if(typeof e=="string"){ne(t,` ${e}`);return}if(Array.isArray(e)&&e.every(o=>typeof o=="string")){Pe(e,t);return}ne(t,Mn(mt(e),2))}function Bm(e,t){for(const o of e){if(!qe(o)){Pr(o,t);continue}const n=typeof o.title=="string"?o.title:"Example";ne(t,` ${Ue(t,re.bold,n)}`),typeof o.description=="string"&&o.description&&ne(t,` ${o.description}`);const r=o.mcp??o.command??o.example;r!==void 0&&Pr(r,t)}}function Bc(e,t=new Set){return e.filter(([n,r])=>!t.has(n)&&Is(r)).map(([n,r])=>({key:n,value:r})).sort((n,r)=>Xa(n.key)-Xa(r.key)||n.key.localeCompare(r.key)).slice(0,8)}function Xa(e){return Cm.get(e)??Fc.length+100}function Lm(e){return Object.entries(e).filter(([,t])=>Is(t)).map(([t,o])=>({key:t,value:o}))}function Um(e){if(Is(e))return yn(e);if(!qe(e))return null;const t=Bc(Object.entries(e));return t.length===0?null:t.slice(0,4).map(o=>`${gn(o.key)}: ${yn(o.value)}`).join(" · ")}function jm(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?[e.join(", ")]:Array.isArray(e)?e.filter(t=>Array.isArray(t)&&t.every(o=>typeof o=="string")).map(t=>t.join(", ")):[]}function At(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function mt(e){return JSON.stringify(e,null,2)}function gn(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map(t=>{const o=t.toLowerCase();return["id","ids","url","api","sql","json","ocr","html"].includes(o)?o.toUpperCase():o.charAt(0).toUpperCase()+o.slice(1)}).join(" ")}function yn(e){return typeof e=="string"?Hm(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":mt(e)}function Hm(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Mn(e,t){const o=" ".repeat(t);return e.split(`
81
+ `);return}if(e==null){ge("success","Done",t);return}if(Array.isArray(e)){ge("info",`${e.length} item${e.length===1?"":"s"}`,t),Ss(e,"Items",t);return}if(!qe(e)){re(t,mt(e));return}const o=e;if($c(o)){Bm(o,t);return}if(Mc(o)){Um(o,t);return}const n=o;if(Array.isArray(n.data)&&typeof n.total=="number"&&typeof n.page=="number"){Fm(o,t);return}qm(o,t)}function Fm(e,t){const o=Array.isArray(e.data)?e.data:[],n=typeof e.total=="number"?e.total:o.length,r=typeof e.page=="number"?e.page:1,s=typeof e.pageCount=="number"?e.pageCount:"?",a=typeof e.pageSize=="number"?e.pageSize:void 0;ge("success",`${o.length} of ${n} items · page ${r}/${s}`,t),Me([...a!==void 0?[{key:"pageSize",value:a}]:[],...typeof e.hasNextPage=="boolean"?[{key:"hasNextPage",value:e.hasNextPage}]:[]],t),Ss(o,"Items",t,{maxItems:o.length}),e.hasNextPage&&(ne("Next Step",t),ve("Tip","More pages are available. In a TTY, press Enter/n for next page, or re-run with `--page <n>`.",t))}function qm(e,t){const o=e.success===!0,n=typeof e.message=="string"?e.message:void 0,r=Object.entries(e).filter(([c])=>c!=="success");o?ge("success",n??"Success",t):n&&ge("info",n,t);const s=Uc(r,new Set(n?["message"]:[]));s.length>0&&Me(s,t);const a=new Set(s.map(c=>c.key));n&&a.add("message");const i=r.filter(([c])=>!a.has(c));if(i.length===0){!o&&!n&&s.length===0&&re(t,mt(e));return}for(const[c,l]of i)Lm(c,l,t)}function Lm(e,t,o){if(t!==void 0){if(Array.isArray(t)){Ss(t,_n(e),o);return}if(ne(_n(e),o),qe(t)){const n=Hm(t);if(n.length>0&&n.length===Object.keys(t).length){Me(n,o);return}re(o,Bn(mt(t),2));return}re(o,` ${vn(t)}`)}}function Ss(e,t,o,n={}){if(e.length===0){ne(t,o),Qa(" No items.",o);return}ne(t,o);const r=n.maxItems??10,s=e.slice(0,r);for(const a of s){const i=Vm(a);if(i){re(o,` • ${i}`);continue}re(o,Bn(mt(a),2))}e.length>s.length&&Qa(` … ${e.length-s.length} more item(s) not shown. Use --json for full output.`,o)}function Bm(e,t){const o=typeof e.tool=="string"?e.tool:"tool";Je(`${o} tool`,t);const n=Tt(e.guidance);n.length>0&&(ne("Guidance",t),Pe(n,t)),ei("Common Actions",Tt(e.commonActions),e.actionSummaries,t),ei("Advanced Actions",Tt(e.advancedActions),e.actionSummaries,t);const r=Tt(e.requiresConfirmation);r.length>0&&(ne("Confirmation",t),Pe(r.map(s=>`${s} requires explicit confirmation.`),t,"warning")),typeof e.detailsHint=="string"&&e.detailsHint&&(ne("Next Step",t),ve("Tip",e.detailsHint,t))}function Um(e,t){const o=typeof e.tool=="string"?e.tool:"tool",n=typeof e.action=="string"?e.action:"help";Je(`${o} ${n}`,t),typeof e.hint=="string"&&e.hint&&ge("info",e.hint,t);const r=Tt(e.shapes);r.length>0&&(ne("Accepted Shapes",t),Pe(r,t));const s=Zm(e.requiredFields);s.length>0&&(ne("Required Fields",t),Pe(s,t));const a=Array.isArray(e.examples)?e.examples:[];a.length>0?(ne("Examples",t),jm(a,t)):e.example!==void 0&&(ne("Example",t),xr(e.example,t));const i=Tt(e.guidance);i.length>0&&(ne("Guidance",t),Pe(i,t)),e.requiresConfirmation===!0&&(ne("Safety",t),Pe(["This action requires explicit confirmation."],t,"warning")),typeof e.fullDocResource=="string"&&e.fullDocResource&&(ne("Reference",t),ve("Resource",e.fullDocResource,t))}function ei(e,t,o,n){if(t.length===0)return;const r=qe(o)?o:{};ne(e,n),Pe(t.map(s=>{const a=typeof r[s]=="string"?String(r[s]):"";return a?`${s} — ${a}`:s}),n)}function xr(e,t){if(typeof e=="string"){re(t,` ${e}`);return}if(Array.isArray(e)&&e.every(o=>typeof o=="string")){Pe(e,t);return}re(t,Bn(mt(e),2))}function jm(e,t){for(const o of e){if(!qe(o)){xr(o,t);continue}const n=typeof o.title=="string"?o.title:"Example";re(t,` ${Ue(t,se.bold,n)}`),typeof o.description=="string"&&o.description&&re(t,` ${o.description}`);const r=o.mcp??o.command??o.example;r!==void 0&&xr(r,t)}}function Uc(e,t=new Set){return e.filter(([n,r])=>!t.has(n)&&Ds(r)).map(([n,r])=>({key:n,value:r})).sort((n,r)=>ti(n.key)-ti(r.key)||n.key.localeCompare(r.key)).slice(0,8)}function ti(e){return Om.get(e)??Lc.length+100}function Hm(e){return Object.entries(e).filter(([,t])=>Ds(t)).map(([t,o])=>({key:t,value:o}))}function Vm(e){if(Ds(e))return vn(e);if(!qe(e))return null;const t=Uc(Object.entries(e));return t.length===0?null:t.slice(0,4).map(o=>`${_n(o.key)}: ${vn(o.value)}`).join(" · ")}function Zm(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?[e.join(", ")]:Array.isArray(e)?e.filter(t=>Array.isArray(t)&&t.every(o=>typeof o=="string")).map(t=>t.join(", ")):[]}function Tt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function mt(e){return JSON.stringify(e,null,2)}function _n(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map(t=>{const o=t.toLowerCase();return["id","ids","url","api","sql","json","ocr","html"].includes(o)?o.toUpperCase():o.charAt(0).toUpperCase()+o.slice(1)}).join(" ")}function vn(e){return typeof e=="string"?Ym(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":mt(e)}function Ym(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Bn(e,t){const o=" ".repeat(t);return e.split(`
82
82
  `).map(n=>`${o}${n}`).join(`
83
- `)}function Is(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vm(e){switch(e.configAction){case"list":return Zm(e);case"get":return Ym(e);case"set":return Wm(e);case"use":return Gm(e);default:throw new Error("Unknown config action.")}}function Zm(e){const t=ht(no(e.configPath)),o=process.stdout;Je("SiYuan profiles",o);for(const[n,r]of Object.entries(t.profiles)){const s=n===t.currentProfile?" (current)":"";process.stdout.write(` ${n}${s}
84
- `),Me([{key:"apiUrl",value:r.apiUrl||""},{key:"token",value:r.token?"configured":"empty"}],o)}return oe("Next Step",o),ve("Tip","Use `siyuan-sisyphus config use <name>` to switch the active profile.",o),0}function Ym(e){const t=ht(no(e.configPath)),o=e.configName||t.currentProfile,n=t.profiles[o];if(!n)throw new Error(`Unknown profile "${o}".`);return Je(`Profile ${o}`),Me([{key:"current",value:o===t.currentProfile?"yes":"no"},{key:"apiUrl",value:n.apiUrl||""},{key:"token",value:n.token?"configured":"empty"}]),0}function Wm(e){var i;const t=e.configName;if(!t)throw new Error("Missing profile name. Usage: siyuan-sisyphus config set <name> --url <url> [--token <token>]");if(!e.url)throw new Error("Missing --url. Usage: siyuan-sisyphus config set <name> --url <url> [--token <token>]");const o=no(e.configPath),n=!!(o.apiUrl||o.token||o.currentProfile||o.profiles&&Object.keys(o.profiles).length>0),r=ht(o).currentProfile,s=Rc(o,t,{apiUrl:e.url,token:e.token},{makeCurrent:!n||r===t}),a=ks(s,e.configPath);return ge("success","Profile saved."),Me([{key:"path",value:a},{key:"profile",value:t},{key:"apiUrl",value:e.url},{key:"token",value:e.token||(i=s.profiles[t])!=null&&i.token?"configured":"empty"}]),process.stdout.write(`
85
- `),ve("Next",`Run \`siyuan-sisyphus config use ${t}\` to make it the default profile.`),0}function Gm(e){const t=e.configName;if(!t)throw new Error("Missing profile name. Usage: siyuan-sisyphus config use <name>");const o=gm(no(e.configPath),t),n=ks(o,e.configPath);return ge("success","Active profile updated."),Me([{key:"path",value:n},{key:"profile",value:t}]),0}const Qe=["fs","notebook","document","block","av","file","search","tag","system","flashcard","extension","mascot","feedback"],Ss=["ls","tree","read","write","replace","rm","mv","search"],Ds=["list","create","set_open_state","remove","rename","get_conf","set_conf","set_icon","get_permissions","set_permission","get_child_docs"],As=["create","lookup","rename","remove","move","get_child_blocks","get_child_docs","set_attr","list_tree","search_docs","get_doc","create_daily_note","duplicate","heading_to_doc","doc_to_heading"],Ts=["insert","prepend","append","update","replace","delete","move","set_fold_state","get_kramdown","get_children","transfer_references","set_attrs","get_attrs","info","breadcrumb","dom","recent_updated","word_count","add_to_daily_note","docs_info"],Ps=["get","render","get_attribute_view_keys","get_attribute_view_filter_sort","search","add_rows","remove_rows","add_column","remove_column","set_cells","duplicate","get_primary_key_values"],Es=["upload_asset","list_templates","read_template","create_template","update_template","delete_template","save_doc_as_template","render","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","extract_doc"],Cs=["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"],Rs=["list","rename","remove"],xs=["workspace_info","network","conf","notify","changelog","perform_sync","get_version","get_current_time"],Os=["list_cards","get_decks","get_cards","review_card","create_card","remove_card"],Lc=["list"],Ns=["get_balance","shop","buy"],$s=["submit"],So="/data/storage/petal/siyuan-plugins-mcp-sisyphus/mcpToolsConfig",ie="/AGENTS.md",ze="/USER_RULES.md",ei=new Set,zn={fs:Ss,notebook:Ds,document:As,block:Ts,av:Ps,file:Es,search:Cs,tag:Rs,system:xs,flashcard:Os,extension:Lc,mascot:Ns,feedback:$s},Km={fs:{ls:"basic",tree:"basic",read:"basic",write:"basic",replace:"basic",search:"basic",rm:"advanced",mv:"advanced"},notebook:{list:"basic",create:"basic",set_open_state:"basic",rename:"basic",get_conf:"basic",get_child_docs:"basic",remove:"advanced",set_conf:"advanced",set_icon:"advanced",get_permissions:"advanced",set_permission:"advanced"},document:{create:"basic",lookup:"basic",get_doc:"basic",get_child_blocks:"basic",get_child_docs:"basic",search_docs:"basic",rename:"basic",remove:"advanced",move:"advanced",set_attr:"advanced",list_tree:"advanced",create_daily_note:"advanced",duplicate:"advanced",heading_to_doc:"advanced",doc_to_heading:"advanced"},block:{get_kramdown:"basic",get_children:"basic",get_attrs:"basic",info:"basic",append:"basic",prepend:"basic",insert:"basic",update:"basic",replace:"basic",delete:"advanced",move:"advanced",set_fold_state:"advanced",transfer_references:"advanced",set_attrs:"advanced",breadcrumb:"advanced",dom:"advanced",recent_updated:"advanced",word_count:"advanced",add_to_daily_note:"advanced",docs_info:"advanced"},av:{get:"basic",render:"basic",get_attribute_view_keys:"basic",get_attribute_view_filter_sort:"basic",search:"basic",get_primary_key_values:"basic",add_rows:"advanced",remove_rows:"advanced",add_column:"advanced",remove_column:"advanced",set_cells:"advanced",duplicate:"advanced"},file:{export_md:"basic",upload_asset:"basic",list_templates:"basic",read_template:"basic",create_template:"basic",update_template:"basic",save_doc_as_template:"basic",get_doc_assets:"basic",extract_doc:"basic",render:"advanced",delete_template:"advanced",export_resources:"advanced",list_unused_assets:"advanced",get_image_ocr_text:"advanced",remove_unused_assets:"advanced",rename_asset:"advanced",delete_asset:"advanced"},search:{fulltext:"basic",query_sql:"basic",get_backlinks:"basic",search_refs:"advanced",find_replace:"advanced",search_assets:"advanced",fulltext_asset_content:"advanced",list_invalid_refs:"advanced"},tag:{list:"basic",rename:"basic",remove:"advanced"},system:{get_version:"basic",get_current_time:"basic",conf:"basic",changelog:"basic",workspace_info:"advanced",network:"advanced",notify:"advanced",perform_sync:"advanced"},flashcard:{list_cards:"basic",get_decks:"basic",get_cards:"basic",review_card:"advanced",create_card:"advanced",remove_card:"advanced"},extension:{list:"basic"},mascot:{get_balance:"basic",shop:"basic",buy:"basic"},feedback:{submit:"basic"}};function Do(e,t){var o;return((o=Km[e])==null?void 0:o[t])??"advanced"}const Jm={fs:new Set(["rm","mv"]),notebook:new Set(["remove","set_permission"]),document:new Set(["remove","move"]),block:new Set(["delete","move"]),av:new Set,file:new Set(["upload_asset","delete_template","remove_unused_assets","delete_asset"]),search:new Set(["find_replace"]),tag:new Set(["remove"]),system:new Set(["workspace_info","perform_sync"]),flashcard:new Set(["remove_card"]),extension:new Set,mascot:new Set,feedback:new Set},be=(e,t)=>{const o=new Set(t);return e.reduce((n,r)=>(n[r]=o.has(r),n),{})};function Ao(){return{fs:{enabled:!0,actions:be(Ss,["ls","tree","read","write","replace","rm","mv","search"])},notebook:{enabled:!0,actions:be(Ds,["list","create","set_open_state","rename","get_conf","set_conf","set_icon","get_permissions","get_child_docs"])},document:{enabled:!0,actions:be(As,["create","lookup","rename","move","get_child_blocks","get_child_docs","set_attr","list_tree","search_docs","get_doc","create_daily_note","duplicate","heading_to_doc","doc_to_heading"])},block:{enabled:!0,actions:be(Ts,["insert","prepend","append","update","replace","move","set_fold_state","get_kramdown","get_children","transfer_references","set_attrs","get_attrs","info","breadcrumb","dom","recent_updated","word_count","add_to_daily_note","docs_info"])},av:{enabled:!0,actions:be(Ps,["get","render","get_attribute_view_keys","get_attribute_view_filter_sort","search","add_rows","remove_rows","add_column","remove_column","set_cells","duplicate","get_primary_key_values"])},file:{enabled:!0,actions:be(Es,["upload_asset","list_templates","read_template","create_template","update_template","save_doc_as_template","render","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","extract_doc"]),uploadLargeFileThresholdMB:10},search:{enabled:!0,actions:be(Cs,["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"])},tag:{enabled:!0,actions:be(Rs,["list","rename","remove"])},system:{enabled:!0,actions:be(xs,["network","conf","notify","changelog","perform_sync","get_version","get_current_time"])},flashcard:{enabled:!0,actions:be(Os,["list_cards","get_decks","get_cards","review_card","create_card","remove_card"])},extension:{enabled:!0,actions:be(Lc,["list"]),includeNativeTools:!1,blockedTools:[]},mascot:{enabled:!0,actions:be(Ns,["get_balance","shop","buy"])},feedback:{enabled:!0,actions:be($s,["submit"])},userRulesText:"创建文档/日记后主动设图标",agentSiyuanMemoryText:"",agentSiyuanMemoryUpdatedAt:"",debug:{includeUiRefreshMetadata:!1,slimResponses:!0}}}function yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qm(e){const t=[];for(const n of Qe){const r=e[n];if(typeof r=="boolean"){t.push(`${n}=<boolean>`);continue}Array.isArray(r)&&t.push(`${n}=[...]`)}const o=Object.entries(e).filter(([n,r])=>!["userRulesText","agentSiyuanMemoryText","agentSiyuanMemoryUpdatedAt"].includes(n)&&!Qe.includes(n)&&typeof r=="boolean").map(([n])=>n);if(o.length>0){const n=o.slice(0,3).join(", ");t.push(o.length>3?`${n}, ...`:n)}return t}function Xm(e,t="mcpToolsConfig"){if(!yo(e))return null;const o=Qm(e);return o.length===0?null:[`[MCP] Detected legacy tool config format in ${t}.`,"Only nested { category: { enabled, actions } } config is supported now.","Legacy keys are ignored and defaults may be used instead.","Open MCP settings and save once to rewrite the config.",`Detected legacy fields: ${o.join("; ")}`].join(" ")}function eg(e,t=o=>console.warn(o)){return e?(ei.has(e)||(ei.add(e),t(e)),e):null}function Uc(e,t={}){const o=Xm(e,t.source);return eg(o,t.warn)}function tg(e){if(typeof e!="number"||!Number.isFinite(e))return 10;const t=Math.floor(e);return t<1?1:t>1024?1024:t}function og(e,t){typeof t.userRulesText=="string"&&(e.userRulesText=t.userRulesText),typeof t.agentSiyuanMemoryText=="string"&&(e.agentSiyuanMemoryText=t.agentSiyuanMemoryText),typeof t.agentSiyuanMemoryUpdatedAt=="string"&&(e.agentSiyuanMemoryUpdatedAt=t.agentSiyuanMemoryUpdatedAt),yo(t.debug)&&(typeof t.debug.includeUiRefreshMetadata=="boolean"&&(e.debug.includeUiRefreshMetadata=t.debug.includeUiRefreshMetadata),typeof t.debug.slimResponses=="boolean"&&(e.debug.slimResponses=t.debug.slimResponses));for(const o of Qe){const n=t[o];if(yo(n)&&(typeof n.enabled=="boolean"&&(e[o].enabled=n.enabled),o==="file"&&"uploadLargeFileThresholdMB"in n&&(e.file.uploadLargeFileThresholdMB=tg(n.uploadLargeFileThresholdMB)),o==="extension"&&(typeof n.includeNativeTools=="boolean"&&(e.extension.includeNativeTools=n.includeNativeTools),Array.isArray(n.blockedTools)&&(e.extension.blockedTools=Array.from(new Set(n.blockedTools.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))).sort())),!!yo(n.actions)))for(const r of zn[o]){const s=n.actions[r];typeof s=="boolean"&&(e[o].actions[r]=s)}}}function Ms(e){const t=Ao();if(!yo(e))return t;og(t,e);for(const o of Qe)t[o].enabled&&To(t[o]).length===0&&(t[o].enabled=!1);return t}function To(e){return Object.entries(e.actions).filter(([,t])=>t).map(([t])=>t)}function ng(e){return e instanceof Error?e.message:String(e)}async function rg(e){try{const t=await e.readFile(So);if(!t)return{config:Ao(),ok:!0,source:"api_file",rawLength:0};const o=JSON.parse(t);return Uc(o,{source:`SiYuan API file "${So}"`}),{config:Ms(o),ok:!0,source:"api_file",rawLength:t.length}}catch(t){return{config:Ao(),ok:!1,source:"default_fallback",errorMessage:ng(t)}}}async function zs(e){return(await rg(e)).config}async function sg(e,t){const o=Ms(t);return await e.writeFile(So,JSON.stringify(o,null,2)),o}async function Fs(e,t){const o=await zs(e);return sg(e,{...o,agentSiyuanMemoryText:t,agentSiyuanMemoryUpdatedAt:t.trim()?new Date().toISOString():""})}function Bt(e,t){return Jm[e].has(t)}const ag={list:["ls"],ls:["list"],move:["mv"],mv:["move"],remove:["rm","delete"],rm:["remove","delete"],delete:["rm","remove"],del:["delete","rm","remove"]};function ro(e,t){const o=t.replace(/-/g,"_"),n=zn[e];return n.includes(o)?o:(ag[o]??[]).find(s=>n.includes(s))??o}const ig=`# 更新日志
83
+ `)}function Ds(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e){switch(e.configAction){case"list":return Gm(e);case"get":return Km(e);case"set":return Jm(e);case"use":return Qm(e);default:throw new Error("Unknown config action.")}}function Gm(e){const t=ht(ro(e.configPath)),o=process.stdout;Je("SiYuan profiles",o);for(const[n,r]of Object.entries(t.profiles)){const s=n===t.currentProfile?" (current)":"";process.stdout.write(` ${n}${s}
84
+ `),Me([{key:"apiUrl",value:r.apiUrl||""},{key:"token",value:r.token?"configured":"empty"}],o)}return ne("Next Step",o),ve("Tip","Use `siyuan-sisyphus config use <name>` to switch the active profile.",o),0}function Km(e){const t=ht(ro(e.configPath)),o=e.configName||t.currentProfile,n=t.profiles[o];if(!n)throw new Error(`Unknown profile "${o}".`);return Je(`Profile ${o}`),Me([{key:"current",value:o===t.currentProfile?"yes":"no"},{key:"apiUrl",value:n.apiUrl||""},{key:"token",value:n.token?"configured":"empty"}]),0}function Jm(e){var i;const t=e.configName;if(!t)throw new Error("Missing profile name. Usage: siyuan-sisyphus config set <name> --url <url> [--token <token>]");if(!e.url)throw new Error("Missing --url. Usage: siyuan-sisyphus config set <name> --url <url> [--token <token>]");const o=ro(e.configPath),n=!!(o.apiUrl||o.token||o.currentProfile||o.profiles&&Object.keys(o.profiles).length>0),r=ht(o).currentProfile,s=Oc(o,t,{apiUrl:e.url,token:e.token},{makeCurrent:!n||r===t}),a=vs(s,e.configPath);return ge("success","Profile saved."),Me([{key:"path",value:a},{key:"profile",value:t},{key:"apiUrl",value:e.url},{key:"token",value:e.token||(i=s.profiles[t])!=null&&i.token?"configured":"empty"}]),process.stdout.write(`
85
+ `),ve("Next",`Run \`siyuan-sisyphus config use ${t}\` to make it the default profile.`),0}function Qm(e){const t=e.configName;if(!t)throw new Error("Missing profile name. Usage: siyuan-sisyphus config use <name>");const o=wm(ro(e.configPath),t),n=vs(o,e.configPath);return ge("success","Active profile updated."),Me([{key:"path",value:n},{key:"profile",value:t}]),0}const Qe=["fs","notebook","document","block","av","file","search","tag","system","flashcard","extension","mascot","feedback"],Ts=["ls","tree","read","write","replace","rm","mv","search"],As=["list","create","set_open_state","remove","rename","get_conf","set_conf","set_icon","get_permissions","set_permission","get_child_docs"],Ps=["create","lookup","rename","remove","move","get_child_blocks","get_child_docs","set_attr","list_tree","search_docs","get_doc","create_daily_note","duplicate","heading_to_doc","doc_to_heading"],Cs=["insert","prepend","append","update","replace","delete","move","set_fold_state","get_kramdown","get_children","transfer_references","set_attrs","get_attrs","info","breadcrumb","dom","recent_updated","word_count","add_to_daily_note","docs_info"],Es=["get","render","get_attribute_view_keys","get_attribute_view_filter_sort","search","add_rows","remove_rows","add_column","remove_column","set_cells","duplicate","get_primary_key_values"],Rs=["upload_asset","list_templates","read_template","create_template","update_template","delete_template","save_doc_as_template","render","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","extract_doc"],xs=["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"],Os=["list","rename","remove"],Ns=["workspace_info","network","conf","notify","changelog","perform_sync","get_version","get_current_time"],$s=["list_cards","get_decks","get_cards","review_card","create_card","remove_card"],jc=["list"],Ms=["get_balance","shop","buy"],zs=["submit"],To="/data/storage/petal/siyuan-plugins-mcp-sisyphus/mcpToolsConfig",ie="/AGENTS.md",ze="/USER_RULES.md",oi=new Set,Un={fs:Ts,notebook:As,document:Ps,block:Cs,av:Es,file:Rs,search:xs,tag:Os,system:Ns,flashcard:$s,extension:jc,mascot:Ms,feedback:zs},Xm={fs:{ls:"basic",tree:"basic",read:"basic",write:"basic",replace:"basic",search:"basic",rm:"advanced",mv:"advanced"},notebook:{list:"basic",create:"basic",set_open_state:"basic",rename:"basic",get_conf:"basic",get_child_docs:"basic",remove:"advanced",set_conf:"advanced",set_icon:"advanced",get_permissions:"advanced",set_permission:"advanced"},document:{create:"basic",lookup:"basic",get_doc:"basic",get_child_blocks:"basic",get_child_docs:"basic",search_docs:"basic",rename:"basic",remove:"advanced",move:"advanced",set_attr:"advanced",list_tree:"advanced",create_daily_note:"advanced",duplicate:"advanced",heading_to_doc:"advanced",doc_to_heading:"advanced"},block:{get_kramdown:"basic",get_children:"basic",get_attrs:"basic",info:"basic",append:"basic",prepend:"basic",insert:"basic",update:"basic",replace:"basic",delete:"advanced",move:"advanced",set_fold_state:"advanced",transfer_references:"advanced",set_attrs:"advanced",breadcrumb:"advanced",dom:"advanced",recent_updated:"advanced",word_count:"advanced",add_to_daily_note:"advanced",docs_info:"advanced"},av:{get:"basic",render:"basic",get_attribute_view_keys:"basic",get_attribute_view_filter_sort:"basic",search:"basic",get_primary_key_values:"basic",add_rows:"advanced",remove_rows:"advanced",add_column:"advanced",remove_column:"advanced",set_cells:"advanced",duplicate:"advanced"},file:{export_md:"basic",upload_asset:"basic",list_templates:"basic",read_template:"basic",create_template:"basic",update_template:"basic",save_doc_as_template:"basic",get_doc_assets:"basic",extract_doc:"basic",render:"advanced",delete_template:"advanced",export_resources:"advanced",list_unused_assets:"advanced",get_image_ocr_text:"advanced",remove_unused_assets:"advanced",rename_asset:"advanced",delete_asset:"advanced"},search:{fulltext:"basic",query_sql:"basic",get_backlinks:"basic",search_refs:"advanced",find_replace:"advanced",search_assets:"advanced",fulltext_asset_content:"advanced",list_invalid_refs:"advanced"},tag:{list:"basic",rename:"basic",remove:"advanced"},system:{get_version:"basic",get_current_time:"basic",conf:"basic",changelog:"basic",workspace_info:"advanced",network:"advanced",notify:"advanced",perform_sync:"advanced"},flashcard:{list_cards:"basic",get_decks:"basic",get_cards:"basic",review_card:"advanced",create_card:"advanced",remove_card:"advanced"},extension:{list:"basic"},mascot:{get_balance:"basic",shop:"basic",buy:"basic"},feedback:{submit:"basic"}};function Ao(e,t){var o;return((o=Xm[e])==null?void 0:o[t])??"advanced"}const eg={fs:new Set(["rm","mv"]),notebook:new Set(["remove","set_permission"]),document:new Set(["remove","move"]),block:new Set(["delete","move"]),av:new Set,file:new Set(["upload_asset","delete_template","remove_unused_assets","delete_asset"]),search:new Set(["find_replace"]),tag:new Set(["remove"]),system:new Set(["workspace_info","perform_sync"]),flashcard:new Set(["remove_card"]),extension:new Set,mascot:new Set,feedback:new Set},be=(e,t)=>{const o=new Set(t);return e.reduce((n,r)=>(n[r]=o.has(r),n),{})};function Po(){return{fs:{enabled:!0,actions:be(Ts,["ls","tree","read","write","replace","rm","mv","search"])},notebook:{enabled:!0,actions:be(As,["list","create","set_open_state","rename","get_conf","set_conf","set_icon","get_permissions","get_child_docs"])},document:{enabled:!0,actions:be(Ps,["create","lookup","rename","move","get_child_blocks","get_child_docs","set_attr","list_tree","search_docs","get_doc","create_daily_note","duplicate","heading_to_doc","doc_to_heading"])},block:{enabled:!0,actions:be(Cs,["insert","prepend","append","update","replace","move","set_fold_state","get_kramdown","get_children","transfer_references","set_attrs","get_attrs","info","breadcrumb","dom","recent_updated","word_count","add_to_daily_note","docs_info"])},av:{enabled:!0,actions:be(Es,["get","render","get_attribute_view_keys","get_attribute_view_filter_sort","search","add_rows","remove_rows","add_column","remove_column","set_cells","duplicate","get_primary_key_values"])},file:{enabled:!0,actions:be(Rs,["upload_asset","list_templates","read_template","create_template","update_template","save_doc_as_template","render","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","extract_doc"]),uploadLargeFileThresholdMB:10},search:{enabled:!0,actions:be(xs,["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"])},tag:{enabled:!0,actions:be(Os,["list","rename","remove"])},system:{enabled:!0,actions:be(Ns,["network","conf","notify","changelog","perform_sync","get_version","get_current_time"])},flashcard:{enabled:!0,actions:be($s,["list_cards","get_decks","get_cards","review_card","create_card","remove_card"])},extension:{enabled:!0,actions:be(jc,["list"]),includeNativeTools:!1,blockedTools:[]},mascot:{enabled:!0,actions:be(Ms,["get_balance","shop","buy"])},feedback:{enabled:!0,actions:be(zs,["submit"])},userRulesText:"创建文档/日记后主动设图标",agentSiyuanMemoryText:"",agentSiyuanMemoryUpdatedAt:"",debug:{includeUiRefreshMetadata:!1,slimResponses:!0}}}function bo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tg(e){const t=[];for(const n of Qe){const r=e[n];if(typeof r=="boolean"){t.push(`${n}=<boolean>`);continue}Array.isArray(r)&&t.push(`${n}=[...]`)}const o=Object.entries(e).filter(([n,r])=>!["userRulesText","agentSiyuanMemoryText","agentSiyuanMemoryUpdatedAt"].includes(n)&&!Qe.includes(n)&&typeof r=="boolean").map(([n])=>n);if(o.length>0){const n=o.slice(0,3).join(", ");t.push(o.length>3?`${n}, ...`:n)}return t}function og(e,t="mcpToolsConfig"){if(!bo(e))return null;const o=tg(e);return o.length===0?null:[`[MCP] Detected legacy tool config format in ${t}.`,"Only nested { category: { enabled, actions } } config is supported now.","Legacy keys are ignored and defaults may be used instead.","Open MCP settings and save once to rewrite the config.",`Detected legacy fields: ${o.join("; ")}`].join(" ")}function ng(e,t=o=>console.warn(o)){return e?(oi.has(e)||(oi.add(e),t(e)),e):null}function Hc(e,t={}){const o=og(e,t.source);return ng(o,t.warn)}function rg(e){if(typeof e!="number"||!Number.isFinite(e))return 10;const t=Math.floor(e);return t<1?1:t>1024?1024:t}function sg(e,t){typeof t.userRulesText=="string"&&(e.userRulesText=t.userRulesText),typeof t.agentSiyuanMemoryText=="string"&&(e.agentSiyuanMemoryText=t.agentSiyuanMemoryText),typeof t.agentSiyuanMemoryUpdatedAt=="string"&&(e.agentSiyuanMemoryUpdatedAt=t.agentSiyuanMemoryUpdatedAt),bo(t.debug)&&(typeof t.debug.includeUiRefreshMetadata=="boolean"&&(e.debug.includeUiRefreshMetadata=t.debug.includeUiRefreshMetadata),typeof t.debug.slimResponses=="boolean"&&(e.debug.slimResponses=t.debug.slimResponses));for(const o of Qe){const n=t[o];if(bo(n)&&(typeof n.enabled=="boolean"&&(e[o].enabled=n.enabled),o==="file"&&"uploadLargeFileThresholdMB"in n&&(e.file.uploadLargeFileThresholdMB=rg(n.uploadLargeFileThresholdMB)),o==="extension"&&(typeof n.includeNativeTools=="boolean"&&(e.extension.includeNativeTools=n.includeNativeTools),Array.isArray(n.blockedTools)&&(e.extension.blockedTools=Array.from(new Set(n.blockedTools.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))).sort())),!!bo(n.actions)))for(const r of Un[o]){const s=n.actions[r];typeof s=="boolean"&&(e[o].actions[r]=s)}}}function Fs(e){const t=Po();if(!bo(e))return t;sg(t,e);for(const o of Qe)t[o].enabled&&Co(t[o]).length===0&&(t[o].enabled=!1);return t}function Co(e){return Object.entries(e.actions).filter(([,t])=>t).map(([t])=>t)}function ag(e){return e instanceof Error?e.message:String(e)}async function ig(e){try{const t=await e.readFile(To);if(!t)return{config:Po(),ok:!0,source:"api_file",rawLength:0};const o=JSON.parse(t);return Hc(o,{source:`SiYuan API file "${To}"`}),{config:Fs(o),ok:!0,source:"api_file",rawLength:t.length}}catch(t){return{config:Po(),ok:!1,source:"default_fallback",errorMessage:ag(t)}}}async function qs(e){return(await ig(e)).config}async function cg(e,t){const o=Fs(t);return await e.writeFile(To,JSON.stringify(o,null,2)),o}async function Ls(e,t){const o=await qs(e);return cg(e,{...o,agentSiyuanMemoryText:t,agentSiyuanMemoryUpdatedAt:t.trim()?new Date().toISOString():""})}function Bt(e,t){return eg[e].has(t)}const lg={list:["ls"],ls:["list"],move:["mv"],mv:["move"],remove:["rm","delete"],rm:["remove","delete"],delete:["rm","remove"],del:["delete","rm","remove"]};function so(e,t){const o=t.replace(/-/g,"_"),n=Un[e];return n.includes(o)?o:(lg[o]??[]).find(s=>n.includes(s))??o}const ug=`# 更新日志
86
86
 
87
87
  本文件记录项目的主要版本变更。
88
88
 
89
+ ## v0.5.1 - 2026-07-28
90
+
91
+ - 隔离思源官方 MCP 扩展链路:仅在需要扩展 Tool 时惰性连接,连接失败时完整降级,不再影响 Sisyphus 自带工具、CLI 与外层 MCP Server 启动
92
+ - 在设置页新增 MCP 与 CLI 配置 Prompt 一键复制,引导 AI 安全合并连接配置并完成只读验证;更新日志升级为可滚动时间轴并补全历史里程碑
93
+ - 同步完善双语文案与测试覆盖;CLI 包提升至 v0.2.1
94
+
89
95
  ## v0.5.0 - 2026-07-28
90
96
 
91
97
  - 正式接入思源官方 MCP 插件生态,新增 \`extension\` 聚合工具,可动态发现、筛选并调用其他插件注册的 Tool,同时保持原有工作流兼容
@@ -416,64 +422,64 @@ Flag naming:
416
422
  ## v0.1.0 - 2026-02-20
417
423
 
418
424
  - 更新插件图标与预览图资源
419
- `,ti="siyuan://help/changelog",cg=5,lg=50,oi=[{area:"tool-config",pattern:/工具配置|tool config|action|聚合工具|工具设置|settings panel|设置面板/i},{area:"user-rules",pattern:/用户规则|custom rules|USER_RULES|个性化|偏好/i},{area:"agent-memory",pattern:/AGENTS\.md|Agent 记忆|workspace memory|虚拟.*记忆/i},{area:"permissions",pattern:/权限|permission|dangerous|确认|高风险/i},{area:"connection",pattern:/MCP|HTTP|HTTPS|stdio|CLI|Docker|远程|连接|token|profile|环境变量/i},{area:"appearance",pattern:/主题|配色|外观|猫猫|i18n|国际化|语言/i},{area:"timeline",pattern:/文档时间线|timeline|Dock|侧边栏|历史版本/i}];function Be(e){return e.trim().replace(/^v/i,"")}function ug(e){var t;return"0.5.0".trim()?Be("0.5.0"):((t=e[0])==null?void 0:t.version)??"0.0.0"}function dg(e,t){const o=Be(e).split(/[.-]/).map(s=>Number.parseInt(s,10)),n=Be(t).split(/[.-]/).map(s=>Number.parseInt(s,10)),r=Math.max(o.length,n.length,3);for(let s=0;s<r;s++){const a=Number.isFinite(o[s])?o[s]:0,i=Number.isFinite(n[s])?n[s]:0;if(a!==i)return a>i?1:-1}return 0}function pg(e){return e.split(`
420
- `).map(t=>t.trim()).filter(t=>t.startsWith("- ")).map(t=>t.slice(2).trim()).filter(Boolean)}function fg(e,t){const o=new Set,n=[];for(const r of e){const s=oi.filter(({pattern:a})=>a.test(r)).map(({area:a})=>a);s.length!==0&&(s.forEach(a=>o.add(a)),n.push(r))}if(n.length===0)for(const{area:r,pattern:s}of oi)s.test(t)&&o.add(r);return{mayAffectPersonalization:o.size>0,areas:[...o].sort(),matchedItems:n}}function hg(e=ig){const t=[...e.matchAll(/^##\s+(v?[0-9][^\s]*)\s*(?:-\s*(.+))?\s*$/gm)];return t.map((o,n)=>{var l,u;const r=o.index??0,s=((l=t[n+1])==null?void 0:l.index)??e.length,a=e.slice(r,s).trim(),i=pg(a);return{version:Be(o[1]??""),date:(u=o[2])==null?void 0:u.trim(),title:o[0].trim(),items:i,rawMarkdown:a,personalizationImpact:fg(i,a)}}).filter(o=>o.version)}function jc(e){return typeof e!="number"||!Number.isFinite(e)?cg:Math.max(1,Math.min(lg,Math.trunc(e)))}function mg(e,t){var n,r;if((n=t.version)!=null&&n.trim()){const s=Be(t.version);return e.filter(a=>Be(a.version)===s).slice(0,1)}const o=jc(t.limit);if((r=t.fromVersion)!=null&&r.trim()){const s=Be(t.fromVersion);return e.filter(a=>dg(a.version,s)>0).slice(0,o)}return e.slice(0,o)}function gg(e={}){const t=hg(),o=mg(t,e),n=o.filter(r=>r.personalizationImpact.mayAffectPersonalization);return{source:"bundled CHANGELOG.md",resource:ti,pluginVersion:ug(t),totalEntries:t.length,returnedEntries:o.length,query:{version:e.version?Be(e.version):void 0,fromVersion:e.fromVersion?Be(e.fromVersion):void 0,limit:jc(e.limit),includeRaw:e.includeRaw===!0},entries:o.map(r=>({version:r.version,date:r.date,title:r.title,items:r.items,personalizationImpact:r.personalizationImpact,...e.includeRaw?{rawMarkdown:r.rawMarkdown}:{}})),personalizationReview:{shouldReview:n.length>0,affectedVersions:n.map(r=>r.version),affectedAreas:[...new Set(n.flatMap(r=>r.personalizationImpact.areas))].sort(),hints:[`Read ${ti} or call system(action="changelog", fromVersion="<previousVersion>") after upgrades.`,"If affectedAreas includes user-rules, agent-memory, permissions, connection, appearance, timeline, or tool-config, compare the changelog with active user rules and /AGENTS.md before changing behavior.","When a configured preference may be stale, remind the user what changed and ask before rewriting persistent configuration or memory."]}}}const Hc=["Use fs first for ordinary document file operations: list, tree, read, write, move, delete, and grep-like search.","fs paths are human-readable workspace paths such as /Notebook/Folder/Doc; fs outputs the same human-readable path shape and hides notebook IDs, block IDs, and storage paths.","fs is a pure Markdown convenience layer. If a document contains SiYuan-native structures such as database blocks, super blocks, embeds, media blocks, query embeds, widgets, HTML, or precise block-tree layout, inspect and modify those structures with advanced tools such as block, av, file, document, or search instead.",`fs.read returns an AI-editable Markdown view built from block kramdown, not /api/export/exportMdContent. It preserves SiYuan double-links as ((id 'title')), preserves tags as #tag#, strips SiYuan zero-width tag markers, and hides block/list-item IAL metadata such as {: id="..." updated="..."} from normal list editing.`,"fs.read always returns complete display-block windows. Use blockStart/blockLimit/tokenBudget to continue long documents; code, math, tables, lists, quotes, and other container blocks are never split. The response includes a full heading outline and nextWindow when more blocks remain.",'Copy old snippets for fs.replace from fs.read output. fs.replace uses the same AI-editable view for matching, so list items like "- item" can be replaced without including hidden IAL metadata. For inline styled text, use the plain text inside the style markers as old text: replace "hello" inside **hello** or `hello`, not "**hello**" or "`hello`"; DOM writeback preserves the existing inline style.',"Use document, block, search, or av for advanced SiYuan-specific operations such as block-level layout, metadata, database rows, SQL, backlinks, or assets.",'fs(action="write") creates missing documents. Do not include a leading # Title in markdown; the document title is rendered automatically. Existing documents are protected unless overwrite=true.',"For double-links in fs.write or fs.replace replacement text, use ((block-id 'anchor text')) with a real block ID and human-readable anchor text. Naked ((id)) is resolved before writing; if anchor lookup fails, MCP falls back to ((id 'id')) with a warning.",'For tags in fs.write or fs.replace replacement text, use #tag# or hierarchical tag syntax such as #parent/child#; verify global tag state with tag(action="list", query="tag").','fs(action="replace") performs exact string replacement only inside non-complex Markdown blocks. If a document also contains complex SiYuan-native blocks, those blocks are skipped; replacements that only exist inside skipped blocks, or cross block boundaries, are rejected without writing.','If fs.read reports attributeViews or avToolHint, the document contains real database blocks. Use av(action="get"|"render"|"set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column") for AV rows, columns, and cells instead of editing the database placeholder as Markdown.','fs(action="rm") and fs(action="mv") require explicit user confirmation before execution.'],Vc=["Use notebook IDs for set_open_state, rename, get_conf, and set_conf.",'notebook(action="get_permissions") supports notebook="all" (or omission) for all notebooks, and a specific notebook ID for one notebook.','notebook(action="remove") requires explicit user confirmation before execution.','notebook(action="get_child_docs") returns direct child documents at the notebook root and retries short closed-or-initializing windows before failing.','Right after notebook(action="set_open_state", opened=false), get_child_docs may still return a retryable closed-or-initializing error; open the notebook first or retry shortly.'],Zc=['For ordinary document file operations, prefer fs(action="ls"|"tree"|"read"|"write"|"search") because it accepts human-readable paths and hides storage paths and IDs.','document(action="create") creates both non-empty and empty documents. Prefer path for child documents; path is a notebook-local human-readable hpath such as /Folder/Parent/New Child, not /Notebook/Folder/... and not a .sy storage path.','Do not put # Title at the start of document(action="create") markdown. SiYuan renders the document title as H1 automatically, and MCP strips a matching leading H1 to avoid duplicate titles.','document(action="create", parentPath=..., title=...) is also supported. parentPath accepts either a notebook-local human-readable parent hpath such as /Folder/Parent, or a storage path ending in .sy returned by document(action="lookup").','fs(action="write", path="/Notebook/Folder/Doc") uses a workspace path that includes the notebook name; document(action="create", notebook=..., path="/Folder/Doc") uses a notebook-local hpath. Do not mix these two path formats.','For document(action="lookup"), path means a storage path such as /20240318112233-abc123.sy; use hpath/hPath for human-readable paths such as /Inbox/Weekly Note.','Other document actions that use notebook + path expect storage paths returned by document(action="lookup").','If document(action="create") reports a duplicate-name error, verify the intended child with document(action="lookup", notebook=..., hpath="/Folder/Parent/New Child", include=["id","path","hpath"]) or document(action="get_child_docs", id=<parent-doc-id>). New create results may take a short indexing delay before lookup/search sees them.',"A safe path-based workflow is lookup -> rename/remove/move.",'document(action="get_child_blocks") and document(action="get_child_docs") return direct children for a document ID.','document(action="set_attr") updates document metadata such as icon and cover; use attrs.cover=null or an empty string to clear the cover.','document(action="search_docs") remains title-based, but MCP now post-filters results by notebook permission and optional storage path scope.','For recently created documents, document(action="lookup", hpath=...) may briefly lag behind create because it depends on SiYuan indexing; retry if needed.','document(action="lookup", id=...) may hit the same short indexing delay right after create; MCP retries briefly and then returns a timing-specific hint if indexing still has not settled.'],Yc=['block(action="prepend") or block(action="append") with a document ID targets the document start or end.','block(action="update") is best for single-block replacement. Multi-line markdown may be truncated to the first line by SiYuan; use append/prepend/insert when you need multiple blocks, tables, or longer multi-line content.','block(action="replace") only searches the kramdown of the single block identified by id. It does not traverse child blocks, sibling blocks, headings with their following content, or the whole document.','Before block(action="replace"), call block(action="get_kramdown", id=...) and copy an exact old snippet from that result. It writes back through the original DOM text nodes; naked ((id)) references, footnotes, and siyuan://blocks links are allowed with backlink-semantics hints.',`block(action="prepend") or block(action="append") with a block ID targets that block's child list.`,'To create real SiYuan tags inside markdown content, use the syntax #tag# with both leading and trailing # characters, then verify with tag(action="list", query="tag").','To turn a block into a flashcard, prefer flashcard(action="create_card"). It writes "custom-riff-decks" and registers the riff card together.','block(action="set_fold_state") requires a foldable block ID, not a document ID.','block(action="recent_updated") is read-only; MCP filters unreadable notebooks first and then applies count.','block(action="recent_updated") now presents the document-grouped summary as the primary user-facing view while keeping the raw block stream for advanced consumers.'],Wc=["AV actions operate on real SiYuan attribute views (database blocks), not Markdown tables.",'To initialize a new AV definition, call av(action="render", blockID, createIfNotExist=true). MCP can generate the AV ID automatically and materialize a SiYuan-style NodeAttributeView block in the target document through a transaction.',"Most follow-up AV reads and writes only need avID. MCP resolves the owning database block from row bindings, mirror database blocks, or the blocks-table AV block record; pass blockID when you need an exact database-block view context or fallback.",'Use strong typed fields such as valueType=text/number/date/checkbox/select when calling av(action="set_cells").',"For cell writes, rowID must be the database row item ID stored in each AV value's blockID field. The value id field is only the cell value ID, and block.id is the original bound source block ID.","AV permission checks resolve from registered database blocks. For createIfNotExist=true, provide blockID as the creation target; after materialization, MCP can usually rediscover that owning database block automatically.",'av(action="search") first queries kernel search results, then MCP post-filters unreadable or unresolvable AVs and reports the filtering metadata.','av(action="search") is best for database names and primary-key matches. Do not assume it will find arbitrary non-primary-key cell text immediately after writes.'],Gc=['file(action="upload_asset") reads a local file path and uploads that file into SiYuan assets. Because it reads the local filesystem, it requires explicit user confirmation before execution.',"If the file is larger than the configured large-upload threshold (10 MB by default), MCP must stop and ask the user for explicit confirmation before retrying with confirmLargeFile=true.",'file(action="export_resources") exports the given paths as a ZIP archive, normalizes common asset path formats, and can optionally save the ZIP to a local filesystem path.','file(action="export_resources", outputPath=...) writes to the local filesystem and requires explicit user confirmation before execution.','Use file(action="list_templates") before rendering when you need to discover valid workspace template paths under data/templates.','file(action="read_template") reads Markdown template source through SiYuan’s authenticated /templates/ route; it does not expose arbitrary workspace files.','file(action="create_template"|"update_template") writes Markdown templates through SiYuan’s /api/file/putFile workspace API; it does not write data/templates through the local filesystem.','file(action="delete_template") removes an existing Markdown template resolved from SiYuan’s template picker and requires explicit user confirmation before execution.','file(action="save_doc_as_template") saves an existing document as a root-level template after read-permission checks; use create_template when you need a nested template path.','file(action="render", engine="template") requires a template path inside the SiYuan workspace; arbitrary local paths like /tmp/... are rejected by the kernel.','file(action="render", engine="template") uses SiYuan workspace template syntax .action{.title}, .action{.id}, .action{.name}, and .action{.alias}; it does not replace {{...}} placeholders.','file(action="render", engine="sprig") uses inline Go/Sprig template syntax such as {{ now | date "2006-01-02" }}, but it has no document context.','file(action="extract_doc") exports a document and all its assets into a self-contained uncompressed folder, so AI tools can read the files directly. Prefer this over export_resources when the goal is to inspect attachment content such as images, spreadsheets, or other binary files.'],Kc=["Tag actions operate across the whole workspace rather than a single notebook.","There is no direct create action for tags; tags are created by writing #tag# into block markdown content.",'tag(action="remove") requires explicit user confirmation before execution.',"Recently written tags may appear with a short indexing delay in tag list/search results; retry briefly before treating that as a failure."],Jc=["Most system actions in this tool are read-only; perform_sync is the mutating exception and requires explicit user confirmation before execution.",'system(action="workspace_info") exposes the workspace path and is high-risk; it is disabled by default.','system(action="perform_sync") triggers SiYuan sync immediately; it does not modify sync provider settings.','system(action="conf") returns masked configuration, not raw secrets.','Use system(action="changelog", fromVersion="<previousVersion>") after plugin upgrades to see whether old personalized settings, rules, memory, or connection snippets need review.','Use system(action="conf", mode="summary") first, then mode="get" + keyPath such as conf.appearance.mode or conf.langs[0].'],Qc=["flashcard actions cover review-first flashcard workflows and deck discovery.",`list_cards always reads from the kernel due-card endpoints and MCP post-filters cards by state for filter="new" or filter="old"; pass reviewedCards to match SiYuan's in-review filtering.`,"get_cards returns all cards in a deck (not just due ones), with pagination. Use it to browse or audit deck contents.",'Prefer flashcard(action="create_card", deckID, blockIDs) when the goal is to turn existing blocks into real flashcards.',`create_card validates non-built-in deck IDs against get_decks, then calls SiYuan's riff add-card operation, which writes "custom-riff-decks" and registers the riff card transactionally.`,"Create or locate the intended content block IDs first, then pass those IDs to create_card. Document block IDs are rejected; use content blocks such as headings or paragraphs.",'create_card(mode="attach") is retained for compatibility; SiYuan still writes the deck binding during the riff add-card operation. remove_card removes existing content block IDs such as paragraphs or headings from a deck; document blocks are rejected for creation.',"review_card requires a concrete deckID and cardID. Use list_cards or get_cards to resolve them; an empty deckID is not valid for review.","Flashcard removal only removes riff card bindings from a deck. It does not delete the underlying note blocks; deleting note blocks is a separate block/document delete workflow.",'flashcard(action="remove_card") requires explicit user confirmation before execution.'],yg=["extension bridges tools from the official SiYuan /mcp endpoint and requires SiYuan 3.7.0 or newer.",'Plugin tools are exposed by default. Native SiYuan tools are exposed only when extension.includeNativeTools is enabled; external source="mcp" tools remain excluded.','Use extension(action="list", refresh=true) to refresh discovery and inspect official tool names, sources, schemas, read-only declarations, and blocked state.','Call a discovered tool with extension(action="<official tool name>", arguments={...}). Downstream parameters must stay inside arguments, including a downstream action field.',"Tools without readOnlyHint=true may mutate data or trigger side effects and require explicit user confirmation before calling.","Forwarded official MCP tool calls are never retried. A transport error after dispatch means execution status is unknown and must be checked before retrying.","Native tools can overlap with Sisyphus actions and substantially increase schema size, so includeNativeTools is disabled by default."],Xc=["mascot actions operate on the cat’s spendable balance.","Every successful MCP tool call earns 1 coin for the cat, so the fastest way to earn balance is simply to keep using SiYuan MCP tools.",'Use mascot(action="shop") to list available items and their stable item IDs.','Use mascot(action="buy", item_id=...) to purchase an item and spend from the balance.'],el=["feedback submits plain-text product feedback to the developer through the configured WPS form channel.",'Use feedback(action="submit") when the user asks you to pass along feedback, or when an AI client needs to report MCP tool friction after explaining what will be sent.',"Prefer GitHub Issue-style feedback for bugs, confusing names/parameters/help/errors, or rough workflows encountered during an AI session.","Put the full issue-style body in description with these headings when useful: ## Summary, ## What happened, ## Expected behavior, ## Steps or context, ## Impact, ## Suggested fix.","Use impact for a one- or two-sentence impact summary, and suggestion for the most direct improvement idea without repeating the full description.","Do not include secrets, private note content, API tokens, or sensitive document paths in feedback."],tl={ls:'Use a human-readable path. "/" lists readable notebook roots; /Notebook or /Notebook/Folder lists direct child documents.',tree:"Use a human-readable path. maxDepth defaults to 3 and keeps output compact.",read:"Use a human-readable document path. Returns an AI-editable Markdown window made only of complete display blocks. Continue with nextWindow or blockStart/blockLimit/tokenBudget; page/pageSize character pagination was removed. The response includes a full heading outline, and includeBlockIds=true adds a sidecar blockRefs mapping without polluting content. When complex SiYuan blocks are detected, use block.dom, file.export_md, av, or other advanced tools for inspection and editing.",write:"Creates a missing document. Do not include a leading # Title in markdown; the document title is automatic. Existing pure Markdown documents are protected unless overwrite=true; overwrite refuses documents containing complex SiYuan-native blocks. Use ((id 'title')) for double-links and #tag# for tags; use advanced tools for database rows, cells, super blocks, embeds, widgets, HTML, and media.",replace:"Edits matched non-complex Markdown blocks by exact old/new matching against the same AI-editable view returned by fs.read. Canonical input is edit={old,new}; shorthand old + new is also accepted. If the document contains complex SiYuan-native blocks, fs.replace skips those blocks and returns skippedComplexBlocks; matches only inside skipped blocks or across block boundaries are rejected without writing. For inline formatting, old should be plain text without Markdown style delimiters such as **, *, `, or ~~; existing DOM inline styles are preserved. Naked ((id)) refs are normalized, and footnotes/siyuan://blocks links are allowed but do not create backlinks. replace_all=true replaces every exact match across editable blocks. Use ((id 'title')) for new double-links and #tag# for tags.",rm:"Deletes a document by human-readable path. This action requires explicit user confirmation.",mv:"Moves or renames a document using human-readable paths. This action requires explicit user confirmation.",search:"Searches Markdown lines under a human-readable document or folder path. Use regex=true for regular expressions."},ol={remove:"This action requires explicit user confirmation.",set_icon:'Use a notebook ID + icon. Prefer a Unicode hex code string such as "1f4d4" for 📔; raw emoji characters may not render correctly.',get_permissions:'Omit notebook or pass notebook="all" to return all notebook permissions. Pass a specific notebook ID to return one notebook only.',get_child_docs:"Use a notebook ID. Returns direct child documents at the notebook root, retries short initialization windows, and distinguishes notebook-not-found / closed-or-initializing failures."},nl={create:"Use notebook + path for the most direct child-document flow. path is a notebook-local hpath like /Folder/Parent/New Child, not /Notebook/... and not .sy. parentPath + title is also supported. markdown is optional and must not start with # Title; a matching leading H1 is stripped to avoid duplicate titles.",lookup:"Look up one reference at a time. Use id, notebook + storage path, or notebook + hpath/hPath. The path field means storage path like /20240318112233-abc123.sy; use hpath for human-readable paths.",rename:"Use either id + title or notebook + path + title.",remove:"Use either id or notebook + storage path. This action requires explicit user confirmation. If bulk ids/paths hit SiYuan's short indexing window, retry by deleting one document at a time with notebook + storage path.",move:"Use either fromIDs + toID or fromPaths + toNotebook + toPath. For path-based moves, toPath must be the storage path of an existing destination document. This action requires explicit user confirmation.",get_child_blocks:"Use a document ID. Returns direct child blocks only.",get_child_docs:"Use a document ID. Returns direct child documents only.",set_attr:"Use id + attrs. attrs.icon sets the document icon; attrs.cover sets an http(s) URL or /assets/... cover, and null/empty clears it.",list_tree:"Use notebook + path, where path is a storage path such as / or /20240318112233-abc123.sy.",search_docs:"Use notebook + query, and optionally path as a storage-path scope. Search is title-based in SiYuan; MCP then filters by notebook permission and optional storage path.",get_doc:'Use a document ID. mode="markdown" returns clean Markdown in complete display-block windows with outline, token budget, and nextWindow metadata; use blockStart/blockLimit/tokenBudget and optionally includeBlockIds. page/pageSize character pagination was removed. mode="html" uses the current focus view.',create_daily_note:"Use a notebook ID and optionally pass app for downstream SiYuan event routing. When the user asks for a diary, journal entry, daily log, or today’s note in a notebook, prefer this action over manually creating a path and then appending content."},rl={insert:"nextID inserts BEFORE that block; previousID inserts AFTER that block. Provide at least one of nextID, previousID, or parentID. Returns a slim success object with the created block ID. Use #tag# syntax in markdown when you want SiYuan to register a real tag.",prepend:"parentID can be either a document ID or block ID; behavior differs. Returns a slim success object with the created block ID. Use #tag# syntax in markdown when you want SiYuan to register a real tag.",append:"parentID can be either a document ID or block ID; behavior differs. Returns a slim success object with the created block ID. Prefer append when you need to add multi-line markdown, tables, or multiple new blocks. Use #tag# syntax in markdown when you want SiYuan to register a real tag.",update:'Use dataType + data + id to replace block content. Returns a slim success object instead of raw DOM operations. block(action="update") is best for single-block replacement; multi-line markdown may be truncated to the first line by SiYuan, so use append/prepend/insert when you need multiple blocks or tables. If the content should create tags, write them as #tag#.',replace:'Use id + edit to replace exact text inside one block kramdown content only. First read block(action="get_kramdown", id=...) and copy old from the block body. The writeback patches original DOM text nodes, preserving inline structure while rejecting IAL metadata edits. Naked ((id)) refs are normalized; footnotes and siyuan://blocks links are allowed but do not create backlinks.',set_attrs:'Use attrs to write block attributes such as custom metadata. For flashcards, this only writes metadata such as {"custom-riff-decks":"<deck-id>"}; prefer flashcard(action="create_card") when you want a block to become a real review card.',delete:"This action requires explicit user confirmation.",move:"Provide id or ids plus previousID, parentID, or both to describe the destination. When ids is provided, pass IDs in the desired final order; MCP calls SiYuan from last to first internally and returns apiCallOrder for debugging. This action requires explicit user confirmation.",set_fold_state:"Use a foldable block ID + folded (true to fold, false to unfold).",get_children:"Accepts both document IDs and block IDs. Returns direct child blocks. Use page/pageSize to paginate when there are many children.",info:"Returns root document positioning metadata for a block.",breadcrumb:"Optional excludeTypes removes matching block types from the breadcrumb.",dom:"Returns rendered DOM, useful for preview-style consumers.",recent_updated:"Returns recent updates across the workspace, then MCP filters unreadable notebooks and applies count when provided. documents is the primary user-facing summary; items remains the raw block stream.",word_count:"Provide one or more block IDs to receive aggregate stat data.",add_to_daily_note:'Use notebook + dataType + data + position ("append" or "prepend") to add content to today’s daily note.'},sl={get:"Use an attribute view ID. Returns the full AV payload after permission checks. blockID is optional and only needed for an exact database-block context or fallback permission resolution.",render:"Use id (the AV ID; avID is accepted as a compatibility alias) plus optional blockID/viewID/page/pageSize/query to render database rows with the active view context. With createIfNotExist=true, blockID becomes the creation target; if id is omitted, MCP generates one and materializes the database block automatically via a SiYuan-style transaction.",get_attribute_view_keys:"Use id to return database keys/columns for a block-bound attribute view.",get_attribute_view_filter_sort:"Use id + blockID to return the filters and sorts applied to that database block view.",search:"Searches AV/database definitions by keyword and post-filters unreadable results. Unresolvable matches remain discoverable in unresolvedResults, alongside raw result counts and filtering reasons. Match scope primarily covers AV names plus primary-key fallback results, not arbitrary cell text.",add_rows:'Use avID + blockIDs to add existing blocks as bound rows, or avID + primaryKeyTexts to add detached rows whose primary key is plain text. Optional blockID/viewID/groupID/previousID refine the insertion target and preserve the intended database-block view/group defaults. MCP polls briefly after insertion and only reports success when each new row resolves to a writable rowID. To add initial non-primary-key cell values, follow add_rows with av(action="set_cells", avID, cells=[{rowID, columnID, valueType, ...}, ...]); reuse the rowID returned by add_rows.',remove_rows:"Use avID + srcIDs to remove rows from the AV. Optional blockID pins a specific registered database block when you need explicit block-view context.",add_column:'Use avID + keyName + keyType, and optionally keyID or blockID. MCP generates keyID automatically when omitted. Supported keyType values match the 16 SiYuan addable column types, including keyType="mSelect", keyType="mAsset", and keyType="lineNumber". Optional blockID must be a registered database block for this AV if you need to pin a specific block view.',remove_column:"Use avID + keyID, and optionally blockID to target a specific registered database block. removeRelationDest only matters for relation columns.",set_cells:'Use avID + cells[]. Each item requires rowID + columnID + valueType and its matching typed field. For a single-cell write, pass rowID + columnID + valueType directly. rowID must be the AV row item ID stored in value.blockID, not value.id or the bound source block ID. Optional blockID must be a registered database block for this AV if you need to pin a specific block view. valueType="mAsset" accepts assets[].',duplicate:"Matches SiYuan copy-as-mirror behavior: call the kernel duplicate API, spin the AV block DOM, then commit an insert transaction. previousID overrides the insertion target; otherwise MCP uses blockID or the resolved owning database block.",get_primary_key_values:"Returns the AV name plus primary-key rows, with optional keyword/page/pageSize filtering."},al={upload_asset:"Use assetsDirPath + localFilePath to read a local file and upload it into SiYuan assets. The file alias is accepted for localFilePath, and omitted assetsDirPath uses /assets/. This action reads the local filesystem and requires explicit user confirmation. Files larger than the configured large-upload threshold (10 MB by default) must be stopped, confirmed by the user, and retried with confirmLargeFile=true.",list_templates:"Searches SiYuan data/templates via the kernel template picker endpoint. Empty query lists all visible Markdown templates. Results include readArgs and renderArgsTemplate for reuse.",read_template:"Use a path from list_templates, /data/templates/..., /templates/..., or a path relative to data/templates. Reads only Markdown template source and supports offset/limit pagination.",create_template:"Use path + markdown to create a Markdown template under data/templates. overwrite=false by default returns template_exists when the path already exists; pass overwrite=true to replace it.",update_template:"Use path + markdown to replace an existing Markdown template. The template must resolve through list_templates first; otherwise MCP returns template_not_found.",delete_template:"Deletes an existing Markdown template after resolving it through SiYuan’s template picker. This action is dangerous and disabled by default.",save_doc_as_template:"Use id + name to save a document as a root-level template through SiYuan’s docSaveAsTemplate API. Slashes are rejected; pass overwrite=true to replace an existing root template.",render:'Use engine="template" with id + path for a workspace template; that engine uses .action{...} delimiters and exposes limited document fields such as id/title/name/alias. Set preview=true for SiYuan preview DOM. Use engine="sprig" with inline template for {{...}} syntax; Sprig has functions but no document context.',export_resources:"Provide one or more existing resource paths. Asset paths like assets/foo.txt are normalized to /data/assets/foo.txt before export. Set outputPath to also copy the exported ZIP to a local filesystem path. Using outputPath is high-risk and requires explicit user confirmation. To extract attachments for direct reading without a ZIP archive, prefer extract_doc which produces an uncompressed folder.",get_doc_assets:'Use a document ID to list assets directly referenced by the current document tree after read-permission checks. This does not expand query embed blocks; when the user needs to inspect the full document content and assets, guide them to file(action="extract_doc") instead. Use assetType="image" to return only direct image assets.',get_image_ocr_text:"Use an asset path to read stored OCR text. If path is omitted, SiYuan returns an empty text payload.",extract_doc:"Use a document ID + optional outputDir. Exports the document markdown and all referenced assets into an uncompressed folder, preserving original filenames. If outputDir is omitted, the default output root is ~/siyuan-extracted/; pass outputDir explicitly for a predictable path such as /private/tmp. Clears the entire output root directory first to prevent accumulation from previous exports. The returned extractedDir is an absolute path ready for direct file access."},il=["All search actions are read-only except find_replace, which modifies content and requires explicit user confirmation.",'search(action="query_sql") only accepts SELECT statements; mutation queries will be rejected, and returned rows are filtered by notebook permission.',"When calling query_sql, always add LIMIT yourself. MCP may still truncate large result sets and will tell you when to refine the query.","The blocks table columns include: id, parent_id, root_id, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated.","In SQL results, blocks.type uses SiYuan short codes such as d=document, h=heading, p=paragraph, l=list, i=list-item, b=blockquote, c=code, m=math, t=table, html=html, video=video, audio=audio, widget=widget.",'Use search(action="fulltext") for natural language searches; use search(action="query_sql") for structured queries.','search(action="fulltext") types field auto-expands shortcodes: {"h": true, "p": true} is equivalent to {"heading": true, "paragraph": true}. Shortcodes: d/h/p/l/i/b/c/m/t/s/html/embed/av. Prefer semantic aliases such as methodName/sortBy over numeric method/orderBy.','search(action="fulltext") supports parentId to scope results within a document subtree, and hasTags to filter by tag presence.',"Right after creating or editing content, full-text and tag search can lag behind writes because SiYuan indexing is eventually consistent; brief retries are expected in live tests."],cl={fulltext:'Pass a query string. Supports keyword, query syntax, SQL, and regex modes via methodName (preferred) or method. fulltext now returns plainContent/excerpt by default. types accepts shortcodes directly: {"h": true, "c": true} auto-expands to {"heading": true, "codeBlock": true}. Use sortBy="relevance" or "date" instead of numeric orderBy. Use parentId to scope within a document, hasTags to filter tagged blocks.',query_sql:"Execute a SELECT statement. Common tables: blocks, spans, assets. Prefer sql over stmt when prompting an AI. Always use LIMIT to control result size. MCP returns data plus truncation and permission-filtering metadata when applicable.",get_backlinks:'Returns documents/blocks that contain references and/or text mentions for the given block ID. Use mode="links" | "mentions" | "both". Partial permission-filtered results include machine-readable metadata.',search_refs:"Returns block-level reference contexts for the target id. Use this when you need the surrounding block content, not just the document-level backlink list. beforeLen controls how much leading context is included in each hit.",find_replace:"This is the mutating exception inside the search tool. It performs content replacement after write-permission checks and still requires explicit user confirmation.",search_assets:"Searches asset filenames. Prefer query over k when prompting an AI. If you need OCR or indexed inner-text matches, use fulltext_asset_content instead.",fulltext_asset_content:"Searches indexed asset/OCR text. Prefer methodName and sortBy over numeric method/orderBy. Provide assetId for an exact asset-content lookup."},ll={list:"Optional keyword/query searches tags; sort, ignoreMaxListHint, and app are passed through to SiYuan for plain listing.",rename:"Renames a workspace tag label everywhere it appears.",remove:"Deletes a workspace tag label. This action requires explicit user confirmation."},ul={workspace_info:"Returns workspace path metadata and current SiYuan version. High-risk: leaks the absolute workspace path; disabled by default and requires explicit user confirmation.",network:"Returns masked proxy information only.",conf:'Defaults to a navigable summary. Use mode="get" with keyPath to read one config field or subtree at a time, e.g. conf.appearance.mode or conf.langs[0].',notify:"Show an info or error notification in the SiYuan UI. Optional timeout is in milliseconds.",changelog:"Reads the bundled plugin CHANGELOG with structured personalizationReview hints. Pass fromVersion after upgrades, version for one exact entry, or includeRaw=true for Markdown.",perform_sync:"Triggers SiYuan sync immediately through /api/sync/performSync. This action can change local and remote sync state and requires explicit user confirmation.",get_version:"Returns the current SiYuan version as {version}.",get_current_time:"Returns the current system time as {currentTime} epoch milliseconds and {iso} ISO 8601 text."},dl={list_cards:`Use scope="all" | "deck" | "notebook" | "tree" plus filter="due" | "new" | "old". For scope="all", omit deckID; an empty string is treated as omitted. For scope="deck", pass a non-empty deckID. For scope="notebook", pass notebook. For scope="tree", pass rootID. reviewedCards is optional and follows SiYuan's review flow.`,get_decks:"Returns available flashcard decks so the caller can discover deckID values.",get_cards:"Use deckID + optional page/pageSize to list all cards in a deck (regardless of due state). Use empty string deckID to query across all decks. Returns cards, total count, and pageCount.",review_card:"Use a concrete deckID + cardID + rating, or pass skip=true to skip. Resolve deckID/cardID through list_cards or get_cards first; empty deckID is rejected. reviewedCards is optional; each entry must include cardID because SiYuan only reads reviewedCards[].cardID.",create_card:"Use deckID + content blockIDs to turn existing blocks into flashcards; single blockID is accepted as a convenience alias. Non-built-in deck IDs must already exist. Document block IDs are rejected. This calls SiYuan's addRiffCards flow, writes custom-riff-decks, verifies the binding, and creates deck records together.",remove_card:"Use deckID + blockIDs to remove flashcard bindings from a deck. This does not delete the underlying note blocks. This action requires explicit user confirmation."},pl={get_balance:"Returns the cat’s current balance and lifetime earned count. Each successful MCP tool call adds 1 coin and increments the lifetime count.",shop:"Returns the current mascot shop inventory including stable item IDs, labels, cost, type, and emoji.",buy:"Buys one shop item by item_id and deducts its configured cost from balance."},fl={submit:"Sends plain-text feedback. Put a GitHub Issue-style report in description when reporting bugs, confusing behavior, or rough workflows. Recommended headings: ## Summary, ## What happened, ## Expected behavior, ## Steps or context, ## Impact, ## Suggested fix. impact should be a short impact summary; suggestion should be the direct fix idea. Avoid private note content and secrets."},bg={list:"Set refresh=true to re-read the official SiYuan MCP tool registry. The result separates plugin/native sources and reports the currently exposed schema size. Discovery failures preserve the last successful cache."},hl={fs:Hc,notebook:Vc,document:Zc,block:Yc,av:Wc,file:Gc,search:il,tag:Kc,system:Jc,flashcard:Qc,extension:yg,mascot:Xc,feedback:el},Po={fs:tl,notebook:ol,document:nl,block:rl,av:sl,file:al,search:cl,tag:ll,system:ul,flashcard:dl,extension:bg,mascot:pl,feedback:fl},wg={document:{create:[{title:"Create a child document by notebook-local hpath (recommended)",description:"The path is inside the notebook. Do not include the notebook name, and do not pass a .sy storage path here.",mcp:{action:"create",notebook:"20210808180117-czj9bvb",path:"/Folder/Parent/New Child",markdown:"正文从这里开始,不要再写 # New Child。"}},{title:"Create with a human-readable parent hpath plus title",description:"Use this when the parent hpath is already known and you want the title separated from the parent path.",mcp:{action:"create",notebook:"20210808180117-czj9bvb",parentPath:"/Folder/Parent",title:"New Child",markdown:"正文从这里开始,不要再写 # New Child。"}},{title:"Create with a storage parent path returned by lookup",description:"Only parentPath accepts this .sy storage path form; path does not.",mcp:{action:"create",notebook:"20210808180117-czj9bvb",parentPath:"/20240318112233-abc123.sy",title:"New Child"}}]},fs:{replace:[{title:"Replace exact text with canonical edit object",mcp:{action:"replace",path:"/Notebook/Folder/Doc",edit:{old:"ORIGINAL_TEXT",new:"NEW_TEXT"}}},{title:"Replace exact text with shorthand old/new",description:'Equivalent CLI form: siyuan-sisyphus fs replace --path "/Notebook/Folder/Doc" --old ORIGINAL_TEXT --new NEW_TEXT',mcp:{action:"replace",path:"/Notebook/Folder/Doc",old:"ORIGINAL_TEXT",new:"NEW_TEXT",replace_all:!1}}]},notebook:{},block:{word_count:[{title:"Get word count for one block",description:"id is accepted as a convenience alias for ids=[id].",mcp:{action:"word_count",id:"20240318112233-abc123"}},{title:"Get word count for multiple blocks",mcp:{action:"word_count",ids:["20240318112233-abc123","20240318112233-def456"]}}]},av:{render:[{title:"Render an AV returned by search",description:"av.search results include renderArgs; pass id or the compatibility alias avID.",mcp:{action:"render",id:"20240318112233-abc123",page:1,pageSize:20}},{title:"Render with avID compatibility alias",mcp:{action:"render",avID:"20240318112233-abc123"}}]},file:{upload_asset:[{title:"Upload a local file with canonical fields",mcp:{action:"upload_asset",assetsDirPath:"/assets/",localFilePath:"/private/tmp/demo.txt"}},{title:"Upload a local file with file shorthand",description:"When assetsDirPath is omitted, upload_asset uses /assets/.",mcp:{action:"upload_asset",file:"/private/tmp/demo.txt"}}],create_template:[{title:"Create a nested Markdown template",mcp:{action:"create_template",path:"reports/monthly.md",markdown:`# .action{.title}
425
+ `,ni="siyuan://help/changelog",dg=5,pg=50,ri=[{area:"tool-config",pattern:/工具配置|tool config|action|聚合工具|工具设置|settings panel|设置面板/i},{area:"user-rules",pattern:/用户规则|custom rules|USER_RULES|个性化|偏好/i},{area:"agent-memory",pattern:/AGENTS\.md|Agent 记忆|workspace memory|虚拟.*记忆/i},{area:"permissions",pattern:/权限|permission|dangerous|确认|高风险/i},{area:"connection",pattern:/MCP|HTTP|HTTPS|stdio|CLI|Docker|远程|连接|token|profile|环境变量/i},{area:"appearance",pattern:/主题|配色|外观|猫猫|i18n|国际化|语言/i},{area:"timeline",pattern:/文档时间线|timeline|Dock|侧边栏|历史版本/i}];function Le(e){return e.trim().replace(/^v/i,"")}function fg(e){var t;return"0.5.1".trim()?Le("0.5.1"):((t=e[0])==null?void 0:t.version)??"0.0.0"}function hg(e,t){const o=Le(e).split(/[.-]/).map(s=>Number.parseInt(s,10)),n=Le(t).split(/[.-]/).map(s=>Number.parseInt(s,10)),r=Math.max(o.length,n.length,3);for(let s=0;s<r;s++){const a=Number.isFinite(o[s])?o[s]:0,i=Number.isFinite(n[s])?n[s]:0;if(a!==i)return a>i?1:-1}return 0}function mg(e){return e.split(`
426
+ `).map(t=>t.trim()).filter(t=>t.startsWith("- ")).map(t=>t.slice(2).trim()).filter(Boolean)}function gg(e,t){const o=new Set,n=[];for(const r of e){const s=ri.filter(({pattern:a})=>a.test(r)).map(({area:a})=>a);s.length!==0&&(s.forEach(a=>o.add(a)),n.push(r))}if(n.length===0)for(const{area:r,pattern:s}of ri)s.test(t)&&o.add(r);return{mayAffectPersonalization:o.size>0,areas:[...o].sort(),matchedItems:n}}function yg(e=ug){const t=[...e.matchAll(/^##\s+(v?[0-9][^\s]*)\s*(?:-\s*(.+))?\s*$/gm)];return t.map((o,n)=>{var l,u;const r=o.index??0,s=((l=t[n+1])==null?void 0:l.index)??e.length,a=e.slice(r,s).trim(),i=mg(a);return{version:Le(o[1]??""),date:(u=o[2])==null?void 0:u.trim(),title:o[0].trim(),items:i,rawMarkdown:a,personalizationImpact:gg(i,a)}}).filter(o=>o.version)}function Vc(e){return typeof e!="number"||!Number.isFinite(e)?dg:Math.max(1,Math.min(pg,Math.trunc(e)))}function bg(e,t){var n,r;if((n=t.version)!=null&&n.trim()){const s=Le(t.version);return e.filter(a=>Le(a.version)===s).slice(0,1)}const o=Vc(t.limit);if((r=t.fromVersion)!=null&&r.trim()){const s=Le(t.fromVersion);return e.filter(a=>hg(a.version,s)>0).slice(0,o)}return e.slice(0,o)}function wg(e={}){const t=yg(),o=bg(t,e),n=o.filter(r=>r.personalizationImpact.mayAffectPersonalization);return{source:"bundled CHANGELOG.md",resource:ni,pluginVersion:fg(t),totalEntries:t.length,returnedEntries:o.length,query:{version:e.version?Le(e.version):void 0,fromVersion:e.fromVersion?Le(e.fromVersion):void 0,limit:Vc(e.limit),includeRaw:e.includeRaw===!0},entries:o.map(r=>({version:r.version,date:r.date,title:r.title,items:r.items,personalizationImpact:r.personalizationImpact,...e.includeRaw?{rawMarkdown:r.rawMarkdown}:{}})),personalizationReview:{shouldReview:n.length>0,affectedVersions:n.map(r=>r.version),affectedAreas:[...new Set(n.flatMap(r=>r.personalizationImpact.areas))].sort(),hints:[`Read ${ni} or call system(action="changelog", fromVersion="<previousVersion>") after upgrades.`,"If affectedAreas includes user-rules, agent-memory, permissions, connection, appearance, timeline, or tool-config, compare the changelog with active user rules and /AGENTS.md before changing behavior.","When a configured preference may be stale, remind the user what changed and ask before rewriting persistent configuration or memory."]}}}const Zc=["Use fs first for ordinary document file operations: list, tree, read, write, move, delete, and grep-like search.","fs paths are human-readable workspace paths such as /Notebook/Folder/Doc; fs outputs the same human-readable path shape and hides notebook IDs, block IDs, and storage paths.","fs is a pure Markdown convenience layer. If a document contains SiYuan-native structures such as database blocks, super blocks, embeds, media blocks, query embeds, widgets, HTML, or precise block-tree layout, inspect and modify those structures with advanced tools such as block, av, file, document, or search instead.",`fs.read returns an AI-editable Markdown view built from block kramdown, not /api/export/exportMdContent. It preserves SiYuan double-links as ((id 'title')), preserves tags as #tag#, strips SiYuan zero-width tag markers, and hides block/list-item IAL metadata such as {: id="..." updated="..."} from normal list editing.`,"fs.read always returns complete display-block windows. Use blockStart/blockLimit/tokenBudget to continue long documents; code, math, tables, lists, quotes, and other container blocks are never split. The response includes a full heading outline and nextWindow when more blocks remain.",'Copy old snippets for fs.replace from fs.read output. fs.replace uses the same AI-editable view for matching, so list items like "- item" can be replaced without including hidden IAL metadata. For inline styled text, use the plain text inside the style markers as old text: replace "hello" inside **hello** or `hello`, not "**hello**" or "`hello`"; DOM writeback preserves the existing inline style.',"Use document, block, search, or av for advanced SiYuan-specific operations such as block-level layout, metadata, database rows, SQL, backlinks, or assets.",'fs(action="write") creates missing documents. Do not include a leading # Title in markdown; the document title is rendered automatically. Existing documents are protected unless overwrite=true.',"For double-links in fs.write or fs.replace replacement text, use ((block-id 'anchor text')) with a real block ID and human-readable anchor text. Naked ((id)) is resolved before writing; if anchor lookup fails, MCP falls back to ((id 'id')) with a warning.",'For tags in fs.write or fs.replace replacement text, use #tag# or hierarchical tag syntax such as #parent/child#; verify global tag state with tag(action="list", query="tag").','fs(action="replace") performs exact string replacement only inside non-complex Markdown blocks. If a document also contains complex SiYuan-native blocks, those blocks are skipped; replacements that only exist inside skipped blocks, or cross block boundaries, are rejected without writing.','If fs.read reports attributeViews or avToolHint, the document contains real database blocks. Use av(action="get"|"render"|"set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column") for AV rows, columns, and cells instead of editing the database placeholder as Markdown.','fs(action="rm") and fs(action="mv") require explicit user confirmation before execution.'],Yc=["Use notebook IDs for set_open_state, rename, get_conf, and set_conf.",'notebook(action="get_permissions") supports notebook="all" (or omission) for all notebooks, and a specific notebook ID for one notebook.','notebook(action="remove") requires explicit user confirmation before execution.','notebook(action="get_child_docs") returns direct child documents at the notebook root and retries short closed-or-initializing windows before failing.','Right after notebook(action="set_open_state", opened=false), get_child_docs may still return a retryable closed-or-initializing error; open the notebook first or retry shortly.'],Wc=['For ordinary document file operations, prefer fs(action="ls"|"tree"|"read"|"write"|"search") because it accepts human-readable paths and hides storage paths and IDs.','document(action="create") creates both non-empty and empty documents. Prefer path for child documents; path is a notebook-local human-readable hpath such as /Folder/Parent/New Child, not /Notebook/Folder/... and not a .sy storage path.','Do not put # Title at the start of document(action="create") markdown. SiYuan renders the document title as H1 automatically, and MCP strips a matching leading H1 to avoid duplicate titles.','document(action="create", parentPath=..., title=...) is also supported. parentPath accepts either a notebook-local human-readable parent hpath such as /Folder/Parent, or a storage path ending in .sy returned by document(action="lookup").','fs(action="write", path="/Notebook/Folder/Doc") uses a workspace path that includes the notebook name; document(action="create", notebook=..., path="/Folder/Doc") uses a notebook-local hpath. Do not mix these two path formats.','For document(action="lookup"), path means a storage path such as /20240318112233-abc123.sy; use hpath/hPath for human-readable paths such as /Inbox/Weekly Note.','Other document actions that use notebook + path expect storage paths returned by document(action="lookup").','If document(action="create") reports a duplicate-name error, verify the intended child with document(action="lookup", notebook=..., hpath="/Folder/Parent/New Child", include=["id","path","hpath"]) or document(action="get_child_docs", id=<parent-doc-id>). New create results may take a short indexing delay before lookup/search sees them.',"A safe path-based workflow is lookup -> rename/remove/move.",'document(action="get_child_blocks") and document(action="get_child_docs") return direct children for a document ID.','document(action="set_attr") updates document metadata such as icon and cover; use attrs.cover=null or an empty string to clear the cover.','document(action="search_docs") remains title-based, but MCP now post-filters results by notebook permission and optional storage path scope.','For recently created documents, document(action="lookup", hpath=...) may briefly lag behind create because it depends on SiYuan indexing; retry if needed.','document(action="lookup", id=...) may hit the same short indexing delay right after create; MCP retries briefly and then returns a timing-specific hint if indexing still has not settled.'],Gc=['block(action="prepend") or block(action="append") with a document ID targets the document start or end.','block(action="update") is best for single-block replacement. Multi-line markdown may be truncated to the first line by SiYuan; use append/prepend/insert when you need multiple blocks, tables, or longer multi-line content.','block(action="replace") only searches the kramdown of the single block identified by id. It does not traverse child blocks, sibling blocks, headings with their following content, or the whole document.','Before block(action="replace"), call block(action="get_kramdown", id=...) and copy an exact old snippet from that result. It writes back through the original DOM text nodes; naked ((id)) references, footnotes, and siyuan://blocks links are allowed with backlink-semantics hints.',`block(action="prepend") or block(action="append") with a block ID targets that block's child list.`,'To create real SiYuan tags inside markdown content, use the syntax #tag# with both leading and trailing # characters, then verify with tag(action="list", query="tag").','To turn a block into a flashcard, prefer flashcard(action="create_card"). It writes "custom-riff-decks" and registers the riff card together.','block(action="set_fold_state") requires a foldable block ID, not a document ID.','block(action="recent_updated") is read-only; MCP filters unreadable notebooks first and then applies count.','block(action="recent_updated") now presents the document-grouped summary as the primary user-facing view while keeping the raw block stream for advanced consumers.'],Kc=["AV actions operate on real SiYuan attribute views (database blocks), not Markdown tables.",'To initialize a new AV definition, call av(action="render", blockID, createIfNotExist=true). MCP can generate the AV ID automatically and materialize a SiYuan-style NodeAttributeView block in the target document through a transaction.',"Most follow-up AV reads and writes only need avID. MCP resolves the owning database block from row bindings, mirror database blocks, or the blocks-table AV block record; pass blockID when you need an exact database-block view context or fallback.",'Use strong typed fields such as valueType=text/number/date/checkbox/select when calling av(action="set_cells").',"For cell writes, rowID must be the database row item ID stored in each AV value's blockID field. The value id field is only the cell value ID, and block.id is the original bound source block ID.","AV permission checks resolve from registered database blocks. For createIfNotExist=true, provide blockID as the creation target; after materialization, MCP can usually rediscover that owning database block automatically.",'av(action="search") first queries kernel search results, then MCP post-filters unreadable or unresolvable AVs and reports the filtering metadata.','av(action="search") is best for database names and primary-key matches. Do not assume it will find arbitrary non-primary-key cell text immediately after writes.'],Jc=['file(action="upload_asset") reads a local file path and uploads that file into SiYuan assets. Because it reads the local filesystem, it requires explicit user confirmation before execution.',"If the file is larger than the configured large-upload threshold (10 MB by default), MCP must stop and ask the user for explicit confirmation before retrying with confirmLargeFile=true.",'file(action="export_resources") exports the given paths as a ZIP archive, normalizes common asset path formats, and can optionally save the ZIP to a local filesystem path.','file(action="export_resources", outputPath=...) writes to the local filesystem and requires explicit user confirmation before execution.','Use file(action="list_templates") before rendering when you need to discover valid workspace template paths under data/templates.','file(action="read_template") reads Markdown template source through SiYuan’s authenticated /templates/ route; it does not expose arbitrary workspace files.','file(action="create_template"|"update_template") writes Markdown templates through SiYuan’s /api/file/putFile workspace API; it does not write data/templates through the local filesystem.','file(action="delete_template") removes an existing Markdown template resolved from SiYuan’s template picker and requires explicit user confirmation before execution.','file(action="save_doc_as_template") saves an existing document as a root-level template after read-permission checks; use create_template when you need a nested template path.','file(action="render", engine="template") requires a template path inside the SiYuan workspace; arbitrary local paths like /tmp/... are rejected by the kernel.','file(action="render", engine="template") uses SiYuan workspace template syntax .action{.title}, .action{.id}, .action{.name}, and .action{.alias}; it does not replace {{...}} placeholders.','file(action="render", engine="sprig") uses inline Go/Sprig template syntax such as {{ now | date "2006-01-02" }}, but it has no document context.','file(action="extract_doc") exports a document and all its assets into a self-contained uncompressed folder, so AI tools can read the files directly. Prefer this over export_resources when the goal is to inspect attachment content such as images, spreadsheets, or other binary files.'],Qc=["Tag actions operate across the whole workspace rather than a single notebook.","There is no direct create action for tags; tags are created by writing #tag# into block markdown content.",'tag(action="remove") requires explicit user confirmation before execution.',"Recently written tags may appear with a short indexing delay in tag list/search results; retry briefly before treating that as a failure."],Xc=["Most system actions in this tool are read-only; perform_sync is the mutating exception and requires explicit user confirmation before execution.",'system(action="workspace_info") exposes the workspace path and is high-risk; it is disabled by default.','system(action="perform_sync") triggers SiYuan sync immediately; it does not modify sync provider settings.','system(action="conf") returns masked configuration, not raw secrets.','Use system(action="changelog", fromVersion="<previousVersion>") after plugin upgrades to see whether old personalized settings, rules, memory, or connection snippets need review.','Use system(action="conf", mode="summary") first, then mode="get" + keyPath such as conf.appearance.mode or conf.langs[0].'],el=["flashcard actions cover review-first flashcard workflows and deck discovery.",`list_cards always reads from the kernel due-card endpoints and MCP post-filters cards by state for filter="new" or filter="old"; pass reviewedCards to match SiYuan's in-review filtering.`,"get_cards returns all cards in a deck (not just due ones), with pagination. Use it to browse or audit deck contents.",'Prefer flashcard(action="create_card", deckID, blockIDs) when the goal is to turn existing blocks into real flashcards.',`create_card validates non-built-in deck IDs against get_decks, then calls SiYuan's riff add-card operation, which writes "custom-riff-decks" and registers the riff card transactionally.`,"Create or locate the intended content block IDs first, then pass those IDs to create_card. Document block IDs are rejected; use content blocks such as headings or paragraphs.",'create_card(mode="attach") is retained for compatibility; SiYuan still writes the deck binding during the riff add-card operation. remove_card removes existing content block IDs such as paragraphs or headings from a deck; document blocks are rejected for creation.',"review_card requires a concrete deckID and cardID. Use list_cards or get_cards to resolve them; an empty deckID is not valid for review.","Flashcard removal only removes riff card bindings from a deck. It does not delete the underlying note blocks; deleting note blocks is a separate block/document delete workflow.",'flashcard(action="remove_card") requires explicit user confirmation before execution.'],kg=["extension bridges tools from the official SiYuan /mcp endpoint and requires SiYuan 3.7.0 or newer.",'Plugin tools are exposed by default. Native SiYuan tools are exposed only when extension.includeNativeTools is enabled; external source="mcp" tools remain excluded.','Use extension(action="list", refresh=true) to refresh discovery and inspect official tool names, sources, schemas, read-only declarations, and blocked state.','Call a discovered tool with extension(action="<official tool name>", arguments={...}). Downstream parameters must stay inside arguments, including a downstream action field.',"Tools without readOnlyHint=true may mutate data or trigger side effects and require explicit user confirmation before calling.","Forwarded official MCP tool calls are never retried. A transport error after dispatch means execution status is unknown and must be checked before retrying.","Native tools can overlap with Sisyphus actions and substantially increase schema size, so includeNativeTools is disabled by default."],tl=["mascot actions operate on the cat’s spendable balance.","Every successful MCP tool call earns 1 coin for the cat, so the fastest way to earn balance is simply to keep using SiYuan MCP tools.",'Use mascot(action="shop") to list available items and their stable item IDs.','Use mascot(action="buy", item_id=...) to purchase an item and spend from the balance.'],ol=["feedback submits plain-text product feedback to the developer through the configured WPS form channel.",'Use feedback(action="submit") when the user asks you to pass along feedback, or when an AI client needs to report MCP tool friction after explaining what will be sent.',"Prefer GitHub Issue-style feedback for bugs, confusing names/parameters/help/errors, or rough workflows encountered during an AI session.","Put the full issue-style body in description with these headings when useful: ## Summary, ## What happened, ## Expected behavior, ## Steps or context, ## Impact, ## Suggested fix.","Use impact for a one- or two-sentence impact summary, and suggestion for the most direct improvement idea without repeating the full description.","Do not include secrets, private note content, API tokens, or sensitive document paths in feedback."],nl={ls:'Use a human-readable path. "/" lists readable notebook roots; /Notebook or /Notebook/Folder lists direct child documents.',tree:"Use a human-readable path. maxDepth defaults to 3 and keeps output compact.",read:"Use a human-readable document path. Returns an AI-editable Markdown window made only of complete display blocks. Continue with nextWindow or blockStart/blockLimit/tokenBudget; page/pageSize character pagination was removed. The response includes a full heading outline, and includeBlockIds=true adds a sidecar blockRefs mapping without polluting content. When complex SiYuan blocks are detected, use block.dom, file.export_md, av, or other advanced tools for inspection and editing.",write:"Creates a missing document. Do not include a leading # Title in markdown; the document title is automatic. Existing pure Markdown documents are protected unless overwrite=true; overwrite refuses documents containing complex SiYuan-native blocks. Use ((id 'title')) for double-links and #tag# for tags; use advanced tools for database rows, cells, super blocks, embeds, widgets, HTML, and media.",replace:"Edits matched non-complex Markdown blocks by exact old/new matching against the same AI-editable view returned by fs.read. Canonical input is edit={old,new}; shorthand old + new is also accepted. If the document contains complex SiYuan-native blocks, fs.replace skips those blocks and returns skippedComplexBlocks; matches only inside skipped blocks or across block boundaries are rejected without writing. For inline formatting, old should be plain text without Markdown style delimiters such as **, *, `, or ~~; existing DOM inline styles are preserved. Naked ((id)) refs are normalized, and footnotes/siyuan://blocks links are allowed but do not create backlinks. replace_all=true replaces every exact match across editable blocks. Use ((id 'title')) for new double-links and #tag# for tags.",rm:"Deletes a document by human-readable path. This action requires explicit user confirmation.",mv:"Moves or renames a document using human-readable paths. This action requires explicit user confirmation.",search:"Searches Markdown lines under a human-readable document or folder path. Use regex=true for regular expressions."},rl={remove:"This action requires explicit user confirmation.",set_icon:'Use a notebook ID + icon. Prefer a Unicode hex code string such as "1f4d4" for 📔; raw emoji characters may not render correctly.',get_permissions:'Omit notebook or pass notebook="all" to return all notebook permissions. Pass a specific notebook ID to return one notebook only.',get_child_docs:"Use a notebook ID. Returns direct child documents at the notebook root, retries short initialization windows, and distinguishes notebook-not-found / closed-or-initializing failures."},sl={create:"Use notebook + path for the most direct child-document flow. path is a notebook-local hpath like /Folder/Parent/New Child, not /Notebook/... and not .sy. parentPath + title is also supported. markdown is optional and must not start with # Title; a matching leading H1 is stripped to avoid duplicate titles.",lookup:"Look up one reference at a time. Use id, notebook + storage path, or notebook + hpath/hPath. The path field means storage path like /20240318112233-abc123.sy; use hpath for human-readable paths.",rename:"Use either id + title or notebook + path + title.",remove:"Use either id or notebook + storage path. This action requires explicit user confirmation. If bulk ids/paths hit SiYuan's short indexing window, retry by deleting one document at a time with notebook + storage path.",move:"Use either fromIDs + toID or fromPaths + toNotebook + toPath. For path-based moves, toPath must be the storage path of an existing destination document. This action requires explicit user confirmation.",get_child_blocks:"Use a document ID. Returns direct child blocks only.",get_child_docs:"Use a document ID. Returns direct child documents only.",set_attr:"Use id + attrs. attrs.icon sets the document icon; attrs.cover sets an http(s) URL or /assets/... cover, and null/empty clears it.",list_tree:"Use notebook + path, where path is a storage path such as / or /20240318112233-abc123.sy.",search_docs:"Use notebook + query, and optionally path as a storage-path scope. Search is title-based in SiYuan; MCP then filters by notebook permission and optional storage path.",get_doc:'Use a document ID. mode="markdown" returns clean Markdown in complete display-block windows with outline, token budget, and nextWindow metadata; use blockStart/blockLimit/tokenBudget and optionally includeBlockIds. page/pageSize character pagination was removed. mode="html" uses the current focus view.',create_daily_note:"Use a notebook ID and optionally pass app for downstream SiYuan event routing. When the user asks for a diary, journal entry, daily log, or today’s note in a notebook, prefer this action over manually creating a path and then appending content."},al={insert:"nextID inserts BEFORE that block; previousID inserts AFTER that block. Provide at least one of nextID, previousID, or parentID. Returns a slim success object with the created block ID. Use #tag# syntax in markdown when you want SiYuan to register a real tag.",prepend:"parentID can be either a document ID or block ID; behavior differs. Returns a slim success object with the created block ID. Use #tag# syntax in markdown when you want SiYuan to register a real tag.",append:"parentID can be either a document ID or block ID; behavior differs. Returns a slim success object with the created block ID. Prefer append when you need to add multi-line markdown, tables, or multiple new blocks. Use #tag# syntax in markdown when you want SiYuan to register a real tag.",update:'Use dataType + data + id to replace block content. Returns a slim success object instead of raw DOM operations. block(action="update") is best for single-block replacement; multi-line markdown may be truncated to the first line by SiYuan, so use append/prepend/insert when you need multiple blocks or tables. If the content should create tags, write them as #tag#.',replace:'Use id + edit to replace exact text inside one block kramdown content only. First read block(action="get_kramdown", id=...) and copy old from the block body. The writeback patches original DOM text nodes, preserving inline structure while rejecting IAL metadata edits. Naked ((id)) refs are normalized; footnotes and siyuan://blocks links are allowed but do not create backlinks.',set_attrs:'Use attrs to write block attributes such as custom metadata. For flashcards, this only writes metadata such as {"custom-riff-decks":"<deck-id>"}; prefer flashcard(action="create_card") when you want a block to become a real review card.',delete:"This action requires explicit user confirmation.",move:"Provide id or ids plus previousID, parentID, or both to describe the destination. When ids is provided, pass IDs in the desired final order; MCP calls SiYuan from last to first internally and returns apiCallOrder for debugging. This action requires explicit user confirmation.",set_fold_state:"Use a foldable block ID + folded (true to fold, false to unfold).",get_children:"Accepts both document IDs and block IDs. Returns direct child blocks. Use page/pageSize to paginate when there are many children.",info:"Returns root document positioning metadata for a block.",breadcrumb:"Optional excludeTypes removes matching block types from the breadcrumb.",dom:"Returns rendered DOM, useful for preview-style consumers.",recent_updated:"Returns recent updates across the workspace, then MCP filters unreadable notebooks and applies count when provided. documents is the primary user-facing summary; items remains the raw block stream.",word_count:"Provide one or more block IDs to receive aggregate stat data.",add_to_daily_note:'Use notebook + dataType + data + position ("append" or "prepend") to add content to today’s daily note.'},il={get:"Use an attribute view ID. Returns the full AV payload after permission checks. blockID is optional and only needed for an exact database-block context or fallback permission resolution.",render:"Use id (the AV ID; avID is accepted as a compatibility alias) plus optional blockID/viewID/page/pageSize/query to render database rows with the active view context. With createIfNotExist=true, blockID becomes the creation target; if id is omitted, MCP generates one and materializes the database block automatically via a SiYuan-style transaction.",get_attribute_view_keys:"Use id to return database keys/columns for a block-bound attribute view.",get_attribute_view_filter_sort:"Use id + blockID to return the filters and sorts applied to that database block view.",search:"Searches AV/database definitions by keyword and post-filters unreadable results. Unresolvable matches remain discoverable in unresolvedResults, alongside raw result counts and filtering reasons. Match scope primarily covers AV names plus primary-key fallback results, not arbitrary cell text.",add_rows:'Use avID + blockIDs to add existing blocks as bound rows, or avID + primaryKeyTexts to add detached rows whose primary key is plain text. Optional blockID/viewID/groupID/previousID refine the insertion target and preserve the intended database-block view/group defaults. MCP polls briefly after insertion and only reports success when each new row resolves to a writable rowID. To add initial non-primary-key cell values, follow add_rows with av(action="set_cells", avID, cells=[{rowID, columnID, valueType, ...}, ...]); reuse the rowID returned by add_rows.',remove_rows:"Use avID + srcIDs to remove rows from the AV. Optional blockID pins a specific registered database block when you need explicit block-view context.",add_column:'Use avID + keyName + keyType, and optionally keyID or blockID. MCP generates keyID automatically when omitted. Supported keyType values match the 16 SiYuan addable column types, including keyType="mSelect", keyType="mAsset", and keyType="lineNumber". Optional blockID must be a registered database block for this AV if you need to pin a specific block view.',remove_column:"Use avID + keyID, and optionally blockID to target a specific registered database block. removeRelationDest only matters for relation columns.",set_cells:'Use avID + cells[]. Each item requires rowID + columnID + valueType and its matching typed field. For a single-cell write, pass rowID + columnID + valueType directly. rowID must be the AV row item ID stored in value.blockID, not value.id or the bound source block ID. Optional blockID must be a registered database block for this AV if you need to pin a specific block view. valueType="mAsset" accepts assets[].',duplicate:"Matches SiYuan copy-as-mirror behavior: call the kernel duplicate API, spin the AV block DOM, then commit an insert transaction. previousID overrides the insertion target; otherwise MCP uses blockID or the resolved owning database block.",get_primary_key_values:"Returns the AV name plus primary-key rows, with optional keyword/page/pageSize filtering."},cl={upload_asset:"Use assetsDirPath + localFilePath to read a local file and upload it into SiYuan assets. The file alias is accepted for localFilePath, and omitted assetsDirPath uses /assets/. This action reads the local filesystem and requires explicit user confirmation. Files larger than the configured large-upload threshold (10 MB by default) must be stopped, confirmed by the user, and retried with confirmLargeFile=true.",list_templates:"Searches SiYuan data/templates via the kernel template picker endpoint. Empty query lists all visible Markdown templates. Results include readArgs and renderArgsTemplate for reuse.",read_template:"Use a path from list_templates, /data/templates/..., /templates/..., or a path relative to data/templates. Reads only Markdown template source and supports offset/limit pagination.",create_template:"Use path + markdown to create a Markdown template under data/templates. overwrite=false by default returns template_exists when the path already exists; pass overwrite=true to replace it.",update_template:"Use path + markdown to replace an existing Markdown template. The template must resolve through list_templates first; otherwise MCP returns template_not_found.",delete_template:"Deletes an existing Markdown template after resolving it through SiYuan’s template picker. This action is dangerous and disabled by default.",save_doc_as_template:"Use id + name to save a document as a root-level template through SiYuan’s docSaveAsTemplate API. Slashes are rejected; pass overwrite=true to replace an existing root template.",render:'Use engine="template" with id + path for a workspace template; that engine uses .action{...} delimiters and exposes limited document fields such as id/title/name/alias. Set preview=true for SiYuan preview DOM. Use engine="sprig" with inline template for {{...}} syntax; Sprig has functions but no document context.',export_resources:"Provide one or more existing resource paths. Asset paths like assets/foo.txt are normalized to /data/assets/foo.txt before export. Set outputPath to also copy the exported ZIP to a local filesystem path. Using outputPath is high-risk and requires explicit user confirmation. To extract attachments for direct reading without a ZIP archive, prefer extract_doc which produces an uncompressed folder.",get_doc_assets:'Use a document ID to list assets directly referenced by the current document tree after read-permission checks. This does not expand query embed blocks; when the user needs to inspect the full document content and assets, guide them to file(action="extract_doc") instead. Use assetType="image" to return only direct image assets.',get_image_ocr_text:"Use an asset path to read stored OCR text. If path is omitted, SiYuan returns an empty text payload.",extract_doc:"Use a document ID + optional outputDir. Exports the document markdown and all referenced assets into an uncompressed folder, preserving original filenames. If outputDir is omitted, the default output root is ~/siyuan-extracted/; pass outputDir explicitly for a predictable path such as /private/tmp. Clears the entire output root directory first to prevent accumulation from previous exports. The returned extractedDir is an absolute path ready for direct file access."},ll=["All search actions are read-only except find_replace, which modifies content and requires explicit user confirmation.",'search(action="query_sql") only accepts SELECT statements; mutation queries will be rejected, and returned rows are filtered by notebook permission.',"When calling query_sql, always add LIMIT yourself. MCP may still truncate large result sets and will tell you when to refine the query.","The blocks table columns include: id, parent_id, root_id, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated.","In SQL results, blocks.type uses SiYuan short codes such as d=document, h=heading, p=paragraph, l=list, i=list-item, b=blockquote, c=code, m=math, t=table, html=html, video=video, audio=audio, widget=widget.",'Use search(action="fulltext") for natural language searches; use search(action="query_sql") for structured queries.','search(action="fulltext") types field auto-expands shortcodes: {"h": true, "p": true} is equivalent to {"heading": true, "paragraph": true}. Shortcodes: d/h/p/l/i/b/c/m/t/s/html/embed/av. Prefer semantic aliases such as methodName/sortBy over numeric method/orderBy.','search(action="fulltext") supports parentId to scope results within a document subtree, and hasTags to filter by tag presence.',"Right after creating or editing content, full-text and tag search can lag behind writes because SiYuan indexing is eventually consistent; brief retries are expected in live tests."],ul={fulltext:'Pass a query string. Supports keyword, query syntax, SQL, and regex modes via methodName (preferred) or method. fulltext now returns plainContent/excerpt by default. types accepts shortcodes directly: {"h": true, "c": true} auto-expands to {"heading": true, "codeBlock": true}. Use sortBy="relevance" or "date" instead of numeric orderBy. Use parentId to scope within a document, hasTags to filter tagged blocks.',query_sql:"Execute a SELECT statement. Common tables: blocks, spans, assets. Prefer sql over stmt when prompting an AI. Always use LIMIT to control result size. MCP returns data plus truncation and permission-filtering metadata when applicable.",get_backlinks:'Returns documents/blocks that contain references and/or text mentions for the given block ID. Use mode="links" | "mentions" | "both". Partial permission-filtered results include machine-readable metadata.',search_refs:"Returns block-level reference contexts for the target id. Use this when you need the surrounding block content, not just the document-level backlink list. beforeLen controls how much leading context is included in each hit.",find_replace:"This is the mutating exception inside the search tool. It performs content replacement after write-permission checks and still requires explicit user confirmation.",search_assets:"Searches asset filenames. Prefer query over k when prompting an AI. If you need OCR or indexed inner-text matches, use fulltext_asset_content instead.",fulltext_asset_content:"Searches indexed asset/OCR text. Prefer methodName and sortBy over numeric method/orderBy. Provide assetId for an exact asset-content lookup."},dl={list:"Optional keyword/query searches tags; sort, ignoreMaxListHint, and app are passed through to SiYuan for plain listing.",rename:"Renames a workspace tag label everywhere it appears.",remove:"Deletes a workspace tag label. This action requires explicit user confirmation."},pl={workspace_info:"Returns workspace path metadata and current SiYuan version. High-risk: leaks the absolute workspace path; disabled by default and requires explicit user confirmation.",network:"Returns masked proxy information only.",conf:'Defaults to a navigable summary. Use mode="get" with keyPath to read one config field or subtree at a time, e.g. conf.appearance.mode or conf.langs[0].',notify:"Show an info or error notification in the SiYuan UI. Optional timeout is in milliseconds.",changelog:"Reads the bundled plugin CHANGELOG with structured personalizationReview hints. Pass fromVersion after upgrades, version for one exact entry, or includeRaw=true for Markdown.",perform_sync:"Triggers SiYuan sync immediately through /api/sync/performSync. This action can change local and remote sync state and requires explicit user confirmation.",get_version:"Returns the current SiYuan version as {version}.",get_current_time:"Returns the current system time as {currentTime} epoch milliseconds and {iso} ISO 8601 text."},fl={list_cards:`Use scope="all" | "deck" | "notebook" | "tree" plus filter="due" | "new" | "old". For scope="all", omit deckID; an empty string is treated as omitted. For scope="deck", pass a non-empty deckID. For scope="notebook", pass notebook. For scope="tree", pass rootID. reviewedCards is optional and follows SiYuan's review flow.`,get_decks:"Returns available flashcard decks so the caller can discover deckID values.",get_cards:"Use deckID + optional page/pageSize to list all cards in a deck (regardless of due state). Use empty string deckID to query across all decks. Returns cards, total count, and pageCount.",review_card:"Use a concrete deckID + cardID + rating, or pass skip=true to skip. Resolve deckID/cardID through list_cards or get_cards first; empty deckID is rejected. reviewedCards is optional; each entry must include cardID because SiYuan only reads reviewedCards[].cardID.",create_card:"Use deckID + content blockIDs to turn existing blocks into flashcards; single blockID is accepted as a convenience alias. Non-built-in deck IDs must already exist. Document block IDs are rejected. This calls SiYuan's addRiffCards flow, writes custom-riff-decks, verifies the binding, and creates deck records together.",remove_card:"Use deckID + blockIDs to remove flashcard bindings from a deck. This does not delete the underlying note blocks. This action requires explicit user confirmation."},hl={get_balance:"Returns the cat’s current balance and lifetime earned count. Each successful MCP tool call adds 1 coin and increments the lifetime count.",shop:"Returns the current mascot shop inventory including stable item IDs, labels, cost, type, and emoji.",buy:"Buys one shop item by item_id and deducts its configured cost from balance."},ml={submit:"Sends plain-text feedback. Put a GitHub Issue-style report in description when reporting bugs, confusing behavior, or rough workflows. Recommended headings: ## Summary, ## What happened, ## Expected behavior, ## Steps or context, ## Impact, ## Suggested fix. impact should be a short impact summary; suggestion should be the direct fix idea. Avoid private note content and secrets."},_g={list:"Set refresh=true to re-read the official SiYuan MCP tool registry. The result separates plugin/native sources and reports the currently exposed schema size. Discovery failures preserve the last successful cache."},gl={fs:Zc,notebook:Yc,document:Wc,block:Gc,av:Kc,file:Jc,search:ll,tag:Qc,system:Xc,flashcard:el,extension:kg,mascot:tl,feedback:ol},Eo={fs:nl,notebook:rl,document:sl,block:al,av:il,file:cl,search:ul,tag:dl,system:pl,flashcard:fl,extension:_g,mascot:hl,feedback:ml},vg={document:{create:[{title:"Create a child document by notebook-local hpath (recommended)",description:"The path is inside the notebook. Do not include the notebook name, and do not pass a .sy storage path here.",mcp:{action:"create",notebook:"20210808180117-czj9bvb",path:"/Folder/Parent/New Child",markdown:"正文从这里开始,不要再写 # New Child。"}},{title:"Create with a human-readable parent hpath plus title",description:"Use this when the parent hpath is already known and you want the title separated from the parent path.",mcp:{action:"create",notebook:"20210808180117-czj9bvb",parentPath:"/Folder/Parent",title:"New Child",markdown:"正文从这里开始,不要再写 # New Child。"}},{title:"Create with a storage parent path returned by lookup",description:"Only parentPath accepts this .sy storage path form; path does not.",mcp:{action:"create",notebook:"20210808180117-czj9bvb",parentPath:"/20240318112233-abc123.sy",title:"New Child"}}]},fs:{replace:[{title:"Replace exact text with canonical edit object",mcp:{action:"replace",path:"/Notebook/Folder/Doc",edit:{old:"ORIGINAL_TEXT",new:"NEW_TEXT"}}},{title:"Replace exact text with shorthand old/new",description:'Equivalent CLI form: siyuan-sisyphus fs replace --path "/Notebook/Folder/Doc" --old ORIGINAL_TEXT --new NEW_TEXT',mcp:{action:"replace",path:"/Notebook/Folder/Doc",old:"ORIGINAL_TEXT",new:"NEW_TEXT",replace_all:!1}}]},notebook:{},block:{word_count:[{title:"Get word count for one block",description:"id is accepted as a convenience alias for ids=[id].",mcp:{action:"word_count",id:"20240318112233-abc123"}},{title:"Get word count for multiple blocks",mcp:{action:"word_count",ids:["20240318112233-abc123","20240318112233-def456"]}}]},av:{render:[{title:"Render an AV returned by search",description:"av.search results include renderArgs; pass id or the compatibility alias avID.",mcp:{action:"render",id:"20240318112233-abc123",page:1,pageSize:20}},{title:"Render with avID compatibility alias",mcp:{action:"render",avID:"20240318112233-abc123"}}]},file:{upload_asset:[{title:"Upload a local file with canonical fields",mcp:{action:"upload_asset",assetsDirPath:"/assets/",localFilePath:"/private/tmp/demo.txt"}},{title:"Upload a local file with file shorthand",description:"When assetsDirPath is omitted, upload_asset uses /assets/.",mcp:{action:"upload_asset",file:"/private/tmp/demo.txt"}}],create_template:[{title:"Create a nested Markdown template",mcp:{action:"create_template",path:"reports/monthly.md",markdown:`# .action{.title}
421
427
 
422
428
  ## Summary
423
429
  `}}],update_template:[{title:"Replace an existing template source",mcp:{action:"update_template",path:"reports/monthly.md",markdown:`# .action{.title}
424
430
 
425
431
  ## Updated Summary
426
- `}}],save_doc_as_template:[{title:"Save a document as a root template",mcp:{action:"save_doc_as_template",id:"20240318112233-abc123",name:"meeting-note"}}],extract_doc:[{title:"Extract a document to an explicit local output root",description:"If outputDir is omitted, extract_doc defaults to ~/siyuan-extracted/.",mcp:{action:"extract_doc",id:"20240318112233-abc123",outputDir:"/private/tmp/siyuan-extracted"}}]},search:{},tag:{},system:{changelog:[{title:"Review changes after a known previous plugin version",description:"Use this after an upgrade to decide whether user rules, /AGENTS.md memory, connection snippets, permissions, appearance, timeline settings, or tool config need attention.",mcp:{action:"changelog",fromVersion:"0.4.8"}},{title:"Read one exact release entry with raw Markdown",mcp:{action:"changelog",version:"0.4.11",includeRaw:!0}}]},flashcard:{create_card:[{title:"Create one flashcard from a content block",description:"blockID is accepted as a convenience alias for blockIDs=[blockID].",mcp:{action:"create_card",deckID:"20230218211946-2kw8jgx",blockID:"20240318112233-abc123"}},{title:"Create flashcards from multiple content blocks",mcp:{action:"create_card",deckID:"20230218211946-2kw8jgx",blockIDs:["20240318112233-abc123","20240318112233-def456"]}}]},extension:{list:[{title:"Refresh official MCP tool discovery",mcp:{action:"list",refresh:!0}}]},mascot:{},feedback:{}};function kg(e,t){var o;if(!(!e||!t)&&e in Po)return(o=Po[e])==null?void 0:o[t]}const _g=Object.freeze({status:"aborted"});function v(e,t,o){function n(i,c){if(i._zod||Object.defineProperty(i,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1}),i._zod.traits.has(e))return;i._zod.traits.add(e),t(i,c);const l=a.prototype,u=Object.keys(l);for(let p=0;p<u.length;p++){const f=u[p];f in i||(i[f]=l[f].bind(i))}}const r=(o==null?void 0:o.Parent)??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function a(i){var c;const l=o!=null&&o.Parent?new s:this;n(l,i),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var c,l;return o!=null&&o.Parent&&i instanceof o.Parent?!0:(l=(c=i==null?void 0:i._zod)==null?void 0:c.traits)==null?void 0:l.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Ot extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ml extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const gl={};function Xe(e){return gl}function yl(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}function Er(e,t){return typeof t=="bigint"?t.toString():t}function Fn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qs(e){return e==null}function Bs(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function vg(e,t){const o=(e.toString().split(".")[1]||"").length,n=t.toString();let r=(n.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(n)){const c=n.match(/\d?e-(\d?)/);c!=null&&c[1]&&(r=Number.parseInt(c[1]))}const s=o>r?o:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}const ni=Symbol("evaluating");function V(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==ni)return n===void 0&&(n=ni,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function gt(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function nt(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function ri(e){return JSON.stringify(e)}function Ig(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const bl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Eo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Sg=Fn(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Lt(e){if(Eo(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(Eo(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function wl(e){return Lt(e)?{...e}:Array.isArray(e)?[...e]:e}const Dg=new Set(["string","number","symbol"]);function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,o){const n=new e._zod.constr(t??e._zod.def);return(!t||o!=null&&o.parent)&&(n._zod.parent=e),n}function R(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ag(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Tg={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Pg(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=nt(e._zod.def,{get shape(){const a={};for(const i in t){if(!(i in o.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(a[i]=o.shape[i])}return gt(this,"shape",a),a},checks:[]});return rt(e,s)}function Eg(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=nt(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const i in t){if(!(i in o.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete a[i]}return gt(this,"shape",a),a},checks:[]});return rt(e,s)}function Cg(e,t){if(!Lt(t))throw new Error("Invalid input to extend: expected a plain object");const o=e._zod.def.checks;if(o&&o.length>0){const s=e._zod.def.shape;for(const a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=nt(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return gt(this,"shape",s),s}});return rt(e,r)}function Rg(e,t){if(!Lt(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=nt(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return gt(this,"shape",n),n}});return rt(e,o)}function xg(e,t){const o=nt(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return gt(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return rt(e,o)}function Og(e,t,o){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=nt(t._zod.def,{get shape(){const i=t._zod.def.shape,c={...i};if(o)for(const l in o){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);o[l]&&(c[l]=e?new e({type:"optional",innerType:i[l]}):i[l])}else for(const l in i)c[l]=e?new e({type:"optional",innerType:i[l]}):i[l];return gt(this,"shape",c),c},checks:[]});return rt(t,a)}function Ng(e,t,o){const n=nt(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(o)for(const a in o){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);o[a]&&(s[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)s[a]=new e({type:"nonoptional",innerType:r[a]});return gt(this,"shape",s),s}});return rt(t,n)}function Tt(e,t=0){var o;if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(((o=e.issues[n])==null?void 0:o.continue)!==!0)return!0;return!1}function Pt(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function en(e){return typeof e=="string"?e:e==null?void 0:e.message}function et(e,t,o){var r,s,a,i,c,l;const n={...e,path:e.path??[]};if(!e.message){const u=en((a=(s=(r=e.inst)==null?void 0:r._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??en((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??en((c=o.customError)==null?void 0:c.call(o,e))??en((l=o.localeError)==null?void 0:l.call(o,e))??"Invalid input";n.message=u}return delete n.inst,delete n.continue,t!=null&&t.reportInput||delete n.input,n}function Ls(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Co(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const kl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Er,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_l=v("$ZodError",kl),vl=v("$ZodError",kl,{Parent:Error});function $g(e,t=o=>o.message){const o={},n=[];for(const r of e.issues)r.path.length>0?(o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:o}}function Mg(e,t=o=>o.message){const o={_errors:[]},n=r=>{for(const s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)o._errors.push(t(s));else{let a=o,i=0;for(;i<s.path.length;){const c=s.path[i];i===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(s))):a[c]=a[c]||{_errors:[]},a=a[c],i++}}};return n(e),o}const Us=e=>(t,o,n,r)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:o,issues:[]},s);if(a instanceof Promise)throw new Ot;if(a.issues.length){const i=new((r==null?void 0:r.Err)??e)(a.issues.map(c=>et(c,s,Xe())));throw bl(i,r==null?void 0:r.callee),i}return a.value},js=e=>async(t,o,n,r)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:o,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new((r==null?void 0:r.Err)??e)(a.issues.map(c=>et(c,s,Xe())));throw bl(i,r==null?void 0:r.callee),i}return a.value},qn=e=>(t,o,n)=>{const r=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw new Ot;return s.issues.length?{success:!1,error:new(e??_l)(s.issues.map(a=>et(a,r,Xe())))}:{success:!0,data:s.value}},Il=qn(vl),Bn=e=>async(t,o,n)=>{const r=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:o,issues:[]},r);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>et(a,r,Xe())))}:{success:!0,data:s.value}},zg=Bn(vl),Fg=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Us(e)(t,o,r)},qg=e=>(t,o,n)=>Us(e)(t,o,n),Bg=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return js(e)(t,o,r)},Lg=e=>async(t,o,n)=>js(e)(t,o,n),Ug=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return qn(e)(t,o,r)},jg=e=>(t,o,n)=>qn(e)(t,o,n),Hg=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Bn(e)(t,o,r)},Vg=e=>async(t,o,n)=>Bn(e)(t,o,n),Zg=/^[cC][^\s-]{8,}$/,Yg=/^[0-9a-z]+$/,Wg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gg=/^[0-9a-vA-V]{20}$/,Kg=/^[A-Za-z0-9]{27}$/,Jg=/^[a-zA-Z0-9_-]{21}$/,Qg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,si=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ey=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ty="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function oy(){return new RegExp(ty,"u")}const ny=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ry=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,sy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ay=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,iy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Sl=/^[A-Za-z0-9_-]*$/,cy=/^\+[1-9]\d{6,14}$/,Dl="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ly=new RegExp(`^${Dl}$`);function Al(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function uy(e){return new RegExp(`^${Al(e)}$`)}function dy(e){const t=Al({precision:e.precision}),o=["Z"];e.local&&o.push(""),e.offset&&o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${o.join("|")})`;return new RegExp(`^${Dl}T(?:${n})$`)}const py=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},fy=/^-?\d+$/,Tl=/^-?\d+(?:\.\d+)?$/,hy=/^(?:true|false)$/i,my=/^null$/i,gy=/^[^A-Z]*$/,yy=/^[^a-z]*$/,ye=v("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),Pl={number:"number",bigint:"bigint",object:"date"},El=v("$ZodCheckLessThan",(e,t)=>{ye.init(e,t);const o=Pl[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:o,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Cl=v("$ZodCheckGreaterThan",(e,t)=>{ye.init(e,t);const o=Pl[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:o,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),by=v("$ZodCheckMultipleOf",(e,t)=>{ye.init(e,t),e._zod.onattach.push(o=>{var n;(n=o._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=o=>{if(typeof o.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%t.value===BigInt(0):vg(o.value,t.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:t.value,input:o.value,inst:e,continue:!t.abort})}}),wy=v("$ZodCheckNumberFormat",(e,t)=>{var a;ye.init(e,t),t.format=t.format||"float64";const o=(a=t.format)==null?void 0:a.includes("int"),n=o?"int":"number",[r,s]=Tg[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=r,c.maximum=s,o&&(c.pattern=fy)}),e._zod.check=i=>{const c=i.value;if(o){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<r&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),ky=v("$ZodCheckMaxLength",(e,t)=>{var o;ye.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!qs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const a=Ls(r);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),_y=v("$ZodCheckMinLength",(e,t)=>{var o;ye.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!qs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const a=Ls(r);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),vy=v("$ZodCheckLengthEquals",(e,t)=>{var o;ye.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!qs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const a=Ls(r),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ln=v("$ZodCheckStringFormat",(e,t)=>{var o,n;ye.init(e,t),e._zod.onattach.push(r=>{const s=r._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(o=e._zod).check??(o.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Iy=v("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Sy=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=gy),Ln.init(e,t)}),Dy=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yy),Ln.init(e,t)}),Ay=v("$ZodCheckIncludes",(e,t)=>{ye.init(e,t);const o=Ut(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${o}`:o);t.pattern=n,e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Ty=v("$ZodCheckStartsWith",(e,t)=>{ye.init(e,t);const o=new RegExp(`^${Ut(t.prefix)}.*`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Py=v("$ZodCheckEndsWith",(e,t)=>{ye.init(e,t);const o=new RegExp(`.*${Ut(t.suffix)}$`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ey=v("$ZodCheckOverwrite",(e,t)=>{ye.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class Cy{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
432
+ `}}],save_doc_as_template:[{title:"Save a document as a root template",mcp:{action:"save_doc_as_template",id:"20240318112233-abc123",name:"meeting-note"}}],extract_doc:[{title:"Extract a document to an explicit local output root",description:"If outputDir is omitted, extract_doc defaults to ~/siyuan-extracted/.",mcp:{action:"extract_doc",id:"20240318112233-abc123",outputDir:"/private/tmp/siyuan-extracted"}}]},search:{},tag:{},system:{changelog:[{title:"Review changes after a known previous plugin version",description:"Use this after an upgrade to decide whether user rules, /AGENTS.md memory, connection snippets, permissions, appearance, timeline settings, or tool config need attention.",mcp:{action:"changelog",fromVersion:"0.4.8"}},{title:"Read one exact release entry with raw Markdown",mcp:{action:"changelog",version:"0.4.11",includeRaw:!0}}]},flashcard:{create_card:[{title:"Create one flashcard from a content block",description:"blockID is accepted as a convenience alias for blockIDs=[blockID].",mcp:{action:"create_card",deckID:"20230218211946-2kw8jgx",blockID:"20240318112233-abc123"}},{title:"Create flashcards from multiple content blocks",mcp:{action:"create_card",deckID:"20230218211946-2kw8jgx",blockIDs:["20240318112233-abc123","20240318112233-def456"]}}]},extension:{list:[{title:"Refresh official MCP tool discovery",mcp:{action:"list",refresh:!0}}]},mascot:{},feedback:{}};function Ig(e,t){var o;if(!(!e||!t)&&e in Eo)return(o=Eo[e])==null?void 0:o[t]}const Sg=Object.freeze({status:"aborted"});function v(e,t,o){function n(i,c){if(i._zod||Object.defineProperty(i,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1}),i._zod.traits.has(e))return;i._zod.traits.add(e),t(i,c);const l=a.prototype,u=Object.keys(l);for(let p=0;p<u.length;p++){const f=u[p];f in i||(i[f]=l[f].bind(i))}}const r=(o==null?void 0:o.Parent)??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function a(i){var c;const l=o!=null&&o.Parent?new s:this;n(l,i),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var c,l;return o!=null&&o.Parent&&i instanceof o.Parent?!0:(l=(c=i==null?void 0:i._zod)==null?void 0:c.traits)==null?void 0:l.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Nt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class yl extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const bl={};function Xe(e){return bl}function wl(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}function Or(e,t){return typeof t=="bigint"?t.toString():t}function jn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Bs(e){return e==null}function Us(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function Dg(e,t){const o=(e.toString().split(".")[1]||"").length,n=t.toString();let r=(n.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(n)){const c=n.match(/\d?e-(\d?)/);c!=null&&c[1]&&(r=Number.parseInt(c[1]))}const s=o>r?o:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}const si=Symbol("evaluating");function V(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==si)return n===void 0&&(n=si,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function gt(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function nt(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function ai(e){return JSON.stringify(e)}function Tg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const kl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ag=jn(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ut(e){if(Ro(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(Ro(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function _l(e){return Ut(e)?{...e}:Array.isArray(e)?[...e]:e}const Pg=new Set(["string","number","symbol"]);function jt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,o){const n=new e._zod.constr(t??e._zod.def);return(!t||o!=null&&o.parent)&&(n._zod.parent=e),n}function R(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Cg(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Eg={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Rg(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=nt(e._zod.def,{get shape(){const a={};for(const i in t){if(!(i in o.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(a[i]=o.shape[i])}return gt(this,"shape",a),a},checks:[]});return rt(e,s)}function xg(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=nt(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const i in t){if(!(i in o.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete a[i]}return gt(this,"shape",a),a},checks:[]});return rt(e,s)}function Og(e,t){if(!Ut(t))throw new Error("Invalid input to extend: expected a plain object");const o=e._zod.def.checks;if(o&&o.length>0){const s=e._zod.def.shape;for(const a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=nt(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return gt(this,"shape",s),s}});return rt(e,r)}function Ng(e,t){if(!Ut(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=nt(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return gt(this,"shape",n),n}});return rt(e,o)}function $g(e,t){const o=nt(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return gt(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return rt(e,o)}function Mg(e,t,o){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=nt(t._zod.def,{get shape(){const i=t._zod.def.shape,c={...i};if(o)for(const l in o){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);o[l]&&(c[l]=e?new e({type:"optional",innerType:i[l]}):i[l])}else for(const l in i)c[l]=e?new e({type:"optional",innerType:i[l]}):i[l];return gt(this,"shape",c),c},checks:[]});return rt(t,a)}function zg(e,t,o){const n=nt(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(o)for(const a in o){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);o[a]&&(s[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)s[a]=new e({type:"nonoptional",innerType:r[a]});return gt(this,"shape",s),s}});return rt(t,n)}function At(e,t=0){var o;if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(((o=e.issues[n])==null?void 0:o.continue)!==!0)return!0;return!1}function Pt(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function on(e){return typeof e=="string"?e:e==null?void 0:e.message}function et(e,t,o){var r,s,a,i,c,l;const n={...e,path:e.path??[]};if(!e.message){const u=on((a=(s=(r=e.inst)==null?void 0:r._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??on((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??on((c=o.customError)==null?void 0:c.call(o,e))??on((l=o.localeError)==null?void 0:l.call(o,e))??"Invalid input";n.message=u}return delete n.inst,delete n.continue,t!=null&&t.reportInput||delete n.input,n}function js(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function xo(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const vl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Or,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Il=v("$ZodError",vl),Sl=v("$ZodError",vl,{Parent:Error});function Fg(e,t=o=>o.message){const o={},n=[];for(const r of e.issues)r.path.length>0?(o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:o}}function qg(e,t=o=>o.message){const o={_errors:[]},n=r=>{for(const s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)o._errors.push(t(s));else{let a=o,i=0;for(;i<s.path.length;){const c=s.path[i];i===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(s))):a[c]=a[c]||{_errors:[]},a=a[c],i++}}};return n(e),o}const Hs=e=>(t,o,n,r)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:o,issues:[]},s);if(a instanceof Promise)throw new Nt;if(a.issues.length){const i=new((r==null?void 0:r.Err)??e)(a.issues.map(c=>et(c,s,Xe())));throw kl(i,r==null?void 0:r.callee),i}return a.value},Vs=e=>async(t,o,n,r)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:o,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new((r==null?void 0:r.Err)??e)(a.issues.map(c=>et(c,s,Xe())));throw kl(i,r==null?void 0:r.callee),i}return a.value},Hn=e=>(t,o,n)=>{const r=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw new Nt;return s.issues.length?{success:!1,error:new(e??Il)(s.issues.map(a=>et(a,r,Xe())))}:{success:!0,data:s.value}},Dl=Hn(Sl),Vn=e=>async(t,o,n)=>{const r=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:o,issues:[]},r);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>et(a,r,Xe())))}:{success:!0,data:s.value}},Lg=Vn(Sl),Bg=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Hs(e)(t,o,r)},Ug=e=>(t,o,n)=>Hs(e)(t,o,n),jg=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Vs(e)(t,o,r)},Hg=e=>async(t,o,n)=>Vs(e)(t,o,n),Vg=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Hn(e)(t,o,r)},Zg=e=>(t,o,n)=>Hn(e)(t,o,n),Yg=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Vn(e)(t,o,r)},Wg=e=>async(t,o,n)=>Vn(e)(t,o,n),Gg=/^[cC][^\s-]{8,}$/,Kg=/^[0-9a-z]+$/,Jg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Qg=/^[0-9a-vA-V]{20}$/,Xg=/^[A-Za-z0-9]{27}$/,ey=/^[a-zA-Z0-9_-]{21}$/,ty=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oy=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ii=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ny=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ry="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sy(){return new RegExp(ry,"u")}const ay=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ly=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tl=/^[A-Za-z0-9_-]*$/,dy=/^\+[1-9]\d{6,14}$/,Al="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",py=new RegExp(`^${Al}$`);function Pl(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fy(e){return new RegExp(`^${Pl(e)}$`)}function hy(e){const t=Pl({precision:e.precision}),o=["Z"];e.local&&o.push(""),e.offset&&o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${o.join("|")})`;return new RegExp(`^${Al}T(?:${n})$`)}const my=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gy=/^-?\d+$/,Cl=/^-?\d+(?:\.\d+)?$/,yy=/^(?:true|false)$/i,by=/^null$/i,wy=/^[^A-Z]*$/,ky=/^[^a-z]*$/,ye=v("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),El={number:"number",bigint:"bigint",object:"date"},Rl=v("$ZodCheckLessThan",(e,t)=>{ye.init(e,t);const o=El[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:o,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xl=v("$ZodCheckGreaterThan",(e,t)=>{ye.init(e,t);const o=El[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:o,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_y=v("$ZodCheckMultipleOf",(e,t)=>{ye.init(e,t),e._zod.onattach.push(o=>{var n;(n=o._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=o=>{if(typeof o.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%t.value===BigInt(0):Dg(o.value,t.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:t.value,input:o.value,inst:e,continue:!t.abort})}}),vy=v("$ZodCheckNumberFormat",(e,t)=>{var a;ye.init(e,t),t.format=t.format||"float64";const o=(a=t.format)==null?void 0:a.includes("int"),n=o?"int":"number",[r,s]=Eg[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=r,c.maximum=s,o&&(c.pattern=gy)}),e._zod.check=i=>{const c=i.value;if(o){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<r&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Iy=v("$ZodCheckMaxLength",(e,t)=>{var o;ye.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Bs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const a=js(r);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Sy=v("$ZodCheckMinLength",(e,t)=>{var o;ye.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Bs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const a=js(r);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Dy=v("$ZodCheckLengthEquals",(e,t)=>{var o;ye.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Bs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const a=js(r),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Zn=v("$ZodCheckStringFormat",(e,t)=>{var o,n;ye.init(e,t),e._zod.onattach.push(r=>{const s=r._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(o=e._zod).check??(o.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Ty=v("$ZodCheckRegex",(e,t)=>{Zn.init(e,t),e._zod.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ay=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=wy),Zn.init(e,t)}),Py=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ky),Zn.init(e,t)}),Cy=v("$ZodCheckIncludes",(e,t)=>{ye.init(e,t);const o=jt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${o}`:o);t.pattern=n,e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Ey=v("$ZodCheckStartsWith",(e,t)=>{ye.init(e,t);const o=new RegExp(`^${jt(t.prefix)}.*`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ry=v("$ZodCheckEndsWith",(e,t)=>{ye.init(e,t);const o=new RegExp(`.*${jt(t.suffix)}$`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),xy=v("$ZodCheckOverwrite",(e,t)=>{ye.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class Oy{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
427
433
  `).filter(a=>a),r=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(r)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,o=this==null?void 0:this.args,r=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new t(...o,r.join(`
428
- `))}}const Ry={major:4,minor:3,patch:6},J=v("$ZodType",(e,t)=>{var r;var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ry;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const s of n)for(const a of s._zod.onattach)a(e);if(n.length===0)(o=e._zod).deferred??(o.deferred=[]),(r=e._zod.deferred)==null||r.push(()=>{e._zod.run=e._zod.parse});else{const s=(i,c,l)=>{let u=Tt(i),p;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(i))continue}else if(u)continue;const h=i.issues.length,g=f._zod.check(i);if(g instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Ot;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,i.issues.length!==h&&(u||(u=Tt(i,h)))});else{if(i.issues.length===h)continue;u||(u=Tt(i,h))}}return p?p.then(()=>i):i},a=(i,c,l)=>{if(Tt(i))return i.aborted=!0,i;const u=s(c,n,l);if(u instanceof Promise){if(l.async===!1)throw new Ot;return u.then(p=>e._zod.parse(p,l))}return e._zod.parse(u,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const u=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(p=>a(p,i,c)):a(u,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Ot;return l.then(u=>s(u,n,c))}return s(l,n,c)}}V(e,"~standard",()=>({validate:s=>{var a;try{const i=Il(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return zg(e,s).then(c=>{var l;return c.success?{value:c.data}:{issues:(l=c.error)==null?void 0:l.issues}})}},vendor:"zod",version:1}))}),Hs=v("$ZodString",(e,t)=>{var o;J.init(e,t),e._zod.pattern=[...((o=e==null?void 0:e._zod.bag)==null?void 0:o.patterns)??[]].pop()??py(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),X=v("$ZodStringFormat",(e,t)=>{Ln.init(e,t),Hs.init(e,t)}),xy=v("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xg),X.init(e,t)}),Oy=v("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=si(n))}else t.pattern??(t.pattern=si());X.init(e,t)}),Ny=v("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ey),X.init(e,t)}),$y=v("$ZodURL",(e,t)=>{X.init(e,t),e._zod.check=o=>{try{const n=o.value.trim(),r=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:o.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:o.value,inst:e,continue:!t.abort})),t.normalize?o.value=r.href:o.value=n;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:e,continue:!t.abort})}}}),My=v("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=oy()),X.init(e,t)}),zy=v("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Jg),X.init(e,t)}),Fy=v("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Zg),X.init(e,t)}),qy=v("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yg),X.init(e,t)}),By=v("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Wg),X.init(e,t)}),Ly=v("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Gg),X.init(e,t)}),Uy=v("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Kg),X.init(e,t)}),jy=v("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=dy(t)),X.init(e,t)}),Hy=v("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ly),X.init(e,t)}),Vy=v("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=uy(t)),X.init(e,t)}),Zy=v("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qg),X.init(e,t)}),Yy=v("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ny),X.init(e,t),e._zod.bag.format="ipv4"}),Wy=v("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ry),X.init(e,t),e._zod.bag.format="ipv6",e._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:e,continue:!t.abort})}}}),Gy=v("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=sy),X.init(e,t)}),Ky=v("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ay),X.init(e,t),e._zod.check=o=>{const n=o.value.split("/");try{if(n.length!==2)throw new Error;const[r,s]=n;if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:e,continue:!t.abort})}}});function Rl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Jy=v("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=iy),X.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{Rl(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function Qy(e){if(!Sl.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return Rl(o)}const Xy=v("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Sl),X.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{Qy(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),eb=v("$ZodE164",(e,t)=>{t.pattern??(t.pattern=cy),X.init(e,t)});function tb(e,t=null){try{const o=e.split(".");if(o.length!==3)return!1;const[n]=o;if(!n)return!1;const r=JSON.parse(atob(n));return!("typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const ob=v("$ZodJWT",(e,t)=>{X.init(e,t),e._zod.check=o=>{tb(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),xl=v("$ZodNumber",(e,t)=>{J.init(e,t),e._zod.pattern=e._zod.bag.pattern??Tl,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=Number(o.value)}catch{}const r=o.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return o;const s=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),o}}),nb=v("$ZodNumberFormat",(e,t)=>{wy.init(e,t),xl.init(e,t)}),rb=v("$ZodBoolean",(e,t)=>{J.init(e,t),e._zod.pattern=hy,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=!!o.value}catch{}const r=o.value;return typeof r=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),o}}),sb=v("$ZodNull",(e,t)=>{J.init(e,t),e._zod.pattern=my,e._zod.values=new Set([null]),e._zod.parse=(o,n)=>{const r=o.value;return r===null||o.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),o}}),ab=v("$ZodAny",(e,t)=>{J.init(e,t),e._zod.parse=o=>o}),ib=v("$ZodUnknown",(e,t)=>{J.init(e,t),e._zod.parse=o=>o}),cb=v("$ZodNever",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function ai(e,t,o){e.issues.length&&t.issues.push(...Pt(o,e.issues)),t.value[o]=e.value}const lb=v("$ZodArray",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Array.isArray(r))return o.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),o;o.value=Array(r.length);const s=[];for(let a=0;a<r.length;a++){const i=r[a],c=t.element._zod.run({value:i,issues:[]},n);c instanceof Promise?s.push(c.then(l=>ai(l,o,a))):ai(c,o,a)}return s.length?Promise.all(s).then(()=>o):o}});function bn(e,t,o,n,r){if(e.issues.length){if(r&&!(o in n))return;t.issues.push(...Pt(o,e.issues))}e.value===void 0?o in n&&(t.value[o]=void 0):t.value[o]=e.value}function Ol(e){var n,r,s,a;const t=Object.keys(e.shape);for(const i of t)if(!((a=(s=(r=(n=e.shape)==null?void 0:n[i])==null?void 0:r._zod)==null?void 0:s.traits)!=null&&a.has("$ZodType")))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const o=Ag(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Nl(e,t,o,n,r,s){const a=[],i=r.keySet,c=r.catchall._zod,l=c.def.type,u=c.optout==="optional";for(const p in t){if(i.has(p))continue;if(l==="never"){a.push(p);continue}const f=c.run({value:t[p],issues:[]},n);f instanceof Promise?e.push(f.then(h=>bn(h,o,p,t,u))):bn(f,o,p,t,u)}return a.length&&o.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>o):o}const ub=v("$ZodObject",(e,t)=>{J.init(e,t);const o=Object.getOwnPropertyDescriptor(t,"shape");if(!(o!=null&&o.get)){const i=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...i};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=Fn(()=>Ol(t));V(e._zod,"propValues",()=>{const i=t.shape,c={};for(const l in i){const u=i[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(const p of u.values)c[l].add(p)}}return c});const r=Eo,s=t.catchall;let a;e._zod.parse=(i,c)=>{a??(a=n.value);const l=i.value;if(!r(l))return i.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),i;i.value={};const u=[],p=a.shape;for(const f of a.keys){const h=p[f],g=h._zod.optout==="optional",b=h._zod.run({value:l[f],issues:[]},c);b instanceof Promise?u.push(b.then(_=>bn(_,i,f,l,g))):bn(b,i,f,l,g)}return s?Nl(u,l,i,c,n.value,e):u.length?Promise.all(u).then(()=>i):i}}),db=v("$ZodObjectJIT",(e,t)=>{ub.init(e,t);const o=e._zod.parse,n=Fn(()=>Ol(t)),r=f=>{var D;const h=new Cy(["shape","payload","ctx"]),g=n.value,b=T=>{const A=ri(T);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};h.write("const input = payload.value;");const _=Object.create(null);let w=0;for(const T of g.keys)_[T]=`key_${w++}`;h.write("const newResult = {};");for(const T of g.keys){const A=_[T],O=ri(T),C=f[T],L=((D=C==null?void 0:C._zod)==null?void 0:D.optout)==="optional";h.write(`const ${A} = ${b(T)};`),L?h.write(`
429
- if (${A}.issues.length) {
434
+ `))}}const Ny={major:4,minor:3,patch:6},J=v("$ZodType",(e,t)=>{var r;var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ny;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const s of n)for(const a of s._zod.onattach)a(e);if(n.length===0)(o=e._zod).deferred??(o.deferred=[]),(r=e._zod.deferred)==null||r.push(()=>{e._zod.run=e._zod.parse});else{const s=(i,c,l)=>{let u=At(i),p;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(i))continue}else if(u)continue;const h=i.issues.length,g=f._zod.check(i);if(g instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Nt;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,i.issues.length!==h&&(u||(u=At(i,h)))});else{if(i.issues.length===h)continue;u||(u=At(i,h))}}return p?p.then(()=>i):i},a=(i,c,l)=>{if(At(i))return i.aborted=!0,i;const u=s(c,n,l);if(u instanceof Promise){if(l.async===!1)throw new Nt;return u.then(p=>e._zod.parse(p,l))}return e._zod.parse(u,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const u=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(p=>a(p,i,c)):a(u,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Nt;return l.then(u=>s(u,n,c))}return s(l,n,c)}}V(e,"~standard",()=>({validate:s=>{var a;try{const i=Dl(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return Lg(e,s).then(c=>{var l;return c.success?{value:c.data}:{issues:(l=c.error)==null?void 0:l.issues}})}},vendor:"zod",version:1}))}),Zs=v("$ZodString",(e,t)=>{var o;J.init(e,t),e._zod.pattern=[...((o=e==null?void 0:e._zod.bag)==null?void 0:o.patterns)??[]].pop()??my(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),X=v("$ZodStringFormat",(e,t)=>{Zn.init(e,t),Zs.init(e,t)}),$y=v("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=oy),X.init(e,t)}),My=v("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ii(n))}else t.pattern??(t.pattern=ii());X.init(e,t)}),zy=v("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ny),X.init(e,t)}),Fy=v("$ZodURL",(e,t)=>{X.init(e,t),e._zod.check=o=>{try{const n=o.value.trim(),r=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:o.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:o.value,inst:e,continue:!t.abort})),t.normalize?o.value=r.href:o.value=n;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:e,continue:!t.abort})}}}),qy=v("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=sy()),X.init(e,t)}),Ly=v("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ey),X.init(e,t)}),By=v("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Gg),X.init(e,t)}),Uy=v("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Kg),X.init(e,t)}),jy=v("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Jg),X.init(e,t)}),Hy=v("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Qg),X.init(e,t)}),Vy=v("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xg),X.init(e,t)}),Zy=v("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=hy(t)),X.init(e,t)}),Yy=v("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=py),X.init(e,t)}),Wy=v("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=fy(t)),X.init(e,t)}),Gy=v("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ty),X.init(e,t)}),Ky=v("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ay),X.init(e,t),e._zod.bag.format="ipv4"}),Jy=v("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iy),X.init(e,t),e._zod.bag.format="ipv6",e._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:e,continue:!t.abort})}}}),Qy=v("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cy),X.init(e,t)}),Xy=v("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ly),X.init(e,t),e._zod.check=o=>{const n=o.value.split("/");try{if(n.length!==2)throw new Error;const[r,s]=n;if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:e,continue:!t.abort})}}});function Ol(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const eb=v("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=uy),X.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{Ol(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function tb(e){if(!Tl.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ol(o)}const ob=v("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Tl),X.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{tb(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),nb=v("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dy),X.init(e,t)});function rb(e,t=null){try{const o=e.split(".");if(o.length!==3)return!1;const[n]=o;if(!n)return!1;const r=JSON.parse(atob(n));return!("typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const sb=v("$ZodJWT",(e,t)=>{X.init(e,t),e._zod.check=o=>{rb(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),Nl=v("$ZodNumber",(e,t)=>{J.init(e,t),e._zod.pattern=e._zod.bag.pattern??Cl,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=Number(o.value)}catch{}const r=o.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return o;const s=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),o}}),ab=v("$ZodNumberFormat",(e,t)=>{vy.init(e,t),Nl.init(e,t)}),ib=v("$ZodBoolean",(e,t)=>{J.init(e,t),e._zod.pattern=yy,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=!!o.value}catch{}const r=o.value;return typeof r=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),o}}),cb=v("$ZodNull",(e,t)=>{J.init(e,t),e._zod.pattern=by,e._zod.values=new Set([null]),e._zod.parse=(o,n)=>{const r=o.value;return r===null||o.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),o}}),lb=v("$ZodAny",(e,t)=>{J.init(e,t),e._zod.parse=o=>o}),ub=v("$ZodUnknown",(e,t)=>{J.init(e,t),e._zod.parse=o=>o}),db=v("$ZodNever",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function ci(e,t,o){e.issues.length&&t.issues.push(...Pt(o,e.issues)),t.value[o]=e.value}const pb=v("$ZodArray",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Array.isArray(r))return o.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),o;o.value=Array(r.length);const s=[];for(let a=0;a<r.length;a++){const i=r[a],c=t.element._zod.run({value:i,issues:[]},n);c instanceof Promise?s.push(c.then(l=>ci(l,o,a))):ci(c,o,a)}return s.length?Promise.all(s).then(()=>o):o}});function In(e,t,o,n,r){if(e.issues.length){if(r&&!(o in n))return;t.issues.push(...Pt(o,e.issues))}e.value===void 0?o in n&&(t.value[o]=void 0):t.value[o]=e.value}function $l(e){var n,r,s,a;const t=Object.keys(e.shape);for(const i of t)if(!((a=(s=(r=(n=e.shape)==null?void 0:n[i])==null?void 0:r._zod)==null?void 0:s.traits)!=null&&a.has("$ZodType")))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const o=Cg(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Ml(e,t,o,n,r,s){const a=[],i=r.keySet,c=r.catchall._zod,l=c.def.type,u=c.optout==="optional";for(const p in t){if(i.has(p))continue;if(l==="never"){a.push(p);continue}const f=c.run({value:t[p],issues:[]},n);f instanceof Promise?e.push(f.then(h=>In(h,o,p,t,u))):In(f,o,p,t,u)}return a.length&&o.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>o):o}const fb=v("$ZodObject",(e,t)=>{J.init(e,t);const o=Object.getOwnPropertyDescriptor(t,"shape");if(!(o!=null&&o.get)){const i=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...i};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=jn(()=>$l(t));V(e._zod,"propValues",()=>{const i=t.shape,c={};for(const l in i){const u=i[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(const p of u.values)c[l].add(p)}}return c});const r=Ro,s=t.catchall;let a;e._zod.parse=(i,c)=>{a??(a=n.value);const l=i.value;if(!r(l))return i.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),i;i.value={};const u=[],p=a.shape;for(const f of a.keys){const h=p[f],g=h._zod.optout==="optional",b=h._zod.run({value:l[f],issues:[]},c);b instanceof Promise?u.push(b.then(_=>In(_,i,f,l,g))):In(b,i,f,l,g)}return s?Ml(u,l,i,c,n.value,e):u.length?Promise.all(u).then(()=>i):i}}),hb=v("$ZodObjectJIT",(e,t)=>{fb.init(e,t);const o=e._zod.parse,n=jn(()=>$l(t)),r=f=>{var D;const h=new Oy(["shape","payload","ctx"]),g=n.value,b=A=>{const T=ai(A);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};h.write("const input = payload.value;");const _=Object.create(null);let w=0;for(const A of g.keys)_[A]=`key_${w++}`;h.write("const newResult = {};");for(const A of g.keys){const T=_[A],O=ai(A),E=f[A],B=((D=E==null?void 0:E._zod)==null?void 0:D.optout)==="optional";h.write(`const ${T} = ${b(A)};`),B?h.write(`
435
+ if (${T}.issues.length) {
430
436
  if (${O} in input) {
431
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
437
+ payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
432
438
  ...iss,
433
439
  path: iss.path ? [${O}, ...iss.path] : [${O}]
434
440
  })));
435
441
  }
436
442
  }
437
443
 
438
- if (${A}.value === undefined) {
444
+ if (${T}.value === undefined) {
439
445
  if (${O} in input) {
440
446
  newResult[${O}] = undefined;
441
447
  }
442
448
  } else {
443
- newResult[${O}] = ${A}.value;
449
+ newResult[${O}] = ${T}.value;
444
450
  }
445
451
 
446
452
  `):h.write(`
447
- if (${A}.issues.length) {
448
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
453
+ if (${T}.issues.length) {
454
+ payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
449
455
  ...iss,
450
456
  path: iss.path ? [${O}, ...iss.path] : [${O}]
451
457
  })));
452
458
  }
453
459
 
454
- if (${A}.value === undefined) {
460
+ if (${T}.value === undefined) {
455
461
  if (${O} in input) {
456
462
  newResult[${O}] = undefined;
457
463
  }
458
464
  } else {
459
- newResult[${O}] = ${A}.value;
465
+ newResult[${O}] = ${T}.value;
460
466
  }
461
467
 
462
- `)}h.write("payload.value = newResult;"),h.write("return payload;");const P=h.compile();return(T,A)=>P(f,T,A)};let s;const a=Eo,i=!gl.jitless,l=i&&Sg.value,u=t.catchall;let p;e._zod.parse=(f,h)=>{p??(p=n.value);const g=f.value;return a(g)?i&&l&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(s||(s=r(t.shape)),f=s(f,h),u?Nl([],g,f,h,p,e):f):o(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),f)}});function ii(e,t,o,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const r=e.filter(s=>!Tt(s));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:o,errors:e.map(s=>s.issues.map(a=>et(a,n,Xe())))}),t)}const $l=v("$ZodUnion",(e,t)=>{J.init(e,t),V(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),V(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),V(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),V(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${r.map(s=>Bs(s.source)).join("|")})$`)}});const o=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,s)=>{if(o)return n(r,s);let a=!1;const i=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},s);if(l instanceof Promise)i.push(l),a=!0;else{if(l.issues.length===0)return l;i.push(l)}}return a?Promise.all(i).then(c=>ii(c,r,e,s)):ii(i,r,e,s)}}),pb=v("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,$l.init(e,t);const o=e._zod.parse;V(e._zod,"propValues",()=>{const r={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,c]of Object.entries(a)){r[i]||(r[i]=new Set);for(const l of c)r[i].add(l)}}return r});const n=Fn(()=>{var a;const r=t.options,s=new Map;for(const i of r){const c=(a=i._zod.propValues)==null?void 0:a[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of c){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(r,s)=>{const a=r.value;if(!Eo(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;const i=n.value.get(a==null?void 0:a[t.discriminator]);return i?i._zod.run(r,s):t.unionFallback?o(r,s):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),r)}}),fb=v("$ZodIntersection",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{const r=o.value,s=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([c,l])=>ci(o,c,l)):ci(o,s,a)}});function Cr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Lt(e)&&Lt(t)){const o=Object.keys(t),n=Object.keys(e).filter(s=>o.indexOf(s)!==-1),r={...e,...t};for(const s of n){const a=Cr(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r[s]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let n=0;n<e.length;n++){const r=e[n],s=t[n],a=Cr(r,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};o.push(a.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function ci(e,t,o){const n=new Map;let r;for(const i of t.issues)if(i.code==="unrecognized_keys"){r??(r=i);for(const c of i.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(i);for(const i of o.issues)if(i.code==="unrecognized_keys")for(const c of i.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(i);const s=[...n].filter(([,i])=>i.l&&i.r).map(([i])=>i);if(s.length&&r&&e.issues.push({...r,keys:s}),Tt(e))return e;const a=Cr(t.value,o.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const hb=v("$ZodRecord",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Lt(r))return o.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),o;const s=[],a=t.keyType._zod.values;if(a){o.value={};const i=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){i.add(typeof l=="number"?l.toString():l);const u=t.valueType._zod.run({value:r[l],issues:[]},n);u instanceof Promise?s.push(u.then(p=>{p.issues.length&&o.issues.push(...Pt(l,p.issues)),o.value[l]=p.value})):(u.issues.length&&o.issues.push(...Pt(l,u.issues)),o.value[l]=u.value)}let c;for(const l in r)i.has(l)||(c=c??[],c.push(l));c&&c.length>0&&o.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{o.value={};for(const i of Reflect.ownKeys(r)){if(i==="__proto__")continue;let c=t.keyType._zod.run({value:i,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof i=="string"&&Tl.test(i)&&c.issues.length){const p=t.keyType._zod.run({value:Number(i),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(c=p)}if(c.issues.length){t.mode==="loose"?o.value[i]=r[i]:o.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(p=>et(p,n,Xe())),input:i,path:[i],inst:e});continue}const u=t.valueType._zod.run({value:r[i],issues:[]},n);u instanceof Promise?s.push(u.then(p=>{p.issues.length&&o.issues.push(...Pt(i,p.issues)),o.value[c.value]=p.value})):(u.issues.length&&o.issues.push(...Pt(i,u.issues)),o.value[c.value]=u.value)}}return s.length?Promise.all(s).then(()=>o):o}}),mb=v("$ZodEnum",(e,t)=>{J.init(e,t);const o=yl(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>Dg.has(typeof r)).map(r=>typeof r=="string"?Ut(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{const a=r.value;return n.has(a)||r.issues.push({code:"invalid_value",values:o,input:a,inst:e}),r}}),gb=v("$ZodLiteral",(e,t)=>{if(J.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const o=new Set(t.values);e._zod.values=o,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Ut(n):n?Ut(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const s=n.value;return o.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),yb=v("$ZodTransform",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new ml(e.constructor.name);const r=t.transform(o.value,o);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(a=>(o.value=a,o));if(r instanceof Promise)throw new Ot;return o.value=r,o}});function li(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Ml=v("$ZodOptional",(e,t)=>{J.init(e,t),e._zod.optin="optional",e._zod.optout="optional",V(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),V(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Bs(o.source)})?$`):void 0}),e._zod.parse=(o,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>li(s,o.value)):li(r,o.value)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),bb=v("$ZodExactOptional",(e,t)=>{Ml.init(e,t),V(e._zod,"values",()=>t.innerType._zod.values),V(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),wb=v("$ZodNullable",(e,t)=>{J.init(e,t),V(e._zod,"optin",()=>t.innerType._zod.optin),V(e._zod,"optout",()=>t.innerType._zod.optout),V(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Bs(o.source)}|null)$`):void 0}),V(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(o,n)=>o.value===null?o:t.innerType._zod.run(o,n)}),kb=v("$ZodDefault",(e,t)=>{J.init(e,t),e._zod.optin="optional",V(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);if(o.value===void 0)return o.value=t.defaultValue,o;const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>ui(s,t)):ui(r,t)}});function ui(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const _b=v("$ZodPrefault",(e,t)=>{J.init(e,t),e._zod.optin="optional",V(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>(n.direction==="backward"||o.value===void 0&&(o.value=t.defaultValue),t.innerType._zod.run(o,n))}),vb=v("$ZodNonOptional",(e,t)=>{J.init(e,t),V(e._zod,"values",()=>{const o=t.innerType._zod.values;return o?new Set([...o].filter(n=>n!==void 0)):void 0}),e._zod.parse=(o,n)=>{const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>di(s,e)):di(r,e)}});function di(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ib=v("$ZodCatch",(e,t)=>{J.init(e,t),V(e._zod,"optin",()=>t.innerType._zod.optin),V(e._zod,"optout",()=>t.innerType._zod.optout),V(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>(o.value=s.value,s.issues.length&&(o.value=t.catchValue({...o,error:{issues:s.issues.map(a=>et(a,n,Xe()))},input:o.value}),o.issues=[]),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(s=>et(s,n,Xe()))},input:o.value}),o.issues=[]),o)}}),Sb=v("$ZodPipe",(e,t)=>{J.init(e,t),V(e._zod,"values",()=>t.in._zod.values),V(e._zod,"optin",()=>t.in._zod.optin),V(e._zod,"optout",()=>t.out._zod.optout),V(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(o,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(o,n);return s instanceof Promise?s.then(a=>tn(a,t.in,n)):tn(s,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(s=>tn(s,t.out,n)):tn(r,t.out,n)}});function tn(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},o)}const Db=v("$ZodReadonly",(e,t)=>{J.init(e,t),V(e._zod,"propValues",()=>t.innerType._zod.propValues),V(e._zod,"values",()=>t.innerType._zod.values),V(e._zod,"optin",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optin}),V(e._zod,"optout",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optout}),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(pi):pi(r)}});function pi(e){return e.value=Object.freeze(e.value),e}const Ab=v("$ZodCustom",(e,t)=>{ye.init(e,t),J.init(e,t),e._zod.parse=(o,n)=>o,e._zod.check=o=>{const n=o.value,r=t.fn(n);if(r instanceof Promise)return r.then(s=>fi(s,o,n,e));fi(r,o,n,e)}});function fi(e,t,o,n){if(!e){const r={code:"custom",input:o,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(Co(r))}}var hi;class Tb{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...o){const n=o[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const o=this._map.get(t);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(t),this}get(t){const o=t._zod.parent;if(o){const n={...this.get(o)??{}};delete n.id;const r={...n,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Pb(){return new Tb}(hi=globalThis).__zod_globalRegistry??(hi.__zod_globalRegistry=Pb());const fo=globalThis.__zod_globalRegistry;function Eb(e,t){return new e({type:"string",...R(t)})}function Cb(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function mi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Rb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function xb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Ob(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function Nb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function zl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function $b(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function Mb(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function zb(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function Fb(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function qb(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function Bb(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function Lb(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function Ub(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function jb(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function Hb(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function Vb(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function Zb(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function Yb(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function Wb(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function Gb(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function Kb(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function Jb(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function Qb(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function Xb(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function ew(e,t){return new e({type:"number",checks:[],...R(t)})}function tw(e,t){return new e({type:"number",coerce:!0,checks:[],...R(t)})}function ow(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function nw(e,t){return new e({type:"boolean",...R(t)})}function rw(e,t){return new e({type:"null",...R(t)})}function sw(e){return new e({type:"any"})}function aw(e){return new e({type:"unknown"})}function iw(e,t){return new e({type:"never",...R(t)})}function gi(e,t){return new El({check:"less_than",...R(t),value:e,inclusive:!1})}function lr(e,t){return new El({check:"less_than",...R(t),value:e,inclusive:!0})}function yi(e,t){return new Cl({check:"greater_than",...R(t),value:e,inclusive:!1})}function ur(e,t){return new Cl({check:"greater_than",...R(t),value:e,inclusive:!0})}function bi(e,t){return new by({check:"multiple_of",...R(t),value:e})}function Fl(e,t){return new ky({check:"max_length",...R(t),maximum:e})}function wn(e,t){return new _y({check:"min_length",...R(t),minimum:e})}function ql(e,t){return new vy({check:"length_equals",...R(t),length:e})}function cw(e,t){return new Iy({check:"string_format",format:"regex",...R(t),pattern:e})}function lw(e){return new Sy({check:"string_format",format:"lowercase",...R(e)})}function uw(e){return new Dy({check:"string_format",format:"uppercase",...R(e)})}function dw(e,t){return new Ay({check:"string_format",format:"includes",...R(t),includes:e})}function pw(e,t){return new Ty({check:"string_format",format:"starts_with",...R(t),prefix:e})}function fw(e,t){return new Py({check:"string_format",format:"ends_with",...R(t),suffix:e})}function so(e){return new Ey({check:"overwrite",tx:e})}function hw(e){return so(t=>t.normalize(e))}function mw(){return so(e=>e.trim())}function gw(){return so(e=>e.toLowerCase())}function yw(){return so(e=>e.toUpperCase())}function bw(){return so(e=>Ig(e))}function ww(e,t,o){return new e({type:"array",element:t,...R(o)})}function kw(e,t,o){const n=R(o);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function _w(e,t,o){return new e({type:"custom",check:"custom",fn:t,...R(o)})}function vw(e){const t=Iw(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Co(n,o.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=o.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),o.issues.push(Co(r))}},e(o.value,o)));return t}function Iw(e,t){const o=new ye({check:"custom",...R(t)});return o._zod.check=e,o}function kn(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??fo,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function G(e,t,o={path:[],schemaPath:[]}){var u,p;var n;const r=e._zod.def,s=t.seen.get(e);if(s)return s.count++,o.schemaPath.includes(e)&&(s.cycle=o.path),s.schema;const a={schema:{},count:1,cycle:void 0,path:o.path};t.seen.set(e,a);const i=(p=(u=e._zod).toJSONSchema)==null?void 0:p.call(u);if(i)a.schema=i;else{const f={...o,schemaPath:[...o.schemaPath,e],path:o.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,f);else{const g=a.schema,b=t.processors[r.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);b(e,t,g,f)}const h=e._zod.parent;h&&(a.ref||(a.ref=h),G(h,t,f),t.seen.get(h).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),t.io==="input"&&he(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function _n(e,t){var a,i,c,l;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const u of e.seen.entries()){const p=(a=e.metadataRegistry.get(u[0]))==null?void 0:a.id;if(p){const f=n.get(p);if(f&&f!==u[0])throw new Error(`Duplicate schema id "${p}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(p,u[0])}}const r=u=>{var b;const p=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const _=(b=e.external.registry.get(u[0]))==null?void 0:b.id,w=e.external.uri??(D=>D);if(_)return{ref:w(_)};const P=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=P,{defId:P,ref:`${w("__shared")}#/${p}/${P}`}}if(u[1]===o)return{ref:"#"};const h=`#/${p}/`,g=u[1].schema.id??`__schema${e.counter++}`;return{defId:g,ref:h+g}},s=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:f,defId:h}=r(u);p.def={...p.schema},h&&(p.defId=h);const g=p.schema;for(const b in g)delete g[b];g.$ref=f};if(e.cycles==="throw")for(const u of e.seen.entries()){const p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${(i=p.cycle)==null?void 0:i.join("/")}/<root>
468
+ `)}h.write("payload.value = newResult;"),h.write("return payload;");const P=h.compile();return(A,T)=>P(f,A,T)};let s;const a=Ro,i=!bl.jitless,l=i&&Ag.value,u=t.catchall;let p;e._zod.parse=(f,h)=>{p??(p=n.value);const g=f.value;return a(g)?i&&l&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(s||(s=r(t.shape)),f=s(f,h),u?Ml([],g,f,h,p,e):f):o(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),f)}});function li(e,t,o,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const r=e.filter(s=>!At(s));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:o,errors:e.map(s=>s.issues.map(a=>et(a,n,Xe())))}),t)}const zl=v("$ZodUnion",(e,t)=>{J.init(e,t),V(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),V(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),V(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),V(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${r.map(s=>Us(s.source)).join("|")})$`)}});const o=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,s)=>{if(o)return n(r,s);let a=!1;const i=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},s);if(l instanceof Promise)i.push(l),a=!0;else{if(l.issues.length===0)return l;i.push(l)}}return a?Promise.all(i).then(c=>li(c,r,e,s)):li(i,r,e,s)}}),mb=v("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,zl.init(e,t);const o=e._zod.parse;V(e._zod,"propValues",()=>{const r={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,c]of Object.entries(a)){r[i]||(r[i]=new Set);for(const l of c)r[i].add(l)}}return r});const n=jn(()=>{var a;const r=t.options,s=new Map;for(const i of r){const c=(a=i._zod.propValues)==null?void 0:a[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of c){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(r,s)=>{const a=r.value;if(!Ro(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;const i=n.value.get(a==null?void 0:a[t.discriminator]);return i?i._zod.run(r,s):t.unionFallback?o(r,s):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),r)}}),gb=v("$ZodIntersection",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{const r=o.value,s=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([c,l])=>ui(o,c,l)):ui(o,s,a)}});function Nr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ut(e)&&Ut(t)){const o=Object.keys(t),n=Object.keys(e).filter(s=>o.indexOf(s)!==-1),r={...e,...t};for(const s of n){const a=Nr(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r[s]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let n=0;n<e.length;n++){const r=e[n],s=t[n],a=Nr(r,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};o.push(a.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function ui(e,t,o){const n=new Map;let r;for(const i of t.issues)if(i.code==="unrecognized_keys"){r??(r=i);for(const c of i.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(i);for(const i of o.issues)if(i.code==="unrecognized_keys")for(const c of i.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(i);const s=[...n].filter(([,i])=>i.l&&i.r).map(([i])=>i);if(s.length&&r&&e.issues.push({...r,keys:s}),At(e))return e;const a=Nr(t.value,o.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const yb=v("$ZodRecord",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Ut(r))return o.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),o;const s=[],a=t.keyType._zod.values;if(a){o.value={};const i=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){i.add(typeof l=="number"?l.toString():l);const u=t.valueType._zod.run({value:r[l],issues:[]},n);u instanceof Promise?s.push(u.then(p=>{p.issues.length&&o.issues.push(...Pt(l,p.issues)),o.value[l]=p.value})):(u.issues.length&&o.issues.push(...Pt(l,u.issues)),o.value[l]=u.value)}let c;for(const l in r)i.has(l)||(c=c??[],c.push(l));c&&c.length>0&&o.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{o.value={};for(const i of Reflect.ownKeys(r)){if(i==="__proto__")continue;let c=t.keyType._zod.run({value:i,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof i=="string"&&Cl.test(i)&&c.issues.length){const p=t.keyType._zod.run({value:Number(i),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(c=p)}if(c.issues.length){t.mode==="loose"?o.value[i]=r[i]:o.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(p=>et(p,n,Xe())),input:i,path:[i],inst:e});continue}const u=t.valueType._zod.run({value:r[i],issues:[]},n);u instanceof Promise?s.push(u.then(p=>{p.issues.length&&o.issues.push(...Pt(i,p.issues)),o.value[c.value]=p.value})):(u.issues.length&&o.issues.push(...Pt(i,u.issues)),o.value[c.value]=u.value)}}return s.length?Promise.all(s).then(()=>o):o}}),bb=v("$ZodEnum",(e,t)=>{J.init(e,t);const o=wl(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>Pg.has(typeof r)).map(r=>typeof r=="string"?jt(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{const a=r.value;return n.has(a)||r.issues.push({code:"invalid_value",values:o,input:a,inst:e}),r}}),wb=v("$ZodLiteral",(e,t)=>{if(J.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const o=new Set(t.values);e._zod.values=o,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?jt(n):n?jt(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const s=n.value;return o.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),kb=v("$ZodTransform",(e,t)=>{J.init(e,t),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new yl(e.constructor.name);const r=t.transform(o.value,o);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(a=>(o.value=a,o));if(r instanceof Promise)throw new Nt;return o.value=r,o}});function di(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Fl=v("$ZodOptional",(e,t)=>{J.init(e,t),e._zod.optin="optional",e._zod.optout="optional",V(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),V(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Us(o.source)})?$`):void 0}),e._zod.parse=(o,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>di(s,o.value)):di(r,o.value)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),_b=v("$ZodExactOptional",(e,t)=>{Fl.init(e,t),V(e._zod,"values",()=>t.innerType._zod.values),V(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),vb=v("$ZodNullable",(e,t)=>{J.init(e,t),V(e._zod,"optin",()=>t.innerType._zod.optin),V(e._zod,"optout",()=>t.innerType._zod.optout),V(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Us(o.source)}|null)$`):void 0}),V(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(o,n)=>o.value===null?o:t.innerType._zod.run(o,n)}),Ib=v("$ZodDefault",(e,t)=>{J.init(e,t),e._zod.optin="optional",V(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);if(o.value===void 0)return o.value=t.defaultValue,o;const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>pi(s,t)):pi(r,t)}});function pi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Sb=v("$ZodPrefault",(e,t)=>{J.init(e,t),e._zod.optin="optional",V(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>(n.direction==="backward"||o.value===void 0&&(o.value=t.defaultValue),t.innerType._zod.run(o,n))}),Db=v("$ZodNonOptional",(e,t)=>{J.init(e,t),V(e._zod,"values",()=>{const o=t.innerType._zod.values;return o?new Set([...o].filter(n=>n!==void 0)):void 0}),e._zod.parse=(o,n)=>{const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>fi(s,e)):fi(r,e)}});function fi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Tb=v("$ZodCatch",(e,t)=>{J.init(e,t),V(e._zod,"optin",()=>t.innerType._zod.optin),V(e._zod,"optout",()=>t.innerType._zod.optout),V(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>(o.value=s.value,s.issues.length&&(o.value=t.catchValue({...o,error:{issues:s.issues.map(a=>et(a,n,Xe()))},input:o.value}),o.issues=[]),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(s=>et(s,n,Xe()))},input:o.value}),o.issues=[]),o)}}),Ab=v("$ZodPipe",(e,t)=>{J.init(e,t),V(e._zod,"values",()=>t.in._zod.values),V(e._zod,"optin",()=>t.in._zod.optin),V(e._zod,"optout",()=>t.out._zod.optout),V(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(o,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(o,n);return s instanceof Promise?s.then(a=>nn(a,t.in,n)):nn(s,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(s=>nn(s,t.out,n)):nn(r,t.out,n)}});function nn(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},o)}const Pb=v("$ZodReadonly",(e,t)=>{J.init(e,t),V(e._zod,"propValues",()=>t.innerType._zod.propValues),V(e._zod,"values",()=>t.innerType._zod.values),V(e._zod,"optin",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optin}),V(e._zod,"optout",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optout}),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(hi):hi(r)}});function hi(e){return e.value=Object.freeze(e.value),e}const Cb=v("$ZodCustom",(e,t)=>{ye.init(e,t),J.init(e,t),e._zod.parse=(o,n)=>o,e._zod.check=o=>{const n=o.value,r=t.fn(n);if(r instanceof Promise)return r.then(s=>mi(s,o,n,e));mi(r,o,n,e)}});function mi(e,t,o,n){if(!e){const r={code:"custom",input:o,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(xo(r))}}var gi;class Eb{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...o){const n=o[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const o=this._map.get(t);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(t),this}get(t){const o=t._zod.parent;if(o){const n={...this.get(o)??{}};delete n.id;const r={...n,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Rb(){return new Eb}(gi=globalThis).__zod_globalRegistry??(gi.__zod_globalRegistry=Rb());const ho=globalThis.__zod_globalRegistry;function xb(e,t){return new e({type:"string",...R(t)})}function Ob(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function yi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Nb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function $b(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Mb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function zb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function ql(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function Fb(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function qb(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function Lb(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function Bb(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function Ub(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function jb(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function Hb(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function Vb(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function Zb(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function Yb(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function Wb(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function Gb(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function Kb(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function Jb(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function Qb(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function Xb(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function ew(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function tw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function ow(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function nw(e,t){return new e({type:"number",checks:[],...R(t)})}function rw(e,t){return new e({type:"number",coerce:!0,checks:[],...R(t)})}function sw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function aw(e,t){return new e({type:"boolean",...R(t)})}function iw(e,t){return new e({type:"null",...R(t)})}function cw(e){return new e({type:"any"})}function lw(e){return new e({type:"unknown"})}function uw(e,t){return new e({type:"never",...R(t)})}function bi(e,t){return new Rl({check:"less_than",...R(t),value:e,inclusive:!1})}function hr(e,t){return new Rl({check:"less_than",...R(t),value:e,inclusive:!0})}function wi(e,t){return new xl({check:"greater_than",...R(t),value:e,inclusive:!1})}function mr(e,t){return new xl({check:"greater_than",...R(t),value:e,inclusive:!0})}function ki(e,t){return new _y({check:"multiple_of",...R(t),value:e})}function Ll(e,t){return new Iy({check:"max_length",...R(t),maximum:e})}function Sn(e,t){return new Sy({check:"min_length",...R(t),minimum:e})}function Bl(e,t){return new Dy({check:"length_equals",...R(t),length:e})}function dw(e,t){return new Ty({check:"string_format",format:"regex",...R(t),pattern:e})}function pw(e){return new Ay({check:"string_format",format:"lowercase",...R(e)})}function fw(e){return new Py({check:"string_format",format:"uppercase",...R(e)})}function hw(e,t){return new Cy({check:"string_format",format:"includes",...R(t),includes:e})}function mw(e,t){return new Ey({check:"string_format",format:"starts_with",...R(t),prefix:e})}function gw(e,t){return new Ry({check:"string_format",format:"ends_with",...R(t),suffix:e})}function ao(e){return new xy({check:"overwrite",tx:e})}function yw(e){return ao(t=>t.normalize(e))}function bw(){return ao(e=>e.trim())}function ww(){return ao(e=>e.toLowerCase())}function kw(){return ao(e=>e.toUpperCase())}function _w(){return ao(e=>Tg(e))}function vw(e,t,o){return new e({type:"array",element:t,...R(o)})}function Iw(e,t,o){const n=R(o);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Sw(e,t,o){return new e({type:"custom",check:"custom",fn:t,...R(o)})}function Dw(e){const t=Tw(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(xo(n,o.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=o.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),o.issues.push(xo(r))}},e(o.value,o)));return t}function Tw(e,t){const o=new ye({check:"custom",...R(t)});return o._zod.check=e,o}function Dn(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??ho,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function G(e,t,o={path:[],schemaPath:[]}){var u,p;var n;const r=e._zod.def,s=t.seen.get(e);if(s)return s.count++,o.schemaPath.includes(e)&&(s.cycle=o.path),s.schema;const a={schema:{},count:1,cycle:void 0,path:o.path};t.seen.set(e,a);const i=(p=(u=e._zod).toJSONSchema)==null?void 0:p.call(u);if(i)a.schema=i;else{const f={...o,schemaPath:[...o.schemaPath,e],path:o.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,f);else{const g=a.schema,b=t.processors[r.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);b(e,t,g,f)}const h=e._zod.parent;h&&(a.ref||(a.ref=h),G(h,t,f),t.seen.get(h).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),t.io==="input"&&he(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Tn(e,t){var a,i,c,l;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const u of e.seen.entries()){const p=(a=e.metadataRegistry.get(u[0]))==null?void 0:a.id;if(p){const f=n.get(p);if(f&&f!==u[0])throw new Error(`Duplicate schema id "${p}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(p,u[0])}}const r=u=>{var b;const p=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const _=(b=e.external.registry.get(u[0]))==null?void 0:b.id,w=e.external.uri??(D=>D);if(_)return{ref:w(_)};const P=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=P,{defId:P,ref:`${w("__shared")}#/${p}/${P}`}}if(u[1]===o)return{ref:"#"};const h=`#/${p}/`,g=u[1].schema.id??`__schema${e.counter++}`;return{defId:g,ref:h+g}},s=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:f,defId:h}=r(u);p.def={...p.schema},h&&(p.defId=h);const g=p.schema;for(const b in g)delete g[b];g.$ref=f};if(e.cycles==="throw")for(const u of e.seen.entries()){const p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${(i=p.cycle)==null?void 0:i.join("/")}/<root>
463
469
 
464
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const p=u[1];if(t===u[0]){s(u);continue}if(e.external){const h=(c=e.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&h){s(u);continue}}if((l=e.metadataRegistry.get(u[0]))==null?void 0:l.id){s(u);continue}if(p.cycle){s(u);continue}if(p.count>1&&e.reused==="ref"){s(u);continue}}}function vn(e,t){var a,i,c;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=l=>{const u=e.seen.get(l);if(u.ref===null)return;const p=u.def??u.schema,f={...p},h=u.ref;if(u.ref=null,h){n(h);const b=e.seen.get(h),_=b.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(_)):Object.assign(p,_),Object.assign(p,f),l._zod.parent===h)for(const P in p)P==="$ref"||P==="allOf"||P in f||delete p[P];if(_.$ref&&b.def)for(const P in p)P==="$ref"||P==="allOf"||P in b.def&&JSON.stringify(p[P])===JSON.stringify(b.def[P])&&delete p[P]}const g=l._zod.parent;if(g&&g!==h){n(g);const b=e.seen.get(g);if(b!=null&&b.schema.$ref&&(p.$ref=b.schema.$ref,b.def))for(const _ in p)_==="$ref"||_==="allOf"||_ in b.def&&JSON.stringify(p[_])===JSON.stringify(b.def[_])&&delete p[_]}e.override({zodSchema:l,jsonSchema:p,path:u.path??[]})};for(const l of[...e.seen.entries()].reverse())n(l[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,(a=e.external)!=null&&a.uri){const l=(i=e.external.registry.get(t))==null?void 0:i.id;if(!l)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(l)}Object.assign(r,o.def??o.schema);const s=((c=e.external)==null?void 0:c.defs)??{};for(const l of e.seen.entries()){const u=l[1];u.def&&u.defId&&(s[u.defId]=u.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const l=JSON.parse(JSON.stringify(r));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:In(t,"input",e.processors),output:In(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function he(e,t){const o=t??{seen:new Set};if(o.seen.has(e))return!1;o.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return he(n.element,o);if(n.type==="set")return he(n.valueType,o);if(n.type==="lazy")return he(n.getter(),o);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return he(n.innerType,o);if(n.type==="intersection")return he(n.left,o)||he(n.right,o);if(n.type==="record"||n.type==="map")return he(n.keyType,o)||he(n.valueType,o);if(n.type==="pipe")return he(n.in,o)||he(n.out,o);if(n.type==="object"){for(const r in n.shape)if(he(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(he(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(he(r,o))return!0;return!!(n.rest&&he(n.rest,o))}return!1}const Sw=(e,t={})=>o=>{const n=kn({...o,processors:t});return G(e,n),_n(n,e),vn(n,e)},In=(e,t,o={})=>n=>{const{libraryOptions:r,target:s}=n??{},a=kn({...r??{},target:s,io:t,processors:o});return G(e,a),_n(a,e),vn(a,e)},Dw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Bl=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:s,maximum:a,format:i,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof a=="number"&&(r.maxLength=a),i&&(r.format=Dw[i]??i,r.format===""&&delete r.format,i==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const u=[...c];u.length===1?r.pattern=u[0].source:u.length>1&&(r.allOf=[...u.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Ll=(e,t,o,n)=>{const r=o,{minimum:s,maximum:a,format:i,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof i=="string"&&i.includes("int")?r.type="integer":r.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u),typeof s=="number"&&(r.minimum=s,typeof u=="number"&&t.target!=="draft-04"&&(u>=s?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof a=="number"&&(r.maximum=a,typeof l=="number"&&t.target!=="draft-04"&&(l<=a?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},Ul=(e,t,o,n)=>{o.type="boolean"},Aw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Tw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},jl=(e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},Pw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Ew=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Hl=(e,t,o,n)=>{o.not={}},Vl=(e,t,o,n)=>{},Zl=(e,t,o,n)=>{},Cw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Yl=(e,t,o,n)=>{const r=e._zod.def,s=yl(r.entries);s.every(a=>typeof a=="number")&&(o.type="number"),s.every(a=>typeof a=="string")&&(o.type="string"),o.enum=s},Wl=(e,t,o,n)=>{const r=e._zod.def,s=[];for(const a of r.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(a))}else s.push(a);if(s.length!==0)if(s.length===1){const a=s[0];o.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?o.enum=[a]:o.const=a}else s.every(a=>typeof a=="number")&&(o.type="number"),s.every(a=>typeof a=="string")&&(o.type="string"),s.every(a=>typeof a=="boolean")&&(o.type="boolean"),s.every(a=>a===null)&&(o.type="null"),o.enum=s},Rw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},xw=(e,t,o,n)=>{const r=o,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=s.source},Ow=(e,t,o,n)=>{const r=o,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:i,mime:c}=e._zod.bag;a!==void 0&&(s.minLength=a),i!==void 0&&(s.maxLength=i),c?c.length===1?(s.contentMediaType=c[0],Object.assign(r,s)):(Object.assign(r,s),r.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(r,s)},Nw=(e,t,o,n)=>{o.type="boolean"},Gl=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},$w=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Kl=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Mw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},zw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Jl=(e,t,o,n)=>{const r=o,s=e._zod.def,{minimum:a,maximum:i}=e._zod.bag;typeof a=="number"&&(r.minItems=a),typeof i=="number"&&(r.maxItems=i),r.type="array",r.items=G(s.element,t,{...n,path:[...n.path,"items"]})},Ql=(e,t,o,n)=>{var l;const r=o,s=e._zod.def;r.type="object",r.properties={};const a=s.shape;for(const u in a)r.properties[u]=G(a[u],t,{...n,path:[...n.path,"properties",u]});const i=new Set(Object.keys(a)),c=new Set([...i].filter(u=>{const p=s.shape[u]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));c.size>0&&(r.required=Array.from(c)),((l=s.catchall)==null?void 0:l._zod.def.type)==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=G(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Xl=(e,t,o,n)=>{const r=e._zod.def,s=r.inclusive===!1,a=r.options.map((i,c)=>G(i,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?o.oneOf=a:o.anyOf=a},eu=(e,t,o,n)=>{const r=e._zod.def,s=G(r.left,t,{...n,path:[...n.path,"allOf",0]}),a=G(r.right,t,{...n,path:[...n.path,"allOf",1]}),i=l=>"allOf"in l&&Object.keys(l).length===1,c=[...i(s)?s.allOf:[s],...i(a)?a.allOf:[a]];o.allOf=c},Fw=(e,t,o,n)=>{const r=o,s=e._zod.def;r.type="array";const a=t.target==="draft-2020-12"?"prefixItems":"items",i=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((f,h)=>G(f,t,{...n,path:[...n.path,a,h]})),l=s.rest?G(s.rest,t,{...n,path:[...n.path,i,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=c,l&&(r.items=l)):t.target==="openapi-3.0"?(r.items={anyOf:c},l&&r.items.anyOf.push(l),r.minItems=c.length,l||(r.maxItems=c.length)):(r.items=c,l&&(r.additionalItems=l));const{minimum:u,maximum:p}=e._zod.bag;typeof u=="number"&&(r.minItems=u),typeof p=="number"&&(r.maxItems=p)},tu=(e,t,o,n)=>{const r=o,s=e._zod.def;r.type="object";const a=s.keyType,i=a._zod.bag,c=i==null?void 0:i.patterns;if(s.mode==="loose"&&c&&c.size>0){const u=G(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const p of c)r.patternProperties[p.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=G(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=G(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const l=a._zod.values;if(l){const u=[...l].filter(p=>typeof p=="string"||typeof p=="number");u.length>0&&(r.required=u)}},ou=(e,t,o,n)=>{const r=e._zod.def,s=G(r.innerType,t,n),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=r.innerType,o.nullable=!0):o.anyOf=[s,{type:"null"}]},nu=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},ru=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},su=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,t.io==="input"&&(o._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},au=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}o.default=a},iu=(e,t,o,n)=>{const r=e._zod.def,s=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;G(s,t,n);const a=t.seen.get(e);a.ref=s},cu=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.readOnly=!0},qw=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Vs=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Bw=(e,t,o,n)=>{const r=e._zod.innerType;G(r,t,n);const s=t.seen.get(e);s.ref=r},wi={string:Bl,number:Ll,boolean:Ul,bigint:Aw,symbol:Tw,null:jl,undefined:Pw,void:Ew,never:Hl,any:Vl,unknown:Zl,date:Cw,enum:Yl,literal:Wl,nan:Rw,template_literal:xw,file:Ow,success:Nw,custom:Gl,function:$w,transform:Kl,map:Mw,set:zw,array:Jl,object:Ql,union:Xl,intersection:eu,tuple:Fw,record:tu,nullable:ou,nonoptional:nu,default:ru,prefault:su,catch:au,pipe:iu,readonly:cu,promise:qw,optional:Vs,lazy:Bw};function Lw(e,t){if("_idmap"in e){const n=e,r=kn({...t,processors:wi}),s={};for(const c of n._idmap.entries()){const[l,u]=c;G(u,r)}const a={},i={registry:n,uri:t==null?void 0:t.uri,defs:s};r.external=i;for(const c of n._idmap.entries()){const[l,u]=c;_n(r,u),a[l]=vn(r,u)}if(Object.keys(s).length>0){const c=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:s}}return{schemas:a}}const o=kn({...t,processors:wi});return G(e,o),_n(o,e),vn(o,e)}const Uw=v("ZodISODateTime",(e,t)=>{jy.init(e,t),te.init(e,t)});function lu(e){return Kb(Uw,e)}const jw=v("ZodISODate",(e,t)=>{Hy.init(e,t),te.init(e,t)});function Hw(e){return Jb(jw,e)}const Vw=v("ZodISOTime",(e,t)=>{Vy.init(e,t),te.init(e,t)});function Zw(e){return Qb(Vw,e)}const Yw=v("ZodISODuration",(e,t)=>{Zy.init(e,t),te.init(e,t)});function Ww(e){return Xb(Yw,e)}const uu=(e,t)=>{_l.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>Mg(e,o)},flatten:{value:o=>$g(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,Er,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,Er,2)}},isEmpty:{get(){return e.issues.length===0}}})},Gw=v("ZodError",uu),Se=v("ZodError",uu,{Parent:Error}),Kw=Us(Se),Jw=js(Se),Qw=qn(Se),Xw=Bn(Se),ek=Fg(Se),tk=qg(Se),ok=Bg(Se),nk=Lg(Se),rk=Ug(Se),sk=jg(Se),ak=Hg(Se),ik=Vg(Se),Q=v("ZodType",(e,t)=>(J.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:In(e,"input"),output:In(e,"output")}}),e.toJSONSchema=Sw(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...o)=>e.clone(nt(t,{checks:[...t.checks??[],...o.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(o,n)=>rt(e,o,n),e.brand=()=>e,e.register=(o,n)=>(o.add(e,n),e),e.parse=(o,n)=>Kw(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>Qw(e,o,n),e.parseAsync=async(o,n)=>Jw(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>Xw(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>ek(e,o,n),e.decode=(o,n)=>tk(e,o,n),e.encodeAsync=async(o,n)=>ok(e,o,n),e.decodeAsync=async(o,n)=>nk(e,o,n),e.safeEncode=(o,n)=>rk(e,o,n),e.safeDecode=(o,n)=>sk(e,o,n),e.safeEncodeAsync=async(o,n)=>ak(e,o,n),e.safeDecodeAsync=async(o,n)=>ik(e,o,n),e.refine=(o,n)=>e.check(e_(o,n)),e.superRefine=o=>e.check(t_(o)),e.overwrite=o=>e.check(so(o)),e.optional=()=>ee(e),e.exactOptional=()=>Lk(e),e.nullable=()=>vi(e),e.nullish=()=>ee(vi(e)),e.nonoptional=o=>Yk(e,o),e.array=()=>I(e),e.or=o=>W([e,o]),e.and=o=>Ys(e,o),e.transform=o=>xr(e,yu(o)),e.default=o=>Hk(e,o),e.prefault=o=>Zk(e,o),e.catch=o=>Gk(e,o),e.pipe=o=>xr(e,o),e.readonly=()=>Qk(e),e.describe=o=>{const n=e.clone();return fo.add(n,{description:o}),n},Object.defineProperty(e,"description",{get(){var o;return(o=fo.get(e))==null?void 0:o.description},configurable:!0}),e.meta=(...o)=>{if(o.length===0)return fo.get(e);const n=e.clone();return fo.add(n,o[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=o=>o(e),e)),du=v("_ZodString",(e,t)=>{Hs.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Bl(e,n,r);const o=e._zod.bag;e.format=o.format??null,e.minLength=o.minimum??null,e.maxLength=o.maximum??null,e.regex=(...n)=>e.check(cw(...n)),e.includes=(...n)=>e.check(dw(...n)),e.startsWith=(...n)=>e.check(pw(...n)),e.endsWith=(...n)=>e.check(fw(...n)),e.min=(...n)=>e.check(wn(...n)),e.max=(...n)=>e.check(Fl(...n)),e.length=(...n)=>e.check(ql(...n)),e.nonempty=(...n)=>e.check(wn(1,...n)),e.lowercase=n=>e.check(lw(n)),e.uppercase=n=>e.check(uw(n)),e.trim=()=>e.check(mw()),e.normalize=(...n)=>e.check(hw(...n)),e.toLowerCase=()=>e.check(gw()),e.toUpperCase=()=>e.check(yw()),e.slugify=()=>e.check(bw())}),ck=v("ZodString",(e,t)=>{Hs.init(e,t),du.init(e,t),e.email=o=>e.check(Cb(lk,o)),e.url=o=>e.check(zl(pu,o)),e.jwt=o=>e.check(Gb(Dk,o)),e.emoji=o=>e.check($b(dk,o)),e.guid=o=>e.check(mi(ki,o)),e.uuid=o=>e.check(Rb(on,o)),e.uuidv4=o=>e.check(xb(on,o)),e.uuidv6=o=>e.check(Ob(on,o)),e.uuidv7=o=>e.check(Nb(on,o)),e.nanoid=o=>e.check(Mb(pk,o)),e.guid=o=>e.check(mi(ki,o)),e.cuid=o=>e.check(zb(fk,o)),e.cuid2=o=>e.check(Fb(hk,o)),e.ulid=o=>e.check(qb(mk,o)),e.base64=o=>e.check(Zb(vk,o)),e.base64url=o=>e.check(Yb(Ik,o)),e.xid=o=>e.check(Bb(gk,o)),e.ksuid=o=>e.check(Lb(yk,o)),e.ipv4=o=>e.check(Ub(bk,o)),e.ipv6=o=>e.check(jb(wk,o)),e.cidrv4=o=>e.check(Hb(kk,o)),e.cidrv6=o=>e.check(Vb(_k,o)),e.e164=o=>e.check(Wb(Sk,o)),e.datetime=o=>e.check(lu(o)),e.date=o=>e.check(Hw(o)),e.time=o=>e.check(Zw(o)),e.duration=o=>e.check(Ww(o))});function d(e){return Eb(ck,e)}const te=v("ZodStringFormat",(e,t)=>{X.init(e,t),du.init(e,t)}),lk=v("ZodEmail",(e,t)=>{Ny.init(e,t),te.init(e,t)}),ki=v("ZodGUID",(e,t)=>{xy.init(e,t),te.init(e,t)}),on=v("ZodUUID",(e,t)=>{Oy.init(e,t),te.init(e,t)}),pu=v("ZodURL",(e,t)=>{$y.init(e,t),te.init(e,t)});function uk(e){return zl(pu,e)}const dk=v("ZodEmoji",(e,t)=>{My.init(e,t),te.init(e,t)}),pk=v("ZodNanoID",(e,t)=>{zy.init(e,t),te.init(e,t)}),fk=v("ZodCUID",(e,t)=>{Fy.init(e,t),te.init(e,t)}),hk=v("ZodCUID2",(e,t)=>{qy.init(e,t),te.init(e,t)}),mk=v("ZodULID",(e,t)=>{By.init(e,t),te.init(e,t)}),gk=v("ZodXID",(e,t)=>{Ly.init(e,t),te.init(e,t)}),yk=v("ZodKSUID",(e,t)=>{Uy.init(e,t),te.init(e,t)}),bk=v("ZodIPv4",(e,t)=>{Yy.init(e,t),te.init(e,t)}),wk=v("ZodIPv6",(e,t)=>{Wy.init(e,t),te.init(e,t)}),kk=v("ZodCIDRv4",(e,t)=>{Gy.init(e,t),te.init(e,t)}),_k=v("ZodCIDRv6",(e,t)=>{Ky.init(e,t),te.init(e,t)}),vk=v("ZodBase64",(e,t)=>{Jy.init(e,t),te.init(e,t)}),Ik=v("ZodBase64URL",(e,t)=>{Xy.init(e,t),te.init(e,t)}),Sk=v("ZodE164",(e,t)=>{eb.init(e,t),te.init(e,t)}),Dk=v("ZodJWT",(e,t)=>{ob.init(e,t),te.init(e,t)}),Zs=v("ZodNumber",(e,t)=>{xl.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Ll(e,n,r),e.gt=(n,r)=>e.check(yi(n,r)),e.gte=(n,r)=>e.check(ur(n,r)),e.min=(n,r)=>e.check(ur(n,r)),e.lt=(n,r)=>e.check(gi(n,r)),e.lte=(n,r)=>e.check(lr(n,r)),e.max=(n,r)=>e.check(lr(n,r)),e.int=n=>e.check(_i(n)),e.safe=n=>e.check(_i(n)),e.positive=n=>e.check(yi(0,n)),e.nonnegative=n=>e.check(ur(0,n)),e.negative=n=>e.check(gi(0,n)),e.nonpositive=n=>e.check(lr(0,n)),e.multipleOf=(n,r)=>e.check(bi(n,r)),e.step=(n,r)=>e.check(bi(n,r)),e.finite=()=>e;const o=e._zod.bag;e.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),e.isFinite=!0,e.format=o.format??null});function E(e){return ew(Zs,e)}const Ak=v("ZodNumberFormat",(e,t)=>{nb.init(e,t),Zs.init(e,t)});function _i(e){return ow(Ak,e)}const Tk=v("ZodBoolean",(e,t)=>{rb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ul(e,o,n)});function x(e){return nw(Tk,e)}const Pk=v("ZodNull",(e,t)=>{sb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>jl(e,o,n)});function fu(e){return rw(Pk,e)}const Ek=v("ZodAny",(e,t)=>{ab.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Vl()});function Ck(){return sw(Ek)}const Rk=v("ZodUnknown",(e,t)=>{ib.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Zl()});function K(){return aw(Rk)}const xk=v("ZodNever",(e,t)=>{cb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Hl(e,o,n)});function Ok(e){return iw(xk,e)}const Nk=v("ZodArray",(e,t)=>{lb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Jl(e,o,n,r),e.element=t.element,e.min=(o,n)=>e.check(wn(o,n)),e.nonempty=o=>e.check(wn(1,o)),e.max=(o,n)=>e.check(Fl(o,n)),e.length=(o,n)=>e.check(ql(o,n)),e.unwrap=()=>e.element});function I(e,t){return ww(Nk,e,t)}const hu=v("ZodObject",(e,t)=>{db.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ql(e,o,n,r),V(e,"shape",()=>t.shape),e.keyof=()=>z(Object.keys(e._zod.def.shape)),e.catchall=o=>e.clone({...e._zod.def,catchall:o}),e.passthrough=()=>e.clone({...e._zod.def,catchall:K()}),e.loose=()=>e.clone({...e._zod.def,catchall:K()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ok()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=o=>Cg(e,o),e.safeExtend=o=>Rg(e,o),e.merge=o=>xg(e,o),e.pick=o=>Pg(e,o),e.omit=o=>Eg(e,o),e.partial=(...o)=>Og(bu,e,o[0]),e.required=(...o)=>Ng(wu,e,o[0])});function m(e,t){const o={type:"object",shape:e??{},...R(t)};return new hu(o)}function ue(e,t){return new hu({type:"object",shape:e,catchall:K(),...R(t)})}const mu=v("ZodUnion",(e,t)=>{$l.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Xl(e,o,n,r),e.options=t.options});function W(e,t){return new mu({type:"union",options:e,...R(t)})}const $k=v("ZodDiscriminatedUnion",(e,t)=>{mu.init(e,t),pb.init(e,t)});function gu(e,t,o){return new $k({type:"union",options:t,discriminator:e,...R(o)})}const Mk=v("ZodIntersection",(e,t)=>{fb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>eu(e,o,n,r)});function Ys(e,t){return new Mk({type:"intersection",left:e,right:t})}const zk=v("ZodRecord",(e,t)=>{hb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>tu(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function j(e,t,o){return new zk({type:"record",keyType:e,valueType:t,...R(o)})}const Rr=v("ZodEnum",(e,t)=>{mb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Yl(e,n,r),e.enum=t.entries,e.options=Object.values(t.entries);const o=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const s={};for(const a of n)if(o.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Rr({...t,checks:[],...R(r),entries:s})},e.exclude=(n,r)=>{const s={...t.entries};for(const a of n)if(o.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Rr({...t,checks:[],...R(r),entries:s})}});function z(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Rr({type:"enum",entries:o,...R(t)})}const Fk=v("ZodLiteral",(e,t)=>{gb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Wl(e,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function y(e,t){return new Fk({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}const qk=v("ZodTransform",(e,t)=>{yb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Kl(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new ml(e.constructor.name);o.addIssue=s=>{if(typeof s=="string")o.issues.push(Co(s,o.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=o.value),a.inst??(a.inst=e),o.issues.push(Co(a))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(s=>(o.value=s,o)):(o.value=r,o)}});function yu(e){return new qk({type:"transform",transform:e})}const bu=v("ZodOptional",(e,t)=>{Ml.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Vs(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function ee(e){return new bu({type:"optional",innerType:e})}const Bk=v("ZodExactOptional",(e,t)=>{bb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Vs(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Lk(e){return new Bk({type:"optional",innerType:e})}const Uk=v("ZodNullable",(e,t)=>{wb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ou(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function vi(e){return new Uk({type:"nullable",innerType:e})}const jk=v("ZodDefault",(e,t)=>{kb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ru(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hk(e,t){return new jk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():wl(t)}})}const Vk=v("ZodPrefault",(e,t)=>{_b.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>su(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Zk(e,t){return new Vk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():wl(t)}})}const wu=v("ZodNonOptional",(e,t)=>{vb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>nu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Yk(e,t){return new wu({type:"nonoptional",innerType:e,...R(t)})}const Wk=v("ZodCatch",(e,t)=>{Ib.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>au(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Gk(e,t){return new Wk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Kk=v("ZodPipe",(e,t)=>{Sb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>iu(e,o,n,r),e.in=t.in,e.out=t.out});function xr(e,t){return new Kk({type:"pipe",in:e,out:t})}const Jk=v("ZodReadonly",(e,t)=>{Db.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>cu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Qk(e){return new Jk({type:"readonly",innerType:e})}const ku=v("ZodCustom",(e,t)=>{Ab.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Gl(e,o)});function Xk(e,t){return kw(ku,e??(()=>!0),t)}function e_(e,t={}){return _w(ku,e,t)}function t_(e){return vw(e)}function _u(e,t){return xr(yu(e),t)}const q={custom:"custom"};function o_(e){return tw(Zs,e)}const n_=m({name:d().optional(),closed:x().optional(),refCreateSavePath:d().optional(),createDocNameTemplate:d().optional(),dailyNoteSavePath:d().optional(),dailyNoteTemplatePath:d().optional()}),vu=m({id:d().optional(),notebook:d().optional(),path:d().optional()}),r_=vu.superRefine((e,t)=>{const o=typeof e.id=="string",n=typeof e.notebook=="string"||typeof e.path=="string";if(o===n){t.addIssue({code:q.custom,message:"Provide either id or notebook + path."});return}n&&(!e.notebook||!e.path)&&t.addIssue({code:q.custom,message:"Both notebook and path are required when id is not provided."})}),s_=m({fromPaths:I(d()).optional(),toNotebook:d().optional(),toPath:d().optional(),fromIDs:I(d()).optional(),toID:d().optional()}).superRefine((e,t)=>{const o=Array.isArray(e.fromPaths)||typeof e.toNotebook=="string"||typeof e.toPath=="string",n=Array.isArray(e.fromIDs)||typeof e.toID=="string";if(o===n){t.addIssue({code:q.custom,message:"Provide either fromPaths + toNotebook + toPath or fromIDs + toID."});return}o&&(!e.fromPaths||!e.toNotebook||!e.toPath)&&t.addIssue({code:q.custom,message:"fromPaths, toNotebook, and toPath are required for path-based moves."}),n&&(!e.fromIDs||!e.toID)&&t.addIssue({code:q.custom,message:"fromIDs and toID are required for ID-based moves."})}),a_=z(Ss),i_=z(Ds),c_=z(As),l_=z(Ts),u_=z(Ps),d_=z(Es),p_=z(Os),f_=z(Ns),h_=z($s),Iu=m({action:y("ls"),path:d().describe("Human-readable workspace path, such as /Notebook/Folder or / for notebook roots")}),Su=m({action:y("tree"),path:d().describe("Human-readable workspace path, such as /Notebook/Folder or / for all readable notebooks"),maxDepth:E().int().min(0).max(20).optional().describe("Max tree depth to return (default 3)")}),Du=m({action:y("read"),path:d().describe("Human-readable document path"),blockStart:E().int().min(0).optional().describe("Zero-based display-block index to start reading from (default 0)"),blockLimit:E().int().min(1).max(200).optional().describe("Maximum complete display blocks to return (default 50)"),tokenBudget:E().int().min(1).max(32e3).optional().describe("Approximate token budget for the window (default 2000). A single oversized block is still returned whole."),includeBlockIds:x().optional().describe("Include a sidecar blockRefs mapping without adding block IDs to Markdown content (default false)")}).passthrough().superRefine((e,t)=>{for(const o of["page","pageSize"])e[o]!==void 0&&t.addIssue({code:q.custom,path:[o],message:`${o} character pagination was removed; use blockStart, blockLimit, and tokenBudget.`})}),Au=m({action:y("write"),path:d().describe("Human-readable document path"),markdown:d().describe("Markdown content to create or write. Do not include a leading # Title; a matching create-time H1 is stripped automatically."),overwrite:x().optional().describe("When true, replace an existing document body while keeping the document node and title. This is a full body replacement.")}),Sn=m({old:d().min(1).describe("Original text to match exactly. Supports multi-line strings."),new:d().describe("Replacement text. Supports multi-line strings."),replace_all:x().optional().describe("When true, replace every exact match. Defaults to false.")}),Tu=m({action:y("replace"),path:d().describe("Human-readable document path to modify"),edit:W([Sn,I(Sn).min(1)]).describe("One replacement edit or an array of edits to apply sequentially inside editable non-complex Markdown blocks without rebuilding the document")}),Pu=m({action:y("rm"),path:d().describe("Human-readable document path to delete")}),Eu=m({action:y("mv"),from:d().describe("Human-readable source document path"),to:d().describe("Human-readable destination document path")}),Cu=m({action:y("search"),path:d().describe("Human-readable document or folder path to search within"),query:d().describe("Text or regular expression to search for"),regex:x().optional().describe("Treat query as a JavaScript regular expression"),caseSensitive:x().optional().describe("Use case-sensitive matching"),page:E().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:E().int().min(1).max(200).optional().describe("Matches per page, default 50")}),Ru=m({action:y("list")}),xu=m({action:y("create"),name:d().describe("Notebook name"),icon:d().optional().describe("Optional notebook icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}),Ou=m({action:y("set_open_state"),notebook:d().describe("Notebook ID"),opened:x().describe("true to open, false to close")}),Nu=m({action:y("remove"),notebook:d().describe("Notebook ID")}),$u=m({action:y("rename"),notebook:d().describe("Notebook ID"),name:d().describe("New notebook name")}),Mu=m({action:y("get_conf"),notebook:d().describe("Notebook ID")}),zu=m({action:y("set_conf"),notebook:d().describe("Notebook ID"),conf:n_.describe("Notebook configuration")}),Fu=m({action:y("set_icon"),notebook:d().describe("Notebook ID"),icon:d().describe("Icon value. Prefer a Unicode hex code string such as '1f4d4' for 📔; raw emoji characters may not render correctly. Custom icon paths are also supported.")}),qu=m({action:y("get_permissions"),notebook:d().optional().describe('Notebook ID, or "all" to return every notebook permission entry. Omit to return all notebooks.')}),Bu=m({action:y("set_permission"),notebook:d().describe("Notebook ID"),permission:z(["none","r","rw","rwd"]).describe('Permission level: "none" blocks all access, "r" allows read only, "rw" allows read and write without delete, "rwd" allows read, write, and delete')}),Lu=m({action:y("get_child_docs"),notebook:d().describe("Notebook ID"),page:E().int().positive().optional().describe("Page number (1-based), default 1"),pageSize:E().int().positive().optional().describe("Rows per page, default 50")}),Uu=m({action:y("create"),notebook:d().describe("Notebook ID"),path:d().optional().describe("Human-readable target path, must start with / (e.g., /foo/bar). Parent paths must already exist."),parentPath:d().optional().describe("Parent human-readable path or storage path ending in .sy for title-based creation, must start with /"),title:d().optional().describe("Document title when creating under parentPath"),markdown:d().optional().describe("Markdown content, defaults to empty. Do not include a leading # Title; a matching H1 is stripped automatically."),sorts:I(d()).optional().describe("Compatibility option retained for older callers; title-based creation now uses the reliable path flow"),icon:d().optional().describe("Optional document icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}).superRefine((e,t)=>{const o=typeof e.path=="string",n=typeof e.parentPath=="string"||typeof e.title=="string";if(o&&n){t.addIssue({code:q.custom,message:"Provide either path, or parentPath + title, not both.",path:["path"]});return}!o&&(!e.parentPath||!e.title)&&t.addIssue({code:q.custom,message:"Provide path, or provide both parentPath and title.",path:["path"]})}),m_=z(["id","ids","path","hpath","docInfo"]),ju=m({action:y("lookup"),id:d().optional().describe("Document ID to look up"),notebook:d().optional().describe("Notebook ID, required with path or hpath"),path:d().optional().describe("Storage path to look up when notebook is provided, e.g. /20240318112233-abc123.sy. Human-readable paths should use hpath instead."),hpath:d().optional().describe("Human-readable path to look up when notebook is provided"),hPath:d().optional().describe("Alias for hpath"),include:I(m_).optional().describe('Fields to include: "id", "ids", "path", "hpath", "docInfo"')}).superRefine((e,t)=>{const o=e.hpath??e.hPath;[e.id,e.path,o].filter(r=>typeof r=="string").length!==1&&t.addIssue({code:q.custom,message:"Provide exactly one source: id, notebook + path, or notebook + hpath.",path:["id"]}),!e.id&&!e.notebook&&t.addIssue({code:q.custom,message:"notebook is required when resolving path or hpath.",path:["notebook"]})}),Hu=m({action:y("rename"),title:d().describe("New document title")}).and(r_),Vu=m({action:y("remove"),ids:I(d()).min(1).optional().describe("One or more document IDs to remove"),paths:I(d()).min(1).optional().describe("One or more storage paths to remove in batch")}).and(vu).superRefine((e,t)=>{if([typeof e.id=="string",typeof e.notebook=="string"||typeof e.path=="string",Array.isArray(e.ids),Array.isArray(e.paths)].filter(Boolean).length!==1){t.addIssue({code:q.custom,message:"Provide exactly one removal mode: id, notebook + path, ids, or paths."});return}(e.notebook||e.path)&&(!e.notebook||!e.path)&&t.addIssue({code:q.custom,message:"Both notebook and path are required for path-based remove."})}),Zu=m({action:y("move")}).and(s_),Yu=m({action:y("get_child_blocks"),id:d().describe("Document ID")}),Wu=m({action:y("get_child_docs"),id:d().describe("Document ID")}),Gu=m({action:y("set_attr"),id:d().describe("Document ID"),attrs:m({icon:d().optional().describe("Icon value. Prefer a Unicode hex code string such as '1f4d4'."),cover:W([d(),fu()]).optional().describe("Cover source. Use null or empty string to clear the cover.")}).describe("Document metadata attributes to set")}).superRefine((e,t)=>{e.attrs.icon===void 0&&e.attrs.cover===void 0&&t.addIssue({code:q.custom,message:"Provide at least one of attrs.icon or attrs.cover.",path:["attrs"]})}),Ku=m({action:y("list_tree"),notebook:d().describe("Notebook ID"),path:d().describe("Storage path or / for the notebook root"),maxDepth:E().optional().describe("Max tree depth to return (default 3). Deeper nodes are collapsed to childCount.")}),Ju=m({action:y("search_docs"),notebook:d().describe("Notebook ID"),query:d().describe("Keyword to search in document titles"),path:d().optional().describe("Optional storage path to narrow the search scope after permission filtering")}),Qu=m({action:y("get_doc"),id:d().describe("Document ID"),mode:z(["markdown","html"]).optional().describe('Return mode: "markdown" (default) or "html"'),size:E().optional().describe("Optional maximum content size hint"),blockStart:E().int().min(0).optional().describe("Zero-based display-block index to start reading from in markdown mode (default 0)"),blockLimit:E().int().min(1).max(200).optional().describe("Maximum complete display blocks to return in markdown mode (default 50)"),tokenBudget:E().int().min(1).max(32e3).optional().describe("Approximate token budget for the markdown window (default 2000). A single oversized block is still returned whole."),includeBlockIds:x().optional().describe("Include a sidecar blockRefs mapping in markdown mode without adding block IDs to content (default false)")}).passthrough().superRefine((e,t)=>{for(const o of["page","pageSize"])e[o]!==void 0&&t.addIssue({code:q.custom,path:[o],message:`${o} character pagination was removed; use blockStart, blockLimit, and tokenBudget.`});if(e.mode==="html")for(const o of["blockStart","blockLimit","tokenBudget","includeBlockIds"])e[o]!==void 0&&t.addIssue({code:q.custom,path:[o],message:`${o} is only supported when mode="markdown".`})}),Xu=m({action:y("create_daily_note"),notebook:d().describe("Notebook ID"),app:d().optional().describe("Optional app identifier passed through to SiYuan")}),ed=m({action:y("duplicate"),id:d().describe("Source document ID")}),td=m({action:y("heading_to_doc"),headingID:d().describe("Heading block ID to convert into a document"),targetNotebook:d().describe("Target notebook ID"),targetPath:d().optional().describe("Optional target storage path"),previousPath:d().optional().describe("Optional previous sibling storage path")}),od=m({action:y("doc_to_heading"),srcID:d().describe("Source document ID"),targetID:d().describe("Target document or heading block ID"),after:x().optional().describe("When true, insert after the target heading instead of before it")}),nd=m({action:y("get_balance")}),rd=m({action:y("shop")}),sd=m({action:y("buy"),item_id:d().describe('Stable shop item ID returned by mascot(action="shop")')}),ad=m({action:y("submit"),description:d().trim().min(1).max(4e3).describe("Required feedback text. Prefer a GitHub Issue-style body for bugs, confusing behavior, or rough workflows, with headings such as ## Summary, ## What happened, ## Expected behavior, ## Steps or context, ## Impact, and ## Suggested fix."),impact:d().trim().max(1e3).optional().describe("Optional one- or two-sentence impact summary, such as affected workflow, error risk, confusion, or inconvenience."),suggestion:d().trim().max(1e3).optional().describe("Optional direct improvement suggestion; keep it focused and avoid repeating the full description."),agent:d().trim().max(200).optional().describe("Optional Agent product and model name, such as Claude Desktop / Claude Sonnet 4.5. Defaults to 无."),source:d().trim().max(100).optional().describe("Internal source label. Defaults to the current runtime transport.")}),g_=z(["all","deck","notebook","tree"]),y_=z(["due","new","old"]),id=m({action:y("list_cards"),scope:g_.describe('Query scope: "all", "deck", "notebook", or "tree"'),filter:y_.describe('Filter returned cards: "due", "new", or "old"'),deckID:d().optional().describe('Deck ID, required when scope=deck. For scope="all", omit deckID; an empty string is treated as omitted.'),notebook:d().optional().describe("Notebook ID, required when scope=notebook"),rootID:d().optional().describe("Root document/block ID, required when scope=tree"),reviewedCards:I(m({cardID:d().describe("Reviewed card ID")}).passthrough()).optional().describe("Optional already-reviewed cards; SiYuan reads reviewedCards[].cardID")}).superRefine((e,t)=>{const o=typeof e.deckID=="string"&&e.deckID.length>0,n=typeof e.notebook=="string",r=typeof e.rootID=="string";e.scope==="all"&&(o||n||r)&&t.addIssue({code:q.custom,message:'scope="all" does not accept deckID, notebook, or rootID.'}),e.scope==="deck"&&!o&&t.addIssue({code:q.custom,path:["deckID"],message:'deckID is required when scope="deck".'}),e.scope==="notebook"&&!n&&t.addIssue({code:q.custom,path:["notebook"],message:'notebook is required when scope="notebook".'}),e.scope==="tree"&&!r&&t.addIssue({code:q.custom,path:["rootID"],message:'rootID is required when scope="tree".'})}),cd=m({action:y("get_decks")}),ld=m({action:y("review_card"),deckID:d().describe("Deck ID"),cardID:d().describe("Card ID"),rating:E().optional().describe("Review rating passed through to the kernel"),skip:x().optional().describe("When true, skip the current card instead of submitting a rating"),reviewedCards:I(m({cardID:d().describe("Reviewed card ID")}).passthrough()).optional().describe("Optional already-reviewed cards; SiYuan reads reviewedCards[].cardID")}).superRefine((e,t)=>{e.skip!==!0&&e.rating===void 0&&t.addIssue({code:q.custom,message:"rating is required unless skip=true.",path:["rating"]})}),ud=m({action:y("create_card"),deckID:d().describe("Deck ID"),blockIDs:I(d()).min(1).describe("Existing block IDs to turn into flashcards"),mode:z(["full","attach"]).optional().describe("Compatibility option. SiYuan addRiffCards writes deck attrs and registers cards in both modes.")}),dd=m({action:y("remove_card"),deckID:d().describe("Deck ID"),blockIDs:I(d()).min(1).describe("Existing block IDs to remove from flashcards")}),pd=m({action:y("get_cards"),deckID:d().describe("Deck ID (use empty string to query across all decks)"),page:E().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:E().int().min(1).max(512).optional().describe("Cards per page, default 32")}),fd=m({action:y("insert"),dataType:z(["markdown","dom"]).optional().describe("Data format"),data:d().optional().describe("Block content"),nextID:d().optional().describe("Next block ID"),previousID:d().optional().describe("Previous block ID"),parentID:d().optional().describe("Parent block or document ID"),blocks:I(m({dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),nextID:d().optional().describe("Next block ID"),previousID:d().optional().describe("Previous block ID"),parentID:d().optional().describe("Parent block or document ID")})).min(1).optional().describe("Blocks to insert. Item-level anchors override top-level parentID/previousID/nextID.")}).superRefine((e,t)=>{if(Array.isArray(e.blocks)){(e.dataType||e.data)&&t.addIssue({code:q.custom,message:"Provide either blocks or single insert data, not both.",path:["blocks"]}),e.blocks.forEach((n,r)=>{n.nextID||n.previousID||n.parentID||e.nextID||e.previousID||e.parentID||t.addIssue({code:q.custom,path:["blocks",r,"previousID"],message:"Provide nextID, previousID, or parentID for each block, or set a top-level parentID/previousID/nextID."})});return}e.dataType||t.addIssue({code:q.custom,message:"dataType is required for single insert.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:q.custom,message:"data is required for single insert.",path:["data"]})}),hd=m({action:y("prepend"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),parentID:d().describe("Parent block or document ID")}),md=m({action:y("append"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),parentID:d().describe("Parent block or document ID")}),gd=m({action:y("update"),dataType:z(["markdown","dom"]).optional().describe("Data format"),data:d().optional().describe("New block content"),id:d().optional().describe("Block ID"),items:I(m({id:d().describe("Block ID"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Replacement block content")})).min(1).optional().describe("Blocks to update")}).superRefine((e,t)=>{if(Array.isArray(e.items)){(e.id||e.dataType||e.data!==void 0)&&t.addIssue({code:q.custom,message:"Provide either items or single update fields, not both.",path:["items"]});return}e.id||t.addIssue({code:q.custom,message:"id is required for single update.",path:["id"]}),e.dataType||t.addIssue({code:q.custom,message:"dataType is required for single update.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:q.custom,message:"data is required for single update.",path:["data"]})}),yd=m({action:y("replace"),id:d().describe("Block ID"),edit:W([Sn,I(Sn).min(1)]).describe("One replacement edit or an array of edits to apply sequentially within the same block kramdown")}),bd=m({action:y("delete"),id:d().describe("Block ID")}),wd=m({action:y("move"),id:d().optional().describe("Single block ID"),ids:I(d()).min(1).optional().describe("Multiple block IDs to move as a group. Pass IDs in the desired final order; the tool calls SiYuan's low-level move API from last to first internally to preserve that order."),previousID:d().optional().describe("Previous block ID"),parentID:d().optional().describe("New parent block ID")}).superRefine((e,t)=>{(e.id&&e.ids||!e.id&&!e.ids)&&t.addIssue({code:q.custom,message:"Provide exactly one of id or ids.",path:["id"]}),!e.previousID&&!e.parentID&&t.addIssue({code:q.custom,message:"Provide previousID, parentID, or both to describe the destination.",path:["previousID"]})}),kd=m({action:y("set_fold_state"),id:d().describe("Foldable block ID"),folded:x().describe("true to fold, false to unfold")}),_d=m({action:y("get_kramdown"),id:d().describe("Block ID or document ID")}),vd=m({action:y("get_children"),id:d().describe("Block ID or document ID"),page:E().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:E().int().min(1).max(200).optional().describe("Items per page, default 50")}),Id=m({action:y("transfer_references"),fromID:d().describe("Source block ID"),toID:d().describe("Target block ID"),refIDs:I(d()).optional().describe("Reference block IDs")}),Sd=m({action:y("set_attrs"),id:d().describe("Block ID"),attrs:j(d(),d()).describe("Block attributes")}),Dd=m({action:y("get_attrs"),id:d().describe("Block ID")}),Ad=m({action:y("info"),id:d().describe("Block ID")}),Td=m({action:y("breadcrumb"),id:d().describe("Block ID"),excludeTypes:I(d()).optional().describe("Optional block types to exclude from the breadcrumb")}),Pd=m({action:y("dom"),id:d().describe("Block ID")}),Ed=m({action:y("recent_updated"),count:E().optional().describe("Maximum number of recent readable blocks to return after permission filtering")}),Cd=m({action:y("word_count"),ids:I(d()).describe("One or more block IDs")}),Rd=m({action:y("add_to_daily_note"),notebook:d().describe("Notebook ID"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),position:z(["append","prepend"]).describe("Where to add content in today's daily note")}),xd=m({action:y("docs_info"),id:d().optional().describe("Single document/block ID"),ids:I(d()).min(1).optional().describe("Document IDs"),refCount:x().optional().describe("When true, include reference counts"),av:x().optional().describe("When true, include AV metadata")}).superRefine((e,t)=>{(e.id&&e.ids||!e.id&&!e.ids)&&t.addIssue({code:q.custom,message:"Provide exactly one of id or ids.",path:["ids"]})}),b_=z(["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"]),w_=m({type:z(["image","file"]).describe("Asset entry type"),content:d().describe("Asset path stored by SiYuan, e.g. assets/foo.png"),name:d().optional().describe("Optional display name")}),Od=m({valueType:b_.describe("Cell value type"),text:d().optional().describe("Text value for valueType=text"),number:E().optional().describe("Number value for valueType=number"),numberFormat:d().optional().describe("Optional number format such as commas, percent, USD, or CNY"),date:W([d(),E()]).optional().describe("Date/time value as ISO text or epoch milliseconds for valueType=date"),endDate:W([d(),E()]).optional().describe("Optional end date as ISO text or epoch milliseconds for ranged dates"),includeTime:x().optional().describe("When false, store the date without a time component"),checked:x().optional().describe("Checkbox state for valueType=checkbox"),option:d().optional().describe("Selected option label for valueType=select"),options:I(d()).optional().describe("Selected option labels for valueType=multi_select"),relationBlockIDs:I(d()).optional().describe("Related block IDs for valueType=relation"),url:d().optional().describe("URL value for valueType=url"),email:d().optional().describe("Email value for valueType=email"),phone:d().optional().describe("Phone value for valueType=phone"),assets:I(w_).optional().describe("Asset entries for valueType=mAsset")}),Nd=Od.superRefine((e,t)=>{const n={text:"text",number:"number",date:"date",checkbox:"checked",select:"option",multi_select:"options",relation:"relationBlockIDs",url:"url",email:"email",phone:"phone",mAsset:"assets"}[e.valueType];e[n]===void 0&&t.addIssue({code:q.custom,message:`${String(n)} is required when valueType="${e.valueType}".`,path:[n]})}),Ii=m({rowID:d().describe("Row item ID"),columnID:d().describe("Column key ID")}).and(Nd),$d=m({action:y("get"),id:d().describe("Attribute view ID"),blockID:d().optional().describe("Optional database block ID for exact context or fallback permission resolution")}),Md=m({action:y("render"),id:d().optional().describe("Attribute view ID for render/get-style operations; use id here, not avID. Omit only with createIfNotExist=true to let MCP generate one"),blockID:d().optional().describe("Optional database block ID; required when creating a new AV"),viewID:d().optional().describe("Optional target view ID"),page:E().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:E().int().optional().describe("Rows per page; use -1 or omit for kernel default"),query:d().optional().describe("Optional row query filter"),groupPaging:j(d(),K()).optional().describe("Optional group paging map passed through to SiYuan"),createIfNotExist:x().optional().describe("Create the default view only when explicitly true; provide blockID when creating a new AV")}),zd=m({action:y("get_attribute_view_keys"),id:d().describe("Attribute view ID")}),Fd=m({action:y("get_attribute_view_filter_sort"),id:d().describe("Attribute view ID"),blockID:d().optional().describe("Database block ID (optional)")}),qd=m({action:y("search"),keyword:d().describe("Keyword to search in attribute view names"),excludes:I(d()).optional().describe("Optional AV IDs to exclude")}),Bd=m({action:y("add_rows"),avID:d().describe("Attribute view ID"),blockIDs:I(d()).optional().describe("Existing block IDs to add as bound rows"),primaryKeyTexts:I(d()).optional().describe("Plain-text primary key values to add as detached rows"),blockID:d().optional().describe("Optional database block ID used to pin a specific database-block view context"),viewID:d().optional().describe("Optional target view ID"),groupID:d().optional().describe("Optional target group ID"),previousID:d().optional().describe("Optional previous row item ID"),ignoreDefaultFill:x().optional().describe("When true, skip view/group default value filling")}),Ld=m({action:y("remove_rows"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),srcIDs:I(d()).min(1).describe("Bound row block/item IDs to remove")}),Ud=m({action:y("add_column"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),keyID:d().optional().describe("Optional new column key ID; MCP generates one when omitted"),keyName:d().describe("New column name"),keyType:z(["text","number","date","select","mSelect","url","email","phone","mAsset","template","created","updated","checkbox","relation","rollup","lineNumber"]).describe("Column type"),keyIcon:d().optional().describe("Optional column icon"),previousKeyID:d().optional().describe("Insert after this existing column key ID")}),jd=m({action:y("remove_column"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),keyID:d().optional().describe("Column key ID"),columnID:d().optional().describe("Alias of keyID"),removeRelationDest:x().optional().describe("Also remove reverse relation metadata when deleting a relation column")}).superRefine((e,t)=>{!e.keyID&&!e.columnID&&t.addIssue({code:q.custom,message:"Provide keyID or columnID.",path:["keyID"]})}),Hd=m({action:y("set_cells"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),cells:I(Ii).min(1).optional().describe("Cell updates"),items:I(Ii).min(1).optional().describe("Alias for cells"),rowID:d().optional().describe("Single-cell row item ID"),columnID:d().optional().describe("Single-cell column key ID")}).and(Od.partial()).superRefine((e,t)=>{const o=e.cells??e.items,n=Array.isArray(o),r=typeof e.rowID=="string"||typeof e.columnID=="string"||typeof e.valueType=="string";if(n&&r){t.addIssue({code:q.custom,message:"Provide either cells/items or single-cell fields, not both.",path:["cells"]});return}if(!n){if(e.rowID||t.addIssue({code:q.custom,message:"rowID is required for single-cell set_cells calls.",path:["rowID"]}),e.columnID||t.addIssue({code:q.custom,message:"columnID is required for single-cell set_cells calls.",path:["columnID"]}),!e.valueType){t.addIssue({code:q.custom,message:"valueType is required for single-cell set_cells calls.",path:["valueType"]});return}const s=Nd.safeParse(e);if(!s.success)for(const a of s.error.issues)t.addIssue({code:q.custom,message:a.message,path:a.path})}}),Vd=m({action:y("duplicate"),avID:d().describe("Source attribute view ID"),blockID:d().optional().describe("Optional source database block ID used as exact context and default insertion target"),previousID:d().optional().describe("Optional block ID to insert the duplicated mirror database block after")}),Zd=m({action:y("get_primary_key_values"),avID:d().describe("Attribute view ID"),keyword:d().optional().describe("Optional keyword filter for primary key values"),page:E().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:E().int().min(1).optional().describe("Rows per page, default all")}),Yd=m({action:y("upload_asset"),assetsDirPath:d().describe("Asset directory path (e.g., /assets/)"),localFilePath:d().describe("Local file path to read and upload into the assets directory"),confirmLargeFile:x().optional().describe("Set to true only after the user explicitly confirms uploading a file larger than the configured safety threshold.")}),Wd=m({action:y("list_templates"),query:d().optional().describe("Optional keyword used by SiYuan's template picker. Omit or pass an empty string to list all templates."),page:E().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:E().int().min(1).max(128).optional().describe("Templates per page, default 20")}),Gd=m({action:y("read_template"),path:d().describe("Template path returned by list_templates, /data/templates/... path, /templates/... static path, or path relative to data/templates"),offset:E().int().min(0).optional().describe("Character offset for partial template source reading, default 0"),limit:E().int().min(1).max(2e4).optional().describe("Maximum characters to return, default 8000")}),Kd=m({action:y("create_template"),path:d().describe("Template path to create under data/templates. Accepts relative paths such as reports/monthly.md."),markdown:d().describe("Full Markdown template source to write."),overwrite:x().optional().describe("When true, replace an existing template at the same path. Defaults to false.")}),Jd=m({action:y("update_template"),path:d().describe("Existing template path returned by list_templates, /data/templates/... path, /templates/... static path, or path relative to data/templates."),markdown:d().describe("Full Markdown template source to replace the existing template with.")}),Qd=m({action:y("delete_template"),path:d().describe("Existing template path returned by list_templates, /data/templates/... path, /templates/... static path, or path relative to data/templates.")}),Xd=m({action:y("save_doc_as_template"),id:d().describe("Document ID to save as a root-level template."),name:d().describe("Root template name. Slashes are not supported; .md suffix is optional."),overwrite:x().optional().describe("When true, replace an existing template with the same root name. Defaults to false.")}),ep=m({action:y("render"),engine:z(["template","sprig"]).describe("Template engine to use"),id:d().optional().describe("Document ID for template context"),path:d().optional().describe("Template file path inside the SiYuan workspace"),template:d().optional().describe("Sprig template content"),preview:x().optional().describe('When engine="template", ask SiYuan to render preview DOM instead of insertion DOM.')}).superRefine((e,t)=>{e.engine==="template"&&(e.id||t.addIssue({code:q.custom,message:'id is required when engine="template".',path:["id"]}),e.path||t.addIssue({code:q.custom,message:'path is required when engine="template".',path:["path"]})),e.engine==="sprig"&&!e.template&&t.addIssue({code:q.custom,message:'template is required when engine="sprig".',path:["template"]})}),tp=m({action:y("export_md"),id:d().describe("Document ID to export")}),op=m({action:y("export_resources"),paths:I(d()).describe("Paths to export"),name:d().optional().describe("Export file name"),outputPath:d().optional().describe("Optional local absolute or relative filesystem path to save the exported ZIP")}),np=m({action:y("list_unused_assets")}),rp=m({action:y("get_doc_assets"),id:d().describe("Document ID"),assetType:z(["all","image"]).optional().describe("Filter asset type: 'all' (default) returns all assets, 'image' returns only image assets.")}),sp=m({action:y("get_image_ocr_text"),path:d().optional().describe("Asset path; omit to receive an empty OCR text payload")}),ap=m({action:y("remove_unused_assets")}),ip=m({action:y("rename_asset"),oldPath:d().describe("Existing asset path"),newName:d().describe("New asset file name")}),cp=m({action:y("delete_asset"),path:d().describe("Asset path to delete")}),lp=m({action:y("extract_doc"),id:d().describe("Document ID to extract"),outputDir:d().optional().describe("Output root directory. Defaults to ~/siyuan-extracted/ (resolved to absolute path).")}),k_=z(Cs),Ws=z(["keyword","query","query_syntax","sql","regex"]),up=z(["relevance","date","updated_desc","updated_asc","created_desc","created_asc","type"]),__=z(["relevance","relevance_desc","relevance_asc","updated_asc","updated_desc"]),dp=m({action:y("fulltext"),query:d().describe("Search query string"),method:E().optional().describe("Search method: 0=keyword (default), 1=query syntax, 2=SQL, 3=regex"),methodName:Ws.optional().describe('Semantic alias for method: "keyword" | "query_syntax" | "sql" | "regex". The short alias "query" also maps to query syntax and overrides method when both are provided.'),types:j(d(),x()).optional().describe('Block type filter. Accepts full names (e.g. {"heading": true}) or shortcodes (e.g. {"h": true, "p": true}). Codes: d=document, h=heading, p=paragraph, l=list, i=listItem, b=blockquote, c=codeBlock, m=mathBlock, t=table, s=superBlock, html=htmlBlock, embed=embedBlock, av=databaseBlock.'),typeShortcodes:I(d()).optional().describe('Alternative shorthand type filter as array: ["h","p"]. Merged with types if both provided.'),paths:I(d()).optional().describe("Restrict search to specific notebook paths"),groupBy:E().optional().describe("0=no grouping (default), 1=group by document"),orderBy:E().optional().describe("Legacy numeric sort order: 0=type, 1=created ASC, 2=created DESC, 3=updated ASC, 4=updated DESC, 5=content ASC, 6=content DESC, 7=relevance (default)"),sortBy:up.optional().describe('Semantic sort alias: "relevance", "date", "updated_desc", "updated_asc", "created_desc", "created_asc", or "type". Overrides orderBy if both provided.'),page:E().optional().describe("Page number (1-based), default 1"),pageSize:E().optional().describe("Results per page, default 32, max 128"),parentId:d().optional().describe("Post-filter results to blocks whose root_id or parent_id matches this ID, scoping search within a document subtree."),hasTags:x().optional().describe("When true, only return blocks that have tags. When false, only return blocks without tags."),stripHtml:x().optional().describe("Legacy toggle. plainContent is now returned by default; set this when you want to emphasize plain-text-safe downstream parsing while keeping highlighted HTML content.")}),pp=m({action:y("query_sql"),stmt:d().optional().describe("SQL SELECT statement to execute against the blocks/spans/assets tables; returned rows are permission-filtered"),sql:d().optional().describe("Semantic alias for stmt. Overrides stmt when both are provided.")}).superRefine((e,t)=>{!e.stmt&&!e.sql&&t.addIssue({code:q.custom,message:"Provide stmt or sql.",path:["stmt"]})}),fp=m({action:y("get_backlinks"),id:d().describe("Block or document ID to find backlinks for"),keyword:d().optional().describe("Filter backlinks by keyword"),refTreeID:d().optional().describe("Optional document tree ID to narrow backlink scope"),scopeRootId:d().optional().describe("Semantic alias for refTreeID. Overrides refTreeID when both are provided."),mode:z(["links","mentions","both"]).optional().describe('Result mode: "links", "mentions", or "both" (default).')}),hp=m({action:y("search_refs"),id:d().describe("Referenced block or document ID"),rootID:d().optional().describe("Optional current root document ID"),k:d().optional().describe("Keyword filter"),beforeLen:E().int().min(0).optional().describe("Context length before the reference, default 512"),isSquareBrackets:x().optional().describe("Search in square-bracket reference mode"),isDatabase:x().optional().describe("Whether the reference target is a database"),reqId:d().optional().describe("Optional passthrough request ID")}),mp=m({action:y("find_replace"),k:d().describe("Find keyword"),r:d().describe("Replacement text; use empty string to delete matches"),ids:I(d()).min(1).describe("Document or block IDs to mutate"),paths:I(d()).optional().describe("Optional path scope list"),types:j(d(),x()).optional().describe("Optional block type filter"),method:E().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Ws.optional().describe('Semantic alias for method: "keyword" | "query_syntax" | "sql" | "regex". The short alias "query" also maps to query syntax and overrides method when both are provided.'),orderBy:E().optional().describe("Legacy numeric sort order"),sortBy:up.optional().describe("Semantic sort alias that overrides orderBy when both are provided."),groupBy:E().optional().describe("Grouping mode"),replaceTypes:j(d(),x()).optional().describe("Replace target kinds such as text, code, docTitle, blockRef")}),gp=m({action:y("search_assets"),k:d().optional().describe("Legacy asset filename keyword field"),query:d().optional().describe("Semantic alias for k. Overrides k when both are provided."),exts:I(d()).optional().describe("Optional extension filters")}).superRefine((e,t)=>{!e.k&&!e.query&&t.addIssue({code:q.custom,message:"Provide k or query.",path:["k"]})}),yp=m({action:y("fulltext_asset_content"),query:d().optional().describe("Search query string"),assetId:d().optional().describe("Asset content ID for an exact content lookup"),queryMethod:E().optional().describe("Query method for assetId lookup: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),types:j(d(),x()).optional().describe("Asset type filter"),method:E().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Ws.optional().describe('Semantic alias for method: "keyword" | "query_syntax" | "sql" | "regex". The short alias "query" also maps to query syntax and overrides method when both are provided.'),orderBy:E().optional().describe("Legacy numeric sort order: 0=relevance DESC, 1=relevance ASC, 2=updated ASC, 3=updated DESC"),sortBy:__.optional().describe('Semantic sort alias: "relevance_desc", "relevance_asc", "updated_asc", or "updated_desc". The shorthand "relevance" maps to relevance_desc. Overrides orderBy if both are provided.'),page:E().int().min(1).optional().describe("Page number (1-based)"),pageSize:E().int().min(1).max(128).optional().describe("Results per page")}).superRefine((e,t)=>{!e.query&&!e.assetId&&t.addIssue({code:q.custom,message:"Provide query or assetId.",path:["query"]})}),bp=m({action:y("list_invalid_refs"),page:E().int().min(1).optional().describe("Page number (1-based)"),pageSize:E().int().min(1).max(128).optional().describe("Results per page")}),v_=z(Rs),wp=m({action:y("list"),keyword:d().optional().describe("Optional keyword used to search/filter tags"),query:d().optional().describe("Alias for keyword"),sort:E().optional().describe("Optional tag sort mode"),ignoreMaxListHint:x().optional().describe("Ignore the maximum list hint from SiYuan"),app:d().optional().describe("Optional app identifier passed through to SiYuan")}),kp=m({action:y("rename"),oldLabel:d().describe("Existing tag label"),newLabel:d().describe("New tag label")}),_p=m({action:y("remove"),label:d().describe("Tag label to remove")}),I_=z(xs),vp=m({action:y("workspace_info")}),Ip=m({action:y("network")}),Sp=m({action:y("conf"),mode:z(["summary","get"]).optional().describe('Read mode: "summary" returns a navigable overview, "get" reads a specific key path'),keyPath:d().optional().describe('Dot/bracket path to a specific config field, e.g. "conf.appearance.mode" or "conf.langs[0]"'),maxDepth:E().int().min(0).max(5).optional().describe("Maximum object traversal depth for summary/get responses"),maxItems:E().int().min(1).max(100).optional().describe("Maximum keys/items to include per level")}),Dp=m({action:y("notify"),msg:d().describe("Message content"),level:z(["info","error"]).describe("Notification level"),timeout:E().optional().describe("Display timeout in milliseconds")}),Ap=m({action:y("changelog"),version:d().optional().describe("Exact plugin version to read, e.g. 0.4.11 or v0.4.11"),fromVersion:d().optional().describe("Previous plugin version; returns entries newer than this version"),limit:E().int().min(1).max(50).optional().describe("Maximum number of entries to return when version is omitted"),includeRaw:x().optional().describe("Include raw Markdown for each returned changelog entry")}),Tp=m({action:y("perform_sync")}),Pp=m({action:y("get_version")}),Ep=m({action:y("get_current_time")}),wt={type:"string"},S_={type:"boolean"},Si={type:"integer"};function D_(e,t){return typeof t.action=="string"?ro(e,t.action):void 0}function me(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Bo(e){return typeof e=="string"&&e.length>0}function A_(e,t){return t.some(o=>me(e,o))}function T_(e,t){if(t.action!=="help"||typeof t.topic!="string")return;const o=t.topic.trim();if(!o||o==="overview"){t.topic=o;return}t.topic=ro(e,o)}function P_(e){if(me(e,"edit")&&A_(e,["old","new","replace_all","replaceAll"]))throw new Error("fs.replace accepts either edit or old/new shorthand, not both.");if(!me(e,"edit")&&(me(e,"old")||me(e,"new"))){if(!Bo(e.old))throw new Error("fs.replace shorthand requires a non-empty old value.");if(!me(e,"new"))throw new Error("fs.replace shorthand requires new.");e.edit={old:e.old,new:String(e.new??""),...typeof e.replace_all=="boolean"||typeof e.replaceAll=="boolean"?{replace_all:!!(e.replace_all??e.replaceAll)}:{}}}delete e.old,delete e.new,delete e.replace_all,delete e.replaceAll}function E_(e){!me(e,"id")&&Bo(e.avID)&&(e.id=e.avID),delete e.avID}function C_(e){!me(e,"ids")&&Bo(e.id)&&(e.ids=[e.id]),delete e.id}function R_(e){!me(e,"blockIDs")&&Bo(e.blockID)&&(e.blockIDs=[e.blockID]),delete e.blockID}function x_(e){!(me(e,"file")&&me(e,"fileName")&&!me(e,"localFilePath"))&&!me(e,"localFilePath")&&Bo(e.file)&&(e.localFilePath=e.file,delete e.file),me(e,"assetsDirPath")||(e.assetsDirPath="/assets/")}function O_(e){me(e,"k")||(typeof e.keyword=="string"?e.k=e.keyword:typeof e.query=="string"&&(e.k=e.query)),delete e.keyword,delete e.query}function N_(e,t){const o={...t},n=D_(e,o);return n&&(o.action=n),T_(e,o),e==="fs"&&n==="replace"&&P_(o),e==="av"&&n==="render"&&E_(o),e==="block"&&n==="word_count"&&C_(o),e==="flashcard"&&(n==="create_card"||n==="remove_card")&&R_(o),e==="file"&&n==="upload_asset"&&x_(o),e==="search"&&n==="search_refs"&&O_(o),o}function $_(e){if(!(e!=null&&e.category)||!e.action)return[];const t=ro(e.category,e.action);return e.category==="fs"&&t==="read"||e.category==="document"&&t==="get_doc"?[{canonical:"page",aliases:["page"],schema:Si},{canonical:"pageSize",aliases:["page-size","page_size","pageSize"],schema:Si}]:e.category==="fs"&&t==="replace"?[{canonical:"old",aliases:["old"],schema:wt},{canonical:"new",aliases:["new"],schema:wt},{canonical:"replace_all",aliases:["replace-all","replace_all","replaceAll"],schema:S_}]:e.category==="av"&&t==="render"?[{canonical:"id",aliases:["avID","av-id","av_id"],schema:wt}]:e.category==="block"&&t==="word_count"?[{canonical:"ids",aliases:["id"],schema:{type:"array",items:wt}}]:e.category==="flashcard"&&(t==="create_card"||t==="remove_card")?[{canonical:"blockIDs",aliases:["blockID","block-id","block_id"],schema:{type:"array",items:wt}}]:e.category==="file"&&t==="upload_asset"?[{canonical:"localFilePath",aliases:["file"],schema:wt}]:[]}const M_=[{code:"block_not_found",patterns:[/未找到 ID 为 \[[^\]]+\] 的内容块/,/SiYuan API error:\s*-1\b.*(block|id)/i,/block not found/i],hint:'Verify the block ID with block(action="info", id="...") or locate it via search(action="fulltext", query="...").'},{code:"notebook_not_found",patterns:[/notebook .*not found/i,/笔记本不存在/,/not found in lsNotebooks/i],hint:'List available notebooks via notebook(action="list") and retry with a valid notebook ID.'},{code:"notebook_closed",patterns:[/notebook is currently closed/i,/kernel still initializing/i,/closed_or_initializing/i,/笔记本已关闭/],hint:'Re-open the notebook via notebook(action="set_open_state", opened=true) or retry after a short wait.'},{code:"document_not_found",patterns:[/document .*not found/i,/文档不存在/],hint:'Resolve the document via document(action="lookup") or search(action="search_docs").'},{code:"av_not_found",patterns:[/attribute view .*not found/i,/数据库不存在/,/av .*not found/i],hint:'Locate the attribute view via av(action="search", keyword="...") or av(action="list").'},{code:"permission_denied",patterns:[/permission denied/i,/权限被拒绝/,/no .*permission/i],hint:'Inspect current permissions with notebook(action="get_permissions") and adjust via notebook(action="set_permission").'},{code:"kernel_unreachable",patterns:[/HTTP error:/i,/Request timeout/i,/ECONNREFUSED/i,/fetch failed/i],hint:"MCP server is running but the SiYuan kernel is unreachable. Prompt the user to start SiYuan. Do not explore source files to debug this."}];function Gs(e){const t=e.message??"";for(const o of M_)if(o.patterns.some(n=>n.test(t)))return{code:o.code,hint:o.hint};return null}function Ks(e){var t;return e instanceof Error?((t=Gs(e))==null?void 0:t.code)==="block_not_found":!1}function z_(e){return typeof e.description=="string"?e.description:null}function ao(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Un(e){return Array.isArray(e.required)?e.required.filter(t=>typeof t=="string"):[]}function F_(e,t={}){const o={},n=new Map,r=new Map,s=new Map,a=new Map;for(const i of e){const c=new Set(Un(i.schema));for(const[l,u]of Object.entries(ao(i.schema))){if(l==="action"||!u||typeof u!="object")continue;o[l]=q_(o[l],u);const p=z_(u);if(p){const b=n.get(l)??new Set;b.add(p),n.set(l,b)}const f=u.enum;if(Array.isArray(f)){const b=r.get(l)??new Set;for(const _ of f)b.add(_);r.set(l,b)}const h=c.has(l)?s:a,g=h.get(l)??new Set;g.add(i.action),h.set(l,g)}}for(const[i,c]of Object.entries(o)){const l=n.get(i),u=t[i]??(l&&l.size>0?[...l].join(" / "):void 0),p=[...s.get(i)??[]].sort(),f=[...a.get(i)??[]].sort(),h=[...p.length>0?[`Required by: ${p.join(", ")}`]:[],...f.length>0?[`Optional in: ${f.join(", ")}`]:[]],g=h.length>0?`[${h.join("; ")}]`:"";c.description=u?g?`${u} ${g}`:u:g||void 0;const b=r.get(i);b&&b.size>0&&(c.enum=[...b])}return o}function q_(e,t){if(!e)return{...t};const o={...e,...t};return Di(o,e,t,"minimum"),Di(o,e,t,"exclusiveMinimum"),Ai(o,e,t,"maximum"),Ai(o,e,t,"exclusiveMaximum"),o}function Di(e,t,o,n){const r=t[n],s=o[n];typeof r=="number"&&typeof s=="number"?e[n]=Math.min(r,s):delete e[n]}function Ai(e,t,o,n){const r=t[n],s=o[n];typeof r=="number"&&typeof s=="number"?e[n]=Math.max(r,s):delete e[n]}function je(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};if(t.type==="array"&&(t.items=je(t.items&&typeof t.items=="object"?t.items:{type:"string"})),t.properties&&typeof t.properties=="object"&&!Array.isArray(t.properties)&&(t.properties=Object.fromEntries(Object.entries(t.properties).map(([o,n])=>[o,je(n)]))),t.propertyNames&&typeof t.propertyNames=="object"&&!Array.isArray(t.propertyNames)){const o=t.propertyNames;o.type==="string"&&Object.keys(o).length===1?delete t.propertyNames:t.propertyNames=je(o)}return t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=je(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(o=>je(o))),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(o=>je(o))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(o=>je(o))),t}function Js(e){return je(e)}function Cp(e){return Un(e).filter(t=>t!=="action")}function Ro(e,t){const o=new Set(Cp(e));return Object.entries(ao(e)).flatMap(([n,r])=>n==="action"||!r||typeof r!="object"||Array.isArray(r)?[]:t===!0&&!o.has(n)?[]:t===!1&&o.has(n)?[]:[n])}function Or(e,t){const o=typeof t.description=="string"?t.description:"",n=Array.isArray(t.enum)?t.enum:[];if(n.length>0)return n[0];switch(e){case"notebook":return"20210808180117-czj9bvb";case"deckID":return"20230218211946-2kw8jgx";case"cardID":return"20240318112233-card01";case"rootID":return"20240318112233-root01";case"id":case"parentID":case"previousID":case"nextID":case"fromID":case"toID":return"20240318112233-abc123";case"fromIDs":return["20240318112233-a","20240318112233-b"];case"fromPaths":return["/20240318112233-a.sy","/20240318112233-b.sy"];case"toNotebook":return"20210808180117-czj9bvb";case"toPath":return"/20240318112233-existing-parent.sy";case"path":return o.includes("Human-readable")?"/Inbox/Weekly Note":"/20240318112233-abc123.sy";case"paths":return["/assets/example.png"];case"title":return"Weekly Notes";case"name":return o.includes("Export file name")?"assets-export.zip":"Research";case"markdown":return"- Seed item";case"dataType":return"markdown";case"data":return"- New item";case"template":return'codex-{{ now | date "2006" }}';case"msg":return"Hello from MCP";case"timeout":return 3e3;case"rating":return 3;case"reviewedCards":return[{cardID:"20240318112233-card01",rating:3}];case"assetsDirPath":return"/assets/";case"file":return"SGVsbG8sIFNpWXVhbg==";case"fileName":return"hello.txt";case"attrs":return{"custom-mcp":"demo"};case"conf":return{closed:!1};case"permission":return"none";case"query":return"search keyword";case"stmt":return"SELECT * FROM blocks WHERE content LIKE '%keyword%' LIMIT 20";case"k":return"todo";case"keyword":return"filter text"}if(t.type==="array"){const r=t.items&&typeof t.items=="object"?t.items:{type:"string"};return[Or(`${e}Item`,r)]}if(t.type==="object"){const r=ao(t),s=Object.keys(r)[0];return s?{[s]:Or(s,r[s])}:{}}return t.type==="number"?1:t.type==="boolean"?!1:`<${e}>`}function B_(e,t){return e.filter(n=>n.action===t).map(n=>{const r=ao(n.schema),s={action:t};for(const a of Cp(n.schema))s[a]=Or(a,r[a]??{});return s})}function L_(e,t){var o;return((o=wg[e])==null?void 0:o[t])??[]}function U_(e){return e.length>0?e.join(", "):"no additional fields"}function j_(e){const t=new Map;for(const o of e){const n=U_(Ro(o.schema,!0)),r=t.get(o.action)??[];r.includes(n)||r.push(n),t.set(o.action,r)}return[...t.entries()].map(([o,n])=>`${o}: ${n.join(" | ")}`).join("; ")}function H_(e,t){const o=new Set;return t.flatMap(n=>{if(o.has(n.action))return[];o.add(n.action);const r=Ro(n.schema,!0),s=Ro(n.schema,!1);return[`${e}.${n.action}: required ${r.length>0?`[${r.join(", ")}]`:"[]"} | optional ${s.length>0?`[${s.join(", ")}]`:"[]"}`]}).join(`
465
- `)}function V_(e,t,o){var c;const n={basic:[],advanced:[]};for(const l of t)n[Do(e,l)].push(l);const r={},s={},a=new Set;for(const l of o){if(a.has(l.action))continue;a.add(l.action);const u=(c=Po[e])==null?void 0:c[l.action],p=Ro(l.schema,!0);r[l.action]=u??(p.length>0?`requires: ${p.join(", ")}`:"no extra fields"),s[l.action]={...u?{hint:u}:{},requiresConfirmation:Bt(e,l.action)}}const i=t.filter(l=>Bt(e,l));return{tool:e,commonActions:n.basic,advancedActions:n.advanced,guidance:hl[e]??[],actions:s,actionSummaries:r,...i.length>0?{requiresConfirmation:i}:{},detailsHint:`Call ${e}(action="help", topic="<actionName>") for required fields, shapes, and a minimal example.`,helpResources:[`siyuan://help/action/${e}/{action}`,"siyuan://help/tool-overview","siyuan://help/examples","siyuan://help/ai-layout-guide"]}}function Z_(e,t,o){var c;const n=o.filter(l=>l.action===t),r=n.map(l=>Ro(l.schema,!0)),s=B_(n,t),a=L_(e,t),i=s.length===1?s[0]:s;return{tool:e,action:t,...(c=Po[e])!=null&&c[t]?{hint:Po[e][t]}:{},shapes:r.map(l=>l.length>0?l.join(" + "):"action only"),requiredFields:r.length===1?r[0]:r,example:i,...a.length>0?{examples:a}:{},guidance:hl[e]??[],requiresConfirmation:Bt(e,t),fullDocResource:`siyuan://help/action/${e}/${t}`}}const Y_="x-sisyphus-actionSchemas";function S(e,t,o){const n=ct(Lw(t));return delete n.$schema,o&&!n.description&&(n.description=o),{action:e,schema:Js(n)}}function ct(e){const t={...e};if(t.properties&&typeof t.properties=="object"&&!Array.isArray(t.properties)&&(t.properties=Object.fromEntries(Object.entries(t.properties).map(([i,c])=>[i,c&&typeof c=="object"&&!Array.isArray(c)?ct(c):c]))),t.items&&typeof t.items=="object"&&!Array.isArray(t.items)&&(t.items=ct(t.items)),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=ct(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?ct(i):i)),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?ct(i):i)),!Array.isArray(t.allOf))return t;const o={},n=new Set,r=[];for(const i of t.allOf){if(!i||typeof i!="object"||Array.isArray(i))return e;const c=ct(i);if(c.type!=="object")return e;Object.assign(o,ao(c));for(const l of Un(c))n.add(l);r.push(c)}const{allOf:s,...a}=t;return{...a,type:"object",properties:o,required:[...n],additionalProperties:r.every(i=>i.additionalProperties===!1)?!1:t.additionalProperties}}function W_(e){const t={action:{type:"string",const:e.action,description:"Action to perform"},...ao(e.schema)};return Js({...e.schema,type:"object",additionalProperties:!1,properties:t,required:Array.from(new Set(["action",...Un(e.schema)]))})}function G_(e){const t={...e};return delete t.const,delete t.required,t}function K_(e){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,o&&typeof o=="object"&&!Array.isArray(o)?G_(o):{}]))}function J_(e){return{type:"object",additionalProperties:!1,properties:{action:{type:"string",const:"help",description:"Show help for this tool or one action."},topic:{type:"string",enum:["overview",...e],description:'Optional action name to inspect; omit or use "overview" for the action index.'}},required:["action"]}}function Q_(e,t,o){const n=[],r=o.guidanceInlineLimit??2,s=o.guidance??[];n.push(...s.slice(0,r));const a=t.filter(i=>Bt(e,i));return a.length>0&&n.push(`Requires user confirmation before: ${a.join(", ")}.`),n}function Rp(e){return e.map(t=>typeof t=="number"?`[${t}]`:String(t)).join(".").replace(/\.\[/g,"[")}function X_(e,t){let o=e;for(const n of t){if(o==null)return;if(typeof n=="number"){if(!Array.isArray(o))return;o=o[n];continue}if(typeof o!="object")return;o=o[String(n)]}return o}function ev(e,t){const o=Rp(e.path),n=o?X_(t,e.path):void 0;return e.code==="invalid_type"?n===void 0&&o?`${o} is required.`:o?`${o} has an invalid type.`:"Invalid input type.":e.code==="unrecognized_keys"&&"keys"in e&&Array.isArray(e.keys)?`Unexpected field(s): ${e.keys.join(", ")}.`:e.message&&e.message!=="Invalid input"?e.message:o?`Invalid value for ${o}.`:"Invalid input."}function tv(e,t){return e.issues.map(o=>({path:Rp(o.path),message:ev(o,t)}))}function ov(e,t){return e&&t?`Invalid arguments for ${e}(action="${t}").`:e?`Invalid arguments for tool "${e}".`:"Invalid arguments."}function dr(e){return(e==null?void 0:e.hint)??kg(e==null?void 0:e.tool,e==null?void 0:e.action)}function jt(e,t=!0){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:t}}function nv(e){return e.name==="SiYuanError"||e.message.startsWith("SiYuan API error:")||e.message.startsWith("HTTP error:")||e.message.startsWith("Request timeout")}function rv(){return process.env.SIYUAN_MCP_DEBUG_ERRORS==="1"}function sv(e,t,o,n,r){const s=o.filter(f=>Do(e,f)==="basic"),a=o.filter(f=>Do(e,f)==="advanced"),i=n.filter(f=>s.includes(f.action)),c=j_(i),l=[`${t} Use the "action" field to select the operation.`];s.length>0&&l.push(`Common actions: ${s.join(", ")}. Required fields: ${c}.`),a.length>0&&l.push(`Additional actions: ${a.join(", ")}. Read siyuan://help/action/${e}/{action} for details, or call action="help" if resources are unavailable.`);const u=H_(e,n);u.length>0&&l.push(`Parameter contract per action (fields outside the action's optional list should not be sent):
466
- ${u}`);const p=Q_(e,o,r);return p.length>0&&l.push(p.join(" ")),l.join(`
470
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const p=u[1];if(t===u[0]){s(u);continue}if(e.external){const h=(c=e.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&h){s(u);continue}}if((l=e.metadataRegistry.get(u[0]))==null?void 0:l.id){s(u);continue}if(p.cycle){s(u);continue}if(p.count>1&&e.reused==="ref"){s(u);continue}}}function An(e,t){var a,i,c;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=l=>{const u=e.seen.get(l);if(u.ref===null)return;const p=u.def??u.schema,f={...p},h=u.ref;if(u.ref=null,h){n(h);const b=e.seen.get(h),_=b.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(_)):Object.assign(p,_),Object.assign(p,f),l._zod.parent===h)for(const P in p)P==="$ref"||P==="allOf"||P in f||delete p[P];if(_.$ref&&b.def)for(const P in p)P==="$ref"||P==="allOf"||P in b.def&&JSON.stringify(p[P])===JSON.stringify(b.def[P])&&delete p[P]}const g=l._zod.parent;if(g&&g!==h){n(g);const b=e.seen.get(g);if(b!=null&&b.schema.$ref&&(p.$ref=b.schema.$ref,b.def))for(const _ in p)_==="$ref"||_==="allOf"||_ in b.def&&JSON.stringify(p[_])===JSON.stringify(b.def[_])&&delete p[_]}e.override({zodSchema:l,jsonSchema:p,path:u.path??[]})};for(const l of[...e.seen.entries()].reverse())n(l[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,(a=e.external)!=null&&a.uri){const l=(i=e.external.registry.get(t))==null?void 0:i.id;if(!l)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(l)}Object.assign(r,o.def??o.schema);const s=((c=e.external)==null?void 0:c.defs)??{};for(const l of e.seen.entries()){const u=l[1];u.def&&u.defId&&(s[u.defId]=u.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const l=JSON.parse(JSON.stringify(r));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Pn(t,"input",e.processors),output:Pn(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function he(e,t){const o=t??{seen:new Set};if(o.seen.has(e))return!1;o.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return he(n.element,o);if(n.type==="set")return he(n.valueType,o);if(n.type==="lazy")return he(n.getter(),o);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return he(n.innerType,o);if(n.type==="intersection")return he(n.left,o)||he(n.right,o);if(n.type==="record"||n.type==="map")return he(n.keyType,o)||he(n.valueType,o);if(n.type==="pipe")return he(n.in,o)||he(n.out,o);if(n.type==="object"){for(const r in n.shape)if(he(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(he(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(he(r,o))return!0;return!!(n.rest&&he(n.rest,o))}return!1}const Aw=(e,t={})=>o=>{const n=Dn({...o,processors:t});return G(e,n),Tn(n,e),An(n,e)},Pn=(e,t,o={})=>n=>{const{libraryOptions:r,target:s}=n??{},a=Dn({...r??{},target:s,io:t,processors:o});return G(e,a),Tn(a,e),An(a,e)},Pw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ul=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:s,maximum:a,format:i,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof a=="number"&&(r.maxLength=a),i&&(r.format=Pw[i]??i,r.format===""&&delete r.format,i==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const u=[...c];u.length===1?r.pattern=u[0].source:u.length>1&&(r.allOf=[...u.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},jl=(e,t,o,n)=>{const r=o,{minimum:s,maximum:a,format:i,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof i=="string"&&i.includes("int")?r.type="integer":r.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u),typeof s=="number"&&(r.minimum=s,typeof u=="number"&&t.target!=="draft-04"&&(u>=s?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof a=="number"&&(r.maximum=a,typeof l=="number"&&t.target!=="draft-04"&&(l<=a?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},Hl=(e,t,o,n)=>{o.type="boolean"},Cw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Ew=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Vl=(e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},Rw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},xw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Zl=(e,t,o,n)=>{o.not={}},Yl=(e,t,o,n)=>{},Wl=(e,t,o,n)=>{},Ow=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Gl=(e,t,o,n)=>{const r=e._zod.def,s=wl(r.entries);s.every(a=>typeof a=="number")&&(o.type="number"),s.every(a=>typeof a=="string")&&(o.type="string"),o.enum=s},Kl=(e,t,o,n)=>{const r=e._zod.def,s=[];for(const a of r.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(a))}else s.push(a);if(s.length!==0)if(s.length===1){const a=s[0];o.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?o.enum=[a]:o.const=a}else s.every(a=>typeof a=="number")&&(o.type="number"),s.every(a=>typeof a=="string")&&(o.type="string"),s.every(a=>typeof a=="boolean")&&(o.type="boolean"),s.every(a=>a===null)&&(o.type="null"),o.enum=s},Nw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},$w=(e,t,o,n)=>{const r=o,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=s.source},Mw=(e,t,o,n)=>{const r=o,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:i,mime:c}=e._zod.bag;a!==void 0&&(s.minLength=a),i!==void 0&&(s.maxLength=i),c?c.length===1?(s.contentMediaType=c[0],Object.assign(r,s)):(Object.assign(r,s),r.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(r,s)},zw=(e,t,o,n)=>{o.type="boolean"},Jl=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Fw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Ql=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},qw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Lw=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Xl=(e,t,o,n)=>{const r=o,s=e._zod.def,{minimum:a,maximum:i}=e._zod.bag;typeof a=="number"&&(r.minItems=a),typeof i=="number"&&(r.maxItems=i),r.type="array",r.items=G(s.element,t,{...n,path:[...n.path,"items"]})},eu=(e,t,o,n)=>{var l;const r=o,s=e._zod.def;r.type="object",r.properties={};const a=s.shape;for(const u in a)r.properties[u]=G(a[u],t,{...n,path:[...n.path,"properties",u]});const i=new Set(Object.keys(a)),c=new Set([...i].filter(u=>{const p=s.shape[u]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));c.size>0&&(r.required=Array.from(c)),((l=s.catchall)==null?void 0:l._zod.def.type)==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=G(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},tu=(e,t,o,n)=>{const r=e._zod.def,s=r.inclusive===!1,a=r.options.map((i,c)=>G(i,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?o.oneOf=a:o.anyOf=a},ou=(e,t,o,n)=>{const r=e._zod.def,s=G(r.left,t,{...n,path:[...n.path,"allOf",0]}),a=G(r.right,t,{...n,path:[...n.path,"allOf",1]}),i=l=>"allOf"in l&&Object.keys(l).length===1,c=[...i(s)?s.allOf:[s],...i(a)?a.allOf:[a]];o.allOf=c},Bw=(e,t,o,n)=>{const r=o,s=e._zod.def;r.type="array";const a=t.target==="draft-2020-12"?"prefixItems":"items",i=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((f,h)=>G(f,t,{...n,path:[...n.path,a,h]})),l=s.rest?G(s.rest,t,{...n,path:[...n.path,i,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=c,l&&(r.items=l)):t.target==="openapi-3.0"?(r.items={anyOf:c},l&&r.items.anyOf.push(l),r.minItems=c.length,l||(r.maxItems=c.length)):(r.items=c,l&&(r.additionalItems=l));const{minimum:u,maximum:p}=e._zod.bag;typeof u=="number"&&(r.minItems=u),typeof p=="number"&&(r.maxItems=p)},nu=(e,t,o,n)=>{const r=o,s=e._zod.def;r.type="object";const a=s.keyType,i=a._zod.bag,c=i==null?void 0:i.patterns;if(s.mode==="loose"&&c&&c.size>0){const u=G(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const p of c)r.patternProperties[p.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=G(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=G(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const l=a._zod.values;if(l){const u=[...l].filter(p=>typeof p=="string"||typeof p=="number");u.length>0&&(r.required=u)}},ru=(e,t,o,n)=>{const r=e._zod.def,s=G(r.innerType,t,n),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=r.innerType,o.nullable=!0):o.anyOf=[s,{type:"null"}]},su=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},au=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},iu=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,t.io==="input"&&(o._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},cu=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}o.default=a},lu=(e,t,o,n)=>{const r=e._zod.def,s=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;G(s,t,n);const a=t.seen.get(e);a.ref=s},uu=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.readOnly=!0},Uw=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Ys=(e,t,o,n)=>{const r=e._zod.def;G(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},jw=(e,t,o,n)=>{const r=e._zod.innerType;G(r,t,n);const s=t.seen.get(e);s.ref=r},_i={string:Ul,number:jl,boolean:Hl,bigint:Cw,symbol:Ew,null:Vl,undefined:Rw,void:xw,never:Zl,any:Yl,unknown:Wl,date:Ow,enum:Gl,literal:Kl,nan:Nw,template_literal:$w,file:Mw,success:zw,custom:Jl,function:Fw,transform:Ql,map:qw,set:Lw,array:Xl,object:eu,union:tu,intersection:ou,tuple:Bw,record:nu,nullable:ru,nonoptional:su,default:au,prefault:iu,catch:cu,pipe:lu,readonly:uu,promise:Uw,optional:Ys,lazy:jw};function Hw(e,t){if("_idmap"in e){const n=e,r=Dn({...t,processors:_i}),s={};for(const c of n._idmap.entries()){const[l,u]=c;G(u,r)}const a={},i={registry:n,uri:t==null?void 0:t.uri,defs:s};r.external=i;for(const c of n._idmap.entries()){const[l,u]=c;Tn(r,u),a[l]=An(r,u)}if(Object.keys(s).length>0){const c=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:s}}return{schemas:a}}const o=Dn({...t,processors:_i});return G(e,o),Tn(o,e),An(o,e)}const Vw=v("ZodISODateTime",(e,t)=>{Zy.init(e,t),oe.init(e,t)});function du(e){return Xb(Vw,e)}const Zw=v("ZodISODate",(e,t)=>{Yy.init(e,t),oe.init(e,t)});function Yw(e){return ew(Zw,e)}const Ww=v("ZodISOTime",(e,t)=>{Wy.init(e,t),oe.init(e,t)});function Gw(e){return tw(Ww,e)}const Kw=v("ZodISODuration",(e,t)=>{Gy.init(e,t),oe.init(e,t)});function Jw(e){return ow(Kw,e)}const pu=(e,t)=>{Il.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>qg(e,o)},flatten:{value:o=>Fg(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,Or,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,Or,2)}},isEmpty:{get(){return e.issues.length===0}}})},Qw=v("ZodError",pu),Se=v("ZodError",pu,{Parent:Error}),Xw=Hs(Se),ek=Vs(Se),tk=Hn(Se),ok=Vn(Se),nk=Bg(Se),rk=Ug(Se),sk=jg(Se),ak=Hg(Se),ik=Vg(Se),ck=Zg(Se),lk=Yg(Se),uk=Wg(Se),Q=v("ZodType",(e,t)=>(J.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Pn(e,"input"),output:Pn(e,"output")}}),e.toJSONSchema=Aw(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...o)=>e.clone(nt(t,{checks:[...t.checks??[],...o.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(o,n)=>rt(e,o,n),e.brand=()=>e,e.register=(o,n)=>(o.add(e,n),e),e.parse=(o,n)=>Xw(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>tk(e,o,n),e.parseAsync=async(o,n)=>ek(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>ok(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>nk(e,o,n),e.decode=(o,n)=>rk(e,o,n),e.encodeAsync=async(o,n)=>sk(e,o,n),e.decodeAsync=async(o,n)=>ak(e,o,n),e.safeEncode=(o,n)=>ik(e,o,n),e.safeDecode=(o,n)=>ck(e,o,n),e.safeEncodeAsync=async(o,n)=>lk(e,o,n),e.safeDecodeAsync=async(o,n)=>uk(e,o,n),e.refine=(o,n)=>e.check(n_(o,n)),e.superRefine=o=>e.check(r_(o)),e.overwrite=o=>e.check(ao(o)),e.optional=()=>te(e),e.exactOptional=()=>Hk(e),e.nullable=()=>Si(e),e.nullish=()=>te(Si(e)),e.nonoptional=o=>Kk(e,o),e.array=()=>I(e),e.or=o=>W([e,o]),e.and=o=>Gs(e,o),e.transform=o=>Mr(e,wu(o)),e.default=o=>Yk(e,o),e.prefault=o=>Gk(e,o),e.catch=o=>Qk(e,o),e.pipe=o=>Mr(e,o),e.readonly=()=>t_(e),e.describe=o=>{const n=e.clone();return ho.add(n,{description:o}),n},Object.defineProperty(e,"description",{get(){var o;return(o=ho.get(e))==null?void 0:o.description},configurable:!0}),e.meta=(...o)=>{if(o.length===0)return ho.get(e);const n=e.clone();return ho.add(n,o[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=o=>o(e),e)),fu=v("_ZodString",(e,t)=>{Zs.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Ul(e,n,r);const o=e._zod.bag;e.format=o.format??null,e.minLength=o.minimum??null,e.maxLength=o.maximum??null,e.regex=(...n)=>e.check(dw(...n)),e.includes=(...n)=>e.check(hw(...n)),e.startsWith=(...n)=>e.check(mw(...n)),e.endsWith=(...n)=>e.check(gw(...n)),e.min=(...n)=>e.check(Sn(...n)),e.max=(...n)=>e.check(Ll(...n)),e.length=(...n)=>e.check(Bl(...n)),e.nonempty=(...n)=>e.check(Sn(1,...n)),e.lowercase=n=>e.check(pw(n)),e.uppercase=n=>e.check(fw(n)),e.trim=()=>e.check(bw()),e.normalize=(...n)=>e.check(yw(...n)),e.toLowerCase=()=>e.check(ww()),e.toUpperCase=()=>e.check(kw()),e.slugify=()=>e.check(_w())}),dk=v("ZodString",(e,t)=>{Zs.init(e,t),fu.init(e,t),e.email=o=>e.check(Ob(pk,o)),e.url=o=>e.check(ql(hu,o)),e.jwt=o=>e.check(Qb(Pk,o)),e.emoji=o=>e.check(Fb(hk,o)),e.guid=o=>e.check(yi(vi,o)),e.uuid=o=>e.check(Nb(rn,o)),e.uuidv4=o=>e.check($b(rn,o)),e.uuidv6=o=>e.check(Mb(rn,o)),e.uuidv7=o=>e.check(zb(rn,o)),e.nanoid=o=>e.check(qb(mk,o)),e.guid=o=>e.check(yi(vi,o)),e.cuid=o=>e.check(Lb(gk,o)),e.cuid2=o=>e.check(Bb(yk,o)),e.ulid=o=>e.check(Ub(bk,o)),e.base64=o=>e.check(Gb(Dk,o)),e.base64url=o=>e.check(Kb(Tk,o)),e.xid=o=>e.check(jb(wk,o)),e.ksuid=o=>e.check(Hb(kk,o)),e.ipv4=o=>e.check(Vb(_k,o)),e.ipv6=o=>e.check(Zb(vk,o)),e.cidrv4=o=>e.check(Yb(Ik,o)),e.cidrv6=o=>e.check(Wb(Sk,o)),e.e164=o=>e.check(Jb(Ak,o)),e.datetime=o=>e.check(du(o)),e.date=o=>e.check(Yw(o)),e.time=o=>e.check(Gw(o)),e.duration=o=>e.check(Jw(o))});function d(e){return xb(dk,e)}const oe=v("ZodStringFormat",(e,t)=>{X.init(e,t),fu.init(e,t)}),pk=v("ZodEmail",(e,t)=>{zy.init(e,t),oe.init(e,t)}),vi=v("ZodGUID",(e,t)=>{$y.init(e,t),oe.init(e,t)}),rn=v("ZodUUID",(e,t)=>{My.init(e,t),oe.init(e,t)}),hu=v("ZodURL",(e,t)=>{Fy.init(e,t),oe.init(e,t)});function fk(e){return ql(hu,e)}const hk=v("ZodEmoji",(e,t)=>{qy.init(e,t),oe.init(e,t)}),mk=v("ZodNanoID",(e,t)=>{Ly.init(e,t),oe.init(e,t)}),gk=v("ZodCUID",(e,t)=>{By.init(e,t),oe.init(e,t)}),yk=v("ZodCUID2",(e,t)=>{Uy.init(e,t),oe.init(e,t)}),bk=v("ZodULID",(e,t)=>{jy.init(e,t),oe.init(e,t)}),wk=v("ZodXID",(e,t)=>{Hy.init(e,t),oe.init(e,t)}),kk=v("ZodKSUID",(e,t)=>{Vy.init(e,t),oe.init(e,t)}),_k=v("ZodIPv4",(e,t)=>{Ky.init(e,t),oe.init(e,t)}),vk=v("ZodIPv6",(e,t)=>{Jy.init(e,t),oe.init(e,t)}),Ik=v("ZodCIDRv4",(e,t)=>{Qy.init(e,t),oe.init(e,t)}),Sk=v("ZodCIDRv6",(e,t)=>{Xy.init(e,t),oe.init(e,t)}),Dk=v("ZodBase64",(e,t)=>{eb.init(e,t),oe.init(e,t)}),Tk=v("ZodBase64URL",(e,t)=>{ob.init(e,t),oe.init(e,t)}),Ak=v("ZodE164",(e,t)=>{nb.init(e,t),oe.init(e,t)}),Pk=v("ZodJWT",(e,t)=>{sb.init(e,t),oe.init(e,t)}),Ws=v("ZodNumber",(e,t)=>{Nl.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,r,s)=>jl(e,n,r),e.gt=(n,r)=>e.check(wi(n,r)),e.gte=(n,r)=>e.check(mr(n,r)),e.min=(n,r)=>e.check(mr(n,r)),e.lt=(n,r)=>e.check(bi(n,r)),e.lte=(n,r)=>e.check(hr(n,r)),e.max=(n,r)=>e.check(hr(n,r)),e.int=n=>e.check(Ii(n)),e.safe=n=>e.check(Ii(n)),e.positive=n=>e.check(wi(0,n)),e.nonnegative=n=>e.check(mr(0,n)),e.negative=n=>e.check(bi(0,n)),e.nonpositive=n=>e.check(hr(0,n)),e.multipleOf=(n,r)=>e.check(ki(n,r)),e.step=(n,r)=>e.check(ki(n,r)),e.finite=()=>e;const o=e._zod.bag;e.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),e.isFinite=!0,e.format=o.format??null});function C(e){return nw(Ws,e)}const Ck=v("ZodNumberFormat",(e,t)=>{ab.init(e,t),Ws.init(e,t)});function Ii(e){return sw(Ck,e)}const Ek=v("ZodBoolean",(e,t)=>{ib.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Hl(e,o,n)});function x(e){return aw(Ek,e)}const Rk=v("ZodNull",(e,t)=>{cb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Vl(e,o,n)});function mu(e){return iw(Rk,e)}const xk=v("ZodAny",(e,t)=>{lb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Yl()});function Ok(){return cw(xk)}const Nk=v("ZodUnknown",(e,t)=>{ub.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Wl()});function K(){return lw(Nk)}const $k=v("ZodNever",(e,t)=>{db.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Zl(e,o,n)});function Mk(e){return uw($k,e)}const zk=v("ZodArray",(e,t)=>{pb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Xl(e,o,n,r),e.element=t.element,e.min=(o,n)=>e.check(Sn(o,n)),e.nonempty=o=>e.check(Sn(1,o)),e.max=(o,n)=>e.check(Ll(o,n)),e.length=(o,n)=>e.check(Bl(o,n)),e.unwrap=()=>e.element});function I(e,t){return vw(zk,e,t)}const gu=v("ZodObject",(e,t)=>{hb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>eu(e,o,n,r),V(e,"shape",()=>t.shape),e.keyof=()=>z(Object.keys(e._zod.def.shape)),e.catchall=o=>e.clone({...e._zod.def,catchall:o}),e.passthrough=()=>e.clone({...e._zod.def,catchall:K()}),e.loose=()=>e.clone({...e._zod.def,catchall:K()}),e.strict=()=>e.clone({...e._zod.def,catchall:Mk()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=o=>Og(e,o),e.safeExtend=o=>Ng(e,o),e.merge=o=>$g(e,o),e.pick=o=>Rg(e,o),e.omit=o=>xg(e,o),e.partial=(...o)=>Mg(ku,e,o[0]),e.required=(...o)=>zg(_u,e,o[0])});function m(e,t){const o={type:"object",shape:e??{},...R(t)};return new gu(o)}function ue(e,t){return new gu({type:"object",shape:e,catchall:K(),...R(t)})}const yu=v("ZodUnion",(e,t)=>{zl.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>tu(e,o,n,r),e.options=t.options});function W(e,t){return new yu({type:"union",options:e,...R(t)})}const Fk=v("ZodDiscriminatedUnion",(e,t)=>{yu.init(e,t),mb.init(e,t)});function bu(e,t,o){return new Fk({type:"union",options:t,discriminator:e,...R(o)})}const qk=v("ZodIntersection",(e,t)=>{gb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ou(e,o,n,r)});function Gs(e,t){return new qk({type:"intersection",left:e,right:t})}const Lk=v("ZodRecord",(e,t)=>{yb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>nu(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function j(e,t,o){return new Lk({type:"record",keyType:e,valueType:t,...R(o)})}const $r=v("ZodEnum",(e,t)=>{bb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Gl(e,n,r),e.enum=t.entries,e.options=Object.values(t.entries);const o=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const s={};for(const a of n)if(o.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new $r({...t,checks:[],...R(r),entries:s})},e.exclude=(n,r)=>{const s={...t.entries};for(const a of n)if(o.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new $r({...t,checks:[],...R(r),entries:s})}});function z(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new $r({type:"enum",entries:o,...R(t)})}const Bk=v("ZodLiteral",(e,t)=>{wb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Kl(e,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function y(e,t){return new Bk({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}const Uk=v("ZodTransform",(e,t)=>{kb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ql(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new yl(e.constructor.name);o.addIssue=s=>{if(typeof s=="string")o.issues.push(xo(s,o.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=o.value),a.inst??(a.inst=e),o.issues.push(xo(a))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(s=>(o.value=s,o)):(o.value=r,o)}});function wu(e){return new Uk({type:"transform",transform:e})}const ku=v("ZodOptional",(e,t)=>{Fl.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ys(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function te(e){return new ku({type:"optional",innerType:e})}const jk=v("ZodExactOptional",(e,t)=>{_b.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ys(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Hk(e){return new jk({type:"optional",innerType:e})}const Vk=v("ZodNullable",(e,t)=>{vb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ru(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Si(e){return new Vk({type:"nullable",innerType:e})}const Zk=v("ZodDefault",(e,t)=>{Ib.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>au(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Yk(e,t){return new Zk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():_l(t)}})}const Wk=v("ZodPrefault",(e,t)=>{Sb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>iu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Gk(e,t){return new Wk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():_l(t)}})}const _u=v("ZodNonOptional",(e,t)=>{Db.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>su(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Kk(e,t){return new _u({type:"nonoptional",innerType:e,...R(t)})}const Jk=v("ZodCatch",(e,t)=>{Tb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>cu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qk(e,t){return new Jk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Xk=v("ZodPipe",(e,t)=>{Ab.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>lu(e,o,n,r),e.in=t.in,e.out=t.out});function Mr(e,t){return new Xk({type:"pipe",in:e,out:t})}const e_=v("ZodReadonly",(e,t)=>{Pb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>uu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function t_(e){return new e_({type:"readonly",innerType:e})}const vu=v("ZodCustom",(e,t)=>{Cb.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Jl(e,o)});function o_(e,t){return Iw(vu,e??(()=>!0),t)}function n_(e,t={}){return Sw(vu,e,t)}function r_(e){return Dw(e)}function Iu(e,t){return Mr(wu(e),t)}const q={custom:"custom"};function s_(e){return rw(Ws,e)}const a_=m({name:d().optional(),closed:x().optional(),refCreateSavePath:d().optional(),createDocNameTemplate:d().optional(),dailyNoteSavePath:d().optional(),dailyNoteTemplatePath:d().optional()}),Su=m({id:d().optional(),notebook:d().optional(),path:d().optional()}),i_=Su.superRefine((e,t)=>{const o=typeof e.id=="string",n=typeof e.notebook=="string"||typeof e.path=="string";if(o===n){t.addIssue({code:q.custom,message:"Provide either id or notebook + path."});return}n&&(!e.notebook||!e.path)&&t.addIssue({code:q.custom,message:"Both notebook and path are required when id is not provided."})}),c_=m({fromPaths:I(d()).optional(),toNotebook:d().optional(),toPath:d().optional(),fromIDs:I(d()).optional(),toID:d().optional()}).superRefine((e,t)=>{const o=Array.isArray(e.fromPaths)||typeof e.toNotebook=="string"||typeof e.toPath=="string",n=Array.isArray(e.fromIDs)||typeof e.toID=="string";if(o===n){t.addIssue({code:q.custom,message:"Provide either fromPaths + toNotebook + toPath or fromIDs + toID."});return}o&&(!e.fromPaths||!e.toNotebook||!e.toPath)&&t.addIssue({code:q.custom,message:"fromPaths, toNotebook, and toPath are required for path-based moves."}),n&&(!e.fromIDs||!e.toID)&&t.addIssue({code:q.custom,message:"fromIDs and toID are required for ID-based moves."})}),l_=z(Ts),u_=z(As),d_=z(Ps),p_=z(Cs),f_=z(Es),h_=z(Rs),m_=z($s),g_=z(Ms),y_=z(zs),Du=m({action:y("ls"),path:d().describe("Human-readable workspace path, such as /Notebook/Folder or / for notebook roots")}),Tu=m({action:y("tree"),path:d().describe("Human-readable workspace path, such as /Notebook/Folder or / for all readable notebooks"),maxDepth:C().int().min(0).max(20).optional().describe("Max tree depth to return (default 3)")}),Au=m({action:y("read"),path:d().describe("Human-readable document path"),blockStart:C().int().min(0).optional().describe("Zero-based display-block index to start reading from (default 0)"),blockLimit:C().int().min(1).max(200).optional().describe("Maximum complete display blocks to return (default 50)"),tokenBudget:C().int().min(1).max(32e3).optional().describe("Approximate token budget for the window (default 2000). A single oversized block is still returned whole."),includeBlockIds:x().optional().describe("Include a sidecar blockRefs mapping without adding block IDs to Markdown content (default false)")}).passthrough().superRefine((e,t)=>{for(const o of["page","pageSize"])e[o]!==void 0&&t.addIssue({code:q.custom,path:[o],message:`${o} character pagination was removed; use blockStart, blockLimit, and tokenBudget.`})}),Pu=m({action:y("write"),path:d().describe("Human-readable document path"),markdown:d().describe("Markdown content to create or write. Do not include a leading # Title; a matching create-time H1 is stripped automatically."),overwrite:x().optional().describe("When true, replace an existing document body while keeping the document node and title. This is a full body replacement.")}),Cn=m({old:d().min(1).describe("Original text to match exactly. Supports multi-line strings."),new:d().describe("Replacement text. Supports multi-line strings."),replace_all:x().optional().describe("When true, replace every exact match. Defaults to false.")}),Cu=m({action:y("replace"),path:d().describe("Human-readable document path to modify"),edit:W([Cn,I(Cn).min(1)]).describe("One replacement edit or an array of edits to apply sequentially inside editable non-complex Markdown blocks without rebuilding the document")}),Eu=m({action:y("rm"),path:d().describe("Human-readable document path to delete")}),Ru=m({action:y("mv"),from:d().describe("Human-readable source document path"),to:d().describe("Human-readable destination document path")}),xu=m({action:y("search"),path:d().describe("Human-readable document or folder path to search within"),query:d().describe("Text or regular expression to search for"),regex:x().optional().describe("Treat query as a JavaScript regular expression"),caseSensitive:x().optional().describe("Use case-sensitive matching"),page:C().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:C().int().min(1).max(200).optional().describe("Matches per page, default 50")}),Ou=m({action:y("list")}),Nu=m({action:y("create"),name:d().describe("Notebook name"),icon:d().optional().describe("Optional notebook icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}),$u=m({action:y("set_open_state"),notebook:d().describe("Notebook ID"),opened:x().describe("true to open, false to close")}),Mu=m({action:y("remove"),notebook:d().describe("Notebook ID")}),zu=m({action:y("rename"),notebook:d().describe("Notebook ID"),name:d().describe("New notebook name")}),Fu=m({action:y("get_conf"),notebook:d().describe("Notebook ID")}),qu=m({action:y("set_conf"),notebook:d().describe("Notebook ID"),conf:a_.describe("Notebook configuration")}),Lu=m({action:y("set_icon"),notebook:d().describe("Notebook ID"),icon:d().describe("Icon value. Prefer a Unicode hex code string such as '1f4d4' for 📔; raw emoji characters may not render correctly. Custom icon paths are also supported.")}),Bu=m({action:y("get_permissions"),notebook:d().optional().describe('Notebook ID, or "all" to return every notebook permission entry. Omit to return all notebooks.')}),Uu=m({action:y("set_permission"),notebook:d().describe("Notebook ID"),permission:z(["none","r","rw","rwd"]).describe('Permission level: "none" blocks all access, "r" allows read only, "rw" allows read and write without delete, "rwd" allows read, write, and delete')}),ju=m({action:y("get_child_docs"),notebook:d().describe("Notebook ID"),page:C().int().positive().optional().describe("Page number (1-based), default 1"),pageSize:C().int().positive().optional().describe("Rows per page, default 50")}),Hu=m({action:y("create"),notebook:d().describe("Notebook ID"),path:d().optional().describe("Human-readable target path, must start with / (e.g., /foo/bar). Parent paths must already exist."),parentPath:d().optional().describe("Parent human-readable path or storage path ending in .sy for title-based creation, must start with /"),title:d().optional().describe("Document title when creating under parentPath"),markdown:d().optional().describe("Markdown content, defaults to empty. Do not include a leading # Title; a matching H1 is stripped automatically."),sorts:I(d()).optional().describe("Compatibility option retained for older callers; title-based creation now uses the reliable path flow"),icon:d().optional().describe("Optional document icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}).superRefine((e,t)=>{const o=typeof e.path=="string",n=typeof e.parentPath=="string"||typeof e.title=="string";if(o&&n){t.addIssue({code:q.custom,message:"Provide either path, or parentPath + title, not both.",path:["path"]});return}!o&&(!e.parentPath||!e.title)&&t.addIssue({code:q.custom,message:"Provide path, or provide both parentPath and title.",path:["path"]})}),b_=z(["id","ids","path","hpath","docInfo"]),Vu=m({action:y("lookup"),id:d().optional().describe("Document ID to look up"),notebook:d().optional().describe("Notebook ID, required with path or hpath"),path:d().optional().describe("Storage path to look up when notebook is provided, e.g. /20240318112233-abc123.sy. Human-readable paths should use hpath instead."),hpath:d().optional().describe("Human-readable path to look up when notebook is provided"),hPath:d().optional().describe("Alias for hpath"),include:I(b_).optional().describe('Fields to include: "id", "ids", "path", "hpath", "docInfo"')}).superRefine((e,t)=>{const o=e.hpath??e.hPath;[e.id,e.path,o].filter(r=>typeof r=="string").length!==1&&t.addIssue({code:q.custom,message:"Provide exactly one source: id, notebook + path, or notebook + hpath.",path:["id"]}),!e.id&&!e.notebook&&t.addIssue({code:q.custom,message:"notebook is required when resolving path or hpath.",path:["notebook"]})}),Zu=m({action:y("rename"),title:d().describe("New document title")}).and(i_),Yu=m({action:y("remove"),ids:I(d()).min(1).optional().describe("One or more document IDs to remove"),paths:I(d()).min(1).optional().describe("One or more storage paths to remove in batch")}).and(Su).superRefine((e,t)=>{if([typeof e.id=="string",typeof e.notebook=="string"||typeof e.path=="string",Array.isArray(e.ids),Array.isArray(e.paths)].filter(Boolean).length!==1){t.addIssue({code:q.custom,message:"Provide exactly one removal mode: id, notebook + path, ids, or paths."});return}(e.notebook||e.path)&&(!e.notebook||!e.path)&&t.addIssue({code:q.custom,message:"Both notebook and path are required for path-based remove."})}),Wu=m({action:y("move")}).and(c_),Gu=m({action:y("get_child_blocks"),id:d().describe("Document ID")}),Ku=m({action:y("get_child_docs"),id:d().describe("Document ID")}),Ju=m({action:y("set_attr"),id:d().describe("Document ID"),attrs:m({icon:d().optional().describe("Icon value. Prefer a Unicode hex code string such as '1f4d4'."),cover:W([d(),mu()]).optional().describe("Cover source. Use null or empty string to clear the cover.")}).describe("Document metadata attributes to set")}).superRefine((e,t)=>{e.attrs.icon===void 0&&e.attrs.cover===void 0&&t.addIssue({code:q.custom,message:"Provide at least one of attrs.icon or attrs.cover.",path:["attrs"]})}),Qu=m({action:y("list_tree"),notebook:d().describe("Notebook ID"),path:d().describe("Storage path or / for the notebook root"),maxDepth:C().optional().describe("Max tree depth to return (default 3). Deeper nodes are collapsed to childCount.")}),Xu=m({action:y("search_docs"),notebook:d().describe("Notebook ID"),query:d().describe("Keyword to search in document titles"),path:d().optional().describe("Optional storage path to narrow the search scope after permission filtering")}),ed=m({action:y("get_doc"),id:d().describe("Document ID"),mode:z(["markdown","html"]).optional().describe('Return mode: "markdown" (default) or "html"'),size:C().optional().describe("Optional maximum content size hint"),blockStart:C().int().min(0).optional().describe("Zero-based display-block index to start reading from in markdown mode (default 0)"),blockLimit:C().int().min(1).max(200).optional().describe("Maximum complete display blocks to return in markdown mode (default 50)"),tokenBudget:C().int().min(1).max(32e3).optional().describe("Approximate token budget for the markdown window (default 2000). A single oversized block is still returned whole."),includeBlockIds:x().optional().describe("Include a sidecar blockRefs mapping in markdown mode without adding block IDs to content (default false)")}).passthrough().superRefine((e,t)=>{for(const o of["page","pageSize"])e[o]!==void 0&&t.addIssue({code:q.custom,path:[o],message:`${o} character pagination was removed; use blockStart, blockLimit, and tokenBudget.`});if(e.mode==="html")for(const o of["blockStart","blockLimit","tokenBudget","includeBlockIds"])e[o]!==void 0&&t.addIssue({code:q.custom,path:[o],message:`${o} is only supported when mode="markdown".`})}),td=m({action:y("create_daily_note"),notebook:d().describe("Notebook ID"),app:d().optional().describe("Optional app identifier passed through to SiYuan")}),od=m({action:y("duplicate"),id:d().describe("Source document ID")}),nd=m({action:y("heading_to_doc"),headingID:d().describe("Heading block ID to convert into a document"),targetNotebook:d().describe("Target notebook ID"),targetPath:d().optional().describe("Optional target storage path"),previousPath:d().optional().describe("Optional previous sibling storage path")}),rd=m({action:y("doc_to_heading"),srcID:d().describe("Source document ID"),targetID:d().describe("Target document or heading block ID"),after:x().optional().describe("When true, insert after the target heading instead of before it")}),sd=m({action:y("get_balance")}),ad=m({action:y("shop")}),id=m({action:y("buy"),item_id:d().describe('Stable shop item ID returned by mascot(action="shop")')}),cd=m({action:y("submit"),description:d().trim().min(1).max(4e3).describe("Required feedback text. Prefer a GitHub Issue-style body for bugs, confusing behavior, or rough workflows, with headings such as ## Summary, ## What happened, ## Expected behavior, ## Steps or context, ## Impact, and ## Suggested fix."),impact:d().trim().max(1e3).optional().describe("Optional one- or two-sentence impact summary, such as affected workflow, error risk, confusion, or inconvenience."),suggestion:d().trim().max(1e3).optional().describe("Optional direct improvement suggestion; keep it focused and avoid repeating the full description."),agent:d().trim().max(200).optional().describe("Optional Agent product and model name, such as Claude Desktop / Claude Sonnet 4.5. Defaults to 无."),source:d().trim().max(100).optional().describe("Internal source label. Defaults to the current runtime transport.")}),w_=z(["all","deck","notebook","tree"]),k_=z(["due","new","old"]),ld=m({action:y("list_cards"),scope:w_.describe('Query scope: "all", "deck", "notebook", or "tree"'),filter:k_.describe('Filter returned cards: "due", "new", or "old"'),deckID:d().optional().describe('Deck ID, required when scope=deck. For scope="all", omit deckID; an empty string is treated as omitted.'),notebook:d().optional().describe("Notebook ID, required when scope=notebook"),rootID:d().optional().describe("Root document/block ID, required when scope=tree"),reviewedCards:I(m({cardID:d().describe("Reviewed card ID")}).passthrough()).optional().describe("Optional already-reviewed cards; SiYuan reads reviewedCards[].cardID")}).superRefine((e,t)=>{const o=typeof e.deckID=="string"&&e.deckID.length>0,n=typeof e.notebook=="string",r=typeof e.rootID=="string";e.scope==="all"&&(o||n||r)&&t.addIssue({code:q.custom,message:'scope="all" does not accept deckID, notebook, or rootID.'}),e.scope==="deck"&&!o&&t.addIssue({code:q.custom,path:["deckID"],message:'deckID is required when scope="deck".'}),e.scope==="notebook"&&!n&&t.addIssue({code:q.custom,path:["notebook"],message:'notebook is required when scope="notebook".'}),e.scope==="tree"&&!r&&t.addIssue({code:q.custom,path:["rootID"],message:'rootID is required when scope="tree".'})}),ud=m({action:y("get_decks")}),dd=m({action:y("review_card"),deckID:d().describe("Deck ID"),cardID:d().describe("Card ID"),rating:C().optional().describe("Review rating passed through to the kernel"),skip:x().optional().describe("When true, skip the current card instead of submitting a rating"),reviewedCards:I(m({cardID:d().describe("Reviewed card ID")}).passthrough()).optional().describe("Optional already-reviewed cards; SiYuan reads reviewedCards[].cardID")}).superRefine((e,t)=>{e.skip!==!0&&e.rating===void 0&&t.addIssue({code:q.custom,message:"rating is required unless skip=true.",path:["rating"]})}),pd=m({action:y("create_card"),deckID:d().describe("Deck ID"),blockIDs:I(d()).min(1).describe("Existing block IDs to turn into flashcards"),mode:z(["full","attach"]).optional().describe("Compatibility option. SiYuan addRiffCards writes deck attrs and registers cards in both modes.")}),fd=m({action:y("remove_card"),deckID:d().describe("Deck ID"),blockIDs:I(d()).min(1).describe("Existing block IDs to remove from flashcards")}),hd=m({action:y("get_cards"),deckID:d().describe("Deck ID (use empty string to query across all decks)"),page:C().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:C().int().min(1).max(512).optional().describe("Cards per page, default 32")}),md=m({action:y("insert"),dataType:z(["markdown","dom"]).optional().describe("Data format"),data:d().optional().describe("Block content"),nextID:d().optional().describe("Next block ID"),previousID:d().optional().describe("Previous block ID"),parentID:d().optional().describe("Parent block or document ID"),blocks:I(m({dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),nextID:d().optional().describe("Next block ID"),previousID:d().optional().describe("Previous block ID"),parentID:d().optional().describe("Parent block or document ID")})).min(1).optional().describe("Blocks to insert. Item-level anchors override top-level parentID/previousID/nextID.")}).superRefine((e,t)=>{if(Array.isArray(e.blocks)){(e.dataType||e.data)&&t.addIssue({code:q.custom,message:"Provide either blocks or single insert data, not both.",path:["blocks"]}),e.blocks.forEach((n,r)=>{n.nextID||n.previousID||n.parentID||e.nextID||e.previousID||e.parentID||t.addIssue({code:q.custom,path:["blocks",r,"previousID"],message:"Provide nextID, previousID, or parentID for each block, or set a top-level parentID/previousID/nextID."})});return}e.dataType||t.addIssue({code:q.custom,message:"dataType is required for single insert.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:q.custom,message:"data is required for single insert.",path:["data"]})}),gd=m({action:y("prepend"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),parentID:d().describe("Parent block or document ID")}),yd=m({action:y("append"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),parentID:d().describe("Parent block or document ID")}),bd=m({action:y("update"),dataType:z(["markdown","dom"]).optional().describe("Data format"),data:d().optional().describe("New block content"),id:d().optional().describe("Block ID"),items:I(m({id:d().describe("Block ID"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Replacement block content")})).min(1).optional().describe("Blocks to update")}).superRefine((e,t)=>{if(Array.isArray(e.items)){(e.id||e.dataType||e.data!==void 0)&&t.addIssue({code:q.custom,message:"Provide either items or single update fields, not both.",path:["items"]});return}e.id||t.addIssue({code:q.custom,message:"id is required for single update.",path:["id"]}),e.dataType||t.addIssue({code:q.custom,message:"dataType is required for single update.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:q.custom,message:"data is required for single update.",path:["data"]})}),wd=m({action:y("replace"),id:d().describe("Block ID"),edit:W([Cn,I(Cn).min(1)]).describe("One replacement edit or an array of edits to apply sequentially within the same block kramdown")}),kd=m({action:y("delete"),id:d().describe("Block ID")}),_d=m({action:y("move"),id:d().optional().describe("Single block ID"),ids:I(d()).min(1).optional().describe("Multiple block IDs to move as a group. Pass IDs in the desired final order; the tool calls SiYuan's low-level move API from last to first internally to preserve that order."),previousID:d().optional().describe("Previous block ID"),parentID:d().optional().describe("New parent block ID")}).superRefine((e,t)=>{(e.id&&e.ids||!e.id&&!e.ids)&&t.addIssue({code:q.custom,message:"Provide exactly one of id or ids.",path:["id"]}),!e.previousID&&!e.parentID&&t.addIssue({code:q.custom,message:"Provide previousID, parentID, or both to describe the destination.",path:["previousID"]})}),vd=m({action:y("set_fold_state"),id:d().describe("Foldable block ID"),folded:x().describe("true to fold, false to unfold")}),Id=m({action:y("get_kramdown"),id:d().describe("Block ID or document ID")}),Sd=m({action:y("get_children"),id:d().describe("Block ID or document ID"),page:C().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:C().int().min(1).max(200).optional().describe("Items per page, default 50")}),Dd=m({action:y("transfer_references"),fromID:d().describe("Source block ID"),toID:d().describe("Target block ID"),refIDs:I(d()).optional().describe("Reference block IDs")}),Td=m({action:y("set_attrs"),id:d().describe("Block ID"),attrs:j(d(),d()).describe("Block attributes")}),Ad=m({action:y("get_attrs"),id:d().describe("Block ID")}),Pd=m({action:y("info"),id:d().describe("Block ID")}),Cd=m({action:y("breadcrumb"),id:d().describe("Block ID"),excludeTypes:I(d()).optional().describe("Optional block types to exclude from the breadcrumb")}),Ed=m({action:y("dom"),id:d().describe("Block ID")}),Rd=m({action:y("recent_updated"),count:C().optional().describe("Maximum number of recent readable blocks to return after permission filtering")}),xd=m({action:y("word_count"),ids:I(d()).describe("One or more block IDs")}),Od=m({action:y("add_to_daily_note"),notebook:d().describe("Notebook ID"),dataType:z(["markdown","dom"]).describe("Data format"),data:d().describe("Block content"),position:z(["append","prepend"]).describe("Where to add content in today's daily note")}),Nd=m({action:y("docs_info"),id:d().optional().describe("Single document/block ID"),ids:I(d()).min(1).optional().describe("Document IDs"),refCount:x().optional().describe("When true, include reference counts"),av:x().optional().describe("When true, include AV metadata")}).superRefine((e,t)=>{(e.id&&e.ids||!e.id&&!e.ids)&&t.addIssue({code:q.custom,message:"Provide exactly one of id or ids.",path:["ids"]})}),__=z(["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"]),v_=m({type:z(["image","file"]).describe("Asset entry type"),content:d().describe("Asset path stored by SiYuan, e.g. assets/foo.png"),name:d().optional().describe("Optional display name")}),$d=m({valueType:__.describe("Cell value type"),text:d().optional().describe("Text value for valueType=text"),number:C().optional().describe("Number value for valueType=number"),numberFormat:d().optional().describe("Optional number format such as commas, percent, USD, or CNY"),date:W([d(),C()]).optional().describe("Date/time value as ISO text or epoch milliseconds for valueType=date"),endDate:W([d(),C()]).optional().describe("Optional end date as ISO text or epoch milliseconds for ranged dates"),includeTime:x().optional().describe("When false, store the date without a time component"),checked:x().optional().describe("Checkbox state for valueType=checkbox"),option:d().optional().describe("Selected option label for valueType=select"),options:I(d()).optional().describe("Selected option labels for valueType=multi_select"),relationBlockIDs:I(d()).optional().describe("Related block IDs for valueType=relation"),url:d().optional().describe("URL value for valueType=url"),email:d().optional().describe("Email value for valueType=email"),phone:d().optional().describe("Phone value for valueType=phone"),assets:I(v_).optional().describe("Asset entries for valueType=mAsset")}),Md=$d.superRefine((e,t)=>{const n={text:"text",number:"number",date:"date",checkbox:"checked",select:"option",multi_select:"options",relation:"relationBlockIDs",url:"url",email:"email",phone:"phone",mAsset:"assets"}[e.valueType];e[n]===void 0&&t.addIssue({code:q.custom,message:`${String(n)} is required when valueType="${e.valueType}".`,path:[n]})}),Di=m({rowID:d().describe("Row item ID"),columnID:d().describe("Column key ID")}).and(Md),zd=m({action:y("get"),id:d().describe("Attribute view ID"),blockID:d().optional().describe("Optional database block ID for exact context or fallback permission resolution")}),Fd=m({action:y("render"),id:d().optional().describe("Attribute view ID for render/get-style operations; use id here, not avID. Omit only with createIfNotExist=true to let MCP generate one"),blockID:d().optional().describe("Optional database block ID; required when creating a new AV"),viewID:d().optional().describe("Optional target view ID"),page:C().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:C().int().optional().describe("Rows per page; use -1 or omit for kernel default"),query:d().optional().describe("Optional row query filter"),groupPaging:j(d(),K()).optional().describe("Optional group paging map passed through to SiYuan"),createIfNotExist:x().optional().describe("Create the default view only when explicitly true; provide blockID when creating a new AV")}),qd=m({action:y("get_attribute_view_keys"),id:d().describe("Attribute view ID")}),Ld=m({action:y("get_attribute_view_filter_sort"),id:d().describe("Attribute view ID"),blockID:d().optional().describe("Database block ID (optional)")}),Bd=m({action:y("search"),keyword:d().describe("Keyword to search in attribute view names"),excludes:I(d()).optional().describe("Optional AV IDs to exclude")}),Ud=m({action:y("add_rows"),avID:d().describe("Attribute view ID"),blockIDs:I(d()).optional().describe("Existing block IDs to add as bound rows"),primaryKeyTexts:I(d()).optional().describe("Plain-text primary key values to add as detached rows"),blockID:d().optional().describe("Optional database block ID used to pin a specific database-block view context"),viewID:d().optional().describe("Optional target view ID"),groupID:d().optional().describe("Optional target group ID"),previousID:d().optional().describe("Optional previous row item ID"),ignoreDefaultFill:x().optional().describe("When true, skip view/group default value filling")}),jd=m({action:y("remove_rows"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),srcIDs:I(d()).min(1).describe("Bound row block/item IDs to remove")}),Hd=m({action:y("add_column"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),keyID:d().optional().describe("Optional new column key ID; MCP generates one when omitted"),keyName:d().describe("New column name"),keyType:z(["text","number","date","select","mSelect","url","email","phone","mAsset","template","created","updated","checkbox","relation","rollup","lineNumber"]).describe("Column type"),keyIcon:d().optional().describe("Optional column icon"),previousKeyID:d().optional().describe("Insert after this existing column key ID")}),Vd=m({action:y("remove_column"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),keyID:d().optional().describe("Column key ID"),columnID:d().optional().describe("Alias of keyID"),removeRelationDest:x().optional().describe("Also remove reverse relation metadata when deleting a relation column")}).superRefine((e,t)=>{!e.keyID&&!e.columnID&&t.addIssue({code:q.custom,message:"Provide keyID or columnID.",path:["keyID"]})}),Zd=m({action:y("set_cells"),avID:d().describe("Attribute view ID"),blockID:d().optional().describe("Registered database block ID for explicit database-block context"),cells:I(Di).min(1).optional().describe("Cell updates"),items:I(Di).min(1).optional().describe("Alias for cells"),rowID:d().optional().describe("Single-cell row item ID"),columnID:d().optional().describe("Single-cell column key ID")}).and($d.partial()).superRefine((e,t)=>{const o=e.cells??e.items,n=Array.isArray(o),r=typeof e.rowID=="string"||typeof e.columnID=="string"||typeof e.valueType=="string";if(n&&r){t.addIssue({code:q.custom,message:"Provide either cells/items or single-cell fields, not both.",path:["cells"]});return}if(!n){if(e.rowID||t.addIssue({code:q.custom,message:"rowID is required for single-cell set_cells calls.",path:["rowID"]}),e.columnID||t.addIssue({code:q.custom,message:"columnID is required for single-cell set_cells calls.",path:["columnID"]}),!e.valueType){t.addIssue({code:q.custom,message:"valueType is required for single-cell set_cells calls.",path:["valueType"]});return}const s=Md.safeParse(e);if(!s.success)for(const a of s.error.issues)t.addIssue({code:q.custom,message:a.message,path:a.path})}}),Yd=m({action:y("duplicate"),avID:d().describe("Source attribute view ID"),blockID:d().optional().describe("Optional source database block ID used as exact context and default insertion target"),previousID:d().optional().describe("Optional block ID to insert the duplicated mirror database block after")}),Wd=m({action:y("get_primary_key_values"),avID:d().describe("Attribute view ID"),keyword:d().optional().describe("Optional keyword filter for primary key values"),page:C().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:C().int().min(1).optional().describe("Rows per page, default all")}),Gd=m({action:y("upload_asset"),assetsDirPath:d().describe("Asset directory path (e.g., /assets/)"),localFilePath:d().describe("Local file path to read and upload into the assets directory"),confirmLargeFile:x().optional().describe("Set to true only after the user explicitly confirms uploading a file larger than the configured safety threshold.")}),Kd=m({action:y("list_templates"),query:d().optional().describe("Optional keyword used by SiYuan's template picker. Omit or pass an empty string to list all templates."),page:C().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:C().int().min(1).max(128).optional().describe("Templates per page, default 20")}),Jd=m({action:y("read_template"),path:d().describe("Template path returned by list_templates, /data/templates/... path, /templates/... static path, or path relative to data/templates"),offset:C().int().min(0).optional().describe("Character offset for partial template source reading, default 0"),limit:C().int().min(1).max(2e4).optional().describe("Maximum characters to return, default 8000")}),Qd=m({action:y("create_template"),path:d().describe("Template path to create under data/templates. Accepts relative paths such as reports/monthly.md."),markdown:d().describe("Full Markdown template source to write."),overwrite:x().optional().describe("When true, replace an existing template at the same path. Defaults to false.")}),Xd=m({action:y("update_template"),path:d().describe("Existing template path returned by list_templates, /data/templates/... path, /templates/... static path, or path relative to data/templates."),markdown:d().describe("Full Markdown template source to replace the existing template with.")}),ep=m({action:y("delete_template"),path:d().describe("Existing template path returned by list_templates, /data/templates/... path, /templates/... static path, or path relative to data/templates.")}),tp=m({action:y("save_doc_as_template"),id:d().describe("Document ID to save as a root-level template."),name:d().describe("Root template name. Slashes are not supported; .md suffix is optional."),overwrite:x().optional().describe("When true, replace an existing template with the same root name. Defaults to false.")}),op=m({action:y("render"),engine:z(["template","sprig"]).describe("Template engine to use"),id:d().optional().describe("Document ID for template context"),path:d().optional().describe("Template file path inside the SiYuan workspace"),template:d().optional().describe("Sprig template content"),preview:x().optional().describe('When engine="template", ask SiYuan to render preview DOM instead of insertion DOM.')}).superRefine((e,t)=>{e.engine==="template"&&(e.id||t.addIssue({code:q.custom,message:'id is required when engine="template".',path:["id"]}),e.path||t.addIssue({code:q.custom,message:'path is required when engine="template".',path:["path"]})),e.engine==="sprig"&&!e.template&&t.addIssue({code:q.custom,message:'template is required when engine="sprig".',path:["template"]})}),np=m({action:y("export_md"),id:d().describe("Document ID to export")}),rp=m({action:y("export_resources"),paths:I(d()).describe("Paths to export"),name:d().optional().describe("Export file name"),outputPath:d().optional().describe("Optional local absolute or relative filesystem path to save the exported ZIP")}),sp=m({action:y("list_unused_assets")}),ap=m({action:y("get_doc_assets"),id:d().describe("Document ID"),assetType:z(["all","image"]).optional().describe("Filter asset type: 'all' (default) returns all assets, 'image' returns only image assets.")}),ip=m({action:y("get_image_ocr_text"),path:d().optional().describe("Asset path; omit to receive an empty OCR text payload")}),cp=m({action:y("remove_unused_assets")}),lp=m({action:y("rename_asset"),oldPath:d().describe("Existing asset path"),newName:d().describe("New asset file name")}),up=m({action:y("delete_asset"),path:d().describe("Asset path to delete")}),dp=m({action:y("extract_doc"),id:d().describe("Document ID to extract"),outputDir:d().optional().describe("Output root directory. Defaults to ~/siyuan-extracted/ (resolved to absolute path).")}),I_=z(xs),Ks=z(["keyword","query","query_syntax","sql","regex"]),pp=z(["relevance","date","updated_desc","updated_asc","created_desc","created_asc","type"]),S_=z(["relevance","relevance_desc","relevance_asc","updated_asc","updated_desc"]),fp=m({action:y("fulltext"),query:d().describe("Search query string"),method:C().optional().describe("Search method: 0=keyword (default), 1=query syntax, 2=SQL, 3=regex"),methodName:Ks.optional().describe('Semantic alias for method: "keyword" | "query_syntax" | "sql" | "regex". The short alias "query" also maps to query syntax and overrides method when both are provided.'),types:j(d(),x()).optional().describe('Block type filter. Accepts full names (e.g. {"heading": true}) or shortcodes (e.g. {"h": true, "p": true}). Codes: d=document, h=heading, p=paragraph, l=list, i=listItem, b=blockquote, c=codeBlock, m=mathBlock, t=table, s=superBlock, html=htmlBlock, embed=embedBlock, av=databaseBlock.'),typeShortcodes:I(d()).optional().describe('Alternative shorthand type filter as array: ["h","p"]. Merged with types if both provided.'),paths:I(d()).optional().describe("Restrict search to specific notebook paths"),groupBy:C().optional().describe("0=no grouping (default), 1=group by document"),orderBy:C().optional().describe("Legacy numeric sort order: 0=type, 1=created ASC, 2=created DESC, 3=updated ASC, 4=updated DESC, 5=content ASC, 6=content DESC, 7=relevance (default)"),sortBy:pp.optional().describe('Semantic sort alias: "relevance", "date", "updated_desc", "updated_asc", "created_desc", "created_asc", or "type". Overrides orderBy if both provided.'),page:C().optional().describe("Page number (1-based), default 1"),pageSize:C().optional().describe("Results per page, default 32, max 128"),parentId:d().optional().describe("Post-filter results to blocks whose root_id or parent_id matches this ID, scoping search within a document subtree."),hasTags:x().optional().describe("When true, only return blocks that have tags. When false, only return blocks without tags."),stripHtml:x().optional().describe("Legacy toggle. plainContent is now returned by default; set this when you want to emphasize plain-text-safe downstream parsing while keeping highlighted HTML content.")}),hp=m({action:y("query_sql"),stmt:d().optional().describe("SQL SELECT statement to execute against the blocks/spans/assets tables; returned rows are permission-filtered"),sql:d().optional().describe("Semantic alias for stmt. Overrides stmt when both are provided.")}).superRefine((e,t)=>{!e.stmt&&!e.sql&&t.addIssue({code:q.custom,message:"Provide stmt or sql.",path:["stmt"]})}),mp=m({action:y("get_backlinks"),id:d().describe("Block or document ID to find backlinks for"),keyword:d().optional().describe("Filter backlinks by keyword"),refTreeID:d().optional().describe("Optional document tree ID to narrow backlink scope"),scopeRootId:d().optional().describe("Semantic alias for refTreeID. Overrides refTreeID when both are provided."),mode:z(["links","mentions","both"]).optional().describe('Result mode: "links", "mentions", or "both" (default).')}),gp=m({action:y("search_refs"),id:d().describe("Referenced block or document ID"),rootID:d().optional().describe("Optional current root document ID"),k:d().optional().describe("Keyword filter"),beforeLen:C().int().min(0).optional().describe("Context length before the reference, default 512"),isSquareBrackets:x().optional().describe("Search in square-bracket reference mode"),isDatabase:x().optional().describe("Whether the reference target is a database"),reqId:d().optional().describe("Optional passthrough request ID")}),yp=m({action:y("find_replace"),k:d().describe("Find keyword"),r:d().describe("Replacement text; use empty string to delete matches"),ids:I(d()).min(1).describe("Document or block IDs to mutate"),paths:I(d()).optional().describe("Optional path scope list"),types:j(d(),x()).optional().describe("Optional block type filter"),method:C().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Ks.optional().describe('Semantic alias for method: "keyword" | "query_syntax" | "sql" | "regex". The short alias "query" also maps to query syntax and overrides method when both are provided.'),orderBy:C().optional().describe("Legacy numeric sort order"),sortBy:pp.optional().describe("Semantic sort alias that overrides orderBy when both are provided."),groupBy:C().optional().describe("Grouping mode"),replaceTypes:j(d(),x()).optional().describe("Replace target kinds such as text, code, docTitle, blockRef")}),bp=m({action:y("search_assets"),k:d().optional().describe("Legacy asset filename keyword field"),query:d().optional().describe("Semantic alias for k. Overrides k when both are provided."),exts:I(d()).optional().describe("Optional extension filters")}).superRefine((e,t)=>{!e.k&&!e.query&&t.addIssue({code:q.custom,message:"Provide k or query.",path:["k"]})}),wp=m({action:y("fulltext_asset_content"),query:d().optional().describe("Search query string"),assetId:d().optional().describe("Asset content ID for an exact content lookup"),queryMethod:C().optional().describe("Query method for assetId lookup: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),types:j(d(),x()).optional().describe("Asset type filter"),method:C().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Ks.optional().describe('Semantic alias for method: "keyword" | "query_syntax" | "sql" | "regex". The short alias "query" also maps to query syntax and overrides method when both are provided.'),orderBy:C().optional().describe("Legacy numeric sort order: 0=relevance DESC, 1=relevance ASC, 2=updated ASC, 3=updated DESC"),sortBy:S_.optional().describe('Semantic sort alias: "relevance_desc", "relevance_asc", "updated_asc", or "updated_desc". The shorthand "relevance" maps to relevance_desc. Overrides orderBy if both are provided.'),page:C().int().min(1).optional().describe("Page number (1-based)"),pageSize:C().int().min(1).max(128).optional().describe("Results per page")}).superRefine((e,t)=>{!e.query&&!e.assetId&&t.addIssue({code:q.custom,message:"Provide query or assetId.",path:["query"]})}),kp=m({action:y("list_invalid_refs"),page:C().int().min(1).optional().describe("Page number (1-based)"),pageSize:C().int().min(1).max(128).optional().describe("Results per page")}),D_=z(Os),_p=m({action:y("list"),keyword:d().optional().describe("Optional keyword used to search/filter tags"),query:d().optional().describe("Alias for keyword"),sort:C().optional().describe("Optional tag sort mode"),ignoreMaxListHint:x().optional().describe("Ignore the maximum list hint from SiYuan"),app:d().optional().describe("Optional app identifier passed through to SiYuan")}),vp=m({action:y("rename"),oldLabel:d().describe("Existing tag label"),newLabel:d().describe("New tag label")}),Ip=m({action:y("remove"),label:d().describe("Tag label to remove")}),T_=z(Ns),Sp=m({action:y("workspace_info")}),Dp=m({action:y("network")}),Tp=m({action:y("conf"),mode:z(["summary","get"]).optional().describe('Read mode: "summary" returns a navigable overview, "get" reads a specific key path'),keyPath:d().optional().describe('Dot/bracket path to a specific config field, e.g. "conf.appearance.mode" or "conf.langs[0]"'),maxDepth:C().int().min(0).max(5).optional().describe("Maximum object traversal depth for summary/get responses"),maxItems:C().int().min(1).max(100).optional().describe("Maximum keys/items to include per level")}),Ap=m({action:y("notify"),msg:d().describe("Message content"),level:z(["info","error"]).describe("Notification level"),timeout:C().optional().describe("Display timeout in milliseconds")}),Pp=m({action:y("changelog"),version:d().optional().describe("Exact plugin version to read, e.g. 0.4.11 or v0.4.11"),fromVersion:d().optional().describe("Previous plugin version; returns entries newer than this version"),limit:C().int().min(1).max(50).optional().describe("Maximum number of entries to return when version is omitted"),includeRaw:x().optional().describe("Include raw Markdown for each returned changelog entry")}),Cp=m({action:y("perform_sync")}),Ep=m({action:y("get_version")}),Rp=m({action:y("get_current_time")}),wt={type:"string"},A_={type:"boolean"},Ti={type:"integer"};function P_(e,t){return typeof t.action=="string"?so(e,t.action):void 0}function me(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Uo(e){return typeof e=="string"&&e.length>0}function C_(e,t){return t.some(o=>me(e,o))}function E_(e,t){if(t.action!=="help"||typeof t.topic!="string")return;const o=t.topic.trim();if(!o||o==="overview"){t.topic=o;return}t.topic=so(e,o)}function R_(e){if(me(e,"edit")&&C_(e,["old","new","replace_all","replaceAll"]))throw new Error("fs.replace accepts either edit or old/new shorthand, not both.");if(!me(e,"edit")&&(me(e,"old")||me(e,"new"))){if(!Uo(e.old))throw new Error("fs.replace shorthand requires a non-empty old value.");if(!me(e,"new"))throw new Error("fs.replace shorthand requires new.");e.edit={old:e.old,new:String(e.new??""),...typeof e.replace_all=="boolean"||typeof e.replaceAll=="boolean"?{replace_all:!!(e.replace_all??e.replaceAll)}:{}}}delete e.old,delete e.new,delete e.replace_all,delete e.replaceAll}function x_(e){!me(e,"id")&&Uo(e.avID)&&(e.id=e.avID),delete e.avID}function O_(e){!me(e,"ids")&&Uo(e.id)&&(e.ids=[e.id]),delete e.id}function N_(e){!me(e,"blockIDs")&&Uo(e.blockID)&&(e.blockIDs=[e.blockID]),delete e.blockID}function $_(e){!(me(e,"file")&&me(e,"fileName")&&!me(e,"localFilePath"))&&!me(e,"localFilePath")&&Uo(e.file)&&(e.localFilePath=e.file,delete e.file),me(e,"assetsDirPath")||(e.assetsDirPath="/assets/")}function M_(e){me(e,"k")||(typeof e.keyword=="string"?e.k=e.keyword:typeof e.query=="string"&&(e.k=e.query)),delete e.keyword,delete e.query}function z_(e,t){const o={...t},n=P_(e,o);return n&&(o.action=n),E_(e,o),e==="fs"&&n==="replace"&&R_(o),e==="av"&&n==="render"&&x_(o),e==="block"&&n==="word_count"&&O_(o),e==="flashcard"&&(n==="create_card"||n==="remove_card")&&N_(o),e==="file"&&n==="upload_asset"&&$_(o),e==="search"&&n==="search_refs"&&M_(o),o}function F_(e){if(!(e!=null&&e.category)||!e.action)return[];const t=so(e.category,e.action);return e.category==="fs"&&t==="read"||e.category==="document"&&t==="get_doc"?[{canonical:"page",aliases:["page"],schema:Ti},{canonical:"pageSize",aliases:["page-size","page_size","pageSize"],schema:Ti}]:e.category==="fs"&&t==="replace"?[{canonical:"old",aliases:["old"],schema:wt},{canonical:"new",aliases:["new"],schema:wt},{canonical:"replace_all",aliases:["replace-all","replace_all","replaceAll"],schema:A_}]:e.category==="av"&&t==="render"?[{canonical:"id",aliases:["avID","av-id","av_id"],schema:wt}]:e.category==="block"&&t==="word_count"?[{canonical:"ids",aliases:["id"],schema:{type:"array",items:wt}}]:e.category==="flashcard"&&(t==="create_card"||t==="remove_card")?[{canonical:"blockIDs",aliases:["blockID","block-id","block_id"],schema:{type:"array",items:wt}}]:e.category==="file"&&t==="upload_asset"?[{canonical:"localFilePath",aliases:["file"],schema:wt}]:[]}const q_=[{code:"block_not_found",patterns:[/未找到 ID 为 \[[^\]]+\] 的内容块/,/SiYuan API error:\s*-1\b.*(block|id)/i,/block not found/i],hint:'Verify the block ID with block(action="info", id="...") or locate it via search(action="fulltext", query="...").'},{code:"notebook_not_found",patterns:[/notebook .*not found/i,/笔记本不存在/,/not found in lsNotebooks/i],hint:'List available notebooks via notebook(action="list") and retry with a valid notebook ID.'},{code:"notebook_closed",patterns:[/notebook is currently closed/i,/kernel still initializing/i,/closed_or_initializing/i,/笔记本已关闭/],hint:'Re-open the notebook via notebook(action="set_open_state", opened=true) or retry after a short wait.'},{code:"document_not_found",patterns:[/document .*not found/i,/文档不存在/],hint:'Resolve the document via document(action="lookup") or search(action="search_docs").'},{code:"av_not_found",patterns:[/attribute view .*not found/i,/数据库不存在/,/av .*not found/i],hint:'Locate the attribute view via av(action="search", keyword="...") or av(action="list").'},{code:"permission_denied",patterns:[/permission denied/i,/权限被拒绝/,/no .*permission/i],hint:'Inspect current permissions with notebook(action="get_permissions") and adjust via notebook(action="set_permission").'},{code:"kernel_unreachable",patterns:[/HTTP error:/i,/Request timeout/i,/ECONNREFUSED/i,/fetch failed/i],hint:"MCP server is running but the SiYuan kernel is unreachable. Prompt the user to start SiYuan. Do not explore source files to debug this."}];function Js(e){const t=e.message??"";for(const o of q_)if(o.patterns.some(n=>n.test(t)))return{code:o.code,hint:o.hint};return null}function Qs(e){var t;return e instanceof Error?((t=Js(e))==null?void 0:t.code)==="block_not_found":!1}function L_(e){return typeof e.description=="string"?e.description:null}function io(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Yn(e){return Array.isArray(e.required)?e.required.filter(t=>typeof t=="string"):[]}function B_(e,t={}){const o={},n=new Map,r=new Map,s=new Map,a=new Map;for(const i of e){const c=new Set(Yn(i.schema));for(const[l,u]of Object.entries(io(i.schema))){if(l==="action"||!u||typeof u!="object")continue;o[l]=U_(o[l],u);const p=L_(u);if(p){const b=n.get(l)??new Set;b.add(p),n.set(l,b)}const f=u.enum;if(Array.isArray(f)){const b=r.get(l)??new Set;for(const _ of f)b.add(_);r.set(l,b)}const h=c.has(l)?s:a,g=h.get(l)??new Set;g.add(i.action),h.set(l,g)}}for(const[i,c]of Object.entries(o)){const l=n.get(i),u=t[i]??(l&&l.size>0?[...l].join(" / "):void 0),p=[...s.get(i)??[]].sort(),f=[...a.get(i)??[]].sort(),h=[...p.length>0?[`Required by: ${p.join(", ")}`]:[],...f.length>0?[`Optional in: ${f.join(", ")}`]:[]],g=h.length>0?`[${h.join("; ")}]`:"";c.description=u?g?`${u} ${g}`:u:g||void 0;const b=r.get(i);b&&b.size>0&&(c.enum=[...b])}return o}function U_(e,t){if(!e)return{...t};const o={...e,...t};return Ai(o,e,t,"minimum"),Ai(o,e,t,"exclusiveMinimum"),Pi(o,e,t,"maximum"),Pi(o,e,t,"exclusiveMaximum"),o}function Ai(e,t,o,n){const r=t[n],s=o[n];typeof r=="number"&&typeof s=="number"?e[n]=Math.min(r,s):delete e[n]}function Pi(e,t,o,n){const r=t[n],s=o[n];typeof r=="number"&&typeof s=="number"?e[n]=Math.max(r,s):delete e[n]}function je(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};if(t.type==="array"&&(t.items=je(t.items&&typeof t.items=="object"?t.items:{type:"string"})),t.properties&&typeof t.properties=="object"&&!Array.isArray(t.properties)&&(t.properties=Object.fromEntries(Object.entries(t.properties).map(([o,n])=>[o,je(n)]))),t.propertyNames&&typeof t.propertyNames=="object"&&!Array.isArray(t.propertyNames)){const o=t.propertyNames;o.type==="string"&&Object.keys(o).length===1?delete t.propertyNames:t.propertyNames=je(o)}return t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=je(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(o=>je(o))),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(o=>je(o))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(o=>je(o))),t}function Xs(e){return je(e)}function xp(e){return Yn(e).filter(t=>t!=="action")}function Oo(e,t){const o=new Set(xp(e));return Object.entries(io(e)).flatMap(([n,r])=>n==="action"||!r||typeof r!="object"||Array.isArray(r)?[]:t===!0&&!o.has(n)?[]:t===!1&&o.has(n)?[]:[n])}function zr(e,t){const o=typeof t.description=="string"?t.description:"",n=Array.isArray(t.enum)?t.enum:[];if(n.length>0)return n[0];switch(e){case"notebook":return"20210808180117-czj9bvb";case"deckID":return"20230218211946-2kw8jgx";case"cardID":return"20240318112233-card01";case"rootID":return"20240318112233-root01";case"id":case"parentID":case"previousID":case"nextID":case"fromID":case"toID":return"20240318112233-abc123";case"fromIDs":return["20240318112233-a","20240318112233-b"];case"fromPaths":return["/20240318112233-a.sy","/20240318112233-b.sy"];case"toNotebook":return"20210808180117-czj9bvb";case"toPath":return"/20240318112233-existing-parent.sy";case"path":return o.includes("Human-readable")?"/Inbox/Weekly Note":"/20240318112233-abc123.sy";case"paths":return["/assets/example.png"];case"title":return"Weekly Notes";case"name":return o.includes("Export file name")?"assets-export.zip":"Research";case"markdown":return"- Seed item";case"dataType":return"markdown";case"data":return"- New item";case"template":return'codex-{{ now | date "2006" }}';case"msg":return"Hello from MCP";case"timeout":return 3e3;case"rating":return 3;case"reviewedCards":return[{cardID:"20240318112233-card01",rating:3}];case"assetsDirPath":return"/assets/";case"file":return"SGVsbG8sIFNpWXVhbg==";case"fileName":return"hello.txt";case"attrs":return{"custom-mcp":"demo"};case"conf":return{closed:!1};case"permission":return"none";case"query":return"search keyword";case"stmt":return"SELECT * FROM blocks WHERE content LIKE '%keyword%' LIMIT 20";case"k":return"todo";case"keyword":return"filter text"}if(t.type==="array"){const r=t.items&&typeof t.items=="object"?t.items:{type:"string"};return[zr(`${e}Item`,r)]}if(t.type==="object"){const r=io(t),s=Object.keys(r)[0];return s?{[s]:zr(s,r[s])}:{}}return t.type==="number"?1:t.type==="boolean"?!1:`<${e}>`}function j_(e,t){return e.filter(n=>n.action===t).map(n=>{const r=io(n.schema),s={action:t};for(const a of xp(n.schema))s[a]=zr(a,r[a]??{});return s})}function H_(e,t){var o;return((o=vg[e])==null?void 0:o[t])??[]}function V_(e){return e.length>0?e.join(", "):"no additional fields"}function Z_(e){const t=new Map;for(const o of e){const n=V_(Oo(o.schema,!0)),r=t.get(o.action)??[];r.includes(n)||r.push(n),t.set(o.action,r)}return[...t.entries()].map(([o,n])=>`${o}: ${n.join(" | ")}`).join("; ")}function Y_(e,t){const o=new Set;return t.flatMap(n=>{if(o.has(n.action))return[];o.add(n.action);const r=Oo(n.schema,!0),s=Oo(n.schema,!1);return[`${e}.${n.action}: required ${r.length>0?`[${r.join(", ")}]`:"[]"} | optional ${s.length>0?`[${s.join(", ")}]`:"[]"}`]}).join(`
471
+ `)}function W_(e,t,o){var c;const n={basic:[],advanced:[]};for(const l of t)n[Ao(e,l)].push(l);const r={},s={},a=new Set;for(const l of o){if(a.has(l.action))continue;a.add(l.action);const u=(c=Eo[e])==null?void 0:c[l.action],p=Oo(l.schema,!0);r[l.action]=u??(p.length>0?`requires: ${p.join(", ")}`:"no extra fields"),s[l.action]={...u?{hint:u}:{},requiresConfirmation:Bt(e,l.action)}}const i=t.filter(l=>Bt(e,l));return{tool:e,commonActions:n.basic,advancedActions:n.advanced,guidance:gl[e]??[],actions:s,actionSummaries:r,...i.length>0?{requiresConfirmation:i}:{},detailsHint:`Call ${e}(action="help", topic="<actionName>") for required fields, shapes, and a minimal example.`,helpResources:[`siyuan://help/action/${e}/{action}`,"siyuan://help/tool-overview","siyuan://help/examples","siyuan://help/ai-layout-guide"]}}function G_(e,t,o){var c;const n=o.filter(l=>l.action===t),r=n.map(l=>Oo(l.schema,!0)),s=j_(n,t),a=H_(e,t),i=s.length===1?s[0]:s;return{tool:e,action:t,...(c=Eo[e])!=null&&c[t]?{hint:Eo[e][t]}:{},shapes:r.map(l=>l.length>0?l.join(" + "):"action only"),requiredFields:r.length===1?r[0]:r,example:i,...a.length>0?{examples:a}:{},guidance:gl[e]??[],requiresConfirmation:Bt(e,t),fullDocResource:`siyuan://help/action/${e}/${t}`}}const K_="x-sisyphus-actionSchemas";function S(e,t,o){const n=ct(Hw(t));return delete n.$schema,o&&!n.description&&(n.description=o),{action:e,schema:Xs(n)}}function ct(e){const t={...e};if(t.properties&&typeof t.properties=="object"&&!Array.isArray(t.properties)&&(t.properties=Object.fromEntries(Object.entries(t.properties).map(([i,c])=>[i,c&&typeof c=="object"&&!Array.isArray(c)?ct(c):c]))),t.items&&typeof t.items=="object"&&!Array.isArray(t.items)&&(t.items=ct(t.items)),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=ct(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?ct(i):i)),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?ct(i):i)),!Array.isArray(t.allOf))return t;const o={},n=new Set,r=[];for(const i of t.allOf){if(!i||typeof i!="object"||Array.isArray(i))return e;const c=ct(i);if(c.type!=="object")return e;Object.assign(o,io(c));for(const l of Yn(c))n.add(l);r.push(c)}const{allOf:s,...a}=t;return{...a,type:"object",properties:o,required:[...n],additionalProperties:r.every(i=>i.additionalProperties===!1)?!1:t.additionalProperties}}function J_(e){const t={action:{type:"string",const:e.action,description:"Action to perform"},...io(e.schema)};return Xs({...e.schema,type:"object",additionalProperties:!1,properties:t,required:Array.from(new Set(["action",...Yn(e.schema)]))})}function Q_(e){const t={...e};return delete t.const,delete t.required,t}function X_(e){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,o&&typeof o=="object"&&!Array.isArray(o)?Q_(o):{}]))}function ev(e){return{type:"object",additionalProperties:!1,properties:{action:{type:"string",const:"help",description:"Show help for this tool or one action."},topic:{type:"string",enum:["overview",...e],description:'Optional action name to inspect; omit or use "overview" for the action index.'}},required:["action"]}}function tv(e,t,o){const n=[],r=o.guidanceInlineLimit??2,s=o.guidance??[];n.push(...s.slice(0,r));const a=t.filter(i=>Bt(e,i));return a.length>0&&n.push(`Requires user confirmation before: ${a.join(", ")}.`),n}function Op(e){return e.map(t=>typeof t=="number"?`[${t}]`:String(t)).join(".").replace(/\.\[/g,"[")}function ov(e,t){let o=e;for(const n of t){if(o==null)return;if(typeof n=="number"){if(!Array.isArray(o))return;o=o[n];continue}if(typeof o!="object")return;o=o[String(n)]}return o}function nv(e,t){const o=Op(e.path),n=o?ov(t,e.path):void 0;return e.code==="invalid_type"?n===void 0&&o?`${o} is required.`:o?`${o} has an invalid type.`:"Invalid input type.":e.code==="unrecognized_keys"&&"keys"in e&&Array.isArray(e.keys)?`Unexpected field(s): ${e.keys.join(", ")}.`:e.message&&e.message!=="Invalid input"?e.message:o?`Invalid value for ${o}.`:"Invalid input."}function rv(e,t){return e.issues.map(o=>({path:Op(o.path),message:nv(o,t)}))}function sv(e,t){return e&&t?`Invalid arguments for ${e}(action="${t}").`:e?`Invalid arguments for tool "${e}".`:"Invalid arguments."}function gr(e){return(e==null?void 0:e.hint)??Ig(e==null?void 0:e.tool,e==null?void 0:e.action)}function Ht(e,t=!0){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:t}}function av(e){return e.name==="SiYuanError"||e.message.startsWith("SiYuan API error:")||e.message.startsWith("HTTP error:")||e.message.startsWith("Request timeout")}function iv(){return process.env.SIYUAN_MCP_DEBUG_ERRORS==="1"}function cv(e,t,o,n,r){const s=o.filter(f=>Ao(e,f)==="basic"),a=o.filter(f=>Ao(e,f)==="advanced"),i=n.filter(f=>s.includes(f.action)),c=Z_(i),l=[`${t} Use the "action" field to select the operation.`];s.length>0&&l.push(`Common actions: ${s.join(", ")}. Required fields: ${c}.`),a.length>0&&l.push(`Additional actions: ${a.join(", ")}. Read siyuan://help/action/${e}/{action} for details, or call action="help" if resources are unavailable.`);const u=Y_(e,n);u.length>0&&l.push(`Parameter contract per action (fields outside the action's optional list should not be sent):
472
+ ${u}`);const p=tv(e,o,r);return p.length>0&&l.push(p.join(" ")),l.join(`
467
473
 
468
- `)}function av(e,t,o,n,r={}){if(!o.enabled)return[];const s=To(o),a=new Set(s),i=n.filter(h=>a.has(h.action));if(i.length===0)return[];const c=sv(e,t,s,i,r),l=s.filter(h=>Bt(e,h)),u=F_(i,r.propertyDescriptionOverrides);"topic"in u||(u.topic={type:"string",description:'Optional. Only used when action="help". Pass an action name (e.g. "create") to get per-action help; omit or use "overview" for the action index.'});const p=[...i.map(h=>W_(h)),J_(s)],f=Js({type:"object",properties:{action:{type:"string",enum:[...s,"help"],description:`Action to perform. Supported values: ${s.join(", ")}. Use action="help" for the action index, or action="help" with topic="<actionName>" for per-action details.${l.length>0?` User confirmation is required before calling: ${l.join(", ")}.`:""}`},...K_(u)},additionalProperties:!0});return Object.defineProperty(f,Y_,{value:p,enumerable:!1}),[{name:e,description:c,inputSchema:f}]}function iv(e,t,o,n){if(t.action!=="help")return null;const r=To(o),s=new Set(r),a=n.filter(l=>s.has(l.action)),i=typeof t.topic=="string"?t.topic.trim():"",c=i&&i!=="overview"?i:null;return c?s.has(c)?k(Z_(e,c,a)):jt({error:{type:"unknown_help_topic",message:`Unknown help topic "${c}" for tool "${e}".`,tool:e,topic:c,validTopics:[...r],hint:`Call ${e}(action="help") without topic to see the action index.`}}):k(V_(e,r,a))}function Qs(e,t,o){return e.length<=t?{items:e}:{items:e.slice(0,t),meta:{truncated:!0,showing:t,total:e.length,hint:o}}}function Xs(e,t,o){const n=e.length,r=Math.max(1,Math.ceil(n/o)),s=Math.min(t,r),a=(s-1)*o,i=e.slice(a,a+o);return{items:i,total:n,page:s,pageSize:o,pageCount:r,showing:i.length,truncated:r>1,hasNextPage:s<r}}function We(e,t,o){const n={data:e,total:t.total,page:t.page,pageSize:t.pageSize,pageCount:t.pageCount,hasNextPage:t.hasNextPage??t.page<t.pageCount,...o??{}};return k(n)}function k(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function ea(e,t=!1){return e==="notebook"?t?'Use notebook(action="set_icon") later if you want to change the notebook icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.':'After creation, call notebook(action="set_icon") to set the notebook icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.':t?'Use document(action="set_attr", attrs={ icon }) later if you want to change the document icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.':'After creation, call document(action="set_attr", attrs={ icon }) to set the document icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.'}function xe(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?k({success:!0,...t,...e}):k({success:!0,...e})}function bo(e,t){if(e instanceof Gw){const i=tv(e,t==null?void 0:t.rawArgs),c={error:{type:"validation_error",message:ov(t==null?void 0:t.tool,t==null?void 0:t.action),...t!=null&&t.tool?{tool:t.tool}:{},...t!=null&&t.action?{action:t.action}:{},...i.length>0?{fields:i}:{},...dr(t)?{hint:dr(t)}:{}}};return jt(c)}const o=e instanceof Error?e:new Error(String(e)),n=Gs(o),r=dr(t),s=n&&r?`${n.hint} ${r}`:(n==null?void 0:n.hint)??r,a={error:{type:nv(o)?"api_error":"internal_error",...n?{code:n.code}:{},message:o.message,...t!=null&&t.tool?{tool:t.tool}:{},...t!=null&&t.action?{action:t.action}:{},...s?{hint:s}:{},...rv()&&o.stack?{details:o.stack}:{}}};return jt(a)}function ta(e,t,o){return jt({error:{type:"permission_denied",message:`Notebook "${e}" has permission "${t}", ${o} access is required. Use notebook(action="set_permission") to change.`,notebook:e,current_permission:t,required_permission:o}})}function cv(e,t){return jt({error:{type:"action_disabled",message:`Action "${t}" is disabled for tool "${e}".`,tool:e,action:t,hint:"Enable the action in Settings -> Plugins -> SiYuan MCP sisyphus, or call listTools() again to inspect the currently enabled actions."}})}function lv(e,t,o){return jt({error:{type:"unknown_action",message:`Unknown action "${t}" for tool "${e}".`,tool:e,action:t,validActions:[...o,"help"],hint:`Call ${e}(action="help") to inspect available actions and parameter shapes.`}})}function De(e){const{name:t,description:o,variants:n,handlers:r,actionSchema:s,aggregateOptions:a}=e;return{listTools(i){return av(t,o,i,n,a)},async callTool(i,c,l,u){const p=c??{},f=typeof p.action=="string"?p.action:void 0,h=f?ro(t,f):void 0;let g;try{g=N_(t,h&&h!==f?{...p,action:h}:p)}catch(_){return bo(_,{tool:t,action:h??f,rawArgs:p})}const b=iv(t,g,l,n);if(b)return b;try{const _=n.map(D=>D.action).filter(D=>l.actions[D]);if(f&&!n.some(D=>D.action===h))return lv(t,f,_);const w=s.parse(g.action);if(!l.enabled||!l.actions[w])return cv(t,w);const P=r[w];return P?await P({client:i,rawArgs:g,permMgr:u}):bo(new Error(`No handler registered for action "${w}" on tool "${t}".`),{tool:t,action:w,rawArgs:g})}catch(_){return bo(_,{tool:t,action:h??f,rawArgs:g})}}}}async function oa(e,t){return e.request("/api/av/getAttributeView",{id:t})}async function uv(e,t){return e.request("/api/av/renderAttributeView",t)}async function dv(e,t){return e.request("/api/av/getAttributeViewKeys",{id:t})}async function pv(e,t){return e.request("/api/av/getAttributeViewFilterSort",{...t,blockID:t.blockID??""})}async function fv(e,t,o){return e.request("/api/av/searchAttributeView",{keyword:t,excludes:o})}async function hv(e,t){return e.request("/api/av/duplicateAttributeViewBlock",{avID:t})}async function xp(e,t){return e.request("/api/lute/spinBlockDOM",{dom:t})}async function mv(e,t){return e.request("/api/av/getMirrorDatabaseBlocks",{avID:t})}async function Op(e,t){return e.request("/api/av/getAttributeViewPrimaryKeyValues",t)}async function gv(e,t,o,n,r,s){const a=typeof t=="object"?t:{dataType:t,data:o??"",nextID:n,previousID:r,parentID:s};return e.request("/api/block/insertBlock",a)}async function yv(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/prependBlock",r)}async function Np(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/appendBlock",r)}async function na(e,t,o,n){const r={dataType:t,data:o,id:n};return e.request("/api/block/updateBlock",r)}async function $p(e,t){const o={id:t};return e.request("/api/block/deleteBlock",o)}async function bv(e,t,o,n){const r={id:t,previousID:o,parentID:n};return e.request("/api/block/moveBlock",r)}async function wv(e,t){const o={id:t};return e.request("/api/block/foldBlock",o)}async function kv(e,t){const o={id:t};return e.request("/api/block/unfoldBlock",o)}async function io(e,t){const o={id:t};return e.request("/api/block/getBlockKramdown",o)}async function jn(e,t){const o={id:t};return e.request("/api/block/getChildBlocks",o)}async function Et(e,t){const o={id:t};return e.request("/api/block/getDocInfo",o)}async function _v(e,t,o,n){const r={fromID:t,toID:o,refIDs:n};return e.request("/api/block/transferBlockRef",r)}async function Mp(e,t){return e.request("/api/block/getBlockInfo",{id:t})}async function vv(e,t,o){return e.request("/api/block/getBlockBreadcrumb",{id:t,excludeTypes:o})}async function Hn(e,t){return e.request("/api/block/getBlockDOM",{id:t})}async function Iv(e){return e.request("/api/block/getRecentUpdatedBlocks",{})}async function Sv(e,t){return e.request("/api/block/getBlocksWordCount",{ids:t})}async function Dv(e,t){return e.request("/api/block/batchInsertBlock",{blocks:t})}async function Av(e,t){return e.request("/api/block/batchUpdateBlock",{blocks:t})}async function Tv(e,t,o,n){return e.request("/api/block/appendDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function Pv(e,t,o,n){return e.request("/api/block/prependDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function Ev(e,t,o=!1,n=!1){return e.request("/api/block/getDocsInfo",{ids:t,refCount:o,av:n})}async function zp(e,t){const o={id:t};return e.request("/api/attr/getBlockAttrs",o)}async function Cv(e,t){return e.request("/api/search/fullTextSearchBlock",t)}async function st(e,t){const o={stmt:t},n=await e.request("/api/query/sql",o);return Array.isArray(n)?n:[]}async function Rv(e,t){const o={k:t};return e.request("/api/search/searchTag",o)}async function xv(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBacklinkDoc",r)}async function Ov(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBackmentionDoc",r)}async function Nv(e,t){return e.request("/api/search/searchRefBlock",{reqId:t.reqId,id:t.id,rootID:t.rootID??"",k:t.k??"",beforeLen:t.beforeLen??512,isSquareBrackets:t.isSquareBrackets??!1,isDatabase:t.isDatabase??!1})}async function $v(e,t){return e.request("/api/search/findReplace",t)}async function Mv(e,t,o){return e.request("/api/search/searchAsset",{k:t,exts:o})}async function zv(e,t,o,n=0){return e.request("/api/search/getAssetContent",{id:t,query:o,queryMethod:n})}async function Fv(e,t){return e.request("/api/search/fullTextSearchAssetContent",t)}async function qv(e,t,o){return e.request("/api/search/listInvalidBlockRefs",{page:t,pageSize:o})}async function Oe(e,t,o={}){return e.request("/api/transactions",{transactions:t,reqId:o.reqId??Date.now(),app:o.app??"",session:o.session??""})}async function Fp(e,t,o,n){return e.request("/api/filetree/createDocWithMd",{notebook:t,path:o,markdown:n})}async function Bv(e,t,o,n){return e.request("/api/filetree/renameDoc",{notebook:t,path:o,title:n})}async function qp(e,t,o){return e.request("/api/filetree/renameDocByID",{id:t,title:o})}async function Lv(e,t,o){return e.request("/api/filetree/removeDoc",{notebook:t,path:o})}async function Nr(e,t){return e.request("/api/filetree/removeDocByID",{id:t})}async function Uv(e,t,o,n){return e.request("/api/filetree/moveDocs",{fromPaths:t,toNotebook:o,toPath:n})}async function Bp(e,t,o){return e.request("/api/filetree/moveDocsByID",{fromIDs:t,toID:o})}async function ra(e,t,o){return e.request("/api/filetree/getHPathByPath",{notebook:t,path:o})}async function Vn(e,t){return e.request("/api/filetree/getHPathByID",{id:t})}async function wo(e,t){return e.request("/api/filetree/getPathByID",{id:t})}async function Lp(e,t,o){return e.request("/api/filetree/getIDsByHPath",{path:t,notebook:o})}async function jv(e,t,o){return e.request("/api/filetree/listDocsByPath",{notebook:t,path:o})}async function Nt(e,t,o){return e.request("/api/filetree/listDocTree",{notebook:t,path:o})}async function Hv(e,t,o,n){return e.request("/api/filetree/searchDocs",{k:t,flashcard:o,excludeIDs:n})}async function Vv(e,t,o,n){return e.request("/api/filetree/getDoc",{id:t,mode:o,size:n})}async function Zv(e,t,o){return e.request("/api/filetree/createDailyNote",{notebook:t,app:o})}async function Yv(e,t){return e.request("/api/filetree/duplicateDoc",{id:t})}async function Wv(e,t){return e.request("/api/filetree/removeDocs",{paths:t})}async function Gv(e,t,o,n,r){return e.request("/api/filetree/heading2Doc",{srcHeadingID:t,targetNoteBook:o,targetPath:n,previousPath:r})}async function Kv(e,t,o,n=!1){return e.request("/api/filetree/doc2Heading",{srcID:t,targetID:o,after:n})}async function at(e){return e.request("/api/notebook/lsNotebooks")}async function Jv(e,t){return e.request("/api/notebook/openNotebook",{notebook:t})}async function Qv(e,t){return e.request("/api/notebook/closeNotebook",{notebook:t})}async function Xv(e,t){return e.request("/api/notebook/createNotebook",{name:t})}async function eI(e,t){return e.request("/api/notebook/removeNotebook",{notebook:t})}async function tI(e,t,o){return e.request("/api/notebook/renameNotebook",{notebook:t,name:o})}async function oI(e,t){return e.request("/api/notebook/getNotebookConf",{notebook:t})}async function nI(e,t,o){return e.request("/api/notebook/setNotebookConf",{notebook:t,conf:o})}async function Up(e,t,o){return e.request("/api/notebook/setNotebookIcon",{notebook:t,icon:o})}function rI(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Ge(e){return e.startsWith("/")?e:`/${e}`}function sI(e){const t=Ge(e).split("/").filter(Boolean).at(-1)??"";return t.endsWith(".sy")?t.slice(0,-3):t}function we(e){return e.replace(/\0/g,"").replace(/'/g,"''")}async function aI(e,t){const o=await st(e,`SELECT id, root_id, box, path, hpath, content, type FROM blocks WHERE id = '${we(t)}' LIMIT 1`),n=Array.isArray(o)&&o.length>0&&o[0]&&typeof o[0]=="object"?o[0]:null;if(!n)return null;const r=typeof n.box=="string"&&n.box.length>0?n.box:null,s=typeof n.path=="string"&&n.path.length>0?n.path:null;if(!r||!s)return null;const a=typeof n.root_id=="string"&&n.root_id.length>0?n.root_id:typeof n.id=="string"&&n.id.length>0?n.id:t,i=typeof n.hpath=="string"&&n.hpath.length>0?n.hpath:void 0,c=typeof n.content=="string"&&n.content.length>0?n.content:void 0;return{documentId:a,notebook:r,path:Ge(s),hPath:i,name:c}}async function dt(e,t){try{const s=await aI(e,t);if(s)return s}catch{}const o=await Et(e,t),n=o.rootID||o.id,r=await wo(e,n);return{documentId:n,notebook:r.notebook,path:Ge(r.path),name:o.name}}const iI=500;function jp(e,t,o){if(e.size>=iI){const n=e.keys().next().value;n!==void 0&&e.delete(n)}e.set(t,o)}function Lo(){return{documentContextById:new Map,notebookByPath:new Map}}async function cI(e,t,o){if(!o)return dt(e,t);let n=o.documentContextById.get(t);return n||(n=dt(e,t),jp(o.documentContextById,t,n)),n}async function lI(e,t,o){const n=Ge(t);if(!o)return xo(e,n);let r=o.notebookByPath.get(n);return r||(r=xo(e,n),jp(o.notebookByPath,n,r)),r}async function Uo(e,t,o){if(!t||typeof t!="object")return null;const n=t,r=[n.notebook,n.box,n.boxID,n.notebookId].find(i=>typeof i=="string"&&i.length>0),s=[n.path].find(i=>typeof i=="string"&&i.length>0),a=[n.blockID,n.blockId,n.rootID,n.rootId,n.root_id,n.docID,n.docId,n.id].find(i=>typeof i=="string"&&i.length>0);if(r&&s)return{notebook:r,path:Ge(s),documentId:a};if(a)try{const i=await cI(e,a,o);return{notebook:i.notebook,path:i.path,documentId:i.documentId}}catch{}if(s){const i=await lI(e,s,o);if(i)return{notebook:r??i,path:Ge(s),documentId:a}}return r?{notebook:r,path:s?Ge(s):void 0,documentId:a}:null}async function uI(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t.notebook):o==="write"?e.canWrite(t.notebook):e.canRead(t.notebook))?null:ta(t.notebook,e.get(t.notebook),o)}async function N(e,t,o,n){const r=await dt(e,o),s=await uI(t,r,n);return{context:r,denied:s}}async function Y(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t))?null:ta(t,e.get(t),o)}async function dI(e,t){const n=(await at(e)).notebooks.find(s=>s.id===t);return n?n.id:(await dt(e,t)).notebook}async function xo(e,t){const o=await at(e);for(const n of o.notebooks)try{return await ra(e,n.id,t),n.id}catch{continue}return null}async function Zn(e,t,o){const n=await jv(e,t,o);return n.files.map(r=>({id:typeof r.id=="string"&&r.id.length>0?r.id:sI(r.path),notebook:r.box||n.box||t,path:Ge(r.path),hPath:r.hPath,name:rI(r.name),icon:r.icon,subFileCount:r.subFileCount??r.count}))}async function pI(e){return e.request("/api/system/getWorkspaceInfo",{})}async function fI(e){return e.request("/api/system/getNetwork",{})}async function hI(e){return e.request("/api/system/getConf",{})}async function mI(e){return e.request("/api/sync/performSync",{})}async function gI(e){return e.request("/api/system/version")}async function yI(e){return e.request("/api/system/currentTime")}async function bI(e){return e.request("/api/ui/reloadIcon",{})}async function wI(e){return e.request("/api/ui/reloadFiletree",{})}async function kI(e,t){return e.request("/api/ui/reloadProtyle",{id:t})}async function _I(e,t){return e.request("/api/ui/reloadAttributeView",{id:t})}async function vI(e){return e.request("/api/ui/reloadTag",{})}function II(e){const t=e.content[0];if(!t||t.type!=="text")return null;try{const o=JSON.parse(t.text);return o&&typeof o=="object"&&!Array.isArray(o)?o:null}catch{return null}}function SI(e){const t=new Set,o=[];for(const n of e){const r=`${n.type}:${"id"in n?n.id:""}`;t.has(r)||(t.add(r),o.push(n))}return o}async function DI(e,t){switch(t.type){case"reloadProtyle":await kI(e,t.id);return;case"reloadAttributeView":await _I(e,t.id);return;case"reloadIcon":await bI(e);return;case"reloadFiletree":await wI(e);return;case"reloadTag":await vI(e);return;default:{const o=t;throw new Error(`Unknown UI refresh operation: ${String(o)}`)}}}async function F(e,t,o){if(t.isError||o.length===0||!e||typeof e.request!="function")return t;const n=II(t);if(!n)return t;const r=SI(o),s=[];for(const a of r)try{await DI(e,a)}catch(i){s.push({type:a.type,..."id"in a?{id:a.id}:{},message:i instanceof Error?i.message:String(i)})}return n.uiRefresh={applied:!0,operations:r.map(a=>({type:a.type,..."id"in a?{id:a.id}:{}})),...s.length>0?{partialFailure:s}:{}},{...t,content:[{type:"text",text:JSON.stringify(n,null,2)}]}}function jo(e){return new Promise(t=>{setTimeout(t,e)})}const $t="av";function Mt(e=new Date){const t=(s,a=2)=>String(s).padStart(a,"0"),o=[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),t(e.getHours()),t(e.getMinutes()),t(e.getSeconds())].join(""),n="abcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let s=0;s<7;s+=1)r+=n[Math.floor(Math.random()*n.length)];return`${o}-${r}`}const Ti=6,AI=500,Pi=6,TI=300,PI="/data/storage/av",EI=/^\d{14}-[a-z0-9]{7}$/;function CI(e){var o,n;if(!e||typeof e!="object")return;const t=e.keyValues;if(Array.isArray(t))for(const r of t){if(!r||typeof r!="object")continue;const s=r;if(((o=s.key)==null?void 0:o.type)!=="block"||!Array.isArray(s.values))continue;const a=s.values.find(i=>{var c;return typeof((c=i==null?void 0:i.block)==null?void 0:c.id)=="string"&&i.block.id.length>0});if((n=a==null?void 0:a.block)!=null&&n.id)return a.block.id}}function RI(e){if(!e||typeof e!="object")return[];const t=e.keyValues;return Array.isArray(t)?t.map(o=>o&&typeof o=="object"?o.key:void 0).filter(o=>!!(o&&typeof o=="object")):[]}function sa(e,t){if(!e||typeof e!="object")return;const o=e;for(const n of t){const r=o[n];if(typeof r=="string"&&r.length>0)return r}}function Hp(e,t){let o=e;for(const n of t){if(!o||typeof o!="object")return;o=o[n]}return typeof o=="string"&&o.length>0?o:void 0}function xI(e){return sa(e,["blockID","itemId","itemID","rowID"])??Hp(e,["block","blockID"])}function OI(e){return Hp(e,["block","id"])??sa(e,["srcID","srcId"])}function NI(e){return sa(e,["id"])}function aa(e){const t=new Map,o=[];if(!e||typeof e!="object")return{rows:[],rowIDs:new Set,sourceBlockToRowIDs:new Map,valueIdToRowIDs:new Map};const n=e.keyValues;if(!Array.isArray(n))return{rows:[],rowIDs:new Set,sourceBlockToRowIDs:new Map,valueIdToRowIDs:new Map};for(const c of n){if(!c||typeof c!="object")continue;const l=c,u=l.values;Array.isArray(u)&&u.forEach(p=>{var _;const f=xI(p);if(!f)return;let h=t.get(f);h||(h={rowID:f,valueIDs:[]},t.set(f,h),o.push(h));const g=NI(p),b=((_=l.key)==null?void 0:_.type)==="block"?OI(p):void 0;b&&(h.sourceBlockID=b),g&&!h.valueIDs.includes(g)&&h.valueIDs.push(g)})}const r=o.filter(c=>c.rowID||c.sourceBlockID||c.valueIDs.length>0),s=new Set,a=new Map,i=new Map;for(const c of r){if(c.rowID&&s.add(c.rowID),c.sourceBlockID&&c.rowID){const l=a.get(c.sourceBlockID)??[];l.includes(c.rowID)||(l.push(c.rowID),a.set(c.sourceBlockID,l))}if(c.rowID)for(const l of c.valueIDs){const u=i.get(l)??[];u.includes(c.rowID)||(u.push(c.rowID),i.set(l,u))}}return{rows:r,rowIDs:s,sourceBlockToRowIDs:a,valueIdToRowIDs:i}}function lo(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:$t,action:e,...t}},null,2)}],isError:!0}}function $I(e,t,o,n=[]){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:$t,action:"add_rows",reason:"row_id_sync_timeout",message:`Added rows to attribute view "${e}", but MCP could not observe writable row item IDs before the sync timeout expired.`,avID:e,...t.length>0?{blockIDs:t}:{},...n.length>0?{primaryKeyTexts:n}:{},rows:o.rows,...o.unresolvedBlockIDs.length>0?{unresolvedBlockIDs:o.unresolvedBlockIDs}:{},...o.unresolvedRowIDs&&o.unresolvedRowIDs.length>0?{unresolvedRowIDs:o.unresolvedRowIDs}:{},hint:'Retry av(action="add_rows") or wait briefly and re-read the database. Only call set_cells after add_rows returns rows[].rowID.'}},null,2)}],isError:!0}}function MI(e,t){const o=t.map(r=>{const s=e.sourceBlockToRowIDs.get(r)??[];return s.length===1?{blockID:r,rowID:s[0]}:s.length>1?{blockID:r,rowIDs:s,status:"ambiguous"}:{blockID:r,status:"missing"}}),n=o.filter(r=>!("rowID"in r)).map(r=>r.blockID);return{rows:o,unresolvedBlockIDs:n}}function zI(e,t){const o=t.map(r=>e.rowIDs.has(r.rowID)?r:{...r,status:"missing"}),n=o.filter(r=>"status"in r&&r.status==="missing").map(r=>r.rowID);return{rows:o,unresolvedBlockIDs:[],unresolvedRowIDs:n}}async function FI(e,t,o,n=[]){let r={rows:[...o.map(s=>({blockID:s})),...n],unresolvedBlockIDs:[...o],unresolvedRowIDs:n.map(s=>s.rowID)};for(let s=0;s<Ti;s+=1){const a=await oa(e,t),i=aa(a.av),c=MI(i,o),l=zI(i,n);if(r={rows:[...c.rows,...l.rows],unresolvedBlockIDs:c.unresolvedBlockIDs,unresolvedRowIDs:l.unresolvedRowIDs},r.unresolvedBlockIDs.length===0&&(!r.unresolvedRowIDs||r.unresolvedRowIDs.length===0))return r;s<Ti-1&&await jo(AI)}return r}function qI(e,t,o,n,r){if(o.rowIDs.has(n))return{ok:!0,rowID:n};const s=o.valueIdToRowIDs.get(n);if(s&&s.length===1)return{ok:!1,result:lo(t,{reason:"row_id_alias_detected",message:`rowID "${n}" is a cell value ID in attribute view "${e}", not the database row item ID.`,avID:e,rowID:n,detectedValueID:n,suggestedRowID:s[0],...r===void 0?{}:{itemIndex:r},hint:'Use the AV row item ID stored in each value.blockID, or the rowID returned by av(action="add_rows"). Do not reuse value.id from set_cells responses as rowID.'})};if(s&&s.length>1)return{ok:!1,result:lo(t,{reason:"row_id_alias_ambiguous",message:`rowID "${n}" matches multiple cell value records in attribute view "${e}". Pass a concrete row item ID instead.`,avID:e,rowID:n,detectedValueID:n,candidateRowIDs:s,...r===void 0?{}:{itemIndex:r},hint:"Use the row item ID stored in value.blockID, not value.id."})};const a=o.sourceBlockToRowIDs.get(n);return a&&a.length===1?{ok:!1,result:lo(t,{reason:"row_id_required",message:`rowID "${n}" is a source block ID in attribute view "${e}". Use the row item ID instead.`,avID:e,rowID:n,detectedSourceBlockID:n,suggestedRowID:a[0],...r===void 0?{}:{itemIndex:r},hint:'Use the row item ID stored in value.blockID, or the rowID returned by av(action="add_rows"). The source block ID lives in block.id and is not writable as rowID.'})}:a&&a.length>1?{ok:!1,result:lo(t,{reason:"row_id_ambiguous",message:`rowID "${n}" matches multiple rows in attribute view "${e}". Pass a concrete row item ID instead of the source block ID.`,avID:e,rowID:n,detectedSourceBlockID:n,candidateRowIDs:a,...r===void 0?{}:{itemIndex:r},hint:'Use the exact row item ID returned by av(action="add_rows"), or inspect the AV payload to choose the intended row binding.'})}:{ok:!1,result:lo(t,{reason:"row_id_not_canonical",message:`rowID "${n}" is not a valid database row item ID in attribute view "${e}". Pass the canonical row item ID stored in value.blockID.`,avID:e,rowID:n,...r===void 0?{}:{itemIndex:r},hint:'Use the rowID returned by av(action="add_rows"), or inspect the block column in av(action="get"): value.blockID is the writable row item ID, while value.id is only the cell value ID.'})}}async function BI(e,t){const o=CI(t);return{avData:t,blockID:o}}function LI(e){const t=[];for(const o of e.refDefs??[]){const n=typeof(o==null?void 0:o.refID)=="string"&&o.refID.length>0?o.refID:void 0;n&&!t.includes(n)&&t.push(n)}return t}async function Vp(e,t){try{return LI(await mv(e,t))}catch(o){if(Ks(o))return[];throw o}}async function UI(e,t){const o=we(t),n=await st(e,`SELECT id FROM blocks WHERE type = 'av' AND (markdown LIKE '%${o}%' OR ial LIKE '%${o}%' OR content LIKE '%${o}%') ORDER BY updated DESC LIMIT 20`),r=[];for(const s of n){const a=s&&typeof s=="object"?s.id:void 0;typeof a=="string"&&a.length>0&&!r.includes(a)&&r.push(a)}return r}async function ia(e,t,o){const n=[],r=await BI(e,o);r.blockID&&n.push(r.blockID);const s=await Vp(e,t);for(const i of s)n.includes(i)||n.push(i);const a=await UI(e,t);for(const i of a)n.includes(i)||n.push(i);return n}async function jI(e,t,o,n){if((await ia(e,t,o)).includes(n))return!0;try{const s=await Hn(e,n),a=typeof(s==null?void 0:s.dom)=="string"?s.dom:"";return a.includes('data-type="NodeAttributeView"')&&a.includes(`data-av-id="${t}"`)}catch(s){if(Ks(s))return!1;throw s}}function HI(e,t,o){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:$t,action:e,message:`blockID "${o}" is not a database block for attribute view "${t}".`,fields:[{path:"blockID",message:`blockID "${o}" does not belong to attribute view "${t}".`}],hint:"Pass the materialized database block for this AV, or omit blockID and let MCP resolve a registered mirror block automatically."}},null,2)}],isError:!0}}async function Ie(e,t,o,n,r){const a=(await oa(e,o)).av;if(r!=null&&r.blockID){const{denied:c}=await N(e,t,r.blockID,n);return c?{denied:c,avData:a}:await jI(e,o,a,r.blockID)?{denied:null,avData:a}:{denied:HI(r.action??"get",o,r.blockID),avData:a}}const i=await ia(e,o,a);for(const c of i)try{const{denied:l}=await N(e,t,c,n);return{denied:l,avData:a}}catch(l){if(Ks(l))continue;throw l}throw i.length===0?new Error(`Unable to resolve notebook permission scope for attribute view "${o}". The database may have no rows yet; AV writes require a resolvable owning block context.`):new Error(`Unable to resolve notebook permission scope for attribute view "${o}" because all known owning block references are stale or missing.`)}function VI(e){return e instanceof Error&&e.message.includes("The database may have no rows yet; AV writes require a resolvable owning block context.")}function ZI(e){var t;return e instanceof Error&&((t=Gs(e))==null?void 0:t.code)==="av_not_found"}async function YI(e,t,o,n,r){if(o.createIfNotExist===!0){if(!o.blockID)throw new Error(`Unable to create or render attribute view "${n}" because createIfNotExist=true requires blockID to resolve notebook permission scope.`);if(r){const{denied:s,context:a}=await N(e,t,o.blockID,"write");return{denied:s,shouldMaterialize:!0,targetDocumentId:a.documentId}}try{const{denied:s}=await Ie(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){if(!(VI(s)||ZI(s)))throw s;const{denied:i,context:c}=await N(e,t,o.blockID,"write");return{denied:i,shouldMaterialize:!0,targetDocumentId:c.documentId}}}if(!o.id)throw new Error('av(action="render") requires id unless createIfNotExist=true is provided.');try{const{denied:s}=await Ie(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){throw s}}async function ca(e,t,o){const n=o??(await oa(e,t)).av;return(await ia(e,t,n))[0]}async function Ht(e,t,o,n){const r=[];n&&r.push(n);try{const s=await ca(e,t,o);s&&!r.includes(s)&&r.push(s)}catch{}for(const s of r)try{const a=await dt(e,s);if(a.documentId)return[{type:"reloadProtyle",id:a.documentId}]}catch{}return[{type:"reloadAttributeView",id:t}]}async function WI(e,t,o){const n=Lo();await t.reload();const r=[],s=[];let a=0,i=0,c=0;for(const l of o){const u=await Uo(e,l,n);if(!(u!=null&&u.notebook)){a+=1,i+=1,s.push(l);continue}if(!t.canRead(u.notebook)){a+=1,c+=1;continue}r.push(l)}return{results:r,unresolvedResults:s,rawResultCount:o.length,filteredOutCount:a,unresolvedCount:i,permissionFilteredOutCount:c,...a>0?{partial:!0,reason:c>0?"permission_filtered":"context_unresolved"}:{}}}async function GI(e){const t=await e.request("/api/file/readDir",{path:PI});return(Array.isArray(t)?t:[]).filter(o=>!(o!=null&&o.isDir)&&typeof(o==null?void 0:o.name)=="string"&&o.name.endsWith(".json")).map(o=>o.name.slice(0,-5)).filter(o=>EI.test(o))}function KI(e){if(!e||typeof e!="object")return[];const t=e.values;return Array.isArray(t)?t.filter(o=>!!(o&&typeof o=="object")):[]}async function JI(e,t,o){if(!t.trim())return[];if(typeof e.request!="function")return[];const n=new Set(o??[]),r=await GI(e),s=[];for(const a of r)if(!n.has(a))try{const i=await Op(e,{id:a,keyword:t,page:1,pageSize:3}),c=KI(i.rows);if(c.length===0)continue;const l=Array.isArray(i.blockIDs)?i.blockIDs.filter(u=>typeof u=="string"&&u.length>0):[];if(l.length===0)continue;s.push({avID:a,avName:i.name,blockID:l[0],blockIDs:l,rows:i.rows,matchedRowCount:c.length,matchSource:"primary_key"})}catch{}return s}function Ei(e,t){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite epoch millisecond value.`);return e}const o=Date.parse(e);if(Number.isNaN(o))throw new Error(`${t} must be a valid ISO date string or epoch milliseconds.`);return o}function Zp(e,t){return`<div class="av" data-node-id="${e}" data-av-id="${t}" data-type="NodeAttributeView" data-av-type="table"></div>`}function zt(e,t){for(const o of t){const n=e[o];if(typeof n=="string"&&n.length>0)return n}}function QI(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;for(const o of["content","text","number","isChecked","date","mSelect","select","block"])if(o in t)return t[o];return e}function XI(e){const t=[e.columns,e.keys,e.keyValues,e.attributeViewKeys];for(const o of t){if(!Array.isArray(o))continue;const n=o.flatMap(r=>{if(!r||typeof r!="object"||Array.isArray(r))return[];const s=r,a=s.key&&typeof s.key=="object"&&!Array.isArray(s.key)?s.key:s,i=zt(a,["id","keyID","columnID"]);if(!i)return[];const c=zt(a,["name","title"]),l=zt(a,["type"]);return[{id:i,...c?{name:c}:{},...l?{type:l}:{}}]});if(n.length>0)return n}return[]}function eS(e){return e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const o=t,n=Array.isArray(o.values)?o.values:Array.isArray(o.cells)?o.cells:[],r={};for(const a of n){if(!a||typeof a!="object"||Array.isArray(a))continue;const i=a,c=i.key&&typeof i.key=="object"&&!Array.isArray(i.key)?i.key:{},l=zt(i,["keyID","columnID","id"])??zt(c,["id","keyID"]);l&&(r[l]=QI(i))}if(Object.keys(r).length===0)return[];const s=zt(o,["id","rowID","blockID"]);return[{...s?{id:s}:{},cells:r}]})}function tS(e,t,o){const n=XI(e),r=eS(t);if(!(n.length===0&&r.length===0))return{columns:n,rows:r,rowCount:o}}function oS(e=new Date){const t=o=>String(o).padStart(2,"0");return[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),t(e.getHours()),t(e.getMinutes()),t(e.getSeconds())].join("")}async function Vt(e,t,o,n){return n??await ca(e,t,o)}function Zt(e,t,o){if(!t)return{doOperations:e,undoOperations:[]};const n=oS();return{doOperations:[...e,{action:"doUpdateUpdated",id:t,data:n}],undoOperations:[{action:"doUpdateUpdated",id:t,data:""}]}}function Ci(e,t,o){const n={keyID:e,blockID:t};switch(o.valueType){case"text":return{...n,type:"text",text:{content:o.text}};case"number":return{...n,type:"number",number:{content:o.number,isNotEmpty:!0,format:o.numberFormat??"",formattedContent:""}};case"date":{const r=Ei(o.date,"date"),s=o.endDate===void 0?0:Ei(o.endDate,"endDate");return{...n,type:"date",date:{content:r,isNotEmpty:!0,hasEndDate:o.endDate!==void 0,isNotTime:o.includeTime===!1,content2:s,isNotEmpty2:o.endDate!==void 0,formattedContent:""}}}case"checkbox":return{...n,type:"checkbox",checkbox:{checked:!!o.checked}};case"select":return{...n,type:"select",mSelect:[{content:o.option,color:""}]};case"multi_select":return{...n,type:"mSelect",mSelect:(o.options??[]).map(r=>({content:r,color:""}))};case"relation":return{...n,type:"relation",relation:{blockIDs:o.relationBlockIDs??[],contents:[]}};case"url":return{...n,type:"url",url:{content:o.url}};case"email":return{...n,type:"email",email:{content:o.email}};case"phone":return{...n,type:"phone",phone:{content:o.phone}};case"mAsset":{const r=(o.assets??[]).map(a=>({type:a.type,name:a.name??"",content:a.content})),s=o.text??r.map(a=>a.type==="image"?`![](${a.content})`:`[${a.name||a.content}](${a.content})`).join(`
469
- `);return{...n,type:"mAsset",text:{content:s},mAsset:r}}default:throw new Error(`Unsupported AV valueType: ${o.valueType}`)}}async function nS({client:e,permMgr:t,rawArgs:o}){const n=$d.parse(o),{denied:r,avData:s}=await Ie(e,t,n.id,"read",{blockID:n.blockID,action:"get"});if(r)return r;const a=aa(s);return k({id:n.id,av:s,...a.rows.length>0?{resolvedRows:a.rows.map(i=>({rowID:i.rowID,...i.sourceBlockID?{sourceBlockID:i.sourceBlockID}:{},...i.valueIDs.length>0?{valueIDs:i.valueIDs}:{}}))}:{}})}async function rS({client:e,permMgr:t,rawArgs:o}){const n=qd.parse(o),r=await fv(e,n.keyword,n.excludes),s=Array.isArray(r.results)?r.results:[],a=await JI(e,n.keyword,n.excludes),i=[...s],c=new Set(i.map(p=>p&&typeof p=="object"?p.avID:void 0).filter(p=>typeof p=="string"&&p.length>0));for(const p of a){const f=p.avID;typeof f=="string"&&c.has(f)||(typeof f=="string"&&c.add(f),i.push(p))}const l=await WI(e,t,i),u=l.results.map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return p;const f=p,h=typeof f.avID=="string"&&f.avID.length>0?f.avID:typeof f.id=="string"&&f.id.length>0?f.id:void 0;return h?{...f,id:h,avID:h,renderArgs:{action:"render",id:h}}:f});return k({keyword:n.keyword,searchScope:{kernel:"attribute_view_name_or_kernel_candidates",fallback:"primary_key_values"},...l,results:u,...l.filteredOutCount>0?{emptyReason:u.length===0?l.unresolvedCount>0&&l.permissionFilteredOutCount===0?"no_verified_results_unresolved_candidates_available":l.permissionFilteredOutCount>0&&l.unresolvedCount===0?"all_results_permission_filtered":"all_results_filtered":void 0,unresolvedHint:l.unresolvedResults.length>0?"unresolvedResults contains kernel search candidates that matched, but MCP could not verify notebook context yet.":void 0}:{},...n.keyword.trim().length>0&&l.results.length===0?{warning:"No verified AV matches were found. AV search primarily covers database names and primary-key values; non-primary-key cell text may not be searchable immediately after writes."}:{}})}async function sS({client:e,permMgr:t,rawArgs:o}){const n=Md.parse(o),r=new Date,s=!n.id,a=n.id??Mt(r),i=await YI(e,t,n,a,s);if(i.denied)return i.denied;const c=await uv(e,{id:a,blockID:n.blockID,viewID:n.viewID,page:n.page,pageSize:n.pageSize,query:n.query,groupPaging:n.groupPaging,createIfNotExist:n.createIfNotExist});let l,u;if(i.shouldMaterialize){l=Mt(r);let C=Zp(l,a);try{const L=await xp(e,C);typeof L.dom=="string"&&L.dom.length>0&&(C=L.dom)}catch{}await Oe(e,[{doOperations:[{action:"insert",id:l,data:C,parentID:n.blockID}],undoOperations:[{action:"delete",id:l}]}]),u=!1;for(let L=0;L<Pi;L+=1){if((await Vp(e,a)).includes(l)){u=!0;break}if(L===Pi-1)break;await jo(TI)}}const p=c&&typeof c=="object"&&!Array.isArray(c)?c:{},f=Array.isArray(p.rows)?p.rows:[],h=n.page??1,g=n.pageSize??(f.length||1),b=typeof p.pageCount=="number"?p.pageCount:1,_=typeof p.rowCount=="number"?p.rowCount:f.length,w=tS(p,f,_),{rows:P,pageCount:D,rowCount:T,...A}=p,O=We(f,{total:_,page:h,pageSize:g,pageCount:b,hasNextPage:h<b},{...A,avID:a,id:a,...w?{table:w}:{},...n.createIfNotExist===!0?{generatedAvID:s}:{},...i.shouldMaterialize?{materialized:!0,blockID:l,parentID:n.blockID,databaseBlockRegistrationVerified:u===!0,...u===!1?{warning:`Created attribute view "${a}" and materialized database block "${l}", but MCP could not verify mirror registration before the timeout. If the next AV write cannot resolve by avID yet, retry shortly or pass this blockID as explicit database-block context.`}:{}}:{}});return i.shouldMaterialize?F(e,O,[{type:"reloadAttributeView",id:a},...i.targetDocumentId?[{type:"reloadProtyle",id:i.targetDocumentId}]:[]]):O}async function aS({client:e,permMgr:t,rawArgs:o}){const n=zd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.id,"read");if(r)return r;const a=await dv(e,n.id),i=a&&typeof a=="object"&&!Array.isArray(a)&&Array.isArray(a.keys)?a.keys:Array.isArray(a)&&a.length>0?a:RI(s);return k({avID:n.id,keys:i})}async function iS({client:e,permMgr:t,rawArgs:o}){const n=Fd.parse(o),{denied:r}=await Ie(e,t,n.id,"read");if(r)return r;const s=await pv(e,{id:n.id,blockID:n.blockID??""});return k({avID:n.id,...n.blockID?{blockID:n.blockID}:{},...s})}async function cS({client:e,permMgr:t,rawArgs:o}){const n=Bd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"add_rows"});if(r)return r;const a=n.blockIDs??[],i=n.primaryKeyTexts??[];if(a.length===0&&i.length===0)return xe({action:"add_rows",avID:n.avID,blockIDs:[],primaryKeyTexts:[],rows:[],added:0,skipped:!0,message:"No blockIDs or primaryKeyTexts were provided, so no rows were added."});const c=i.map(g=>({primaryKeyText:g,rowID:Mt(),srcID:Mt()})),l=await Vt(e,n.avID,s,n.blockID),u=[...a.map(g=>({itemID:Mt(),id:g,isDetached:!1})),...c.map(g=>({itemID:g.rowID,id:g.srcID,isDetached:!0,content:g.primaryKeyText}))],p=Zt([{action:"insertAttrViewBlock",avID:n.avID,blockID:l,viewID:n.viewID,groupID:n.groupID,previousID:n.previousID,ignoreDefaultFill:n.ignoreDefaultFill,srcs:u}],l);await Oe(e,[{doOperations:p.doOperations,undoOperations:[{action:"removeAttrViewBlock",srcIDs:[...a,...c.map(g=>g.rowID)],avID:n.avID},...p.undoOperations]}]);const f=await FI(e,n.avID,a,c.map(g=>({primaryKeyText:g.primaryKeyText,rowID:g.rowID})));if(f.unresolvedBlockIDs.length>0||f.unresolvedRowIDs&&f.unresolvedRowIDs.length>0)return $I(n.avID,a,f,i);const h=await Ht(e,n.avID,s,n.blockID);return F(e,xe({action:"add_rows",avID:n.avID,...a.length>0?{blockIDs:a}:{},...i.length>0?{primaryKeyTexts:i}:{},rows:f.rows,added:a.length+i.length}),h)}async function lS({client:e,permMgr:t,rawArgs:o}){const n=Ld.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_rows"});if(r)return r;const a=await Vt(e,n.avID,s,n.blockID),i=Zt([{action:"removeAttrViewBlock",srcIDs:n.srcIDs,avID:n.avID}],a);await Oe(e,[{doOperations:i.doOperations,undoOperations:i.undoOperations}]);const c=await Ht(e,n.avID,s,n.blockID);return F(e,xe({action:"remove_rows",avID:n.avID,srcIDs:n.srcIDs,removed:n.srcIDs.length}),c)}async function uS({client:e,permMgr:t,rawArgs:o}){const n=Ud.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"add_column"});if(r)return r;const a=n.keyID??Mt(),i=await Vt(e,n.avID,s,n.blockID),c=Zt([{action:"addAttrViewCol",name:n.keyName,avID:n.avID,type:n.keyType,id:a,data:n.keyIcon??"",previousID:n.previousKeyID??""}],i);await Oe(e,[{doOperations:c.doOperations,undoOperations:[{action:"removeAttrViewCol",id:a,avID:n.avID},...c.undoOperations]}]);const l=await Ht(e,n.avID,s,n.blockID);return F(e,xe({action:"add_column",avID:n.avID,keyID:a,keyName:n.keyName,keyType:n.keyType}),l)}async function dS({client:e,permMgr:t,rawArgs:o}){const n=jd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_column"});if(r)return r;const a=n.keyID??n.columnID,i=await Vt(e,n.avID,s,n.blockID),c=Zt([{action:"removeAttrViewCol",id:a,avID:n.avID,removeDest:n.removeRelationDest??!1}],i);await Oe(e,[{doOperations:c.doOperations,undoOperations:c.undoOperations}]);const l=await Ht(e,n.avID,s,n.blockID);return F(e,xe({action:"remove_column",avID:n.avID,keyID:a,removeRelationDest:n.removeRelationDest??!1}),l)}async function pS({client:e,permMgr:t,rawArgs:o}){const n=Hd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"set_cells"});if(r)return r;const a=aa(s),i=!n.cells&&!n.items,c=n.cells??n.items??[{rowID:n.rowID,columnID:n.columnID,valueType:n.valueType,text:n.text,number:n.number,numberFormat:n.numberFormat,date:n.date,endDate:n.endDate,includeTime:n.includeTime,checked:n.checked,option:n.option,options:n.options,relationBlockIDs:n.relationBlockIDs,url:n.url,email:n.email,phone:n.phone,assets:n.assets}],l=[];for(let h=0;h<c.length;h+=1){const g=c[h],b=qI(n.avID,"set_cells",a,g.rowID,i?void 0:h);if(b.ok===!1)return b.result;if(i){const _=await Vt(e,n.avID,s,n.blockID),w=Zt([{action:"updateAttrViewCell",avID:n.avID,keyID:g.columnID,rowID:b.rowID,data:Ci(g.columnID,b.rowID,g)}],_);await Oe(e,[{doOperations:w.doOperations,undoOperations:w.undoOperations}]);const P=await Ht(e,n.avID,s,n.blockID);return F(e,xe({action:"set_cells",avID:n.avID,rowID:g.rowID,columnID:g.columnID,valueType:g.valueType}),P)}l.push({action:"updateAttrViewCell",avID:n.avID,keyID:g.columnID,rowID:b.rowID,data:Ci(g.columnID,b.rowID,g)})}const u=await Vt(e,n.avID,s,n.blockID),p=Zt(l,u);await Oe(e,[{doOperations:p.doOperations,undoOperations:p.undoOperations}]);const f=await Ht(e,n.avID,s,n.blockID);return F(e,xe({action:"set_cells",avID:n.avID,updated:c.length}),f)}async function fS({client:e,permMgr:t,rawArgs:o}){const n=Vd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"duplicate"});if(r)return r;const a=await hv(e,n.avID);if(!a.avID||!a.blockID)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:$t,action:"duplicate",reason:"duplicate_identifiers_missing",message:`Duplicate AV returned incomplete identifiers for source "${n.avID}".`,sourceAvID:n.avID,duplicatedAvID:a.avID,duplicatedBlockID:a.blockID}},null,2)}],isError:!0};const i=n.previousID??n.blockID??await ca(e,n.avID,s);if(!i)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:$t,action:"duplicate",reason:"duplicate_insert_target_unresolved",message:`Duplicated AV identifiers were prepared for source "${n.avID}", but MCP could not resolve a database block insertion target.`,sourceAvID:n.avID,duplicatedAvID:a.avID,duplicatedBlockID:a.blockID,hint:"SiYuan kernel duplicateAttributeViewBlock only prepares the duplicated AV definition. Provide previousID or ensure the source AV has a resolvable owning database block in the document tree."}},null,2)}],isError:!0};const c=await N(e,t,i,"write");if(c.denied)return c.denied;let l=Zp(a.blockID,a.avID);try{const u=await xp(e,l);typeof u.dom=="string"&&u.dom.length>0&&(l=u.dom)}catch{}try{await Oe(e,[{doOperations:[{action:"insert",id:a.blockID,data:l,previousID:i}],undoOperations:[{action:"delete",id:a.blockID}]}])}catch(u){const p=u instanceof Error?u:new Error(String(u));return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:$t,action:"duplicate",reason:"duplicate_insert_failed",message:p.message,sourceAvID:n.avID,duplicatedAvID:a.avID,duplicatedBlockID:a.blockID,insertedAfter:i,hint:"The duplicate AV definition was prepared, but MCP failed while inserting the duplicated database block into the document tree."}},null,2)}],isError:!0}}return xe({action:"duplicate",sourceAvID:n.avID,prepared:!0,materialized:!0,insertedAfter:i,semantics:n.previousID?"siyuan_duplicate_mirror_with_override":"siyuan_duplicate_mirror"},a)}async function hS({client:e,permMgr:t,rawArgs:o}){const n=Zd.parse(o),{denied:r}=await Ie(e,t,n.avID,"read");if(r)return r;const s=await Op(e,{id:n.avID,keyword:n.keyword,page:n.page,pageSize:n.pageSize}),a=s.blockIDs??[];if(a.length>0){const i=Lo();await t.reload();const c=[],l=[];let u=0;for(let p=0;p<a.length;p+=1){const f=a[p],h=await Uo(e,{id:f},i)??await dt(e,f).catch(()=>null),g=h&&"notebook"in h?h.notebook:void 0;if(!g||!t.canRead(g)){u+=1;continue}c.push(f),l.push(s.rows[p])}return k({avID:n.avID,name:s.name,blockIDs:c,rows:l,...u>0?{filteredOutCount:u,partial:!0,reason:"permission_filtered"}:{}})}return k({avID:n.avID,...s})}const mS={get:nS,render:sS,get_attribute_view_keys:aS,get_attribute_view_filter_sort:iS,search:rS,add_rows:cS,remove_rows:lS,add_column:uS,remove_column:dS,set_cells:pS,duplicate:fS,get_primary_key_values:hS},gS=[S("get",$d,"Get the full attribute view payload by AV ID; blockID is an optional exact database-block context."),S("render",Md,"Render an attribute view by id (AV ID, not avID) with optional paging/filtering; with createIfNotExist=true, materialize a SiYuan-style AV block under blockID."),S("get_attribute_view_keys",zd,"Get the column (key) definitions of an attribute view."),S("get_attribute_view_filter_sort",Fd,"Get filter and sort settings for an attribute view."),S("search",qd,"Search attribute views by name or primary-key values."),S("add_rows",Bd,"Add bound block rows or detached plain-text primary-key rows to a database."),S("remove_rows",Ld,"Remove rows from a database."),S("add_column",Ud,"Add a column to a database."),S("remove_column",jd,"Remove a column from a database."),S("set_cells",Hd,"Set one or more cell values in a database. Provide cells/items, or pass rowID + columnID + valueType for a single-cell write."),S("duplicate",Vd,"Duplicate an attribute view using SiYuan copy-as-mirror semantics; previousID overrides the insertion target."),S("get_primary_key_values",Zd,"Get primary key values for an attribute view.")],Yp=De({name:"av",description:"🗃️ Grouped attribute-view (database) operations.",variants:gS,actionSchema:u_,aggregateOptions:{guidance:Wc,actionHints:sl},handlers:mS});function yS(e){return Yp.listTools(e)}async function bS(e,t,o,n){return Yp.callTool(e,t,o,n)}const wS=/[\u200B\u200C\u200D\u2060\uFEFF]/g,kS=/<[^>]+>/g;function la(e){return e.replace(wS,"")}function Wp(e){return{...e,content:la(e.content)}}function Gp(e){return{...e,kramdown:la(e.kramdown)}}function Kp(e){return e.replace(kS,"")}function Jp(e){const t=e==null?void 0:e.trim().toLowerCase();return t||void 0}const Qp={d:"document",h:"heading",p:"paragraph",l:"list",i:"listItem",b:"blockquote",c:"codeBlock",m:"mathBlock",t:"table",s:"superBlock",html:"htmlBlock",embed:"embedBlock",av:"databaseBlock",video:"video",audio:"audio",widget:"widget"},Ri={keyword:0,query:1,query_syntax:1,sql:2,regex:3},_S={0:"keyword",1:"query_syntax",2:"sql",3:"regex"};function vS(e){const t={};for(const o of e){const n=Qp[o];n&&(t[n]=!0)}return t}function IS(e){const t={};for(const[o,n]of Object.entries(e)){const r=Qp[o];r?t[r]=n:t[o]=n}return t}function SS(e,t){const o=Jp(e);return o&&o in Ri?Ri[o]:t}function DS(e){if(e!==void 0)return _S[e]}const AS={relevance:7,date:4,updated_desc:4,updated_asc:3,created_desc:2,created_asc:1,type:0},TS={7:"relevance",4:"updated_desc",3:"updated_asc",2:"created_desc",1:"created_asc",0:"type"},PS={relevance:0,relevance_desc:0,relevance_asc:1,updated_asc:2,updated_desc:3},ES={0:"relevance_desc",1:"relevance_asc",2:"updated_asc",3:"updated_desc"};function $r(e,t,o=AS){const n=Jp(e);return n&&n in o?o[n]:t}function xi(e){if(e!==void 0)return TS[e]}function CS(e,t){return $r(e,t,PS)}function RS(e){if(e!==void 0)return ES[e]}function xS(e,t){return Array.isArray(e.blocks)?{...e,blocks:e.blocks.map(o=>{if(!o||typeof o!="object")return o;const n=o,r={...n},s=typeof n.content=="string"?n.content:void 0;return s!==void 0&&(r.plainContent=Kp(s)),r})}:e}const OS=["id","type","box"],NS=["hPath","hpath"],$S=["content","plainContent","markdown","name","alias","memo","tag","subType","subtype","path","parentID","parent_id","rootID","root_id"];function Oi(e){return!(e==null||e===""||Array.isArray(e)&&e.length===0)}function MS(e){const t={};for(const o of OS)o in e&&(t[o]=e[o]);for(const o of NS)if(Oi(e[o])){t.hPath=e[o];break}for(const o of $S)Oi(e[o])&&(t[o]=e[o]);return t}const zS=/<mark>[^<]*<\/mark>/g,pr=400,FS=150;function qS(e,t=FS){if(e.length<=pr)return e;const o=[...e.matchAll(zS)];if(o.length===0)return e.length>pr?e.slice(0,pr)+"...":e;const n=[];for(const a of o){const i=Math.max(0,a.index-t),c=Math.min(e.length,a.index+a[0].length+t);n.push([i,c])}const r=[n[0]];for(let a=1;a<n.length;a++){const i=r[r.length-1],c=n[a];c[0]<=i[1]?i[1]=Math.max(i[1],c[1]):r.push(c)}const s=[];r[0][0]>0&&s.push("...");for(let a=0;a<r.length;a++)a>0&&s.push("..."),s.push(e.slice(r[a][0],r[a][1]));return r[r.length-1][1]<e.length&&s.push("..."),s.join("")}const Ni=400,$i=200;function BS(e){return e.map(t=>{if(!t||typeof t!="object")return t;const n=MS(t);if(n.type==="NodeDocument")return n;if(typeof n.content=="string"){const r=Kp(n.content).trim();r.length>0&&(n.excerpt=r.length>$i?r.slice(0,$i)+"...":r),n.content=qS(n.content)}return typeof n.markdown=="string"&&n.markdown.length>Ni&&(n.markdown=n.markdown.slice(0,Ni)+"..."),n})}function LS(e){const t=xS({blocks:e});return BS(Array.isArray(t.blocks)?t.blocks:[])}function US(e){const t=e.notebook??e.box??e.boxID??e.notebookId;return typeof t=="string"&&t.length>0?t:void 0}async function Xp(e){const t=await at(e),o=new Map;for(const n of t.notebooks??[])n.id&&n.name&&o.set(n.id,n.name);return o}async function Mr(e,t){if(t)try{return(await Xp(e)).get(t)}catch{return}}async function jS(e,t){if(t.filter(n=>n!==null&&typeof n=="object").length===0)return t;try{const n=await Xp(e);return t.map(r=>{if(r===null||typeof r!="object")return r;const s=r,a=US(s),i=a?n.get(a):void 0;return i?{...s,notebookName:i}:r})}catch{return t}}function HS(e){if(!e||typeof e!="object")return;const t=e;return[t.notebook,t.box,t.boxID,t.notebookId].find(n=>typeof n=="string"&&n.length>0)}function zr(e,t){const o=e.filter(n=>{const r=HS(n);return!r||t.canRead(r)});return{items:o,removedCount:e.length-o.length}}function ut(e){return e>0?{partial:!0,filteredOutCount:e,reason:"permission_filtered",permissionSummary:{filteredOutCount:e,reason:"permission_filtered",suggestion:'Some results were hidden due to notebook permissions. Use notebook(action="get_permissions") to review access before retrying broader searches.'}}:{}}function VS(e){return e instanceof Error?/permission[_\s-]?denied|has permission|read access is required|write access is required/i.test(e.message):!1}async function un(e,t,o){const n=Lo(),r=[];let s=0;for(const a of t){const i=await Uo(e,a,n);if(!(i!=null&&i.notebook)||!o.canRead(i.notebook)){s+=1;continue}r.push(a)}return{items:r,removedCount:s}}async function fr(e,t,o,n){const r=Lo(),s=[];let a=0,i=0;const c=typeof n=="string"&&n.length>0?n.startsWith("/")?n:`/${n}`:void 0;for(const l of t){const u=await Uo(e,l,r);if(!(u!=null&&u.notebook)||!o.canRead(u.notebook)){a+=1;continue}if(c&&(!u.path||!(u.path===c||u.path.startsWith(`${c}/`)))){i+=1;continue}s.push(l)}return{items:s,permissionFilteredOutCount:a,pathFilteredOutCount:i}}function Mi(e,t){if(!Array.isArray(e.blocks))return e;const{items:o,removedCount:n}=zr(e.blocks,t),r=new Set;for(const s of o){if(!s||typeof s!="object")continue;const a=s,i=[a.rootID,a.rootId,a.root_id,a.id,a.path].find(c=>typeof c=="string"&&c.length>0);i&&r.add(i)}return{...e,blocks:o,matchedBlockCount:o.length,matchedRootCount:r.size,...n>0?{filteredOutBlockCount:n}:{}}}function dn(e,t){const o=Array.isArray(e.backlinks)?zr(e.backlinks,t):void 0,n=Array.isArray(e.backmentions)?zr(e.backmentions,t):void 0,r=((o==null?void 0:o.removedCount)??0)+((n==null?void 0:n.removedCount)??0);return{...e,...o?{backlinks:o.items}:{},...n?{backmentions:n.items}:{},...ut(r)}}function ZS(e){return e.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_").replace(/'/g,"''")}function YS(e){return!!e&&typeof e=="object"}const Fe="Only SELECT statements and WITH CTEs whose main statement is SELECT are allowed. Mutation queries (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE) are forbidden.";function WS(e){let t="",o=0;for(;o<e.length;){const n=e[o],r=e[o+1];if(n==="-"&&r==="-"){for(t+=" ",o+=2;o<e.length&&e[o]!==`
474
+ `)}function lv(e,t,o,n,r={}){if(!o.enabled)return[];const s=Co(o),a=new Set(s),i=n.filter(h=>a.has(h.action));if(i.length===0)return[];const c=cv(e,t,s,i,r),l=s.filter(h=>Bt(e,h)),u=B_(i,r.propertyDescriptionOverrides);"topic"in u||(u.topic={type:"string",description:'Optional. Only used when action="help". Pass an action name (e.g. "create") to get per-action help; omit or use "overview" for the action index.'});const p=[...i.map(h=>J_(h)),ev(s)],f=Xs({type:"object",properties:{action:{type:"string",enum:[...s,"help"],description:`Action to perform. Supported values: ${s.join(", ")}. Use action="help" for the action index, or action="help" with topic="<actionName>" for per-action details.${l.length>0?` User confirmation is required before calling: ${l.join(", ")}.`:""}`},...X_(u)},additionalProperties:!0});return Object.defineProperty(f,K_,{value:p,enumerable:!1}),[{name:e,description:c,inputSchema:f}]}function uv(e,t,o,n){if(t.action!=="help")return null;const r=Co(o),s=new Set(r),a=n.filter(l=>s.has(l.action)),i=typeof t.topic=="string"?t.topic.trim():"",c=i&&i!=="overview"?i:null;return c?s.has(c)?k(G_(e,c,a)):Ht({error:{type:"unknown_help_topic",message:`Unknown help topic "${c}" for tool "${e}".`,tool:e,topic:c,validTopics:[...r],hint:`Call ${e}(action="help") without topic to see the action index.`}}):k(W_(e,r,a))}function ea(e,t,o){return e.length<=t?{items:e}:{items:e.slice(0,t),meta:{truncated:!0,showing:t,total:e.length,hint:o}}}function ta(e,t,o){const n=e.length,r=Math.max(1,Math.ceil(n/o)),s=Math.min(t,r),a=(s-1)*o,i=e.slice(a,a+o);return{items:i,total:n,page:s,pageSize:o,pageCount:r,showing:i.length,truncated:r>1,hasNextPage:s<r}}function We(e,t,o){const n={data:e,total:t.total,page:t.page,pageSize:t.pageSize,pageCount:t.pageCount,hasNextPage:t.hasNextPage??t.page<t.pageCount,...o??{}};return k(n)}function k(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function oa(e,t=!1){return e==="notebook"?t?'Use notebook(action="set_icon") later if you want to change the notebook icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.':'After creation, call notebook(action="set_icon") to set the notebook icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.':t?'Use document(action="set_attr", attrs={ icon }) later if you want to change the document icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.':'After creation, call document(action="set_attr", attrs={ icon }) to set the document icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.'}function xe(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?k({success:!0,...t,...e}):k({success:!0,...e})}function wo(e,t){if(e instanceof Qw){const i=rv(e,t==null?void 0:t.rawArgs),c={error:{type:"validation_error",message:sv(t==null?void 0:t.tool,t==null?void 0:t.action),...t!=null&&t.tool?{tool:t.tool}:{},...t!=null&&t.action?{action:t.action}:{},...i.length>0?{fields:i}:{},...gr(t)?{hint:gr(t)}:{}}};return Ht(c)}const o=e instanceof Error?e:new Error(String(e)),n=Js(o),r=gr(t),s=n&&r?`${n.hint} ${r}`:(n==null?void 0:n.hint)??r,a={error:{type:av(o)?"api_error":"internal_error",...n?{code:n.code}:{},message:o.message,...t!=null&&t.tool?{tool:t.tool}:{},...t!=null&&t.action?{action:t.action}:{},...s?{hint:s}:{},...iv()&&o.stack?{details:o.stack}:{}}};return Ht(a)}function na(e,t,o){return Ht({error:{type:"permission_denied",message:`Notebook "${e}" has permission "${t}", ${o} access is required. Use notebook(action="set_permission") to change.`,notebook:e,current_permission:t,required_permission:o}})}function dv(e,t){return Ht({error:{type:"action_disabled",message:`Action "${t}" is disabled for tool "${e}".`,tool:e,action:t,hint:"Enable the action in Settings -> Plugins -> SiYuan MCP sisyphus, or call listTools() again to inspect the currently enabled actions."}})}function pv(e,t,o){return Ht({error:{type:"unknown_action",message:`Unknown action "${t}" for tool "${e}".`,tool:e,action:t,validActions:[...o,"help"],hint:`Call ${e}(action="help") to inspect available actions and parameter shapes.`}})}function De(e){const{name:t,description:o,variants:n,handlers:r,actionSchema:s,aggregateOptions:a}=e;return{listTools(i){return lv(t,o,i,n,a)},async callTool(i,c,l,u){const p=c??{},f=typeof p.action=="string"?p.action:void 0,h=f?so(t,f):void 0;let g;try{g=z_(t,h&&h!==f?{...p,action:h}:p)}catch(_){return wo(_,{tool:t,action:h??f,rawArgs:p})}const b=uv(t,g,l,n);if(b)return b;try{const _=n.map(D=>D.action).filter(D=>l.actions[D]);if(f&&!n.some(D=>D.action===h))return pv(t,f,_);const w=s.parse(g.action);if(!l.enabled||!l.actions[w])return dv(t,w);const P=r[w];return P?await P({client:i,rawArgs:g,permMgr:u}):wo(new Error(`No handler registered for action "${w}" on tool "${t}".`),{tool:t,action:w,rawArgs:g})}catch(_){return wo(_,{tool:t,action:h??f,rawArgs:g})}}}}async function ra(e,t){return e.request("/api/av/getAttributeView",{id:t})}async function fv(e,t){return e.request("/api/av/renderAttributeView",t)}async function hv(e,t){return e.request("/api/av/getAttributeViewKeys",{id:t})}async function mv(e,t){return e.request("/api/av/getAttributeViewFilterSort",{...t,blockID:t.blockID??""})}async function gv(e,t,o){return e.request("/api/av/searchAttributeView",{keyword:t,excludes:o})}async function yv(e,t){return e.request("/api/av/duplicateAttributeViewBlock",{avID:t})}async function Np(e,t){return e.request("/api/lute/spinBlockDOM",{dom:t})}async function bv(e,t){return e.request("/api/av/getMirrorDatabaseBlocks",{avID:t})}async function $p(e,t){return e.request("/api/av/getAttributeViewPrimaryKeyValues",t)}async function wv(e,t,o,n,r,s){const a=typeof t=="object"?t:{dataType:t,data:o??"",nextID:n,previousID:r,parentID:s};return e.request("/api/block/insertBlock",a)}async function kv(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/prependBlock",r)}async function Mp(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/appendBlock",r)}async function sa(e,t,o,n){const r={dataType:t,data:o,id:n};return e.request("/api/block/updateBlock",r)}async function zp(e,t){const o={id:t};return e.request("/api/block/deleteBlock",o)}async function _v(e,t,o,n){const r={id:t,previousID:o,parentID:n};return e.request("/api/block/moveBlock",r)}async function vv(e,t){const o={id:t};return e.request("/api/block/foldBlock",o)}async function Iv(e,t){const o={id:t};return e.request("/api/block/unfoldBlock",o)}async function co(e,t){const o={id:t};return e.request("/api/block/getBlockKramdown",o)}async function Wn(e,t){const o={id:t};return e.request("/api/block/getChildBlocks",o)}async function Ct(e,t){const o={id:t};return e.request("/api/block/getDocInfo",o)}async function Sv(e,t,o,n){const r={fromID:t,toID:o,refIDs:n};return e.request("/api/block/transferBlockRef",r)}async function Fp(e,t){return e.request("/api/block/getBlockInfo",{id:t})}async function Dv(e,t,o){return e.request("/api/block/getBlockBreadcrumb",{id:t,excludeTypes:o})}async function Gn(e,t){return e.request("/api/block/getBlockDOM",{id:t})}async function Tv(e){return e.request("/api/block/getRecentUpdatedBlocks",{})}async function Av(e,t){return e.request("/api/block/getBlocksWordCount",{ids:t})}async function Pv(e,t){return e.request("/api/block/batchInsertBlock",{blocks:t})}async function Cv(e,t){return e.request("/api/block/batchUpdateBlock",{blocks:t})}async function Ev(e,t,o,n){return e.request("/api/block/appendDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function Rv(e,t,o,n){return e.request("/api/block/prependDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function xv(e,t,o=!1,n=!1){return e.request("/api/block/getDocsInfo",{ids:t,refCount:o,av:n})}async function qp(e,t){const o={id:t};return e.request("/api/attr/getBlockAttrs",o)}async function Ov(e,t){return e.request("/api/search/fullTextSearchBlock",t)}async function st(e,t){const o={stmt:t},n=await e.request("/api/query/sql",o);return Array.isArray(n)?n:[]}async function Nv(e,t){const o={k:t};return e.request("/api/search/searchTag",o)}async function $v(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBacklinkDoc",r)}async function Mv(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBackmentionDoc",r)}async function zv(e,t){return e.request("/api/search/searchRefBlock",{reqId:t.reqId,id:t.id,rootID:t.rootID??"",k:t.k??"",beforeLen:t.beforeLen??512,isSquareBrackets:t.isSquareBrackets??!1,isDatabase:t.isDatabase??!1})}async function Fv(e,t){return e.request("/api/search/findReplace",t)}async function qv(e,t,o){return e.request("/api/search/searchAsset",{k:t,exts:o})}async function Lv(e,t,o,n=0){return e.request("/api/search/getAssetContent",{id:t,query:o,queryMethod:n})}async function Bv(e,t){return e.request("/api/search/fullTextSearchAssetContent",t)}async function Uv(e,t,o){return e.request("/api/search/listInvalidBlockRefs",{page:t,pageSize:o})}async function Oe(e,t,o={}){return e.request("/api/transactions",{transactions:t,reqId:o.reqId??Date.now(),app:o.app??"",session:o.session??""})}async function Lp(e,t,o,n){return e.request("/api/filetree/createDocWithMd",{notebook:t,path:o,markdown:n})}async function jv(e,t,o,n){return e.request("/api/filetree/renameDoc",{notebook:t,path:o,title:n})}async function Bp(e,t,o){return e.request("/api/filetree/renameDocByID",{id:t,title:o})}async function Hv(e,t,o){return e.request("/api/filetree/removeDoc",{notebook:t,path:o})}async function Fr(e,t){return e.request("/api/filetree/removeDocByID",{id:t})}async function Vv(e,t,o,n){return e.request("/api/filetree/moveDocs",{fromPaths:t,toNotebook:o,toPath:n})}async function Up(e,t,o){return e.request("/api/filetree/moveDocsByID",{fromIDs:t,toID:o})}async function aa(e,t,o){return e.request("/api/filetree/getHPathByPath",{notebook:t,path:o})}async function Kn(e,t){return e.request("/api/filetree/getHPathByID",{id:t})}async function ko(e,t){return e.request("/api/filetree/getPathByID",{id:t})}async function jp(e,t,o){return e.request("/api/filetree/getIDsByHPath",{path:t,notebook:o})}async function Zv(e,t,o){return e.request("/api/filetree/listDocsByPath",{notebook:t,path:o})}async function $t(e,t,o){return e.request("/api/filetree/listDocTree",{notebook:t,path:o})}async function Yv(e,t,o,n){return e.request("/api/filetree/searchDocs",{k:t,flashcard:o,excludeIDs:n})}async function Wv(e,t,o,n){return e.request("/api/filetree/getDoc",{id:t,mode:o,size:n})}async function Gv(e,t,o){return e.request("/api/filetree/createDailyNote",{notebook:t,app:o})}async function Kv(e,t){return e.request("/api/filetree/duplicateDoc",{id:t})}async function Jv(e,t){return e.request("/api/filetree/removeDocs",{paths:t})}async function Qv(e,t,o,n,r){return e.request("/api/filetree/heading2Doc",{srcHeadingID:t,targetNoteBook:o,targetPath:n,previousPath:r})}async function Xv(e,t,o,n=!1){return e.request("/api/filetree/doc2Heading",{srcID:t,targetID:o,after:n})}async function at(e){return e.request("/api/notebook/lsNotebooks")}async function eI(e,t){return e.request("/api/notebook/openNotebook",{notebook:t})}async function tI(e,t){return e.request("/api/notebook/closeNotebook",{notebook:t})}async function oI(e,t){return e.request("/api/notebook/createNotebook",{name:t})}async function nI(e,t){return e.request("/api/notebook/removeNotebook",{notebook:t})}async function rI(e,t,o){return e.request("/api/notebook/renameNotebook",{notebook:t,name:o})}async function sI(e,t){return e.request("/api/notebook/getNotebookConf",{notebook:t})}async function aI(e,t,o){return e.request("/api/notebook/setNotebookConf",{notebook:t,conf:o})}async function Hp(e,t,o){return e.request("/api/notebook/setNotebookIcon",{notebook:t,icon:o})}function iI(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Ge(e){return e.startsWith("/")?e:`/${e}`}function cI(e){const t=Ge(e).split("/").filter(Boolean).at(-1)??"";return t.endsWith(".sy")?t.slice(0,-3):t}function we(e){return e.replace(/\0/g,"").replace(/'/g,"''")}async function lI(e,t){const o=await st(e,`SELECT id, root_id, box, path, hpath, content, type FROM blocks WHERE id = '${we(t)}' LIMIT 1`),n=Array.isArray(o)&&o.length>0&&o[0]&&typeof o[0]=="object"?o[0]:null;if(!n)return null;const r=typeof n.box=="string"&&n.box.length>0?n.box:null,s=typeof n.path=="string"&&n.path.length>0?n.path:null;if(!r||!s)return null;const a=typeof n.root_id=="string"&&n.root_id.length>0?n.root_id:typeof n.id=="string"&&n.id.length>0?n.id:t,i=typeof n.hpath=="string"&&n.hpath.length>0?n.hpath:void 0,c=typeof n.content=="string"&&n.content.length>0?n.content:void 0;return{documentId:a,notebook:r,path:Ge(s),hPath:i,name:c}}async function dt(e,t){try{const s=await lI(e,t);if(s)return s}catch{}const o=await Ct(e,t),n=o.rootID||o.id,r=await ko(e,n);return{documentId:n,notebook:r.notebook,path:Ge(r.path),name:o.name}}const uI=500;function Vp(e,t,o){if(e.size>=uI){const n=e.keys().next().value;n!==void 0&&e.delete(n)}e.set(t,o)}function jo(){return{documentContextById:new Map,notebookByPath:new Map}}async function dI(e,t,o){if(!o)return dt(e,t);let n=o.documentContextById.get(t);return n||(n=dt(e,t),Vp(o.documentContextById,t,n)),n}async function pI(e,t,o){const n=Ge(t);if(!o)return No(e,n);let r=o.notebookByPath.get(n);return r||(r=No(e,n),Vp(o.notebookByPath,n,r)),r}async function Ho(e,t,o){if(!t||typeof t!="object")return null;const n=t,r=[n.notebook,n.box,n.boxID,n.notebookId].find(i=>typeof i=="string"&&i.length>0),s=[n.path].find(i=>typeof i=="string"&&i.length>0),a=[n.blockID,n.blockId,n.rootID,n.rootId,n.root_id,n.docID,n.docId,n.id].find(i=>typeof i=="string"&&i.length>0);if(r&&s)return{notebook:r,path:Ge(s),documentId:a};if(a)try{const i=await dI(e,a,o);return{notebook:i.notebook,path:i.path,documentId:i.documentId}}catch{}if(s){const i=await pI(e,s,o);if(i)return{notebook:r??i,path:Ge(s),documentId:a}}return r?{notebook:r,path:s?Ge(s):void 0,documentId:a}:null}async function fI(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t.notebook):o==="write"?e.canWrite(t.notebook):e.canRead(t.notebook))?null:na(t.notebook,e.get(t.notebook),o)}async function N(e,t,o,n){const r=await dt(e,o),s=await fI(t,r,n);return{context:r,denied:s}}async function Y(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t))?null:na(t,e.get(t),o)}async function hI(e,t){const n=(await at(e)).notebooks.find(s=>s.id===t);return n?n.id:(await dt(e,t)).notebook}async function No(e,t){const o=await at(e);for(const n of o.notebooks)try{return await aa(e,n.id,t),n.id}catch{continue}return null}async function Jn(e,t,o){const n=await Zv(e,t,o);return n.files.map(r=>({id:typeof r.id=="string"&&r.id.length>0?r.id:cI(r.path),notebook:r.box||n.box||t,path:Ge(r.path),hPath:r.hPath,name:iI(r.name),icon:r.icon,subFileCount:r.subFileCount??r.count}))}async function mI(e){return e.request("/api/system/getWorkspaceInfo",{})}async function gI(e){return e.request("/api/system/getNetwork",{})}async function yI(e){return e.request("/api/system/getConf",{})}async function bI(e){return e.request("/api/sync/performSync",{})}async function Zp(e){return e.request("/api/system/version")}async function wI(e){return e.request("/api/system/currentTime")}async function kI(e){return e.request("/api/ui/reloadIcon",{})}async function _I(e){return e.request("/api/ui/reloadFiletree",{})}async function vI(e,t){return e.request("/api/ui/reloadProtyle",{id:t})}async function II(e,t){return e.request("/api/ui/reloadAttributeView",{id:t})}async function SI(e){return e.request("/api/ui/reloadTag",{})}function DI(e){const t=e.content[0];if(!t||t.type!=="text")return null;try{const o=JSON.parse(t.text);return o&&typeof o=="object"&&!Array.isArray(o)?o:null}catch{return null}}function TI(e){const t=new Set,o=[];for(const n of e){const r=`${n.type}:${"id"in n?n.id:""}`;t.has(r)||(t.add(r),o.push(n))}return o}async function AI(e,t){switch(t.type){case"reloadProtyle":await vI(e,t.id);return;case"reloadAttributeView":await II(e,t.id);return;case"reloadIcon":await kI(e);return;case"reloadFiletree":await _I(e);return;case"reloadTag":await SI(e);return;default:{const o=t;throw new Error(`Unknown UI refresh operation: ${String(o)}`)}}}async function F(e,t,o){if(t.isError||o.length===0||!e||typeof e.request!="function")return t;const n=DI(t);if(!n)return t;const r=TI(o),s=[];for(const a of r)try{await AI(e,a)}catch(i){s.push({type:a.type,..."id"in a?{id:a.id}:{},message:i instanceof Error?i.message:String(i)})}return n.uiRefresh={applied:!0,operations:r.map(a=>({type:a.type,..."id"in a?{id:a.id}:{}})),...s.length>0?{partialFailure:s}:{}},{...t,content:[{type:"text",text:JSON.stringify(n,null,2)}]}}function Vo(e){return new Promise(t=>{setTimeout(t,e)})}const Mt="av";function zt(e=new Date){const t=(s,a=2)=>String(s).padStart(a,"0"),o=[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),t(e.getHours()),t(e.getMinutes()),t(e.getSeconds())].join(""),n="abcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let s=0;s<7;s+=1)r+=n[Math.floor(Math.random()*n.length)];return`${o}-${r}`}const Ci=6,PI=500,Ei=6,CI=300,EI="/data/storage/av",RI=/^\d{14}-[a-z0-9]{7}$/;function xI(e){var o,n;if(!e||typeof e!="object")return;const t=e.keyValues;if(Array.isArray(t))for(const r of t){if(!r||typeof r!="object")continue;const s=r;if(((o=s.key)==null?void 0:o.type)!=="block"||!Array.isArray(s.values))continue;const a=s.values.find(i=>{var c;return typeof((c=i==null?void 0:i.block)==null?void 0:c.id)=="string"&&i.block.id.length>0});if((n=a==null?void 0:a.block)!=null&&n.id)return a.block.id}}function OI(e){if(!e||typeof e!="object")return[];const t=e.keyValues;return Array.isArray(t)?t.map(o=>o&&typeof o=="object"?o.key:void 0).filter(o=>!!(o&&typeof o=="object")):[]}function ia(e,t){if(!e||typeof e!="object")return;const o=e;for(const n of t){const r=o[n];if(typeof r=="string"&&r.length>0)return r}}function Yp(e,t){let o=e;for(const n of t){if(!o||typeof o!="object")return;o=o[n]}return typeof o=="string"&&o.length>0?o:void 0}function NI(e){return ia(e,["blockID","itemId","itemID","rowID"])??Yp(e,["block","blockID"])}function $I(e){return Yp(e,["block","id"])??ia(e,["srcID","srcId"])}function MI(e){return ia(e,["id"])}function ca(e){const t=new Map,o=[];if(!e||typeof e!="object")return{rows:[],rowIDs:new Set,sourceBlockToRowIDs:new Map,valueIdToRowIDs:new Map};const n=e.keyValues;if(!Array.isArray(n))return{rows:[],rowIDs:new Set,sourceBlockToRowIDs:new Map,valueIdToRowIDs:new Map};for(const c of n){if(!c||typeof c!="object")continue;const l=c,u=l.values;Array.isArray(u)&&u.forEach(p=>{var _;const f=NI(p);if(!f)return;let h=t.get(f);h||(h={rowID:f,valueIDs:[]},t.set(f,h),o.push(h));const g=MI(p),b=((_=l.key)==null?void 0:_.type)==="block"?$I(p):void 0;b&&(h.sourceBlockID=b),g&&!h.valueIDs.includes(g)&&h.valueIDs.push(g)})}const r=o.filter(c=>c.rowID||c.sourceBlockID||c.valueIDs.length>0),s=new Set,a=new Map,i=new Map;for(const c of r){if(c.rowID&&s.add(c.rowID),c.sourceBlockID&&c.rowID){const l=a.get(c.sourceBlockID)??[];l.includes(c.rowID)||(l.push(c.rowID),a.set(c.sourceBlockID,l))}if(c.rowID)for(const l of c.valueIDs){const u=i.get(l)??[];u.includes(c.rowID)||(u.push(c.rowID),i.set(l,u))}}return{rows:r,rowIDs:s,sourceBlockToRowIDs:a,valueIdToRowIDs:i}}function uo(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:Mt,action:e,...t}},null,2)}],isError:!0}}function zI(e,t,o,n=[]){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:Mt,action:"add_rows",reason:"row_id_sync_timeout",message:`Added rows to attribute view "${e}", but MCP could not observe writable row item IDs before the sync timeout expired.`,avID:e,...t.length>0?{blockIDs:t}:{},...n.length>0?{primaryKeyTexts:n}:{},rows:o.rows,...o.unresolvedBlockIDs.length>0?{unresolvedBlockIDs:o.unresolvedBlockIDs}:{},...o.unresolvedRowIDs&&o.unresolvedRowIDs.length>0?{unresolvedRowIDs:o.unresolvedRowIDs}:{},hint:'Retry av(action="add_rows") or wait briefly and re-read the database. Only call set_cells after add_rows returns rows[].rowID.'}},null,2)}],isError:!0}}function FI(e,t){const o=t.map(r=>{const s=e.sourceBlockToRowIDs.get(r)??[];return s.length===1?{blockID:r,rowID:s[0]}:s.length>1?{blockID:r,rowIDs:s,status:"ambiguous"}:{blockID:r,status:"missing"}}),n=o.filter(r=>!("rowID"in r)).map(r=>r.blockID);return{rows:o,unresolvedBlockIDs:n}}function qI(e,t){const o=t.map(r=>e.rowIDs.has(r.rowID)?r:{...r,status:"missing"}),n=o.filter(r=>"status"in r&&r.status==="missing").map(r=>r.rowID);return{rows:o,unresolvedBlockIDs:[],unresolvedRowIDs:n}}async function LI(e,t,o,n=[]){let r={rows:[...o.map(s=>({blockID:s})),...n],unresolvedBlockIDs:[...o],unresolvedRowIDs:n.map(s=>s.rowID)};for(let s=0;s<Ci;s+=1){const a=await ra(e,t),i=ca(a.av),c=FI(i,o),l=qI(i,n);if(r={rows:[...c.rows,...l.rows],unresolvedBlockIDs:c.unresolvedBlockIDs,unresolvedRowIDs:l.unresolvedRowIDs},r.unresolvedBlockIDs.length===0&&(!r.unresolvedRowIDs||r.unresolvedRowIDs.length===0))return r;s<Ci-1&&await Vo(PI)}return r}function BI(e,t,o,n,r){if(o.rowIDs.has(n))return{ok:!0,rowID:n};const s=o.valueIdToRowIDs.get(n);if(s&&s.length===1)return{ok:!1,result:uo(t,{reason:"row_id_alias_detected",message:`rowID "${n}" is a cell value ID in attribute view "${e}", not the database row item ID.`,avID:e,rowID:n,detectedValueID:n,suggestedRowID:s[0],...r===void 0?{}:{itemIndex:r},hint:'Use the AV row item ID stored in each value.blockID, or the rowID returned by av(action="add_rows"). Do not reuse value.id from set_cells responses as rowID.'})};if(s&&s.length>1)return{ok:!1,result:uo(t,{reason:"row_id_alias_ambiguous",message:`rowID "${n}" matches multiple cell value records in attribute view "${e}". Pass a concrete row item ID instead.`,avID:e,rowID:n,detectedValueID:n,candidateRowIDs:s,...r===void 0?{}:{itemIndex:r},hint:"Use the row item ID stored in value.blockID, not value.id."})};const a=o.sourceBlockToRowIDs.get(n);return a&&a.length===1?{ok:!1,result:uo(t,{reason:"row_id_required",message:`rowID "${n}" is a source block ID in attribute view "${e}". Use the row item ID instead.`,avID:e,rowID:n,detectedSourceBlockID:n,suggestedRowID:a[0],...r===void 0?{}:{itemIndex:r},hint:'Use the row item ID stored in value.blockID, or the rowID returned by av(action="add_rows"). The source block ID lives in block.id and is not writable as rowID.'})}:a&&a.length>1?{ok:!1,result:uo(t,{reason:"row_id_ambiguous",message:`rowID "${n}" matches multiple rows in attribute view "${e}". Pass a concrete row item ID instead of the source block ID.`,avID:e,rowID:n,detectedSourceBlockID:n,candidateRowIDs:a,...r===void 0?{}:{itemIndex:r},hint:'Use the exact row item ID returned by av(action="add_rows"), or inspect the AV payload to choose the intended row binding.'})}:{ok:!1,result:uo(t,{reason:"row_id_not_canonical",message:`rowID "${n}" is not a valid database row item ID in attribute view "${e}". Pass the canonical row item ID stored in value.blockID.`,avID:e,rowID:n,...r===void 0?{}:{itemIndex:r},hint:'Use the rowID returned by av(action="add_rows"), or inspect the block column in av(action="get"): value.blockID is the writable row item ID, while value.id is only the cell value ID.'})}}async function UI(e,t){const o=xI(t);return{avData:t,blockID:o}}function jI(e){const t=[];for(const o of e.refDefs??[]){const n=typeof(o==null?void 0:o.refID)=="string"&&o.refID.length>0?o.refID:void 0;n&&!t.includes(n)&&t.push(n)}return t}async function Wp(e,t){try{return jI(await bv(e,t))}catch(o){if(Qs(o))return[];throw o}}async function HI(e,t){const o=we(t),n=await st(e,`SELECT id FROM blocks WHERE type = 'av' AND (markdown LIKE '%${o}%' OR ial LIKE '%${o}%' OR content LIKE '%${o}%') ORDER BY updated DESC LIMIT 20`),r=[];for(const s of n){const a=s&&typeof s=="object"?s.id:void 0;typeof a=="string"&&a.length>0&&!r.includes(a)&&r.push(a)}return r}async function la(e,t,o){const n=[],r=await UI(e,o);r.blockID&&n.push(r.blockID);const s=await Wp(e,t);for(const i of s)n.includes(i)||n.push(i);const a=await HI(e,t);for(const i of a)n.includes(i)||n.push(i);return n}async function VI(e,t,o,n){if((await la(e,t,o)).includes(n))return!0;try{const s=await Gn(e,n),a=typeof(s==null?void 0:s.dom)=="string"?s.dom:"";return a.includes('data-type="NodeAttributeView"')&&a.includes(`data-av-id="${t}"`)}catch(s){if(Qs(s))return!1;throw s}}function ZI(e,t,o){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:Mt,action:e,message:`blockID "${o}" is not a database block for attribute view "${t}".`,fields:[{path:"blockID",message:`blockID "${o}" does not belong to attribute view "${t}".`}],hint:"Pass the materialized database block for this AV, or omit blockID and let MCP resolve a registered mirror block automatically."}},null,2)}],isError:!0}}async function Ie(e,t,o,n,r){const a=(await ra(e,o)).av;if(r!=null&&r.blockID){const{denied:c}=await N(e,t,r.blockID,n);return c?{denied:c,avData:a}:await VI(e,o,a,r.blockID)?{denied:null,avData:a}:{denied:ZI(r.action??"get",o,r.blockID),avData:a}}const i=await la(e,o,a);for(const c of i)try{const{denied:l}=await N(e,t,c,n);return{denied:l,avData:a}}catch(l){if(Qs(l))continue;throw l}throw i.length===0?new Error(`Unable to resolve notebook permission scope for attribute view "${o}". The database may have no rows yet; AV writes require a resolvable owning block context.`):new Error(`Unable to resolve notebook permission scope for attribute view "${o}" because all known owning block references are stale or missing.`)}function YI(e){return e instanceof Error&&e.message.includes("The database may have no rows yet; AV writes require a resolvable owning block context.")}function WI(e){var t;return e instanceof Error&&((t=Js(e))==null?void 0:t.code)==="av_not_found"}async function GI(e,t,o,n,r){if(o.createIfNotExist===!0){if(!o.blockID)throw new Error(`Unable to create or render attribute view "${n}" because createIfNotExist=true requires blockID to resolve notebook permission scope.`);if(r){const{denied:s,context:a}=await N(e,t,o.blockID,"write");return{denied:s,shouldMaterialize:!0,targetDocumentId:a.documentId}}try{const{denied:s}=await Ie(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){if(!(YI(s)||WI(s)))throw s;const{denied:i,context:c}=await N(e,t,o.blockID,"write");return{denied:i,shouldMaterialize:!0,targetDocumentId:c.documentId}}}if(!o.id)throw new Error('av(action="render") requires id unless createIfNotExist=true is provided.');try{const{denied:s}=await Ie(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){throw s}}async function ua(e,t,o){const n=o??(await ra(e,t)).av;return(await la(e,t,n))[0]}async function Vt(e,t,o,n){const r=[];n&&r.push(n);try{const s=await ua(e,t,o);s&&!r.includes(s)&&r.push(s)}catch{}for(const s of r)try{const a=await dt(e,s);if(a.documentId)return[{type:"reloadProtyle",id:a.documentId}]}catch{}return[{type:"reloadAttributeView",id:t}]}async function KI(e,t,o){const n=jo();await t.reload();const r=[],s=[];let a=0,i=0,c=0;for(const l of o){const u=await Ho(e,l,n);if(!(u!=null&&u.notebook)){a+=1,i+=1,s.push(l);continue}if(!t.canRead(u.notebook)){a+=1,c+=1;continue}r.push(l)}return{results:r,unresolvedResults:s,rawResultCount:o.length,filteredOutCount:a,unresolvedCount:i,permissionFilteredOutCount:c,...a>0?{partial:!0,reason:c>0?"permission_filtered":"context_unresolved"}:{}}}async function JI(e){const t=await e.request("/api/file/readDir",{path:EI});return(Array.isArray(t)?t:[]).filter(o=>!(o!=null&&o.isDir)&&typeof(o==null?void 0:o.name)=="string"&&o.name.endsWith(".json")).map(o=>o.name.slice(0,-5)).filter(o=>RI.test(o))}function QI(e){if(!e||typeof e!="object")return[];const t=e.values;return Array.isArray(t)?t.filter(o=>!!(o&&typeof o=="object")):[]}async function XI(e,t,o){if(!t.trim())return[];if(typeof e.request!="function")return[];const n=new Set(o??[]),r=await JI(e),s=[];for(const a of r)if(!n.has(a))try{const i=await $p(e,{id:a,keyword:t,page:1,pageSize:3}),c=QI(i.rows);if(c.length===0)continue;const l=Array.isArray(i.blockIDs)?i.blockIDs.filter(u=>typeof u=="string"&&u.length>0):[];if(l.length===0)continue;s.push({avID:a,avName:i.name,blockID:l[0],blockIDs:l,rows:i.rows,matchedRowCount:c.length,matchSource:"primary_key"})}catch{}return s}function Ri(e,t){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite epoch millisecond value.`);return e}const o=Date.parse(e);if(Number.isNaN(o))throw new Error(`${t} must be a valid ISO date string or epoch milliseconds.`);return o}function Gp(e,t){return`<div class="av" data-node-id="${e}" data-av-id="${t}" data-type="NodeAttributeView" data-av-type="table"></div>`}function Ft(e,t){for(const o of t){const n=e[o];if(typeof n=="string"&&n.length>0)return n}}function eS(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;for(const o of["content","text","number","isChecked","date","mSelect","select","block"])if(o in t)return t[o];return e}function tS(e){const t=[e.columns,e.keys,e.keyValues,e.attributeViewKeys];for(const o of t){if(!Array.isArray(o))continue;const n=o.flatMap(r=>{if(!r||typeof r!="object"||Array.isArray(r))return[];const s=r,a=s.key&&typeof s.key=="object"&&!Array.isArray(s.key)?s.key:s,i=Ft(a,["id","keyID","columnID"]);if(!i)return[];const c=Ft(a,["name","title"]),l=Ft(a,["type"]);return[{id:i,...c?{name:c}:{},...l?{type:l}:{}}]});if(n.length>0)return n}return[]}function oS(e){return e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const o=t,n=Array.isArray(o.values)?o.values:Array.isArray(o.cells)?o.cells:[],r={};for(const a of n){if(!a||typeof a!="object"||Array.isArray(a))continue;const i=a,c=i.key&&typeof i.key=="object"&&!Array.isArray(i.key)?i.key:{},l=Ft(i,["keyID","columnID","id"])??Ft(c,["id","keyID"]);l&&(r[l]=eS(i))}if(Object.keys(r).length===0)return[];const s=Ft(o,["id","rowID","blockID"]);return[{...s?{id:s}:{},cells:r}]})}function nS(e,t,o){const n=tS(e),r=oS(t);if(!(n.length===0&&r.length===0))return{columns:n,rows:r,rowCount:o}}function rS(e=new Date){const t=o=>String(o).padStart(2,"0");return[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),t(e.getHours()),t(e.getMinutes()),t(e.getSeconds())].join("")}async function Zt(e,t,o,n){return n??await ua(e,t,o)}function Yt(e,t,o){if(!t)return{doOperations:e,undoOperations:[]};const n=rS();return{doOperations:[...e,{action:"doUpdateUpdated",id:t,data:n}],undoOperations:[{action:"doUpdateUpdated",id:t,data:""}]}}function xi(e,t,o){const n={keyID:e,blockID:t};switch(o.valueType){case"text":return{...n,type:"text",text:{content:o.text}};case"number":return{...n,type:"number",number:{content:o.number,isNotEmpty:!0,format:o.numberFormat??"",formattedContent:""}};case"date":{const r=Ri(o.date,"date"),s=o.endDate===void 0?0:Ri(o.endDate,"endDate");return{...n,type:"date",date:{content:r,isNotEmpty:!0,hasEndDate:o.endDate!==void 0,isNotTime:o.includeTime===!1,content2:s,isNotEmpty2:o.endDate!==void 0,formattedContent:""}}}case"checkbox":return{...n,type:"checkbox",checkbox:{checked:!!o.checked}};case"select":return{...n,type:"select",mSelect:[{content:o.option,color:""}]};case"multi_select":return{...n,type:"mSelect",mSelect:(o.options??[]).map(r=>({content:r,color:""}))};case"relation":return{...n,type:"relation",relation:{blockIDs:o.relationBlockIDs??[],contents:[]}};case"url":return{...n,type:"url",url:{content:o.url}};case"email":return{...n,type:"email",email:{content:o.email}};case"phone":return{...n,type:"phone",phone:{content:o.phone}};case"mAsset":{const r=(o.assets??[]).map(a=>({type:a.type,name:a.name??"",content:a.content})),s=o.text??r.map(a=>a.type==="image"?`![](${a.content})`:`[${a.name||a.content}](${a.content})`).join(`
475
+ `);return{...n,type:"mAsset",text:{content:s},mAsset:r}}default:throw new Error(`Unsupported AV valueType: ${o.valueType}`)}}async function sS({client:e,permMgr:t,rawArgs:o}){const n=zd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.id,"read",{blockID:n.blockID,action:"get"});if(r)return r;const a=ca(s);return k({id:n.id,av:s,...a.rows.length>0?{resolvedRows:a.rows.map(i=>({rowID:i.rowID,...i.sourceBlockID?{sourceBlockID:i.sourceBlockID}:{},...i.valueIDs.length>0?{valueIDs:i.valueIDs}:{}}))}:{}})}async function aS({client:e,permMgr:t,rawArgs:o}){const n=Bd.parse(o),r=await gv(e,n.keyword,n.excludes),s=Array.isArray(r.results)?r.results:[],a=await XI(e,n.keyword,n.excludes),i=[...s],c=new Set(i.map(p=>p&&typeof p=="object"?p.avID:void 0).filter(p=>typeof p=="string"&&p.length>0));for(const p of a){const f=p.avID;typeof f=="string"&&c.has(f)||(typeof f=="string"&&c.add(f),i.push(p))}const l=await KI(e,t,i),u=l.results.map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return p;const f=p,h=typeof f.avID=="string"&&f.avID.length>0?f.avID:typeof f.id=="string"&&f.id.length>0?f.id:void 0;return h?{...f,id:h,avID:h,renderArgs:{action:"render",id:h}}:f});return k({keyword:n.keyword,searchScope:{kernel:"attribute_view_name_or_kernel_candidates",fallback:"primary_key_values"},...l,results:u,...l.filteredOutCount>0?{emptyReason:u.length===0?l.unresolvedCount>0&&l.permissionFilteredOutCount===0?"no_verified_results_unresolved_candidates_available":l.permissionFilteredOutCount>0&&l.unresolvedCount===0?"all_results_permission_filtered":"all_results_filtered":void 0,unresolvedHint:l.unresolvedResults.length>0?"unresolvedResults contains kernel search candidates that matched, but MCP could not verify notebook context yet.":void 0}:{},...n.keyword.trim().length>0&&l.results.length===0?{warning:"No verified AV matches were found. AV search primarily covers database names and primary-key values; non-primary-key cell text may not be searchable immediately after writes."}:{}})}async function iS({client:e,permMgr:t,rawArgs:o}){const n=Fd.parse(o),r=new Date,s=!n.id,a=n.id??zt(r),i=await GI(e,t,n,a,s);if(i.denied)return i.denied;const c=await fv(e,{id:a,blockID:n.blockID,viewID:n.viewID,page:n.page,pageSize:n.pageSize,query:n.query,groupPaging:n.groupPaging,createIfNotExist:n.createIfNotExist});let l,u;if(i.shouldMaterialize){l=zt(r);let E=Gp(l,a);try{const B=await Np(e,E);typeof B.dom=="string"&&B.dom.length>0&&(E=B.dom)}catch{}await Oe(e,[{doOperations:[{action:"insert",id:l,data:E,parentID:n.blockID}],undoOperations:[{action:"delete",id:l}]}]),u=!1;for(let B=0;B<Ei;B+=1){if((await Wp(e,a)).includes(l)){u=!0;break}if(B===Ei-1)break;await Vo(CI)}}const p=c&&typeof c=="object"&&!Array.isArray(c)?c:{},f=Array.isArray(p.rows)?p.rows:[],h=n.page??1,g=n.pageSize??(f.length||1),b=typeof p.pageCount=="number"?p.pageCount:1,_=typeof p.rowCount=="number"?p.rowCount:f.length,w=nS(p,f,_),{rows:P,pageCount:D,rowCount:A,...T}=p,O=We(f,{total:_,page:h,pageSize:g,pageCount:b,hasNextPage:h<b},{...T,avID:a,id:a,...w?{table:w}:{},...n.createIfNotExist===!0?{generatedAvID:s}:{},...i.shouldMaterialize?{materialized:!0,blockID:l,parentID:n.blockID,databaseBlockRegistrationVerified:u===!0,...u===!1?{warning:`Created attribute view "${a}" and materialized database block "${l}", but MCP could not verify mirror registration before the timeout. If the next AV write cannot resolve by avID yet, retry shortly or pass this blockID as explicit database-block context.`}:{}}:{}});return i.shouldMaterialize?F(e,O,[{type:"reloadAttributeView",id:a},...i.targetDocumentId?[{type:"reloadProtyle",id:i.targetDocumentId}]:[]]):O}async function cS({client:e,permMgr:t,rawArgs:o}){const n=qd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.id,"read");if(r)return r;const a=await hv(e,n.id),i=a&&typeof a=="object"&&!Array.isArray(a)&&Array.isArray(a.keys)?a.keys:Array.isArray(a)&&a.length>0?a:OI(s);return k({avID:n.id,keys:i})}async function lS({client:e,permMgr:t,rawArgs:o}){const n=Ld.parse(o),{denied:r}=await Ie(e,t,n.id,"read");if(r)return r;const s=await mv(e,{id:n.id,blockID:n.blockID??""});return k({avID:n.id,...n.blockID?{blockID:n.blockID}:{},...s})}async function uS({client:e,permMgr:t,rawArgs:o}){const n=Ud.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"add_rows"});if(r)return r;const a=n.blockIDs??[],i=n.primaryKeyTexts??[];if(a.length===0&&i.length===0)return xe({action:"add_rows",avID:n.avID,blockIDs:[],primaryKeyTexts:[],rows:[],added:0,skipped:!0,message:"No blockIDs or primaryKeyTexts were provided, so no rows were added."});const c=i.map(g=>({primaryKeyText:g,rowID:zt(),srcID:zt()})),l=await Zt(e,n.avID,s,n.blockID),u=[...a.map(g=>({itemID:zt(),id:g,isDetached:!1})),...c.map(g=>({itemID:g.rowID,id:g.srcID,isDetached:!0,content:g.primaryKeyText}))],p=Yt([{action:"insertAttrViewBlock",avID:n.avID,blockID:l,viewID:n.viewID,groupID:n.groupID,previousID:n.previousID,ignoreDefaultFill:n.ignoreDefaultFill,srcs:u}],l);await Oe(e,[{doOperations:p.doOperations,undoOperations:[{action:"removeAttrViewBlock",srcIDs:[...a,...c.map(g=>g.rowID)],avID:n.avID},...p.undoOperations]}]);const f=await LI(e,n.avID,a,c.map(g=>({primaryKeyText:g.primaryKeyText,rowID:g.rowID})));if(f.unresolvedBlockIDs.length>0||f.unresolvedRowIDs&&f.unresolvedRowIDs.length>0)return zI(n.avID,a,f,i);const h=await Vt(e,n.avID,s,n.blockID);return F(e,xe({action:"add_rows",avID:n.avID,...a.length>0?{blockIDs:a}:{},...i.length>0?{primaryKeyTexts:i}:{},rows:f.rows,added:a.length+i.length}),h)}async function dS({client:e,permMgr:t,rawArgs:o}){const n=jd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_rows"});if(r)return r;const a=await Zt(e,n.avID,s,n.blockID),i=Yt([{action:"removeAttrViewBlock",srcIDs:n.srcIDs,avID:n.avID}],a);await Oe(e,[{doOperations:i.doOperations,undoOperations:i.undoOperations}]);const c=await Vt(e,n.avID,s,n.blockID);return F(e,xe({action:"remove_rows",avID:n.avID,srcIDs:n.srcIDs,removed:n.srcIDs.length}),c)}async function pS({client:e,permMgr:t,rawArgs:o}){const n=Hd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"add_column"});if(r)return r;const a=n.keyID??zt(),i=await Zt(e,n.avID,s,n.blockID),c=Yt([{action:"addAttrViewCol",name:n.keyName,avID:n.avID,type:n.keyType,id:a,data:n.keyIcon??"",previousID:n.previousKeyID??""}],i);await Oe(e,[{doOperations:c.doOperations,undoOperations:[{action:"removeAttrViewCol",id:a,avID:n.avID},...c.undoOperations]}]);const l=await Vt(e,n.avID,s,n.blockID);return F(e,xe({action:"add_column",avID:n.avID,keyID:a,keyName:n.keyName,keyType:n.keyType}),l)}async function fS({client:e,permMgr:t,rawArgs:o}){const n=Vd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_column"});if(r)return r;const a=n.keyID??n.columnID,i=await Zt(e,n.avID,s,n.blockID),c=Yt([{action:"removeAttrViewCol",id:a,avID:n.avID,removeDest:n.removeRelationDest??!1}],i);await Oe(e,[{doOperations:c.doOperations,undoOperations:c.undoOperations}]);const l=await Vt(e,n.avID,s,n.blockID);return F(e,xe({action:"remove_column",avID:n.avID,keyID:a,removeRelationDest:n.removeRelationDest??!1}),l)}async function hS({client:e,permMgr:t,rawArgs:o}){const n=Zd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"set_cells"});if(r)return r;const a=ca(s),i=!n.cells&&!n.items,c=n.cells??n.items??[{rowID:n.rowID,columnID:n.columnID,valueType:n.valueType,text:n.text,number:n.number,numberFormat:n.numberFormat,date:n.date,endDate:n.endDate,includeTime:n.includeTime,checked:n.checked,option:n.option,options:n.options,relationBlockIDs:n.relationBlockIDs,url:n.url,email:n.email,phone:n.phone,assets:n.assets}],l=[];for(let h=0;h<c.length;h+=1){const g=c[h],b=BI(n.avID,"set_cells",a,g.rowID,i?void 0:h);if(b.ok===!1)return b.result;if(i){const _=await Zt(e,n.avID,s,n.blockID),w=Yt([{action:"updateAttrViewCell",avID:n.avID,keyID:g.columnID,rowID:b.rowID,data:xi(g.columnID,b.rowID,g)}],_);await Oe(e,[{doOperations:w.doOperations,undoOperations:w.undoOperations}]);const P=await Vt(e,n.avID,s,n.blockID);return F(e,xe({action:"set_cells",avID:n.avID,rowID:g.rowID,columnID:g.columnID,valueType:g.valueType}),P)}l.push({action:"updateAttrViewCell",avID:n.avID,keyID:g.columnID,rowID:b.rowID,data:xi(g.columnID,b.rowID,g)})}const u=await Zt(e,n.avID,s,n.blockID),p=Yt(l,u);await Oe(e,[{doOperations:p.doOperations,undoOperations:p.undoOperations}]);const f=await Vt(e,n.avID,s,n.blockID);return F(e,xe({action:"set_cells",avID:n.avID,updated:c.length}),f)}async function mS({client:e,permMgr:t,rawArgs:o}){const n=Yd.parse(o),{denied:r,avData:s}=await Ie(e,t,n.avID,"write",{blockID:n.blockID,action:"duplicate"});if(r)return r;const a=await yv(e,n.avID);if(!a.avID||!a.blockID)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Mt,action:"duplicate",reason:"duplicate_identifiers_missing",message:`Duplicate AV returned incomplete identifiers for source "${n.avID}".`,sourceAvID:n.avID,duplicatedAvID:a.avID,duplicatedBlockID:a.blockID}},null,2)}],isError:!0};const i=n.previousID??n.blockID??await ua(e,n.avID,s);if(!i)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Mt,action:"duplicate",reason:"duplicate_insert_target_unresolved",message:`Duplicated AV identifiers were prepared for source "${n.avID}", but MCP could not resolve a database block insertion target.`,sourceAvID:n.avID,duplicatedAvID:a.avID,duplicatedBlockID:a.blockID,hint:"SiYuan kernel duplicateAttributeViewBlock only prepares the duplicated AV definition. Provide previousID or ensure the source AV has a resolvable owning database block in the document tree."}},null,2)}],isError:!0};const c=await N(e,t,i,"write");if(c.denied)return c.denied;let l=Gp(a.blockID,a.avID);try{const u=await Np(e,l);typeof u.dom=="string"&&u.dom.length>0&&(l=u.dom)}catch{}try{await Oe(e,[{doOperations:[{action:"insert",id:a.blockID,data:l,previousID:i}],undoOperations:[{action:"delete",id:a.blockID}]}])}catch(u){const p=u instanceof Error?u:new Error(String(u));return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Mt,action:"duplicate",reason:"duplicate_insert_failed",message:p.message,sourceAvID:n.avID,duplicatedAvID:a.avID,duplicatedBlockID:a.blockID,insertedAfter:i,hint:"The duplicate AV definition was prepared, but MCP failed while inserting the duplicated database block into the document tree."}},null,2)}],isError:!0}}return xe({action:"duplicate",sourceAvID:n.avID,prepared:!0,materialized:!0,insertedAfter:i,semantics:n.previousID?"siyuan_duplicate_mirror_with_override":"siyuan_duplicate_mirror"},a)}async function gS({client:e,permMgr:t,rawArgs:o}){const n=Wd.parse(o),{denied:r}=await Ie(e,t,n.avID,"read");if(r)return r;const s=await $p(e,{id:n.avID,keyword:n.keyword,page:n.page,pageSize:n.pageSize}),a=s.blockIDs??[];if(a.length>0){const i=jo();await t.reload();const c=[],l=[];let u=0;for(let p=0;p<a.length;p+=1){const f=a[p],h=await Ho(e,{id:f},i)??await dt(e,f).catch(()=>null),g=h&&"notebook"in h?h.notebook:void 0;if(!g||!t.canRead(g)){u+=1;continue}c.push(f),l.push(s.rows[p])}return k({avID:n.avID,name:s.name,blockIDs:c,rows:l,...u>0?{filteredOutCount:u,partial:!0,reason:"permission_filtered"}:{}})}return k({avID:n.avID,...s})}const yS={get:sS,render:iS,get_attribute_view_keys:cS,get_attribute_view_filter_sort:lS,search:aS,add_rows:uS,remove_rows:dS,add_column:pS,remove_column:fS,set_cells:hS,duplicate:mS,get_primary_key_values:gS},bS=[S("get",zd,"Get the full attribute view payload by AV ID; blockID is an optional exact database-block context."),S("render",Fd,"Render an attribute view by id (AV ID, not avID) with optional paging/filtering; with createIfNotExist=true, materialize a SiYuan-style AV block under blockID."),S("get_attribute_view_keys",qd,"Get the column (key) definitions of an attribute view."),S("get_attribute_view_filter_sort",Ld,"Get filter and sort settings for an attribute view."),S("search",Bd,"Search attribute views by name or primary-key values."),S("add_rows",Ud,"Add bound block rows or detached plain-text primary-key rows to a database."),S("remove_rows",jd,"Remove rows from a database."),S("add_column",Hd,"Add a column to a database."),S("remove_column",Vd,"Remove a column from a database."),S("set_cells",Zd,"Set one or more cell values in a database. Provide cells/items, or pass rowID + columnID + valueType for a single-cell write."),S("duplicate",Yd,"Duplicate an attribute view using SiYuan copy-as-mirror semantics; previousID overrides the insertion target."),S("get_primary_key_values",Wd,"Get primary key values for an attribute view.")],Kp=De({name:"av",description:"🗃️ Grouped attribute-view (database) operations.",variants:bS,actionSchema:f_,aggregateOptions:{guidance:Kc,actionHints:il},handlers:yS});function wS(e){return Kp.listTools(e)}async function kS(e,t,o,n){return Kp.callTool(e,t,o,n)}const _S=/[\u200B\u200C\u200D\u2060\uFEFF]/g,vS=/<[^>]+>/g;function da(e){return e.replace(_S,"")}function Jp(e){return{...e,content:da(e.content)}}function Qp(e){return{...e,kramdown:da(e.kramdown)}}function Xp(e){return e.replace(vS,"")}function ef(e){const t=e==null?void 0:e.trim().toLowerCase();return t||void 0}const tf={d:"document",h:"heading",p:"paragraph",l:"list",i:"listItem",b:"blockquote",c:"codeBlock",m:"mathBlock",t:"table",s:"superBlock",html:"htmlBlock",embed:"embedBlock",av:"databaseBlock",video:"video",audio:"audio",widget:"widget"},Oi={keyword:0,query:1,query_syntax:1,sql:2,regex:3},IS={0:"keyword",1:"query_syntax",2:"sql",3:"regex"};function SS(e){const t={};for(const o of e){const n=tf[o];n&&(t[n]=!0)}return t}function DS(e){const t={};for(const[o,n]of Object.entries(e)){const r=tf[o];r?t[r]=n:t[o]=n}return t}function TS(e,t){const o=ef(e);return o&&o in Oi?Oi[o]:t}function AS(e){if(e!==void 0)return IS[e]}const PS={relevance:7,date:4,updated_desc:4,updated_asc:3,created_desc:2,created_asc:1,type:0},CS={7:"relevance",4:"updated_desc",3:"updated_asc",2:"created_desc",1:"created_asc",0:"type"},ES={relevance:0,relevance_desc:0,relevance_asc:1,updated_asc:2,updated_desc:3},RS={0:"relevance_desc",1:"relevance_asc",2:"updated_asc",3:"updated_desc"};function qr(e,t,o=PS){const n=ef(e);return n&&n in o?o[n]:t}function Ni(e){if(e!==void 0)return CS[e]}function xS(e,t){return qr(e,t,ES)}function OS(e){if(e!==void 0)return RS[e]}function NS(e,t){return Array.isArray(e.blocks)?{...e,blocks:e.blocks.map(o=>{if(!o||typeof o!="object")return o;const n=o,r={...n},s=typeof n.content=="string"?n.content:void 0;return s!==void 0&&(r.plainContent=Xp(s)),r})}:e}const $S=["id","type","box"],MS=["hPath","hpath"],zS=["content","plainContent","markdown","name","alias","memo","tag","subType","subtype","path","parentID","parent_id","rootID","root_id"];function $i(e){return!(e==null||e===""||Array.isArray(e)&&e.length===0)}function FS(e){const t={};for(const o of $S)o in e&&(t[o]=e[o]);for(const o of MS)if($i(e[o])){t.hPath=e[o];break}for(const o of zS)$i(e[o])&&(t[o]=e[o]);return t}const qS=/<mark>[^<]*<\/mark>/g,yr=400,LS=150;function BS(e,t=LS){if(e.length<=yr)return e;const o=[...e.matchAll(qS)];if(o.length===0)return e.length>yr?e.slice(0,yr)+"...":e;const n=[];for(const a of o){const i=Math.max(0,a.index-t),c=Math.min(e.length,a.index+a[0].length+t);n.push([i,c])}const r=[n[0]];for(let a=1;a<n.length;a++){const i=r[r.length-1],c=n[a];c[0]<=i[1]?i[1]=Math.max(i[1],c[1]):r.push(c)}const s=[];r[0][0]>0&&s.push("...");for(let a=0;a<r.length;a++)a>0&&s.push("..."),s.push(e.slice(r[a][0],r[a][1]));return r[r.length-1][1]<e.length&&s.push("..."),s.join("")}const Mi=400,zi=200;function US(e){return e.map(t=>{if(!t||typeof t!="object")return t;const n=FS(t);if(n.type==="NodeDocument")return n;if(typeof n.content=="string"){const r=Xp(n.content).trim();r.length>0&&(n.excerpt=r.length>zi?r.slice(0,zi)+"...":r),n.content=BS(n.content)}return typeof n.markdown=="string"&&n.markdown.length>Mi&&(n.markdown=n.markdown.slice(0,Mi)+"..."),n})}function jS(e){const t=NS({blocks:e});return US(Array.isArray(t.blocks)?t.blocks:[])}function HS(e){const t=e.notebook??e.box??e.boxID??e.notebookId;return typeof t=="string"&&t.length>0?t:void 0}async function of(e){const t=await at(e),o=new Map;for(const n of t.notebooks??[])n.id&&n.name&&o.set(n.id,n.name);return o}async function Lr(e,t){if(t)try{return(await of(e)).get(t)}catch{return}}async function VS(e,t){if(t.filter(n=>n!==null&&typeof n=="object").length===0)return t;try{const n=await of(e);return t.map(r=>{if(r===null||typeof r!="object")return r;const s=r,a=HS(s),i=a?n.get(a):void 0;return i?{...s,notebookName:i}:r})}catch{return t}}function ZS(e){if(!e||typeof e!="object")return;const t=e;return[t.notebook,t.box,t.boxID,t.notebookId].find(n=>typeof n=="string"&&n.length>0)}function Br(e,t){const o=e.filter(n=>{const r=ZS(n);return!r||t.canRead(r)});return{items:o,removedCount:e.length-o.length}}function ut(e){return e>0?{partial:!0,filteredOutCount:e,reason:"permission_filtered",permissionSummary:{filteredOutCount:e,reason:"permission_filtered",suggestion:'Some results were hidden due to notebook permissions. Use notebook(action="get_permissions") to review access before retrying broader searches.'}}:{}}function YS(e){return e instanceof Error?/permission[_\s-]?denied|has permission|read access is required|write access is required/i.test(e.message):!1}async function hn(e,t,o){const n=jo(),r=[];let s=0;for(const a of t){const i=await Ho(e,a,n);if(!(i!=null&&i.notebook)||!o.canRead(i.notebook)){s+=1;continue}r.push(a)}return{items:r,removedCount:s}}async function br(e,t,o,n){const r=jo(),s=[];let a=0,i=0;const c=typeof n=="string"&&n.length>0?n.startsWith("/")?n:`/${n}`:void 0;for(const l of t){const u=await Ho(e,l,r);if(!(u!=null&&u.notebook)||!o.canRead(u.notebook)){a+=1;continue}if(c&&(!u.path||!(u.path===c||u.path.startsWith(`${c}/`)))){i+=1;continue}s.push(l)}return{items:s,permissionFilteredOutCount:a,pathFilteredOutCount:i}}function Fi(e,t){if(!Array.isArray(e.blocks))return e;const{items:o,removedCount:n}=Br(e.blocks,t),r=new Set;for(const s of o){if(!s||typeof s!="object")continue;const a=s,i=[a.rootID,a.rootId,a.root_id,a.id,a.path].find(c=>typeof c=="string"&&c.length>0);i&&r.add(i)}return{...e,blocks:o,matchedBlockCount:o.length,matchedRootCount:r.size,...n>0?{filteredOutBlockCount:n}:{}}}function mn(e,t){const o=Array.isArray(e.backlinks)?Br(e.backlinks,t):void 0,n=Array.isArray(e.backmentions)?Br(e.backmentions,t):void 0,r=((o==null?void 0:o.removedCount)??0)+((n==null?void 0:n.removedCount)??0);return{...e,...o?{backlinks:o.items}:{},...n?{backmentions:n.items}:{},...ut(r)}}function WS(e){return e.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_").replace(/'/g,"''")}function GS(e){return!!e&&typeof e=="object"}const Fe="Only SELECT statements and WITH CTEs whose main statement is SELECT are allowed. Mutation queries (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE) are forbidden.";function KS(e){let t="",o=0;for(;o<e.length;){const n=e[o],r=e[o+1];if(n==="-"&&r==="-"){for(t+=" ",o+=2;o<e.length&&e[o]!==`
470
476
  `;)t+=" ",o+=1;continue}if(n==="/"&&r==="*"){for(t+=" ",o+=2;o<e.length;){if(e[o]==="*"&&e[o+1]==="/"){t+=" ",o+=2;break}t+=e[o]===`
471
477
  `?`
472
478
  `:" ",o+=1}continue}if(n==="'"||n==='"'||n==="`"){const s=n;for(t+=" ",o+=1;o<e.length;){const a=e[o];if(t+=a===`
473
479
  `?`
474
480
  `:" ",o+=1,a===s){if((s==="'"||s==='"')&&e[o]===s){t+=" ",o+=1;continue}break}}continue}if(n==="["){for(t+=" ",o+=1;o<e.length;){const s=e[o];if(t+=s===`
475
481
  `?`
476
- `:" ",o+=1,s==="]")break}continue}t+=n,o+=1}return t}function Ce(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function St(e,t){const o=Ce(e,t),n=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(o));return n?{keyword:n[0].toUpperCase(),end:o+n[0].length}:null}function GS(e,t){const o=Ce(e,t),n=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(e.slice(o));if(!n)throw new Error(Fe);return o+n[0].length}function zi(e,t){const o=Ce(e,t);if(e[o]!=="(")throw new Error(Fe);let n=0;for(let r=o;r<e.length;r+=1)if(e[r]==="("&&(n+=1),e[r]===")"&&(n-=1,n===0))return r+1;throw new Error(Fe)}function KS(e){const t=e.indexOf(";");if(!(t<0)&&e.slice(t+1).trim().length>0)throw new Error(Fe)}function JS(e,t){let o=Ce(e,t);const n=St(e,o);for((n==null?void 0:n.keyword)==="RECURSIVE"&&(o=n.end);o<e.length;){o=GS(e,o),o=Ce(e,o),e[o]==="("&&(o=zi(e,o),o=Ce(e,o));const r=St(e,o);if((r==null?void 0:r.keyword)!=="AS")throw new Error(Fe);o=Ce(e,r.end);const s=St(e,o);if((s==null?void 0:s.keyword)==="MATERIALIZED")o=Ce(e,s.end);else if((s==null?void 0:s.keyword)==="NOT"){const i=St(e,s.end);if((i==null?void 0:i.keyword)!=="MATERIALIZED")throw new Error(Fe);o=Ce(e,i.end)}if(o=zi(e,o),o=Ce(e,o),e[o]===","){o+=1;continue}const a=St(e,o);if((a==null?void 0:a.keyword)!=="SELECT")throw new Error(Fe);return}throw new Error(Fe)}function QS(e){const t=WS(e).trim();KS(t);const o=St(t,0);if((o==null?void 0:o.keyword)!=="SELECT"){if((o==null?void 0:o.keyword)==="WITH"){JS(t,o.end);return}throw new Error(Fe)}}async function XS(e,t){const o=await st(e,`SELECT content, name FROM blocks WHERE id = '${we(t)}' LIMIT 1`),n=Array.isArray(o)&&o[0]&&typeof o[0]=="object"?o[0]:null;if(!n)return;const r=[n.content,n.name].find(s=>typeof s=="string"&&s.trim().length>0);return r==null?void 0:r.trim()}async function eD(e,t,o,n){const s=["s.type = 'textmark block-ref'",`instr(s.markdown, '${we(t)}') > 0`];return n&&s.push(`s.root_id = '${we(n)}'`),o&&o.trim()&&s.push(`b.content LIKE '%${ZS(o.trim())}%' ESCAPE '\\'`),st(e,`
482
+ `:" ",o+=1,s==="]")break}continue}t+=n,o+=1}return t}function Ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function St(e,t){const o=Ee(e,t),n=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(o));return n?{keyword:n[0].toUpperCase(),end:o+n[0].length}:null}function JS(e,t){const o=Ee(e,t),n=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(e.slice(o));if(!n)throw new Error(Fe);return o+n[0].length}function qi(e,t){const o=Ee(e,t);if(e[o]!=="(")throw new Error(Fe);let n=0;for(let r=o;r<e.length;r+=1)if(e[r]==="("&&(n+=1),e[r]===")"&&(n-=1,n===0))return r+1;throw new Error(Fe)}function QS(e){const t=e.indexOf(";");if(!(t<0)&&e.slice(t+1).trim().length>0)throw new Error(Fe)}function XS(e,t){let o=Ee(e,t);const n=St(e,o);for((n==null?void 0:n.keyword)==="RECURSIVE"&&(o=n.end);o<e.length;){o=JS(e,o),o=Ee(e,o),e[o]==="("&&(o=qi(e,o),o=Ee(e,o));const r=St(e,o);if((r==null?void 0:r.keyword)!=="AS")throw new Error(Fe);o=Ee(e,r.end);const s=St(e,o);if((s==null?void 0:s.keyword)==="MATERIALIZED")o=Ee(e,s.end);else if((s==null?void 0:s.keyword)==="NOT"){const i=St(e,s.end);if((i==null?void 0:i.keyword)!=="MATERIALIZED")throw new Error(Fe);o=Ee(e,i.end)}if(o=qi(e,o),o=Ee(e,o),e[o]===","){o+=1;continue}const a=St(e,o);if((a==null?void 0:a.keyword)!=="SELECT")throw new Error(Fe);return}throw new Error(Fe)}function eD(e){const t=KS(e).trim();QS(t);const o=St(t,0);if((o==null?void 0:o.keyword)!=="SELECT"){if((o==null?void 0:o.keyword)==="WITH"){XS(t,o.end);return}throw new Error(Fe)}}async function tD(e,t){const o=await st(e,`SELECT content, name FROM blocks WHERE id = '${we(t)}' LIMIT 1`),n=Array.isArray(o)&&o[0]&&typeof o[0]=="object"?o[0]:null;if(!n)return;const r=[n.content,n.name].find(s=>typeof s=="string"&&s.trim().length>0);return r==null?void 0:r.trim()}async function oD(e,t,o,n){const s=["s.type = 'textmark block-ref'",`instr(s.markdown, '${we(t)}') > 0`];return n&&s.push(`s.root_id = '${we(n)}'`),o&&o.trim()&&s.push(`b.content LIKE '%${WS(o.trim())}%' ESCAPE '\\'`),st(e,`
477
483
  SELECT
478
484
  s.block_id AS id,
479
485
  s.root_id,
@@ -488,7 +494,7 @@ ${u}`);const p=Q_(e,o,r);return p.length>0&&l.push(p.join(" ")),l.join(`
488
494
  WHERE ${s.join(" AND ")}
489
495
  ORDER BY b.updated DESC
490
496
  LIMIT 200
491
- `.trim())}async function ef(e,t,o,n){const r=await XS(e,t);if(!r)return[];const s=[`id != '${we(t)}'`,`instr(content, '${we(r)}') > 0`];return n&&s.push(`root_id = '${we(n)}'`),o&&o.trim()&&s.push(`instr(content, '${we(o.trim())}') > 0`),st(e,`
497
+ `.trim())}async function nf(e,t,o,n){const r=await tD(e,t);if(!r)return[];const s=[`id != '${we(t)}'`,`instr(content, '${we(r)}') > 0`];return n&&s.push(`root_id = '${we(n)}'`),o&&o.trim()&&s.push(`instr(content, '${we(o.trim())}') > 0`),st(e,`
492
498
  SELECT
493
499
  id,
494
500
  root_id,
@@ -502,36 +508,36 @@ ${u}`);const p=Q_(e,o,r);return p.length>0&&l.push(p.join(" ")),l.join(`
502
508
  WHERE ${s.join(" AND ")}
503
509
  ORDER BY updated DESC
504
510
  LIMIT 200
505
- `.trim())}async function tD(e,t,o,n){const r=await xv(e,t,o,n);if(YS(r)&&(Array.isArray(r.backlinks)||Array.isArray(r.backmentions)))return{backlinks:Array.isArray(r.backlinks)?r.backlinks:[],backmentions:Array.isArray(r.backmentions)?r.backmentions:[]};const[s,a]=await Promise.all([eD(e,t,o,n),ef(e,t,o,n)]);return{backlinks:s,backmentions:a,fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}async function oD(e,t,o,n){const r=await Ov(e,t,o,n);return r&&typeof r=="object"&&Array.isArray(r.backmentions)?{backmentions:r.backmentions}:{backmentions:await ef(e,t,o,n),fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}const nD="search";function rD(e){return typeof e=="string"&&e.trim().length>0}function hr(e,t){return rD(t)?t:e}function nn(e){const t=Object.entries(e).filter(([,o])=>o!==void 0);return t.length===0?{}:{resolvedArgs:Object.fromEntries(t)}}function ua(e,t){return t?{showing:t.showing,truncated:t.truncated,hint:t.hint}:{showing:e,truncated:!1}}function uo(e){return Array.isArray(e)?LS(e):[]}function sD(e){let t=e.types?IS(e.types):e.types;return e.typeShortcodes&&e.typeShortcodes.length>0&&(t={...vS(e.typeShortcodes),...t}),t}function aD(e){return e.parentId?Math.min((e.pageSize??32)*3,128):e.pageSize}function iD(e,t){if(!Array.isArray(e.blocks))return;const o=t;e.blocks=e.blocks.filter(n=>n.rootID===o||n.root_id===o||n.parent_id===o||n.parentID===o),e.matchedBlockCount=e.blocks.length,e.parentIdFilter=o}function cD(e,t){Array.isArray(e.blocks)&&(e.blocks=e.blocks.filter(o=>{const r=(typeof o.tag=="string"?o.tag.trim():"").length>0;return t?r:!r}),e.matchedBlockCount=e.blocks.length)}function mr(e){const t=SS(e.methodName,e.method);return{...t!==void 0?{method:t}:{},...t!==void 0?{methodName:DS(t)}:{}}}function lD(e,t,o,n){const r=Array.isArray(e.blocks)?e.blocks:[],s=t.page??1,a=t.pageSize??32,i=Qs(r,20,`Use page/pageSize parameters to paginate. Current page: ${s}.`),c=r.length,l=typeof o.pageCount=="number"?o.pageCount:1,u=typeof e.filteredOutBlockCount=="number"?e.filteredOutBlockCount:0,p=u>0||!!t.parentId||t.hasTags!==void 0,h={total:p?c:typeof o.matchedBlockCount=="number"?o.matchedBlockCount:c,page:s,pageSize:a,pageCount:p?1:l,hasNextPage:p?!1:s<l},{blocks:g,pageCount:b,..._}=e;return We(i.items,h,{..._,...ut(u),...ua(c,i.meta),returnedTotal:c,returnedPageCount:1,returnedHasNextPage:!1,...o.matchedBlockCount!==void 0?{kernelMatchedBlockCount:o.matchedBlockCount}:{},...o.matchedRootCount!==void 0?{kernelMatchedRootCount:o.matchedRootCount}:{},kernelPageCount:l,kernelHasNextPage:s<l,...p?{paginationMode:"post_filtered_window",pagingHint:"kernel* pagination fields describe the raw SiYuan search page before permission and parent/tag post-filtering."}:{},...t.parentId&&c===0?{warning:"No matching blocks were found in the requested document subtree. If the content was just created or updated, SiYuan full-text indexing may still be catching up; retry shortly."}:{},...n?{resolvedArgs:n}:{}})}function uD(e,t,o){const n=Qs(e,50,"Add LIMIT and OFFSET to your SQL for pagination."),r=e.length;return k({data:n.items,total:r,totalRows:r,...ua(r,n.meta),...ut(t),...o?{resolvedArgs:o}:{}})}function dD(e,t,o,n){const r=Qs(t,20,"Use page/pageSize parameters to paginate asset content results."),s=t.length;return k({...e,assetContents:r.items,data:r.items,total:s,...ua(s,r.meta),...ut(o),...n?{resolvedArgs:n}:{}})}const pD={fulltext:async({client:e,permMgr:t,rawArgs:o})=>{const n=dp.parse(o);if(n.parentId){const{denied:f}=await N(e,t,n.parentId,"read");if(f)return f}const r=mr(n),s=$r(n.sortBy,n.orderBy),a=await Cv(e,{query:n.query,method:r.method,types:sD(n),paths:n.paths,groupBy:n.groupBy,orderBy:s,page:n.page,pageSize:aD(n)}),c=Mi(a,t),l={...c,blocks:uo(Array.isArray(c.blocks)?c.blocks:[])};n.parentId&&iD(l,n.parentId),n.hasTags!==void 0&&cD(l,n.hasTags),Array.isArray(l.blocks)&&(l.blocks=await jS(e,l.blocks));const p=n.methodName!==void 0||n.sortBy!==void 0?nn({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:xi(s)}:{}}).resolvedArgs:void 0;return lD(l,n,{matchedBlockCount:typeof a.matchedBlockCount=="number"?a.matchedBlockCount:void 0,matchedRootCount:typeof a.matchedRootCount=="number"?a.matchedRootCount:void 0,pageCount:typeof a.pageCount=="number"?a.pageCount:void 0},p)},query_sql:async({client:e,permMgr:t,rawArgs:o})=>{const n=pp.parse(o),r=hr(n.stmt,n.sql);try{QS(r??"")}catch(l){return bo(l,{tool:nD,action:"query_sql",rawArgs:o})}const s=await st(e,r??""),a=Array.isArray(s)?s:[],i=await un(e,a,t),c=n.sql!==void 0?nn({stmt:r}).resolvedArgs:void 0;return uD(i.items,i.removedCount,c)},get_backlinks:async({client:e,permMgr:t,rawArgs:o})=>{const n=fp.parse(o),r=hr(n.refTreeID,n.scopeRootId),s=n.mode??"both",{denied:a}=await N(e,t,n.id,"read");if(a)return a;try{const i=s!=="mentions"?await tD(e,n.id,n.keyword,r):{},c=s!=="links"?await oD(e,n.id,n.keyword,r):{},l={...i,...c},u=dn(l,t);return k({...u,mode:s,backlinks:s!=="mentions"?uo(Array.isArray(u.backlinks)?u.backlinks:[]):[],backmentions:s!=="links"?uo(Array.isArray(u.backmentions)?u.backmentions:[]):[],...l.sourcePayloadMissing?{sourcePayloadMissing:!0}:{},...l.fallbackQuery?{fallbackQuery:l.fallbackQuery}:{},...l.resultConfidence?{resultConfidence:l.resultConfidence}:{},...n.scopeRootId!==void 0?{resolvedArgs:{refTreeID:r}}:{},...l.fallbackUsed?{warning:"SiYuan returned no backlink/backmention payload; SQL fallback results are shown."}:{}})}catch(i){if(VS(i))return k({backlinks:[],backmentions:[],warning:"SiYuan rejected part of the backlink/backmention query due to restricted notebooks; restricted results were omitted.",partial:!0,reason:"permission_filtered",permissionSummary:ut(1).permissionSummary});throw i}},search_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=hp.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Nv(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.blocks)?a.blocks:[],c=await un(e,i,t),l=uo(c.items);return k({...a,blocks:l,data:l,total:l.length,showing:l.length,truncated:!1,...ut(c.removedCount)})},find_replace:async({client:e,permMgr:t,rawArgs:o})=>{const n=mp.parse(o);for(const i of n.ids){const{denied:c}=await N(e,t,i,"write");if(c)return c}if(Array.isArray(n.paths))for(const i of n.paths){const c=await xo(e,i);if(!c)continue;const l=await Y(t,c,"write");if(l)return l}const r=mr(n),s=$r(n.sortBy,n.orderBy);await $v(e,{k:n.k,r:n.r,ids:n.ids,...n.paths?{paths:n.paths}:{},...n.types?{types:n.types}:{},...r.method!==void 0?{method:r.method}:{},...s!==void 0?{orderBy:s}:{},...n.groupBy!==void 0?{groupBy:n.groupBy}:{},...n.replaceTypes?{replaceTypes:n.replaceTypes}:{}});const a=n.methodName!==void 0||n.sortBy!==void 0;return k({success:!0,replaced:!0,ids:n.ids,k:n.k,r:n.r,...n.paths?{paths:n.paths}:{},...a?{resolvedArgs:nn({...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:xi(s)}:{}}).resolvedArgs}:{}})},search_assets:async({client:e,rawArgs:t})=>{const o=gp.parse(t),n=hr(o.k,o.query)??"",r=await Mv(e,n,o.exts);return o.query===void 0?k(r):k({...r&&typeof r=="object"&&!Array.isArray(r)?r:{data:r},resolvedArgs:{query:n}})},fulltext_asset_content:async({client:e,permMgr:t,rawArgs:o})=>{const n=yp.parse(o);if(n.assetId){const p=await zv(e,n.assetId,n.query??"",n.queryMethod??0);return k(p)}const r=mr(n),s=CS(n.sortBy,n.orderBy),a=await Fv(e,{query:n.query,...n.types?{types:n.types}:{},...r.method!==void 0?{method:r.method}:{},...s!==void 0?{orderBy:s}:{},...n.page!==void 0?{page:n.page}:{},...n.pageSize!==void 0?{pageSize:n.pageSize}:{}}),i=a&&typeof a=="object"?a:{},c=Array.isArray(i.assetContents)?i.assetContents:[],l=await un(e,c,t),u=n.methodName!==void 0||n.sortBy!==void 0;return dD(i,l.items,l.removedCount,u?nn({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:RS(s)}:{}}).resolvedArgs:void 0)},list_invalid_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=bp.parse(o),r=await qv(e,n.page,n.pageSize),a=Mi(r??{},t),i=Array.isArray(a.blocks)?a.blocks:[],c=uo(i);return k({...a,blocks:c,data:c,total:c.length,showing:c.length,truncated:!1,...ut(typeof a.filteredOutBlockCount=="number"?a.filteredOutBlockCount:0)})}},fD="search",hD=[S("fulltext",dp,"Full-text search across all blocks."),S("query_sql",pp,"Execute a read-only SQL query against the database."),S("get_backlinks",fp,"Find documents/blocks that link to or mention the given block."),S("search_refs",hp,"Search blocks that reference a given block or document."),S("find_replace",mp,"Find and replace text in documents or blocks."),S("search_assets",gp,"Search asset files by filename."),S("fulltext_asset_content",yp,"Full-text search indexed asset contents."),S("list_invalid_refs",bp,"List invalid block references.")],tf=De({name:fD,description:"🔍 Grouped search and query operations.",variants:hD,actionSchema:k_,aggregateOptions:{guidance:il,actionHints:cl,guidanceInlineLimit:5},handlers:pD});function mD(e){return tf.listTools(e)}async function gD(e,t,o,n){return tf.callTool(e,t,o,n)}const yD=/\n?\{:\s*(?=[^}]*\bid\s*=)([^}]*)\}\s*$/s,of=/<span\b(?=[^>]*\bdata-type=(?:"[^"]*\bblock-ref\b[^"]*"|'[^']*\bblock-ref\b[^']*'))([^>]*)>([\s\S]*?)<\/span>/gi,bD=/<span\b(?=[^>]*\bdata-type=(?:"[^"]*\btag\b[^"]*"|'[^']*\btag\b[^']*'))([^>]*)>([\s\S]*?)<\/span>/gi,wD=/^<span\b(?=[^>]*\bdata-type=(?:"[^"]*\bblock-ref\b[^"]*"|'[^']*\bblock-ref\b[^']*'))([^>]*)>([\s\S]*?)<\/span>$/i,kD=/^<span\b(?=[^>]*\bdata-type=(?:"[^"]*\btag\b[^"]*"|'[^']*\btag\b[^']*'))([^>]*)>([\s\S]*?)<\/span>$/i,Yt=/\sdata-id=(?:"([^"]+)"|'([^']+)')/i,nf=/\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])(.*?)\2\)\)/g,Fi=/\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])(.*?)\2\)\)/,_D=/^\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])(.*?)\2\)$/,rf=/\(\(([0-9]{14}-[a-z0-9]{7})\)\)/,vD=/\[[^\]]+\]\(siyuan:\/\/blocks\/[0-9]{14}-[a-z0-9]{7}\)/i,ID=/\[\^\d+\]|^\[\^\d+\]:/m,SD=/#([^#\s][^#\n]*?)#/g,qi=/#([^#\s][^#\n]*?)#/,sf=/\sdata-type=(?:"[^"]*\b(?:tag|block-ref)\b[^"]*"|'[^']*\b(?:tag|block-ref)\b[^']*')/i,DD=/^<\s*(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\b/i,AD=/[\u200B\u200C\u200D\u2060\uFEFF]/,af=/[\u200B\u200C\u200D\u2060\uFEFF]/g,Bi=/^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)(.*)$/,TD=/^(\s*(?:>\s*)*)(`{3,}|~{3,}|\$\$).*$/,cf=/^\s*\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,lf=/^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*/,PD=/^(\s*(?:>\s*)+)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,ED=/^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,CD=/^(\s*(?:>\s*)+(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*/,RD=/^(\s*(?:>\s*)+(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,xD=/^\s*(?:>\s*)+$/,OD="siyuan://blocks Markdown links are allowed, but SiYuan treats them as mentions, not backlinks. Use ((id '完整标题')) when you need a real backlink.",ND="Footnote-style references like [^1] are allowed, but they create footnotes or note markers, not SiYuan backlinks. Use ((id '完整标题')) when you need a real backlink.",$D="Naked block references like ((id)) are allowed and normalized before writing. If the target anchor cannot be resolved, MCP uses the block ID as fallback anchor text; pass ((id '完整标题')) when exact readable text matters.";function Wt(e){return vD.test(e)}function Gt(e){return ID.test(e)}function Oo(){return{warning:"siyuan://blocks Markdown links create mentions, not backlinks.",hint:OD}}function No(){return{warning:"Footnote-style references create footnotes or note markers, not backlinks.",hint:ND}}function Kt(e){return/\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])\1\2\)\)/.test(e)}function $o(){return{warning:"Some naked block references used the block ID as fallback anchor text.",hint:$D}}function Ke(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function tt(e){return e.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(t,o)=>{const n=o.toLowerCase();if(n==="amp")return"&";if(n==="lt")return"<";if(n==="gt")return">";if(n==="quot")return'"';if(n==="apos")return"'";if(n==="nbsp")return" ";if(n.startsWith("#x")){const r=Number.parseInt(n.slice(2),16);return Number.isFinite(r)?String.fromCodePoint(r):t}if(n.startsWith("#")){const r=Number.parseInt(n.slice(1),10);return Number.isFinite(r)?String.fromCodePoint(r):t}return t})}function da(e){const t=e.match(yD);return t?{content:Fr(e.slice(0,t.index).trimEnd()),ial:t[0].trim()}:{content:Fr(e.trimEnd()),ial:""}}function MD(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Fr(e){return e.replace(nf,(t,o,n,r)=>`((${o} '${MD(r)}'))`)}function zD(e){return e.replace(of,(t,o,n)=>{var a,i;const r=((a=o.match(Yt))==null?void 0:a[1])??((i=o.match(Yt))==null?void 0:i[2]);if(!r)return t;const s=tt(n.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim().replace(/\\/g,"\\\\").replace(/'/g,"\\'");return s?`((${r} '${s}'))`:t})}function FD(e){return e.replace(bD,(t,o,n)=>{const r=tt(n.replace(/<[^>]+>/g,"")).replace(af,"").replace(/\s+/g," ").trim();return r?r.startsWith("#")&&r.endsWith("#")?r:`#${r}#`:t})}function pa(e,t){const o=e.match(TD);if(!o)return t;const n=o[2];if(!n)return t;const r=n[0],s=n.length;return t?r===t.marker&&s>=t.length?null:t:{marker:r,length:s}}function qD(e,t){if(t!=="l")return e.trimEnd();const o=[];let n=null;for(const r of e.split(/\r?\n/)){const s=n!==null;if(n=pa(r,n),s||s!==(n!==null)){o.push(r);continue}const i=r.replace(lf,"$1");cf.test(i)||o.push(i)}return o.join(`
506
- `).trimEnd()}function BD(e,t){if(t!=="b"&&t!=="callout"&&t!=="s")return e.trimEnd();const o=[];let n=null,r=!1;for(const s of e.split(/\r?\n/)){const a=n!==null;if(n=pa(s,n),a||a!==(n!==null)){o.push(s);continue}if(cf.test(s)){r=!1;continue}if(PD.test(s)){r=!0;continue}if(!(r&&xD.test(s))){if(ED.test(s)||RD.test(s)){r=!1;continue}r=!1,o.push(s.replace(lf,"$1").replace(CD,"$1"))}}return o.join(`
507
- `).trimEnd()}function LD(e){const t=[];let o=null;for(const n of e.split(/\r?\n/)){const r=o!==null;o=pa(n,o);const s=r!==(o!==null);t.push(r||s?n:n.replace(af,""))}return t.join(`
508
- `).trimEnd()}function fa(e){const t=da(e.kramdown),o=FD(zD(t.content));return LD(BD(qD(o,e.type),e.type))}function UD(e,t){return fa({kramdown:e,type:t})}function uf(e,t){const o=e.trimEnd();return t.ial?`${o}
509
- ${t.ial}`:o}function df(e,t){let o=0,n=0;for(;;){if(n=e.indexOf(t,n),n===-1)return o;o+=1,n+=t.length}}function qr(e,t){const o=df(e,t.old);if(o===0)return{content:e,replaced:0,replaceAll:!!t.replace_all};if(t.replace_all)return{content:e.split(t.old).join(t.new),replaced:o,replaceAll:!0};const n=e.indexOf(t.old);return{content:`${e.slice(0,n)}${t.new}${e.slice(n+t.old.length)}`,replaced:1,replaceAll:!1}}function jD(e){if(/[\r\n]/.test(e.old)||/[\r\n]/.test(e.new))return null;const t=e.old.match(Bi);if(!t)return null;const o=e.new.match(Bi);return o&&o[1]!==t[1]?null:{...e,old:t[2]??"",new:o?o[2]??"":e.new}}function HD(e,t,o){if(o==="l"){const r=jD(t);if(r){const s=qr(e,r);if(s.replaced>0)return{edit:r,...s}}}const n=qr(e,t);return{edit:t,...n}}function VD(e){return Ke(e).replace(/\n/g,"<br>")}function ZD(e,t,o){const n=t.old.match(_D);if(!n)return null;const r=n[1],s=n[3];let a=0;return{dom:e.replace(of,(c,l,u)=>{var h,g;if(a>=o)return c;const p=((h=l.match(Yt))==null?void 0:h[1])??((g=l.match(Yt))==null?void 0:g[2]),f=tt(u.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim();return p!==r||f!==s?c:(a+=1,Yn(t.new))}),replaced:a}}function Dn(e,t,o,n){for(const r of t)AD.test(r)||e.push({value:r,start:o,end:n})}function Li(e,t,o){let n=0;for(;n<t.length;){if(t[n]==="&"){const r=t.indexOf(";",n+1);if(r!==-1){const s=t.slice(n,r+1),a=tt(s);if(a!==s){Dn(e,a,o+n,o+r+1),n=r+1;continue}}}Dn(e,t[n],o+n,o+n+1),n+=1}}function Ui(e,t,o){const r=e.slice(o).match(t);return(r==null?void 0:r.index)===void 0?-1:o+r.index}function ji(e,t){const o=e.indexOf(">",t);if(o===-1)return-1;let n=1,r=o+1;for(;r<e.length;){const s=Ui(e,/<\s*span\b[^>]*>/i,r),a=Ui(e,/<\s*\/\s*span\s*>/i,r);if(a===-1)return-1;if(s!==-1&&s<a){n+=1;const c=e.indexOf(">",s);if(c===-1)return-1;r=c+1;continue}n-=1;const i=e.indexOf(">",a);if(i===-1)return-1;if(n===0)return i+1;r=i+1}return-1}function YD(e){var n,r;const t=e.match(wD);if(t){const s=t[1]??"",a=t[2]??"",i=((n=s.match(Yt))==null?void 0:n[1])??((r=s.match(Yt))==null?void 0:r[2]),c=tt(a.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim();return i&&c?`((${i} '${c}'))`:null}const o=e.match(kD);if(o){const s=tt((o[2]??"").replace(/<[^>]+>/g,"")).trim();return s.startsWith("#")&&s.endsWith("#")?s:`#${s}#`}return null}function pf(e){const t=[];let o=0;for(;o<e.length;){const n=e.indexOf("<",o),r=n===-1?e.length:n;if(r>o&&Li(t,e.slice(o,r),o),n===-1)break;const s=e.indexOf(">",n);if(s===-1)break;const a=e.slice(n,s+1);if(sf.test(a)&&/^<\s*span\b/i.test(a)){const i=ji(e,n);if(i!==-1){const c=e.slice(n,i),l=YD(c);if(l){Dn(t,l,n,i),o=i;continue}}}if(/^<\s*br\b/i.test(a)&&Dn(t,`
510
- `,n,s+1),/^<\s*span\b/i.test(a)){const i=ji(e,n);if(i!==-1){const c=e.slice(n,i),l=c.indexOf(">")+1,u=c.lastIndexOf("</span>");if(l>0&&u>=l){const p=c.slice(l,u),f=[];Li(f,p.replace(/<[^>]+>/g,""),n+l);for(const h of f)t.push({value:h.value,start:n,end:i});o=i;continue}}}o=s+1}return t}function WD(e,t,o){var s,a;let n=e,r=0;for(;r<o;){const i=pf(n),l=i.map(h=>h.value).join("").indexOf(t.old);if(l===-1)break;const u=l+t.old.length-1,p=(s=i[l])==null?void 0:s.start,f=(a=i[u])==null?void 0:a.end;if(p===void 0||f===void 0)break;n=`${n.slice(0,p)}${Yn(t.new)}${n.slice(f)}`,r+=1}return{dom:n,replaced:r}}function GD(e,t){const n=pf(e).map(a=>a.value).join(""),r=n.length>240?`${n.slice(0,240)}...`:n,s=t.old.length>160?`${t.old.slice(0,160)}...`:t.old;return` DOM logical text preview: ${JSON.stringify(r)}. Old preview: ${JSON.stringify(s)}.`}function KD(e,t,o,n){if(o<=0)return{segment:e,replaced:0};if(n&&/^#[^#\s][^#\n]*#$/.test(t.old))return{segment:e,replaced:0};const r=tt(e),s=df(r,t.old);if(s===0)return{segment:e,replaced:0};const a=Math.min(s,o);let i="",c=0,l=0;for(;c<a;){const u=r.indexOf(t.old,l);if(u===-1)break;i+=Ke(r.slice(l,u)),i+=n?VD(t.new):Yn(t.new),l=u+t.old.length,c+=1}return i+=Ke(r.slice(l)),{segment:i,replaced:c}}function ff(e,t){if(/^<\s*\/\s*[^>]+>/.test(e)){t.pop();return}/^<\s*[!?]/.test(e)||/\/\s*>$/.test(e)||DD.test(e)||t.push(sf.test(e))}function hf(e,t,o,n,r){const s=ZD(e,t,o);if(s)return s;let a="",i=0,c=0;const l=[];for(;i<e.length;){const u=e.indexOf("<",i),p=u===-1?e.length:u;if(p>i){const g=e.slice(i,p),b=KD(g,t,o===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:o-c,l.some(Boolean));a+=b.segment,c+=b.replaced}if(u===-1)break;const f=e.indexOf(">",u);if(f===-1)throw new Error(`${n} cannot safely update DOM for edit #${r+1}: malformed block DOM.`);const h=e.slice(u,f+1);if(a+=h,ff(h,l),i=f+1,c>=o)return a+=e.slice(i),{dom:a,replaced:c}}return c>0?{dom:a,replaced:c}:WD(e,t,o)}function mf(e,t,o,n,r,s){if(n!==o)throw new Error(`${e} cannot safely map edit #${t+1} from kramdown to DOM. The match may cross unsupported inline formatting; narrow the old text or use block.update/fs.write for a full block rewrite. Expected ${o} DOM replacement(s), got ${n}.${GD(r,s)}`)}function gf(e,t,o){if(/\{:\s*[^}]*\bid=/.test(e.old)||/\{:\s*[^}]*\bid=/.test(e.new))throw new Error(`${t} edit #${o+1} appears to modify block IAL metadata. Use block(action="set_attrs") for attributes and keep content replacements inside the block body.`)}function JD(e,t,o,n){const r=da(e);let s=r.content,a=t;const i=[];o.forEach((l,u)=>{gf(l,n,u);const p=qr(s,l);if(p.replaced===0){const h=" block.replace only searches the content body of the single block identified by id; it does not include child blocks, sibling blocks, the whole document, or block IAL metadata.";throw new Error(`${n} edit #${u+1} did not match any text.${h}`)}const f=hf(a,l,p.replaceAll?Number.POSITIVE_INFINITY:1,n,u);mf(n,u,p.replaced,f.replaced,a,l),s=p.content,a=f.dom,i.push({index:u+1,replaced:p.replaced,replace_all:p.replaceAll})});const c=uf(s,r);return yf(c),{kramdown:c,markdown:s,dom:a,summary:i}}function Br(e){return Fi.test(e.old)||Fi.test(e.new)||qi.test(e.old)||qi.test(e.new)}function QD(e,t,o){const n=e.map(a=>({id:a.id,parsed:da(a.kramdown),editableContent:fa(a),dom:a.dom,type:a.type})),r=new Map,s=[];return t.forEach((a,i)=>{gf(a,o,i);let c=0;for(const l of n){if(!a.replace_all&&c>0)break;const u=l.editableContent,p=HD(l.editableContent,a,l.type);if(p.replaced===0)continue;const f=hf(l.dom,p.edit,p.replaceAll?Number.POSITIVE_INFINITY:1,o,i);if(mf(o,i,p.replaced,f.replaced,l.dom,p.edit),l.editableContent=p.content,l.dom=f.dom,c+=p.replaced,p.content!==u){const h=uf(l.editableContent,l.parsed);yf(h);const g=r.get(l.id);r.set(l.id,{id:l.id,kramdown:h,markdown:l.editableContent,dom:l.dom,type:l.type,touchesIndexedInline:!!(g!=null&&g.touchesIndexedInline)||Br(a)||Br(p.edit)})}}if(c===0)throw new Error(`${o} edit #${i+1} did not match any text in editable document blocks. Cross-block replacements are not allowed because they would require rebuilding blocks.`);s.push({index:i+1,replaced:c,replace_all:!!a.replace_all})}),{blocks:[...r.values()],summary:s}}function yf(e){if(rf.test(e))throw new Error("Refusing to write naked block references like ((id)). Use ((id '完整标题')) so the anchor text is explicit.")}function Lr(e,t,o={}){if(!o.allowNakedBlockRefs&&rf.test(e))throw new Error(`${t} refuses naked block references like ((id)). Use ((id '完整标题')) so the anchor text is explicit.`)}function Hi(e){let t="",o=0;for(const n of e.matchAll(SD)){t+=Ke(e.slice(o,n.index));const r=n[0],s=n[1];t+=`<span data-type="tag">${Ke(s)}</span>`,o=(n.index??0)+r.length}return t+=Ke(e.slice(o)),t}function Yn(e){let t="",o=0;for(const n of e.matchAll(nf)){t+=Hi(e.slice(o,n.index));const r=n[1],s=n[3];t+=`<span data-type="block-ref" data-subtype="s" data-id="${Ke(r)}">${Ke(s)}</span>`,o=(n.index??0)+n[0].length}return t+=Hi(e.slice(o)),t.replace(/\n/g,"<br>")}function XD(e,t){Lr(e,t);let o="",n=0;const r=[];for(;n<e.length;){const s=e.indexOf("<",n),a=s===-1?e.length:s;if(a>n){const l=e.slice(n,a);o+=r.some(Boolean)?l:Yn(tt(l))}if(s===-1)break;const i=e.indexOf(">",s);if(i===-1)throw new Error(`${t} cannot safely normalize DOM: malformed block DOM.`);const c=e.slice(s,i+1);o+=c,ff(c,r),n=i+1}return o}function bf(e,t){var i;const o=t==null?void 0:t.trim(),n=e.replace(/^\uFEFF/,""),r=((i=n.match(/^\s*/))==null?void 0:i[0])??"",s=n.slice(r.length);if(!o)return e;const a=new RegExp(`^#\\s+${eA(o)}(?:\\s*\\r?\\n|\\s*$)`);return a.test(s)?`${r}${s.replace(a,"").replace(/^\r?\n+/,"")}`:e}function eA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Vi=/\(\(([0-9]{14}-[a-z0-9]{7})\)\)/g;function tA(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function oA(e){return e.replace(/\{:\s*[^}]*\}/g,"").replace(/^#{1,6}\s+/,"").replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\(\(([0-9]{14}-[a-z0-9]{7})\s+'([^']+)'\)\)/g,"$2").replace(/[*_~`=]/g,"").replace(/\s+/g," ").trim()}function Zi(e){return e.split(/\r?\n/).map(t=>oA(t)).find(t=>t.length>0)??""}async function nA(e,t){try{const o=await io(e,t),n=typeof o.kramdown=="string"?Zi(UD(o.kramdown)):"";if(n)return n}catch{}try{const o=await Mp(e,t);if(o&&typeof o=="object"){const n=o;for(const r of["content","fcontent","name","markdown"]){const s=n[r];if(typeof s=="string"){const a=Zi(s);if(a)return a}}}}catch{}return t}async function Jt(e,t,o){const n=Fr(t);Lr(n,o,{allowNakedBlockRefs:!0});const r=[...new Set([...n.matchAll(Vi)].map(i=>i[1]))];if(r.length===0)return n;const s=new Map;await Promise.all(r.map(async i=>{s.set(i,await nA(e,i))}));const a=n.replace(Vi,(i,c)=>{const l=s.get(c);return`((${c} '${tA(l??c)}'))`});return Lr(a,o),a}async function wf(e,t,o){return Promise.all(t.map(async n=>({...n,old:await Jt(e,n.old,o),new:await Jt(e,n.new,o)})))}async function Ur(e,t){if(typeof e.request=="function")try{const o=await e.request("/api/query/sql",{stmt:`SELECT type FROM blocks WHERE id = '${String(t).replace(/\0/g,"").replace(/'/g,"''")}' LIMIT 1`}),n=Array.isArray(o)?o[0]:void 0;return n&&typeof n=="object"&&typeof n.type=="string"?n.type:void 0}catch{return}}function jr(e){return{databaseBlock:!0,warning:`${e} operated on a database/attribute-view block container. To read or edit database rows, columns, or cells, use av(action="get"|"render"|"add_rows"|"remove_rows"|"add_column"|"remove_column"|"set_cells") with the attribute view ID instead of editing the block as markdown.`,avToolHint:{read:'av(action="get", id="<av-id>") or av(action="render", id="<av-id>", blockID="<database-block-id>")',write:'av(action="set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column", avID="<av-id>", ...)'}}}function Wn(e,t){return{...e,...Wt(t)?Oo():{},...Gt(t)?No():{},...Kt(t)?$o():{}}}function ha(e){return Wt(e)||Gt(e)||Kt(e)}function Gn(e){return Wn({},e)}function rA(e){return typeof e!="string"?!1:e!=="d"}function sA(e){if(!e||typeof e!="object")return{};const t=e;return{...typeof t.id=="string"?{id:t.id}:{},...typeof t.type=="string"?{type:t.type}:{},...typeof t.subtype=="string"?{subtype:t.subtype}:{},...typeof t.content=="string"?{content:t.content}:{},...typeof t.path=="string"?{path:t.path}:{}}}async function aA(e,t){const o=Lo(),n=new Map;let r=!1;for(const s of t){s&&typeof s=="object"&&rA(s.type)&&(r=!0);const a=await Uo(e,s,o);if(!(a!=null&&a.documentId)||!a.notebook||!a.path)continue;let i=n.get(a.documentId);if(!i){let c,l;try{const u=await dt(e,a.documentId);c=u.name,l=u.hPath}catch{c=void 0,l=void 0}i={documentId:a.documentId,notebook:a.notebook,path:a.path,...l?{hPath:l}:{},...c?{name:c}:{},updatedBlockCount:0,sampleBlocks:[]},n.set(a.documentId,i)}i.updatedBlockCount+=1,i.sampleBlocks.length<3&&i.sampleBlocks.push(sA(s))}return{documents:[...n.values()],containsLowLevelBlocks:r}}function ma(e,t){const o=Array.isArray(e)?e[0]:e,n=o&&typeof o=="object"&&Array.isArray(o.doOperations)?o.doOperations[0]:void 0,r=typeof(n==null?void 0:n.id)=="string"?n.id:void 0,s=typeof(n==null?void 0:n.parentID)=="string"?n.parentID:t.parentID,a=typeof(n==null?void 0:n.previousID)=="string"?n.previousID:t.previousID,i=typeof(n==null?void 0:n.nextID)=="string"?n.nextID:t.nextID,c={action:t.action,...r?{id:r}:{},...s?{parentID:s}:{},...a?{previousID:a}:{},...i?{nextID:i}:{},dataType:t.dataType};for(const[l,u]of Object.entries(t))["action","dataType","parentID","previousID","nextID"].includes(l)||(c[l]=u);return xe(c)}function iA(e,t){const o={success:!0,id:t.id,dataType:t.dataType};for(const[n,r]of Object.entries(t))["id","dataType","data"].includes(n)||(o[n]=r);if(t.dataType==="markdown"&&(o.markdown=la(t.data)),Object.assign(o,Gn(t.data)),e&&typeof e=="object"&&!Array.isArray(e)){const n=e.updated;n!==void 0&&(o.updated=n)}return t.dataType==="markdown"&&/[\r\n]/.test(t.data)&&(o.warning="block(update) is best for single-block replacement. Multi-line markdown may be truncated to the first line by SiYuan; use block(append), block(prepend), or block(insert) when you need multiple blocks or tables."),k(o)}function cA(e){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:"block",action:"insert",message:'Invalid arguments for block(action="insert").',fields:[{path:`blocks[${e}].previousID`,message:"Provide nextID, previousID, or parentID for each block, or set a batch-level parentID/previousID/nextID."}]}},null,2)}],isError:!0}}async function lA(e,t,o){return Promise.all(t.map(async n=>({...n,data:await yt(e,n.dataType,n.data,"block.insert"),nextID:n.nextID??o.nextID,previousID:n.previousID??o.previousID,parentID:n.parentID??o.parentID})))}async function yt(e,t,o,n){return t==="dom"?XD(o,n):Jt(e,o,n)}async function uA(e,t){return Promise.all(t.map(async o=>({...o,data:await yt(e,o.dataType,o.data,"block.update")})))}function dA(e){const t=Array.isArray(e)?e:[e],o=[];for(const n of t){if(!n||typeof n!="object")continue;const r=n.doOperations;if(Array.isArray(r))for(const s of r){if(!s||typeof s!="object")continue;const a=s.id;typeof a=="string"&&a.length>0&&!o.includes(a)&&o.push(a)}}return o}function pA(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:"block",action:"insert",reason:"empty_transaction_result",message:`SiYuan accepted insert for ${e} block(s), but returned no created block IDs.`,hint:"Check that each item includes nextID, previousID, or parentID, or provide one batch-level parentID/previousID/nextID, then retry. MCP now rejects no-op insert responses instead of reporting success.",transactions:t}},null,2)}],isError:!0}}const fA=async({client:e,permMgr:t,rawArgs:o})=>{const n=fd.parse(o);if(n.blocks){const c=await lA(e,n.blocks,{parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),l=new Set;for(const[f,h]of c.entries()){const g=h.nextID||h.previousID||h.parentID;if(!g)return cA(f);const{denied:b,context:_}=await N(e,t,g,"write");if(b)return b;l.add(_.documentId)}const u=await Dv(e,c),p=dA(u);return p.length===0?pA(c.length,u):F(e,k({success:!0,action:"insert",count:c.length,createdBlockIDs:p,transactions:u,...c.some(f=>ha(f.data))?Gn(c.map(f=>f.data).join(`
511
- `)):{}}),[...l].map(f=>({type:"reloadProtyle",id:f})))}const r=n.nextID||n.previousID||n.parentID;let s;if(r){const{denied:c,context:l}=await N(e,t,r,"write");if(c)return c;s=l.documentId}const a=await yt(e,n.dataType,n.data,"block.insert"),i=await gv(e,n.dataType,a,n.nextID,n.previousID,n.parentID);return F(e,ma(i,Wn({action:"insert",dataType:n.dataType,parentID:n.parentID,previousID:n.previousID,nextID:n.nextID},a)),s?[{type:"reloadProtyle",id:s}]:[])},hA=async({client:e,permMgr:t,rawArgs:o})=>{const n=hd.parse(o),{denied:r,context:s}=await N(e,t,n.parentID,"write");if(r)return r;const a=await yt(e,n.dataType,n.data,"block.prepend"),i=await yv(e,n.dataType,a,n.parentID);return F(e,ma(i,Wn({action:"prepend",dataType:n.dataType,parentID:n.parentID},a)),[{type:"reloadProtyle",id:s.documentId}])},mA=async({client:e,permMgr:t,rawArgs:o})=>{const n=md.parse(o),{denied:r,context:s}=await N(e,t,n.parentID,"write");if(r)return r;const a=await yt(e,n.dataType,n.data,"block.append"),i=await Np(e,n.dataType,a,n.parentID);return F(e,ma(i,Wn({action:"append",dataType:n.dataType,parentID:n.parentID},a)),[{type:"reloadProtyle",id:s.documentId}])},gA=async({client:e,permMgr:t,rawArgs:o})=>{const n=gd.parse(o);if(n.items){const l=await uA(e,n.items),u=new Set,p=[];for(const h of l){const{denied:g,context:b}=await N(e,t,h.id,"write");if(g)return g;await Ur(e,h.id)==="av"&&p.push(h.id),u.add(b.documentId)}const f=await Av(e,l);return F(e,k({success:!0,action:"update",count:n.items.length,transactions:f,...l.some(h=>ha(h.data))?Gn(l.map(h=>h.data).join(`
512
- `)):{},...p.length>0?{databaseBlockIds:p,...jr("block.update")}:{}}),[...u].map(h=>({type:"reloadProtyle",id:h})))}const{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a=await Ur(e,n.id)==="av",i=await yt(e,n.dataType,n.data,"block.update"),c=await na(e,n.dataType,i,n.id);return F(e,iA(c,{id:n.id,dataType:n.dataType,data:i,...a?jr("block.update"):{}}),[{type:"reloadProtyle",id:s.documentId}])},yA=async({client:e,permMgr:t,rawArgs:o})=>{const n=yd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a=Gp(await io(e,n.id)),i=typeof a.kramdown=="string"?a.kramdown:"",c=await Hn(e,n.id),l=typeof c.dom=="string"?c.dom:"",u=await wf(e,Array.isArray(n.edit)?n.edit:[n.edit],"block.replace"),{kramdown:p,markdown:f,dom:h,summary:g}=JD(i,l,u,"block.replace"),b=p!==i;if(b){const _=u.some(Br);await na(e,_?"markdown":"dom",_?f:h,n.id)}return F(e,k({success:!0,action:"replace",id:n.id,changed:b,editsApplied:g.length,replacements:g,...ha(p)?Gn(p):{}}),b?[{type:"reloadProtyle",id:s.documentId}]:[])},bA=async({client:e,permMgr:t,rawArgs:o})=>{const n=bd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"delete");if(r)return r;const a=await Ur(e,n.id)==="av";return await $p(e,n.id),F(e,k({success:!0,id:n.id,...a?jr("block.delete"):{}}),[{type:"reloadProtyle",id:s.documentId}])},wA=async({client:e,permMgr:t,rawArgs:o})=>{const n=wd.parse(o),r=n.ids??[n.id],s=new Set;for(const u of r){const p=await N(e,t,u,"write");if(p.denied)return p.denied;s.add(p.context.documentId)}if(n.parentID){const u=await N(e,t,n.parentID,"write");if(u.denied)return u.denied}if(n.previousID){const u=await N(e,t,n.previousID,"write");if(u.denied)return u.denied}const a=[],i=[...r].reverse();for(const u of i)a.push(await bv(e,u,n.previousID,n.parentID));const c=n.ids?a:a[0],l=[...s].map(u=>({type:"reloadProtyle",id:u}));if(n.parentID){const u=await N(e,t,n.parentID,"write");if(u.denied)return u.denied;l.push({type:"reloadProtyle",id:u.context.documentId})}if(n.previousID){const u=await N(e,t,n.previousID,"write");if(u.denied)return u.denied;l.push({type:"reloadProtyle",id:u.context.documentId})}return F(e,xe({...n.ids?{ids:n.ids,finalOrder:n.ids,apiCallOrder:i,count:n.ids.length}:{id:n.id},...n.previousID?{previousID:n.previousID}:{},...n.parentID?{parentID:n.parentID}:{}},c),l)},kA=async({client:e,permMgr:t,rawArgs:o})=>{const n=kd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");return r||(n.folded?await wv(e,n.id):await kv(e,n.id),F(e,k({success:!0,id:n.id,folded:n.folded}),[{type:"reloadProtyle",id:s.documentId}]))},_A=async({client:e,permMgr:t,rawArgs:o})=>{const n=_d.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=Gp(await io(e,n.id));return k(s)},vA=async({client:e,permMgr:t,rawArgs:o})=>{const n=vd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await jn(e,n.id),a=Array.isArray(s)?s:[],i=Xs(a,n.page??1,n.pageSize??50);return We(i.items,i,{...i.truncated?{hint:'Use page/pageSize to paginate. For focused reads, use block(action="get_kramdown") or search(action="query_sql") with a parent_id filter.'}:{}})},IA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Id.parse(o),r=await N(e,t,n.fromID,"write");if(r.denied)return r.denied;const s=await N(e,t,n.toID,"write");return s.denied?s.denied:(await _v(e,n.fromID,n.toID,n.refIDs),F(e,k({success:!0,fromID:n.fromID,toID:n.toID}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId}]))},SA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Sd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");return r||(await Oe(e,[{doOperations:[{action:"setAttrs",id:n.id,data:JSON.stringify(n.attrs)}],undoOperations:[]}]),F(e,k({success:!0,id:n.id,attrs:n.attrs}),[{type:"reloadProtyle",id:s.documentId}]))},DA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Dd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await zp(e,n.id);return k(s)},AA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ad.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Mp(e,n.id);return k(s)},TA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Td.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await vv(e,n.id,n.excludeTypes);return k(s)},PA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Pd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Hn(e,n.id);return k(s)},EA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ed.parse(o),r=await Iv(e),s=Array.isArray(r)?r:[],a=await un(e,s,t),i=typeof n.count=="number"?n.count:void 0,c=typeof i=="number"?a.items.slice(0,i):a.items,l=await aA(e,c);return k({documents:l.documents,documentCount:l.documents.length,count:c.length,containsLowLevelBlocks:l.containsLowLevelBlocks,grouping:"document",primaryView:"documents",items:c,hint:"documents is the user-facing summary grouped by root document; items remains the raw recent block stream for advanced consumers.",...a.removedCount>0?{partial:!0,filteredOutCount:a.removedCount,reason:"permission_filtered"}:{}})},CA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Cd.parse(o);for(const s of n.ids){const{denied:a}=await N(e,t,s,"read");if(a)return a}const r=await Sv(e,n.ids);return k(r)},RA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Rd.parse(o),r=await Y(t,n.notebook,"write");if(r)return r;const s=await yt(e,n.dataType,n.data,"block.add_to_daily_note"),a=n.position==="append"?await Tv(e,n.notebook,n.dataType,s):await Pv(e,n.notebook,n.dataType,s);return F(e,k({success:!0,action:"add_to_daily_note",notebook:n.notebook,dataType:n.dataType,position:n.position,transactions:a}),[{type:"reloadFiletree"}])},xA=async({client:e,permMgr:t,rawArgs:o})=>{const n=xd.parse(o),r=n.ids??[n.id];for(const a of r){const{denied:i}=await N(e,t,a,"read");if(i)return i}const s=await Ev(e,r,n.refCount??!1,n.av??!1);return k(s)},OA={insert:fA,prepend:hA,append:mA,update:gA,replace:yA,delete:bA,move:wA,set_fold_state:kA,get_kramdown:_A,get_children:vA,transfer_references:IA,set_attrs:SA,get_attrs:DA,info:AA,breadcrumb:TA,dom:PA,recent_updated:EA,word_count:CA,add_to_daily_note:RA,docs_info:xA},NA=[S("insert",fd,"Insert one or more blocks at the specified position."),S("prepend",hd,"Insert a block at the beginning of a parent."),S("append",md,"Insert a block at the end of a parent."),S("update",gd,"Update one or more blocks."),S("replace",yd,"Apply exact old/new text replacement edits inside one block body and patch the original DOM."),S("delete",bd,"Delete a block by ID."),S("move",wd,"Move a block to a new position."),S("set_fold_state",kd,"Set the fold state of a foldable block."),S("get_kramdown",_d,"Get block content in kramdown format."),S("get_children",vd,"Get child blocks of a parent with pagination support."),S("transfer_references",Id,"Transfer block references from one block to another."),S("set_attrs",Sd,"Set block attributes."),S("get_attrs",Dd,"Get block attributes."),S("info",Ad,"Get block position and root document metadata."),S("breadcrumb",Td,"Get the breadcrumb path for a block."),S("dom",Pd,"Get rendered DOM for a block."),S("recent_updated",Ed,"Get recently updated blocks."),S("word_count",Cd,"Get word-count statistics for blocks."),S("add_to_daily_note",Rd,"Add a block to today's daily note, creating the note if needed."),S("docs_info",xd,"Get document info for one or more documents.")],kf=De({name:"block",description:"🧱 Grouped block operations.",variants:NA,actionSchema:l_,aggregateOptions:{guidance:Yc,actionHints:rl,propertyDescriptionOverrides:{parentID:"Parent block or document ID. With prepend/append, a document ID targets the document head or tail; a block ID targets that block's child list.",previousID:'Sibling block ID to position after. For block(action="move"), provide previousID, parentID, or both to describe the destination. Successful moves return a structured success object.'}},handlers:OA}),$A=kf.listTools,MA=kf.callTool,_f="approx_context_v1";function Hr(e){return Math.ceil(Math.max(0,e)/4)}function Vr(e){const t=typeof e=="string"?e:"";return{chars:t.length,approxTokens:Hr(t.length)}}function zA(e){const t=(e??[]).map(o=>o.text??"").join("");return Vr(t)}const FA=50,qA=2e3,BA=new Set(["l","b","callout","s","t","table","tb","av","code","c","math","m","html","iframe","widget","query_embed"]);function LA(e){if(!e)return;const t=e.trim();if(!t)return;const o=t.toLowerCase();return o.startsWith("node")?o.includes("paragraph")?"p":o.includes("heading")?"h":o.includes("listitem")?"i":o.includes("list")?"l":o.includes("blockquote")?"b":o.includes("callout")?"callout":o.includes("superblock")?"s":o.includes("table")?"t":o.includes("codeblock")?"c":o.includes("mathblock")?"m":o.includes("attributeview")?"av":o.includes("htmlblock")?"html":o.includes("iframe")?"iframe":o.includes("widget")?"widget":o.includes("video")?"video":o.includes("audio")?"audio":o.includes("blockqueryembed")?"query_embed":o.includes("thematicbreak")?"tb":t:t}function UA(e){if(!e||typeof e!="object")return null;const t=e,o=typeof t.id=="string"?t.id:"";return o?{id:o,type:LA(typeof t.type=="string"?t.type:void 0),subtype:typeof t.subtype=="string"?t.subtype:void 0}:null}function jA(e){return!!(e.type&&BA.has(e.type))}async function vf(e,t,o,n){const r=await jn(e,t);for(const s of r){const a=UA(s);a&&(n.has(a.id)||(n.add(a.id),o.push(a),jA(a)||await vf(e,a.id,o,n)))}}async function Ho(e,t){const o=[];return await vf(e,t,o,new Set([t])),o}function HA(e,t){var r;const o=(r=e.subtype)==null?void 0:r.match(/^h([1-6])$/i);if(o)return Number(o[1]);const n=t.match(/^\s{0,3}(#{1,6})\s+/);return n==null?void 0:n[1].length}function VA(e){var n;const o=(e.split(/\r?\n/,1)[0]??"").match(/^\s{0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$/);return((n=o==null?void 0:o[1])==null?void 0:n.trim())||void 0}function ZA(e,t,o){const n=[];return e.forEach((r,s)=>{if(r.type!=="h")return;const a=t[s]??"",i=HA(r,a),c=VA(a);!i||!c||n.push({blockIndex:s,level:i,title:c,...o?{id:r.id}:{}})}),n}function If(e,t,o){const n=o.blockStart??0,r=o.blockLimit??FA,s=o.tokenBudget??qA,a=o.includeBlockIds??!1,i=e.length,c=[],l=[];let u=0,p=0;if(n<i){const b=Math.min(i,n+r);for(let _=n;_<b;_+=1){const w=t[_]??"",P=w.length>0&&c.length>0?2:0,D=p+P+w.length,T=Hr(D)>s;if(w.length>0&&T&&c.length>0)break;if(u+=1,a){const A=e[_];l.push({blockIndex:_,id:A.id,...A.type?{type:A.type}:{},...A.subtype?{subtype:A.subtype}:{}})}w.length>0&&(c.push(w),p=D)}}const f=Hr(p),h=n+u,g=h<i;return{content:c.join(`
513
-
514
- `),outline:ZA(e,t,a),blockStart:n,blockLimit:r,returnedBlocks:u,totalBlocks:i,tokenBudget:s,estimatedTokens:f,tokenMode:_f,truncated:g,hasNextWindow:g,...g?{nextBlockStart:h}:{},...f>s?{budgetExceeded:!0}:{},...a?{blockRefs:l}:{}}}function YA(e){const t=[];let o=null;for(const n of e.split(/\r?\n/)){const r=n.match(/^\s{0,3}(`{3,}|~{3,})/);if(r){const a=r[1][0];o?a===o.marker&&r[1].length>=o.length&&(o=null):o={marker:a,length:r[1].length};continue}if(o)continue;const s=n.match(/^\s{0,3}(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);s&&t.push({blockIndex:0,level:s[1].length,title:s[2].trim()})}return t}function Yi(e,t={}){const o=e.length>0?[{id:"synthetic",type:"p"}]:[];return{...If(o,e.length>0?[e]:[],{...t,includeBlockIds:!1}),outline:YA(e)}}async function Sf(e,t,o={},n){const r=n??await Ho(e,t),s=await Promise.all(r.map(async a=>{const i=await io(e,a.id);return fa({kramdown:typeof i.kramdown=="string"?i.kramdown:"",type:a.type})}));return If(r,s,o)}const gr=[120,240],WA=["path","hpath"];function GA(e){return e==="/"||/\.sy(?:\/|$)/.test(e)}async function Df(e,t,o){await Oe(e,[{doOperations:[{action:"setAttrs",id:t,data:JSON.stringify(o)}],undoOperations:[]}])}function KA(e){return e instanceof Error&&/SiYuan API error:\s*-1\s*-\s*indexing/i.test(e.message)}async function Af(e,t){let o;for(let r=0;r<=gr.length;r+=1)try{return await Vn(e,t)}catch(s){if(!KA(s)||r===gr.length){o=s;break}o=s,await jo(gr[r])}const n=o instanceof Error?o.message:String(o);throw new Error(`Failed to resolve hierarchical path for document "${t}" because SiYuan indexing is still catching up. Retry shortly after create. Last error: ${n}`)}function rn(e){const t=typeof e.path=="object"?e.path.notebook:e.notebook,o=typeof e.path=="object"?e.path.path:e.path;return{humanPath:{notebookName:e.notebookName??e.notebook,hPath:e.hPath},idPath:{id:e.id,ids:e.ids,notebook:t,path:o}}}function JA(e){const t=e.trim();if(!t)throw new Error("Cover source must not be empty.");const o=/^https?:\/\//i.test(t),n=t.startsWith("/assets/");if(!o&&!n)throw new Error("Cover source must be an http(s) URL or a SiYuan asset path starting with /assets/.");const r=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return{source:t,titleImg:`background-image:url("${r}");`}}function QA(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function XA(e){return e.split("/").filter(Boolean).at(-1)}function eT(e){return/(?:^|\/)\d{14}-[a-z0-9]{7}\.sy$/i.test(e)}async function yr(e,t,o){const n=await Lp(e,o,t);return n.length>0?n:(await st(e,["SELECT id FROM blocks",`WHERE box = '${we(t)}'`,`AND hpath = '${we(o)}'`,"AND type = 'd'","ORDER BY updated DESC"].join(" "))).map(s=>s&&typeof s=="object"?s.id:void 0).filter(s=>typeof s=="string"&&s.length>0)}async function tT(e,t,o){const n=o==="/"?"/":o.replace(/\/+$/,"");return eT(n)?ra(e,t,n):n}function Zr(e,t,o=0){return Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object")return n;const r=n;if(o>=t&&Array.isArray(r.children)&&r.children.length>0){const{children:s,...a}=r;return{...a,childCount:s.length,childrenTruncated:!0}}return Array.isArray(r.children)?{...r,children:Zr(r.children,t,o+1)}:r}):e}async function Yr(e,t,o=new Map){return Array.isArray(t)?Promise.all(t.map(async n=>{if(!n||typeof n!="object")return n;const r=n,s={...r},a=typeof r.id=="string"?r.id:void 0;if(a&&(r.name===void 0||r.icon===void 0))try{let i=o.get(a);i||(i=Et(e,a),o.set(a,i));const c=await i;s.name===void 0&&c.name&&(s.name=c.name.replace(/\.sy$/,"")),s.icon===void 0&&c.icon&&(s.icon=c.icon)}catch{}return Array.isArray(r.children)&&(s.children=await Yr(e,r.children,o)),s})):t}function oT(e,t){if(Array.isArray(e))return dn({backmentions:e},t).backmentions;if(!e||typeof e!="object")return e;const o=e;return Array.isArray(o.files)?{...o,files:dn({backmentions:o.files},t).backmentions}:Array.isArray(o.docs)?{...o,docs:dn({backmentions:o.docs},t).backmentions}:e}async function nT(e,t,o,n){if(Array.isArray(t)){const s=await fr(e,t,o,n);return{data:s.items,permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}if(!t||typeof t!="object")return{data:t,permissionFilteredOutCount:0,pathFilteredOutCount:0};const r=t;if(Array.isArray(r.files)){const s=await fr(e,r.files,o,n);return{data:{...r,files:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}if(Array.isArray(r.docs)){const s=await fr(e,r.docs,o,n);return{data:{...r,docs:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}return{data:oT(t,o),permissionFilteredOutCount:0,pathFilteredOutCount:0}}const rT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Uu.parse(o);if(await t.reload(),!t.canWrite(n.notebook))return ta(n.notebook,t.get(n.notebook),"write");const r=n.parentPath?await tT(e,n.notebook,n.parentPath):void 0,s=n.path??QA(r,n.title),a=await Jt(e,bf(n.markdown??"",n.title??XA(s)),"document.create"),i=await Fp(e,n.notebook,s,a);return n.icon&&await Df(e,i,{icon:n.icon}),F(e,k({success:!0,notebook:n.notebook,path:s,...Wt(a)?Oo():{},...Gt(a)?No():{},...Kt(a)?$o():{},...n.parentPath?{parentPath:n.parentPath}:{},...r&&r!==n.parentPath?{resolvedParentPath:r}:{},...n.title?{title:n.title}:{},id:i,iconHint:ea("document",!!n.icon)}),n.icon?[{type:"reloadIcon"}]:[{type:"reloadProtyle",id:i},{type:"reloadFiletree"}])},sT=async({client:e,permMgr:t,rawArgs:o})=>{const n=ju.parse(o),r=n.hpath??n.hPath,s=new Set(n.include??WA),a={source:n.id?{id:n.id}:n.path?{notebook:n.notebook,path:n.path}:{notebook:n.notebook}};if(n.id){const{denied:p,context:f}=await N(e,t,n.id,"read");if(p)return p;a.id=n.id,a.notebook=f.notebook,a.path=f.path,s.has("path")&&(a.path=await wo(e,n.id)),a.hPath=await Af(e,n.id),s.has("docInfo")&&(a.docInfo=await Et(e,n.id));const h=await Mr(e,f.notebook);return h&&(a.notebookName=h),k(rn(a))}const i=await Y(t,n.notebook,"read");if(i)return i;const c=await Mr(e,n.notebook);if(n.path){if(a.notebook=n.notebook,c&&(a.notebookName=c),a.path=n.path,!GA(n.path)){const f=await yr(e,n.notebook,n.path),h=f[0];return a.source={type:"hpath",notebook:n.notebook,hPath:n.path,providedAs:"path"},a.hPath=n.path,a.interpretedPathAs="hpath",a.hint="document.lookup path expects a storage path such as /20240318112233-abc123.sy. Human-readable paths should be passed as hpath; this call was interpreted as hpath for compatibility.",(s.has("ids")||s.has("id"))&&(a.ids=f,s.has("id")&&(a.id=h)),h&&(a.path=await wo(e,h)),h&&s.has("docInfo")&&(a.docInfo=await Et(e,h)),k(rn(a))}const p=await ra(e,n.notebook,n.path);if(a.hPath=p,s.has("id")||s.has("ids")){const f=await yr(e,n.notebook,p??n.path);a.ids=f,s.has("id")&&(a.id=f[0])}return s.has("docInfo")&&typeof a.id=="string"&&(a.docInfo=await Et(e,a.id)),k(rn(a))}const l=await yr(e,n.notebook,r);a.notebook=n.notebook,c&&(a.notebookName=c),a.hPath=r,(s.has("ids")||s.has("id"))&&(a.ids=l,s.has("id")&&(a.id=l[0]));const u=l[0];if(u){const{denied:p}=await N(e,t,u,"read");if(p)return p;a.path=await wo(e,u)}if(u&&s.has("docInfo")){const{denied:p}=await N(e,t,u,"read");if(p)return p;a.docInfo=await Et(e,u)}return k(rn(a))},aT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Hu.parse(o);if(n.id){const{denied:r,context:s}=await N(e,t,n.id,"write");return r||(await qp(e,n.id,n.title),F(e,k({success:!0,id:n.id,title:n.title}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await Y(t,n.notebook,"write");if(r)return r}return await Bv(e,n.notebook,n.path,n.title),F(e,k({success:!0,notebook:n.notebook,path:n.path,title:n.title}),[{type:"reloadFiletree"}])},iT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Vu.parse(o);if(n.ids){const r=[];for(const s of n.ids){const{denied:a,context:i}=await N(e,t,s,"delete");if(a)return a;r.push(i.documentId)}for(const s of n.ids)await Nr(e,s);return F(e,k({success:!0,ids:n.ids,count:n.ids.length}),[...r.map(s=>({type:"reloadProtyle",id:s})),{type:"reloadFiletree"}])}if(n.paths){for(const r of n.paths){const s=await xo(e,r);if(!s)throw new Error(`Unable to resolve notebook for storage path "${r}" while checking permissions.`);const a=await Y(t,s,"delete");if(a)return a}return await Wv(e,n.paths),F(e,k({success:!0,paths:n.paths,count:n.paths.length}),[{type:"reloadFiletree"}])}if(n.id){const{denied:r,context:s}=await N(e,t,n.id,"delete");return r||(await Nr(e,n.id),F(e,k({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await Y(t,n.notebook,"delete");if(r)return r}return await Lv(e,n.notebook,n.path),F(e,k({success:!0,notebook:n.notebook,path:n.path}),[{type:"reloadFiletree"}])},cT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Zu.parse(o);if(n.toNotebook){const r=await Y(t,n.toNotebook,"write");if(r)return r}if(n.toID){const r=await dI(e,n.toID),s=await Y(t,r,"write");if(s)return s}if(n.fromIDs){const r=[];for(const s of n.fromIDs){const{denied:a,context:i}=await N(e,t,s,"write");if(a)return a;r.push(i.documentId)}return await Bp(e,n.fromIDs,n.toID),F(e,k({success:!0,fromIDs:n.fromIDs,toID:n.toID}),[...r.map(s=>({type:"reloadProtyle",id:s})),{type:"reloadFiletree"}])}for(const r of n.fromPaths){const s=await xo(e,r);if(!s)throw new Error(`Unable to resolve source notebook for storage path "${r}" while checking permissions.`);const a=await Y(t,s,"write");if(a)return a}return await Uv(e,n.fromPaths,n.toNotebook,n.toPath),F(e,k({success:!0,fromPaths:n.fromPaths,toNotebook:n.toNotebook,toPath:n.toPath}),[{type:"reloadFiletree"}])},lT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Yu.parse(o),{denied:r,context:s}=await N(e,t,n.id,"read");if(r)return r;const a=await jn(e,s.documentId);return k(a)},uT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Wu.parse(o),{denied:r,context:s}=await N(e,t,n.id,"read");if(r)return r;const a=await Zn(e,s.notebook,s.path);return k(a)},dT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Gu.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a={},i={success:!0,id:n.id},c=[];if(n.attrs.icon!==void 0&&(a.icon=n.attrs.icon,i.icon=n.attrs.icon,c.push({type:"reloadIcon"},{type:"reloadFiletree"})),n.attrs.cover!==void 0){const l=n.attrs.cover;if(!l)a["title-img"]="",i.clearedCover=!0;else{const u=JA(l);a["title-img"]=u.titleImg,i.cover=u.source,i.titleImg=u.titleImg}c.push({type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"})}return await Df(e,n.id,a),F(e,k(i),c)},pT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ku.parse(o),r=await Y(t,n.notebook,"read");if(r)return r;const s=n.maxDepth??3,a=await Nt(e,n.notebook,n.path),i='Use maxDepth to control tree depth. Use document(action="list_tree") with a deeper path to expand specific subtrees.';if(a&&typeof a=="object"&&Array.isArray(a.tree)){const l=await Yr(e,a.tree);return k({...a,tree:Zr(l,s),maxDepth:s,depthHint:i})}const c=await Yr(e,a);return k({tree:Zr(c,s),maxDepth:s,depthHint:i})},fT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ju.parse(o),r=await Y(t,n.notebook,"read");if(r)return r;const s=await Hv(e,n.query),a=await nT(e,s,t,n.path),i=a.permissionFilteredOutCount+a.pathFilteredOutCount;return k({...a.data&&typeof a.data=="object"&&!Array.isArray(a.data)?a.data:{docs:a.data},...n.path?{path:n.path,pathApplied:!0}:{},...a.permissionFilteredOutCount>0?{partial:!0,reason:"permission_filtered"}:{},...i>0?{filteredOutCount:i}:{},...a.pathFilteredOutCount>0?{pathFilteredOutCount:a.pathFilteredOutCount}:{}})},hT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Qu.parse(o),{denied:r,context:s}=await N(e,t,n.id,"read");if(r)return r;const a=await Mr(e,s.notebook);if(n.mode==="html"){const p=await Vv(e,n.id,0,n.size);return k({id:n.id,mode:"html",notebook:s.notebook,...a?{notebookName:a}:{},...p&&typeof p=="object"?p:{content:p}})}const i=await Sf(e,n.id,{blockStart:n.blockStart,blockLimit:n.blockLimit,tokenBudget:n.tokenBudget,includeBlockIds:n.includeBlockIds}),{nextBlockStart:c,...l}=i,u=c===void 0?void 0:{action:"get_doc",id:n.id,mode:"markdown",blockStart:c,blockLimit:i.blockLimit,tokenBudget:i.tokenBudget,...n.includeBlockIds?{includeBlockIds:!0}:{}};return k({id:n.id,mode:"markdown",notebook:s.notebook,...a?{notebookName:a}:{},hPath:await Af(e,n.id),...l,...u?{nextWindow:u,nextWindowHint:`Continue with document(${JSON.stringify(u)}).`}:{}})},mT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Xu.parse(o),r=await Y(t,n.notebook,"write");if(r)return r;const s=await Zv(e,n.notebook,n.app);let a;try{a=await Vn(e,s.id)}catch{a=void 0}return F(e,k({success:!0,notebook:n.notebook,...s,...a?{hPath:a}:{},iconHint:ea("document")}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}])},gT=async({client:e,permMgr:t,rawArgs:o})=>{const n=ed.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a=await Yv(e,n.id);return F(e,k({success:!0,sourceID:n.id,...a}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}])},yT=async({client:e,permMgr:t,rawArgs:o})=>{const n=td.parse(o),r=await N(e,t,n.headingID,"write");if(r.denied)return r.denied;const s=await Y(t,n.targetNotebook,"write");return s||(await Gv(e,n.headingID,n.targetNotebook,n.targetPath,n.previousPath),F(e,k({success:!0,headingID:n.headingID,targetNotebook:n.targetNotebook,...n.targetPath?{targetPath:n.targetPath}:{},...n.previousPath?{previousPath:n.previousPath}:{}}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadFiletree"}]))},bT=async({client:e,permMgr:t,rawArgs:o})=>{const n=od.parse(o),r=await N(e,t,n.srcID,"write");if(r.denied)return r.denied;const s=await N(e,t,n.targetID,"write");if(s.denied)return s.denied;const a=await Kv(e,n.srcID,n.targetID,n.after??!1);return F(e,k({success:!0,srcID:n.srcID,targetID:n.targetID,after:n.after??!1,...a}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId},{type:"reloadFiletree"}])},wT={create:rT,lookup:sT,rename:aT,remove:iT,move:cT,get_child_blocks:lT,get_child_docs:uT,set_attr:dT,list_tree:pT,search_docs:fT,get_doc:hT,create_daily_note:mT,duplicate:gT,heading_to_doc:yT,doc_to_heading:bT},kT=[S("create",Uu,"Create a new document. Prefer path for child documents; parentPath + title also accepts a human-readable parent path or a storage path ending in .sy."),S("lookup",ju,"Look up document IDs, storage paths, human-readable paths, and document metadata from one document reference."),S("rename",Hu,"Rename a document"),S("remove",Vu,"Delete a document"),S("move",Zu,"Move a document to another location"),S("get_child_blocks",Yu,"Get top-level blocks of a document"),S("get_child_docs",Wu,"Get child documents"),S("set_attr",Gu,"Set document metadata such as icon and cover image."),S("list_tree",Ku,"Get document tree"),S("search_docs",Ju,"Search documents by title"),S("get_doc",Qu,"Read document Markdown in complete block windows, or return the current HTML view."),S("create_daily_note",Xu,"Create or open today's daily note"),S("duplicate",ed,"Duplicate a document"),S("heading_to_doc",td,"Convert a heading to a separate document"),S("doc_to_heading",od,"Merge a document into another as a heading")],Tf=De({name:"document",description:"📝 Grouped document operations.",variants:kT,actionSchema:c_,aggregateOptions:{guidance:Zc,actionHints:nl,propertyDescriptionOverrides:{path:'Path value. For action="create", use a human-readable target path such as /Inbox/Weekly Note. For action="lookup" and path-based rename/remove/move, use a storage path returned by document(action="lookup", id=..., include=["path"]); use hpath for human-readable lookup.',parentPath:'Parent path for title-based creation. Accepts a human-readable parent path such as /Inbox or a storage path ending in .sy returned by document(action="lookup").',fromPaths:'Source storage paths returned by document(action="lookup").',toPath:'Target storage path. Use the storage path of an existing destination document returned by document(action="lookup").'}},handlers:wT});function _T(e){return Tf.listTools(e)}async function vT(e,t,o,n){return Tf.callTool(e,t,o,n)}async function IT(e,t,o,n){const r=new FormData,s=new File([o],n);return r.append("assetsDirPath",t),r.append("file[]",s,n),e.requestFormData("/api/asset/upload",r)}async function ga(e,t){const o={id:t};return e.request("/api/export/exportMdContent",o)}async function ST(e,t,o){const n={paths:t,name:o};return e.request("/api/export/exportResources",n)}async function DT(e){return e.request("/api/asset/getUnusedAssets",{})}async function AT(e,t){return e.request("/api/asset/getDocAssets",{id:t})}async function TT(e,t){return e.request("/api/asset/getDocImageAssets",{id:t})}async function PT(e,t){return e.request("/api/asset/getImageOCRText",t?{path:t}:{})}async function ET(e){return e.request("/api/asset/removeUnusedAssets",{})}async function CT(e,t,o){return e.request("/api/asset/renameAsset",{oldPath:t,newName:o})}async function RT(e,t){return e.request("/api/asset/deleteAsset",{path:t})}function kt(e){const t=new Error(e);return t.reason="invalid_template_path",t}function xT(e){const t=e.trim();if(!t)throw kt("Template path is required.");if(/[\0?#]/.test(t))throw kt("Template path must not contain null bytes, query strings, or hash fragments.");const o=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/"),n=o.toLowerCase(),r="/data/templates/",s=n.lastIndexOf(r);let a;if(s>=0)a=o.slice(s+r.length);else{const c=o.replace(/^\/+/,""),l=c.toLowerCase();if(l.startsWith("data/templates/"))a=c.slice(15);else if(l.startsWith("templates/"))a=c.slice(10);else{if(/^[a-z]:\//i.test(o))throw kt("Template path must be inside data/templates; arbitrary drive paths are not allowed.");if(!o.startsWith("/"))a=c;else throw kt("Template path must be inside data/templates or use the /templates/ static route.")}}a=a.replace(/^\/+/,"").replace(/\/{2,}/g,"/");const i=a.split("/");if(i.length===0||i.some(c=>!c||c==="."||c==="..")||a.startsWith("../")||a.includes("/../")||a.includes(":"))throw kt("Template path must not traverse directories.");if(!a.toLowerCase().endsWith(".md"))throw kt("Template source reading only supports Markdown .md files.");return a}function Vo(e){const t=xT(e),o=`/templates/${t.split("/").map(encodeURIComponent).join("/")}`;return{path:e.trim().replace(/\\/g,"/"),relativePath:t,staticPath:o,workspacePath:`/data/templates/${t}`}}function pt(e,t){const o=new Error(e);return o.reason=t,o}function OT(e){const t=e.trim().replace(/\.md$/i,"");if(!t)throw pt("Template name is required.","invalid_template_name");if(/[\0?#/\\:]/.test(t)||t==="."||t==="..")throw pt("Template name must be a root template name without slashes, drive markers, query strings, or hash fragments.","invalid_template_name");return t}function NT(e){return e.replace(/\.md$/i,"")}function $T(e){try{const t=Vo(e.path);return{path:e.path,content:e.content,relativePath:t.relativePath}}catch{return null}}async function Pf(e,t=""){const o={k:t},n=await e.request("/api/search/searchTemplate",o);return{templates:Array.isArray(n==null?void 0:n.templates)?n.templates:[],k:typeof(n==null?void 0:n.k)=="string"?n.k:t}}async function Zo(e,t){const o=Vo(t),n=[...new Set([NT(o.relativePath),""])];for(const r of n){const a=(await Pf(e,r)).templates.map($T).find(i=>!!i&&i.relativePath===o.relativePath);if(a)return a}throw pt(`Template not found: ${o.relativePath}`,"template_not_found")}async function MT(e,t,o,n){const r={id:t,path:o,...n!==void 0?{preview:n}:{}};return e.request("/api/template/render",r)}async function zT(e,t){const o={template:t};return e.request("/api/template/renderSprig",o)}async function Ef(e,t,o){const n=Vo(t);try{await e.writeFile(n.workspacePath,o)}catch(r){const s=r instanceof Error?r.message:String(r);throw pt(`Failed to write template [${n.relativePath}]: ${s}`,"template_write_failed")}return{path:n.workspacePath,relativePath:n.relativePath,totalChars:o.length}}async function FT(e,t){const o=await Zo(e,t);try{await e.request("/api/search/removeTemplate",{path:o.path})}catch(n){const r=n instanceof Error?n.message:String(n);throw pt(`Failed to delete template [${o.relativePath}]: ${r}`,"template_delete_failed")}return{path:o.path,relativePath:o.relativePath}}async function qT(e,t,o,n=!1){const r=OT(o),s={id:t,name:r,overwrite:n};try{await e.request("/api/template/docSaveAsTemplate",s)}catch(a){const i=a instanceof Error?a.message:String(a);throw/SiYuan API error:\s*1\b/.test(i)?pt(`Template already exists: ${r}.md`,"template_exists"):pt(`Failed to save document as template [${r}]: ${i}`,"template_write_failed")}return{id:t,name:r,relativePath:`${r}.md`}}async function BT(e,t){const o=Vo(t),n=await fetch(`${e.getBaseUrl()}${o.staticPath}`,{method:"GET",headers:e.getAuthHeaders()});if(!n.ok){const r=`Failed to read template source [${o.relativePath}]: HTTP ${n.status} ${n.statusText}`,s=new Error(r);throw s.reason=n.status===404?"template_not_found":"template_source_unavailable",s}return{path:o.path,relativePath:o.relativePath,markdown:await n.text()}}const LT="file",Wr=10;function UT(e){const t=e.trim().replace(/\\/g,"/");if(!t)return"";const o=t.replace(/^\/+/,""),n=o.startsWith("data/")?o:o.startsWith("assets/")?`data/${o}`:o;return(n.startsWith("/")?n:`/${n}`).replace(/\/{2,}/g,"/")}function jT(e){return[...new Set(e.map(UT).filter(Boolean))]}function HT(e){return U.isAbsolute(e)?e:U.resolve(process.cwd(),e)}function VT(e){return U.isAbsolute(e)?e:U.resolve(process.cwd(),e)}function ZT(e){return e instanceof Error&&/is not in workspace/i.test(e.message)}function Le(e,t,o,n,r){const s=t instanceof Error?t.message:String(t);return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:LT,action:e,message:s,reason:o,...r??{},hint:n}},null,2)}],isError:!0}}function ot(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?e.reason:"template_source_unavailable"}function YT(e){return ot(e)==="template_not_found"}function Cf(e){return U.basename(e).replace(/\.md$/i,"")}function WT(e){const t=Vo(e.path);return{path:e.path,relativePath:t.relativePath,name:Cf(t.relativePath),content:e.content,readArgs:{action:"read_template",path:e.path},renderArgsTemplate:{action:"render",engine:"template",id:"<doc-id>",path:e.path}}}function Gr(e,t,o){return{path:e,relativePath:t,name:Cf(t),...typeof o=="number"?{totalChars:o}:{},readArgs:{action:"read_template",path:e},renderArgsTemplate:{action:"render",engine:"template",id:"<doc-id>",path:e}}}async function Rf(e,t,o,n){try{const r=await Zo(e,t);return Gr(r.path,r.relativePath,n)}catch{return Gr(o,t,n)}}const GT=(e,t)=>async({client:o,rawArgs:n})=>{const r=Yd.parse(n),s=VT(r.localFilePath);if(!H.existsSync(s))throw new Error(`Local file does not exist: ${s}`);const a=H.statSync(s);if(!a.isFile())throw new Error(`Local file path must point to a regular file: ${s}`);if(a.size>t&&r.confirmLargeFile!==!0)return k({success:!1,requiresConfirmation:!0,reason:"file_too_large",localFilePath:s,fileSizeBytes:a.size,thresholdBytes:t,thresholdMB:e,message:`File exceeds the large-upload safety threshold (${e} MB). Stop the current operation and ask the user for explicit confirmation before retrying with confirmLargeFile=true.`});const i=U.basename(s),c=H.readFileSync(s),l=await IT(o,r.assetsDirPath,c,i);return k({...l,localFilePath:s,uploadedFileName:i,...a.size>t?{largeFileConfirmed:!0}:{}})},KT=async({client:e,permMgr:t,rawArgs:o})=>{const n=ep.parse(o);if(n.engine==="sprig"){const s=await zT(e,n.template);return k(s)}const{denied:r}=await N(e,t,n.id,"read");if(r)return r;try{const s=await MT(e,n.id,n.path,n.preview);return k(s)}catch(s){if(ZT(s))return Le("render",s,"path_not_in_workspace",'The template path must point to a file inside the SiYuan workspace, not an arbitrary local path such as /tmp/... or your repo checkout. Use file(action="list_templates") to resolve a valid template path.',{workspacePathRequired:!0});throw s}},JT=async({client:e,rawArgs:t})=>{const o=Wd.parse(t),n=o.query??"",r=await Pf(e,n),s=(Array.isArray(r.templates)?r.templates:[]).map(WT),a=Xs(s,o.page??1,o.pageSize??20);return We(a.items,a,{query:r.k,showing:a.showing,truncated:a.truncated})},QT=async({client:e,rawArgs:t})=>{const o=Gd.parse(t);try{const n=await BT(e,o.path),r=n.markdown.length,s=o.offset??0,a=o.limit??8e3,i=n.markdown.slice(s,s+a),c=s+i.length,l=c<r;return k({path:n.path,relativePath:n.relativePath,markdown:i,totalChars:r,offset:s,limit:a,truncated:l,...l?{nextOffset:c}:{}})}catch(n){return Le("read_template",n,ot(n),'Use file(action="list_templates") to resolve a valid Markdown template path. If you only need rendered output, use file(action="render", engine="template").')}},XT=async({client:e,rawArgs:t})=>{const o=Kd.parse(t);if(o.overwrite!==!0)try{const n=await Zo(e,o.path);return Le("create_template",new Error(`Template already exists: ${n.relativePath}`),"template_exists","Pass overwrite=true to replace the existing template, or choose a different template path.",{path:n.path,relativePath:n.relativePath})}catch(n){if(!YT(n))return Le("create_template",n,ot(n),'Use a Markdown template path under data/templates, such as "reports/monthly.md".')}try{const n=await Ef(e,o.path,o.markdown),r=await Rf(e,n.relativePath,n.path,n.totalChars);return k({success:!0,...r})}catch(n){return Le("create_template",n,ot(n),'Use a Markdown template path under data/templates, such as "reports/monthly.md".')}},e0=async({client:e,rawArgs:t})=>{const o=Jd.parse(t);let n;try{n=await Zo(e,o.path)}catch(r){return Le("update_template",r,ot(r),'Use file(action="list_templates") to resolve an existing Markdown template before updating it.')}try{const r=await Ef(e,n.relativePath,o.markdown),s=await Rf(e,r.relativePath,n.path,r.totalChars);return k({success:!0,...s})}catch(r){return Le("update_template",r,ot(r),"The template was found, but writing the replacement Markdown failed.")}},t0=async({client:e,rawArgs:t})=>{const o=Qd.parse(t);try{const n=await FT(e,o.path);return k({success:!0,...n})}catch(n){return Le("delete_template",n,ot(n),'Use file(action="list_templates") to resolve an existing Markdown template before deleting it.')}},o0=async({client:e,permMgr:t,rawArgs:o})=>{const n=Xd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;try{const s=await qT(e,n.id,n.name,n.overwrite??!1);let a;try{const i=await Zo(e,s.relativePath);a=Gr(i.path,i.relativePath)}catch{a=void 0}return k({success:!0,id:s.id,name:s.name,...a?{template:a}:{}})}catch(s){return Le("save_doc_as_template",s,ot(s),"Use a root-level template name without slashes. Pass overwrite=true to replace an existing template.")}},n0=async({client:e,permMgr:t,rawArgs:o})=>{const n=tp.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=Wp(await ga(e,n.id));return k(s)},r0=async({client:e,rawArgs:t})=>{const o=op.parse(t),n=jT(o.paths);if(n.length===0)throw new Error("export_resources requires at least one non-empty resource path.");let r;try{r=await ST(e,n,o.name)}catch(s){const a=s instanceof Error?s.message:String(s);throw new Error(`Failed to export resources. original_paths=${JSON.stringify(o.paths)} normalized_paths=${JSON.stringify(n)} cause=${a}`)}if(o.outputPath){const s=HT(o.outputPath),a=await e.readFileBinary(r.path);return H.mkdirSync(U.dirname(s),{recursive:!0}),H.writeFileSync(s,a),k({...r,outputPath:s,bytes:a.byteLength})}return k(r)},s0=async({client:e,rawArgs:t})=>{np.parse(t);const o=await DT(e);return k({assets:o,count:Array.isArray(o)?o.length:void 0})},a0=async({client:e,permMgr:t,rawArgs:o})=>{const n=rp.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=n.assetType==="image"?await TT(e,n.id):await AT(e,n.id);return k({id:n.id,assetType:n.assetType??"all",assets:s,count:Array.isArray(s)?s.length:void 0})},i0=async({client:e,rawArgs:t})=>{const o=sp.parse(t),n=await PT(e,o.path);return k({path:o.path??null,...n})},c0=async({client:e,rawArgs:t})=>{ap.parse(t);const o=await ET(e);return k({success:!0,...o&&typeof o=="object"&&!Array.isArray(o)?o:{result:o}})},l0=async({client:e,rawArgs:t})=>{const o=ip.parse(t),n=await CT(e,o.oldPath,o.newName);return k({success:!0,oldPath:o.oldPath,newName:o.newName,...n})},u0=async({client:e,rawArgs:t})=>{const o=cp.parse(t),n=await RT(e,o.path);return k({success:!0,path:o.path,...n&&typeof n=="object"&&!Array.isArray(n)?n:{}})},d0=async({client:e,rawArgs:t})=>{var D;const o=lp.parse(t),n=await ga(e,o.id),r=typeof n.content=="string"?n.content:"",a=((D=(typeof n.hPath=="string"?n.hPath:"").split("/").filter(Boolean).pop())==null?void 0:D.replace(/\.sy$/,""))||o.id,i=o.id.slice(-7),c=`${a}-${i}`,l=process.env.USERPROFILE||process.env.HOME||"",u=o.outputDir?U.resolve(o.outputDir):U.join(l,"siyuan-extracted"),p=!o.outputDir,f=U.join(u,c),h=U.join(f,"assets");H.existsSync(u)&&H.rmSync(u,{recursive:!0,force:!0}),H.mkdirSync(h,{recursive:!0});const g=U.join(f,`${a}.md`);H.writeFileSync(g,r,"utf-8");const b=[...r.matchAll(/\]\(assets\/([^\s)"']+)(?:\s+"[^"]*")?\)/g)],_=[`${a}.md`];let w=0,P=0;for(const T of b){const A=T[1],O=U.join(h,A);try{H.mkdirSync(U.dirname(O),{recursive:!0});const C=await e.readFileBinary(`data/assets/${A}`);H.writeFileSync(O,C),_.push(`assets/${A}`),w++}catch{P++}}return k({outputRoot:u,defaultOutputDirUsed:p,extractedDir:f,docMdFile:`${a}.md`,extractedAssetCount:w,skippedAssetCount:P,structure:_,hint:p?"No outputDir was provided, so extract_doc used the default ~/siyuan-extracted/ output root. Pass outputDir explicitly when you need a specific location such as /private/tmp.":"extract_doc wrote to the explicit outputDir root."})};function p0(e,t){return{upload_asset:GT(e,t),list_templates:JT,read_template:QT,create_template:XT,update_template:e0,delete_template:t0,save_doc_as_template:o0,render:KT,export_md:n0,export_resources:r0,list_unused_assets:s0,get_doc_assets:a0,get_image_ocr_text:i0,remove_unused_assets:c0,rename_asset:l0,delete_asset:u0,extract_doc:d0}}const f0=[S("upload_asset",Yd,"Read a local file and upload it to the specified assets directory."),S("list_templates",Wd,"List or search SiYuan workspace templates available under data/templates."),S("read_template",Gd,"Read a Markdown template source through SiYuan’s authenticated template route."),S("create_template",Kd,"Create a Markdown template under data/templates through SiYuan’s workspace file API."),S("update_template",Jd,"Replace an existing Markdown template under data/templates."),S("delete_template",Qd,"Delete an existing Markdown template under data/templates."),S("save_doc_as_template",Xd,"Save an existing SiYuan document as a root-level template."),S("render",ep,"Render a SiYuan workspace template (.action{.title}) or an inline Sprig template ({{...}})."),S("export_md",tp,"Export document content as Markdown."),S("export_resources",op,"Export resources as a ZIP archive."),S("list_unused_assets",np,"List unused asset files."),S("get_doc_assets",rp,"List assets directly referenced by the current document tree. Use extract_doc for complete document asset inspection."),S("get_image_ocr_text",sp,"Get stored OCR text for an image asset."),S("remove_unused_assets",ap,"Remove all unused asset files."),S("rename_asset",ip,"Rename an asset file."),S("delete_asset",cp,"Delete an asset file."),S("extract_doc",lp,"Export a document and all referenced assets into a self-contained uncompressed folder. Prefer this over export_resources when you need to inspect attachment content.")];function xf(e,t){return De({name:"file",description:"📁 Grouped file and asset operations.",variants:f0,actionSchema:d_,aggregateOptions:{guidance:Gc,actionHints:al},handlers:p0(e,t)})}const h0=xf(Wr,Wr*1024*1024);function m0(e){return h0.listTools(e)}async function g0(e,t,o,n){const r="uploadLargeFileThresholdMB"in o&&typeof o.uploadLargeFileThresholdMB=="number"?o.uploadLargeFileThresholdMB:Wr,s=r*1024*1024;return xf(r,s).callTool(e,t,o,n)}function ya(){const e=(process.env.SIYUAN_MCP_TRANSPORT??"").toLowerCase();return e==="cli"||e==="http"?e:"stdio"}const Of="Uq2KRv7t",y0="https://f-api.wps.cn/ksform/api/v3/campaign",b0=`https://f.wps.cn/ksform/w/write/${Of}`,w0="0.5.0",_t={description:"v5nhl6",impact:"bbev5x",suggestion:"6wxpgj",source:"8dcnsl",agent:"fu27dr",pluginVersion:"yl3by8"},k0={settings:{value:"用户"},cli:{value:"CLI"},stdio:{value:"STDIO"},http:{value:"HTTP"}},Nf="无";function pn(e){return(e==null?void 0:e.trim())||Nf}function Dt(e){return{type:"input",strValue:e,isManualInput:!0}}function _0(e){const t=k0[e];return Dt(t.value)}function v0(e,t,o,n="input"){const r=e!=null&&e.questionMap?Object.entries(e.questionMap):[],s=r.find(([,i])=>{var c;return i.title===t&&i.type===n&&((c=i.baseInfo)==null?void 0:c.delete)!==!0});if(s)return s[0];const a=r.find(([,i])=>{var c;return i.title===t&&((c=i.baseInfo)==null?void 0:c.delete)!==!0});return(a==null?void 0:a[0])??o}function I0(e){const t=(e??"").trim().toLowerCase();if(t==="settings"||t==="user"||t==="用户")return"settings";if(t==="cli")return"cli";if(t==="http")return"http";if(t==="stdio")return"stdio";const o=ya();return o==="cli"||o==="http"?o:"stdio"}function S0(e){const t=pn(e);return t!==Nf?t:"0.5.0".trim()?"0.5.0".trim():w0}function D0(e,t){var u,p,f,h;const o=(h=(f=(p=(u=t==null?void 0:t.setting)==null?void 0:u.baseSetting)==null?void 0:p.commitConfig)==null?void 0:f.options)==null?void 0:h[0];if(!(t!=null&&t.token))throw new Error("Feedback form metadata did not include a submit token.");if(!(o!=null&&o.id))throw new Error("Feedback form metadata did not include a submit option.");const n=e.description.trim(),r=pn(e.impact),s=pn(e.suggestion),a=pn(e.agent),i=S0(e.pluginVersion),c=I0(e.source),l=v0(t,"来源",_t.source);return{answerJson:{answers:{[_t.description]:Dt(n),[_t.impact]:Dt(r),[_t.suggestion]:Dt(s),[l]:_0(c),[_t.agent]:Dt(a),[_t.pluginVersion]:Dt(i)},answersProperty:{commitInfo:{optionId:o.id,optionText:""}},consumeTime:2},phoneNumber:"",editVersion:t.editVersion??1,token:t.token,channel:c}}function Wi(e){return{Accept:"application/json, text/plain, */*",Origin:"https://f.wps.cn",Referer:b0,"User-Agent":"siyuan-plugin-mcp-sisyphus feedback",...e}}async function Gi(e,t){const o=await e.text();let n;try{n=JSON.parse(o)}catch{const r=o.length>200?`${o.slice(0,200)}...`:o;throw new Error(`${t} returned invalid JSON: ${r}`)}return n}async function Ki(e,t){const o=await e.text(),n=o.length>300?`${o.slice(0,300)}...`:o;return new Error(`${t} failed: HTTP ${e.status}${n?` ${n}`:""}`)}async function A0(e,t=fetch){var u,p,f,h,g,b;const o=e.description.trim();if(!o)throw new Error("Feedback description is required.");const n=`${y0}/${Of}`,r=await t(n,{method:"GET",headers:Wi()});if(!r.ok)throw await Ki(r,"Feedback metadata request");const s=await Gi(r,"Feedback metadata request");if(s.code!==0||!s.data)throw new Error(`Feedback metadata request failed: ${s.result||s.code}`);if((p=(u=s.data.setting)==null?void 0:u.baseSetting)!=null&&p.checkLogin)throw new Error("Feedback form currently requires WPS login.");const a=`sisyphus${Math.random().toString(36).slice(2)}`,i=D0({...e,description:o},s.data),c=await t(n,{method:"POST",headers:Wi({"Content-Type":"application/json",Cookie:`csrf=${a}`}),body:JSON.stringify({...i,csrfmiddlewaretoken:a})});if(!c.ok)throw await Ki(c,"Feedback submit");const l=await Gi(c,"Feedback submit");if(l.code!==0)throw new Error(`Feedback submit failed: ${l.result||l.code}`);return{success:!0,aid:(f=l.data)==null?void 0:f.aid,answerShareId:(g=(h=l.data)==null?void 0:h.answerShare)==null?void 0:g.asid,createdTs:(b=l.data)==null?void 0:b.createdTs}}const T0="feedback",P0=[S("submit",ad,"Submit plain-text GitHub Issue-style feedback to the developer.")],$f=De({name:T0,description:"💬 Submit plain-text GitHub Issue-style feedback, suggestions, or experience reports to the plugin developer.",variants:P0,actionSchema:h_,aggregateOptions:{guidance:el,actionHints:fl},handlers:{submit:async({rawArgs:e})=>{const t=ad.parse(e),o=await A0({description:t.description,impact:t.impact,suggestion:t.suggestion,agent:t.agent,source:t.source});return k({action:"submit",...o})}}});function E0(e){return $f.listTools(e)}async function C0(e,t,o,n){return $f.callTool(e,t,o,n)}const Mf=["Bridge tools exposed through the official SiYuan /mcp endpoint.","Plugin tools are included by default; native SiYuan tools are included only when includeNativeTools is enabled.",'Use action="list" to inspect discovery status. Every exposed tool keeps its official name as the action.',"Pass downstream parameters inside arguments={...}. Tools without readOnlyHint=true may mutate data and require explicit user confirmation."].join(" "),Kn=new Set(["help","list"]);function Ee(e,t=!1){return{content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}],...t?{isError:!0}:{}}}function ba(e,t){return e.source==="plugin"||t.includeNativeTools}function Qt(e,t){return!e.enabled||!t?[]:Jn(t.bridge.getTools(),e)}function Jn(e,t){const o=new Set(t.blockedTools);return e.filter(n=>ba(n,t)&&!o.has(n.name)&&!Kn.has(n.name))}function Kr(e,t){return Array.isArray(e)?e.map(o=>Kr(o,t)):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([o,n])=>o==="$ref"&&typeof n=="string"&&n.startsWith("#")?[o,`${t}${n.slice(1)}`]:[o,Kr(n,t)]))}function R0(e,t){const o=e.readOnlyHint?"Declared read-only by the official MCP registry.":"May modify data or trigger side effects. Explicit user confirmation is required before calling.",n=e.schemaDegraded?" The original input schema was invalid and has been degraded to a generic object.":"";return{type:"object",title:e.title||e.name,description:`${e.description||e.name} ${o}${n}`,source:e.source,readOnlyHint:e.readOnlyHint,...e.effectScope?{effectScope:e.effectScope}:{},properties:{action:{type:"string",const:e.name,description:`Official SiYuan MCP tool name: ${e.name}`},arguments:Kr(e.inputSchema,`#/oneOf/${t}/properties/arguments`)},required:["action","arguments"],additionalProperties:!1}}function x0(e,t){if(!e.enabled)return[];const o=Qt(e,t),n=["help","list",...o.map(s=>s.name)],r=[{type:"object",title:"Extension help",properties:{action:{type:"string",const:"help"},topic:{type:"string",description:"Optional official MCP tool name."}},required:["action"],additionalProperties:!1},{type:"object",title:"List official MCP tools",properties:{action:{type:"string",const:"list"},refresh:{type:"boolean",description:"Refresh the official SiYuan MCP registry before returning the list."}},required:["action"],additionalProperties:!1},...o.map((s,a)=>R0(s,a+2))];return[{name:"extension",description:[Mf,`Currently exposed actions: ${n.join(", ")}.`].join(`
515
-
516
- `),inputSchema:{type:"object",properties:{action:{type:"string",enum:n,description:"Use list or an exposed official MCP tool name."},arguments:{type:"object",description:"Arguments forwarded unchanged to the selected official MCP tool.",additionalProperties:!0},refresh:{type:"boolean"},topic:{type:"string"}},required:["action"],oneOf:r}}]}async function O0(e,t){if(!e.enabled||!t)return;const o=await t.bridge.refresh();return Jr(e,t,o.tools)&&await Qr(t),o}function Jr(e,t,o=t.bridge.getTools()){const n=JSON.stringify(Jn(o,e)),r=t.exposedToolsFingerprint!==n;return t.exposedToolsFingerprint=n,r}async function Qr(e){var t;try{await((t=e.notifyToolListChanged)==null?void 0:t.call(e))}catch{}}function N0(e,t){const o=new Set(t.blockedTools),n=Jn(e.tools,t),r=e.tools.reduce((s,a)=>(s[a.source]+=1,s),{plugin:0,native:0});return{connected:e.connected,lastSuccessfulRefreshAt:e.lastSuccessfulRefreshAt,lastAttemptAt:e.lastAttemptAt,error:e.error,changed:e.changed,discoveredCount:e.tools.length,discoveredBySource:r,nativeToolsEnabled:t.includeNativeTools,exposedCount:n.length,schemaBytes:JSON.stringify(n.map(s=>s.inputSchema)).length,tools:e.tools.map(s=>({name:s.name,title:s.title,description:s.description,source:s.source,readOnlyHint:s.readOnlyHint,effectScope:s.effectScope,schemaDegraded:s.schemaDegraded,blocked:o.has(s.name),sourceEnabled:ba(s,t),reservedActionConflict:Kn.has(s.name),exposed:n.some(a=>a.name===s.name)})),hint:e.error?"Official MCP tools require SiYuan 3.7.0+, an administrator session, and a valid API token.":t.includeNativeTools?'Plugin and native SiYuan tools are exposed. Call extension(action="<official tool name>", arguments={...}).':"Plugin tools are exposed. Enable includeNativeTools in settings to expose native SiYuan tools."}}function $0(e,t,o){const n=o==null?void 0:o.bridge.getTools().find(r=>r.name===e);if(e&&n){const r=ba(n,t),s=Kn.has(n.name);return Ee({tool:n.name,title:n.title,description:n.description,source:n.source,readOnlyHint:n.readOnlyHint,requiresConfirmation:!n.readOnlyHint,effectScope:n.effectScope,blocked:t.blockedTools.includes(n.name),sourceEnabled:r,reservedActionConflict:s,exposed:r&&!s&&!t.blockedTools.includes(n.name),schemaDegraded:n.schemaDegraded,inputSchema:n.inputSchema,call:{action:n.name,arguments:{}}})}return Ee({tool:"extension",description:Mf,actions:{list:{parameters:{refresh:"boolean, optional"},description:"Inspect or refresh official MCP tool discovery."},"<official tool name>":{parameters:{arguments:"object, required"},description:"Forward one call to the selected official MCP tool. Calls are never retried."}},includeNativeTools:t.includeNativeTools,discoveredTools:(o==null?void 0:o.bridge.getTools().map(r=>({name:r.name,source:r.source,exposed:Qt(t,o).some(s=>s.name===r.name)})))??[]})}async function M0(e,t,o,n,r){const s=typeof(t==null?void 0:t.action)=="string"?t.action:"";if(s==="help")return $0(typeof(t==null?void 0:t.topic)=="string"?t.topic:void 0,o,r);if(!r)return Ee("Official MCP bridge runtime is unavailable.",!0);if(s==="list"){const c=r.bridge.getSnapshot(),l=(t==null?void 0:t.refresh)===!0||!c.lastAttemptAt?await r.bridge.refresh():c;return Jr(o,r,l.tools)&&await Qr(r),Ee(N0(l,o))}if(!s)return Ee('extension.action is required. Use action="list" to inspect available official MCP tools.',!0);if(o.blockedTools.includes(s))return Ee(`Official MCP tool "${s}" is blocked in Sisyphus settings.`,!0);let a=Qt(o,r).find(c=>c.name===s);if(!a){const c=await r.bridge.refresh();Jr(o,r,c.tools)&&await Qr(r),a=Jn(c.tools,o).find(l=>l.name===s)}if(!a){const c=r.bridge.getTools().find(l=>l.name===s);return(c==null?void 0:c.source)==="native"&&!o.includeNativeTools?Ee(`Native SiYuan MCP tool "${s}" is disabled. Enable extension.includeNativeTools in Sisyphus settings first.`,!0):Kn.has(s)?Ee(`Official MCP tool "${s}" conflicts with a reserved extension action and cannot be exposed.`,!0):Ee(`Unknown official MCP tool "${s}". Use extension(action="list", refresh=true) to inspect current tools.`,!0)}const i=t==null?void 0:t.arguments;return i===null||typeof i!="object"||Array.isArray(i)?Ee("extension.arguments must be an object.",!0):r.bridge.callTool(s,i)}async function zf(e){return e.request("/api/riff/getRiffDecks",{})}async function Ji(e,t,o){return e.request("/api/riff/getRiffDueCards",{deckID:t??"",...o!==void 0?{reviewedCards:o}:{}})}async function z0(e,t,o){return e.request("/api/riff/getNotebookRiffDueCards",{notebook:t,...o!==void 0?{reviewedCards:o}:{}})}async function F0(e,t,o){return e.request("/api/riff/getTreeRiffDueCards",{rootID:t,...o!==void 0?{reviewedCards:o}:{}})}async function q0(e,t,o,n,r){return e.request("/api/riff/reviewRiffCard",{deckID:t,cardID:o,rating:n,...r!==void 0?{reviewedCards:r}:{}})}async function B0(e,t,o){return e.request("/api/riff/skipReviewRiffCard",{deckID:t,cardID:o})}async function L0(e,t,o){return e.request("/api/riff/addRiffCards",{deckID:t,blockIDs:o})}async function U0(e,t,o){return e.request("/api/riff/removeRiffCards",{deckID:t,blockIDs:o})}async function Qi(e,t,o,n){return e.request("/api/riff/getRiffCards",{id:t,page:o,...n!==void 0?{pageSize:n}:{}})}async function j0(e,t){return e.request("/api/riff/getRiffCardsByBlockIDs",{blockIDs:t})}const Ze="20230218211946-2kw8jgx",Xi="custom-riff-decks",H0="Built-in Deck",V0=5,Z0=300,ec=6,Y0=300;function W0(e){return typeof e=="string"?["new","0"].includes(e.toLowerCase()):e===0}function G0(e){return typeof e=="string"?["old","1","review"].includes(e.toLowerCase()):e===1}function K0(e,t){return t==="due"?e:t==="new"?e.filter(o=>W0(o.state)):e.filter(o=>G0(o.state))}function Ff(e){return e===""?Ze:e}function J0(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Q0(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.id=="string"&&t.id.length>0)return t.id;if(typeof t.deckID=="string"&&t.deckID.length>0)return t.deckID}async function qf(e,t){const o=await zp(e,t);return o&&typeof o=="object"?o:{}}async function X0(e,t){for(const o of t)if((await qf(e,o)).type==="doc")throw new Error(`Block "${o}" is a document block and cannot be turned into a flashcard. Pass a content block ID such as a paragraph or heading instead.`)}async function Bf(e,t,o){if(t===Ze)return;const n=await zf(e);if(!Array.isArray(n)||!n.some(r=>Q0(r)===t))throw new Error(`flashcard/${o} requires an existing deckID. Deck "${t}" was not found.`)}async function eP(e,t,o,n){for(const r of t){const s=await qf(e,r);if(!J0(s[Xi]).includes(o))throw new Error(`flashcard/${n} did not persist a valid deck binding for block "${r}". Expected ${Xi} to include "${o}".`)}}function tP(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:[]}function oP(e){return typeof e.id=="string"&&e.id.length>0?e.id:typeof e.blockID=="string"&&e.blockID.length>0?e.blockID:void 0}function tc(e){return!e||typeof e!="object"?!1:typeof e.riffCardID=="string"&&e.riffCardID.length>0?!0:!!e.riffCard}async function Lf(e,t,o,n){const r=new Set(t);for(let s=0;s<ec;s+=1){const a=await j0(e,t),i=new Map;for(const l of tP(a)){const u=oP(l);u&&i.set(u,l)}if([...r].every(l=>{const u=i.get(l);return o==="present"?tc(u):!tc(u)}))return;s<ec-1&&await jo(Y0)}throw new Error(o==="present"?`flashcard/${n} did not create readable riff card records for blocks: ${t.join(", ")}`:`flashcard/${n} did not fully remove readable riff card records for blocks: ${t.join(", ")}`)}function Uf(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:Array.isArray(e==null?void 0:e.cards)?e.cards:[]}function nP(e){return(!e.type||e.type==="")&&typeof e.content=="string"&&e.content.includes("不存在符合条件的内容块")}function rP(e){return e.length>0&&e.some(nP)}async function sP(e,t,o,n){let r=await Qi(e,t,o,n);for(let s=1;s<V0;s+=1){if(!rP(Uf(r)))return r;await jo(Z0),r=await Qi(e,t,o,n)}return r}const aP=async({client:e,rawArgs:t})=>{const o=id.parse(t),r=(o.scope==="all"?await Ji(e,"",o.reviewedCards):o.scope==="deck"?await Ji(e,o.deckID,o.reviewedCards):o.scope==="notebook"?await z0(e,o.notebook,o.reviewedCards):await F0(e,o.rootID,o.reviewedCards))??{};return k({...r,action:"list_cards",scope:o.scope,filter:o.filter,...o.deckID?{deckID:o.deckID}:{},...o.notebook?{notebook:o.notebook}:{},...o.rootID?{rootID:o.rootID}:{},...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},cards:K0(Array.isArray(r.cards)?r.cards:[],o.filter)})},iP=async({client:e,rawArgs:t})=>{cd.parse(t);const o=await zf(e),n=Array.isArray(o)?[...o]:[];return n.some(s=>{if(!s||typeof s!="object")return!1;const a=s;return a.id===Ze||a.deckID===Ze})||n.unshift({id:Ze,deckID:Ze,name:H0,builtin:!0}),k({action:"get_decks",decks:n})},cP=async({client:e,rawArgs:t})=>{const o=pd.parse(t),n=await sP(e,o.deckID,o.page??1,o.pageSize);return k({action:"get_cards",deckID:o.deckID,page:o.page??1,...o.pageSize!==void 0?{pageSize:o.pageSize}:{},cards:Uf(n),total:n==null?void 0:n.total,pageCount:n==null?void 0:n.pageCount})},lP=async({client:e,rawArgs:t})=>{const o=ld.parse(t);if(o.deckID==="")throw new Error("flashcard/review_card requires a concrete deckID. Use flashcard/get_cards first to resolve the card deck, then retry.");if(o.skip===!0){const r=await B0(e,o.deckID,o.cardID);return k({action:"review_card",skip:!0,deckID:o.deckID,cardID:o.cardID,result:r})}const n=await q0(e,o.deckID,o.cardID,o.rating,o.reviewedCards);return k({action:"review_card",deckID:o.deckID,cardID:o.cardID,rating:o.rating,...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},result:n})},uP=async({client:e,rawArgs:t})=>{const o=ud.parse(t),n=Ff(o.deckID);await X0(e,o.blockIDs),await Bf(e,n,"create_card");const r=o.mode??"full",s=await L0(e,n,o.blockIDs);return await eP(e,o.blockIDs,n,"create_card"),n===Ze&&await Lf(e,o.blockIDs,"present","create_card"),k({action:"create_card",mode:r,deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:s})},dP=async({client:e,rawArgs:t})=>{const o=dd.parse(t),n=Ff(o.deckID);await Bf(e,n,"remove_card");const r=await U0(e,n,o.blockIDs);return n===Ze&&await Lf(e,o.blockIDs,"absent","remove_card"),k({action:"remove_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})},pP={list_cards:aP,get_decks:iP,get_cards:cP,review_card:lP,create_card:uP,remove_card:dP},fP=[S("list_cards",id,"List due flashcards and optionally filter to new/old cards."),S("get_decks",cd,"Get flashcard deck definitions."),S("get_cards",pd,"List all cards in a deck with pagination (not limited to due cards)."),S("review_card",ld,"Submit a review result or skip one flashcard."),S("create_card",ud,"Turn existing blocks into flashcards or attach existing blocks to a deck."),S("remove_card",dd,"Remove existing blocks from a flashcard deck.")],jf=De({name:"flashcard",description:"🃏 Grouped flashcard review and deck operations.",variants:fP,actionSchema:p_,aggregateOptions:{guidance:Qc,actionHints:dl},handlers:pP}),hP=jf.listTools,mP=jf.callTool;function wa(e){const t=e.trim();if(!t)throw new Error("fs path must not be empty.");const n=(t.startsWith("/")?t:`/${t}`).replace(/\/+/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function gP(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function oc(e){return e.split("/").filter(Boolean).at(-1)??""}function nc(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Ct(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function yP(e,t,o){return o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t)}async function Hf(e){return(await at(e)).notebooks.map(o=>({id:o.id,name:o.name,closed:o.closed}))}async function Xr(e,t,o){let n;try{n=await Lp(e,o,t.id)}catch{n=[]}const r=await st(e,["SELECT id","FROM blocks","WHERE type = 'd'",`AND box = '${we(t.id)}'`,`AND hpath = '${we(o)}'`,"LIMIT 100"].join(" ")).catch(()=>[]);for(const i of r)i&&typeof i=="object"&&typeof i.id=="string"&&n.push(i.id);const s=[...new Set(n)],a=[];for(const i of s){const c=await wo(e,i),l=await Vn(e,i).catch(()=>o),u=wa(l),p=oc(u)||gP(oc(c.path))||i;a.push({type:"document",id:i,notebook:c.notebook||t.id,notebookName:t.name,hPath:u,storagePath:c.path,canonicalPath:Ct(t.name,u),name:p})}return a}function es(e){return e.map(t=>t.canonicalPath).join(", ")}function Re(e,t){const o=new Error(t);return Object.assign(o,{code:e}),o}async function Ne(e,t,o,n="read"){const r=wa(o);if(r==="/")return{type:"root",canonicalPath:"/"};await t.reload();const s=await Hf(e),a=r.split("/").filter(Boolean),i=a[0],c=s.find(u=>u.name===i);if(c){const u=a.length===1?"/":`/${a.slice(1).join("/")}`;if(u==="/")return{type:"notebook",notebook:c.id,notebookName:c.name,hPath:"/",storagePath:"/",canonicalPath:Ct(c.name,"/")};const p=await Xr(e,c,u);if(p.length===0)throw Re("not_found",`No document found at "${r}".`);if(p.length>1)throw Re("ambiguous_path",`Ambiguous fs path "${r}". Candidates: ${es(p)}.`);return p[0]}const l=[];for(const u of s)if(yP(t,u.id,n))try{l.push(...await Xr(e,u,r))}catch{}if(l.length===1)return l[0];throw l.length>1?Re("ambiguous_path",`Ambiguous fs path "${r}". Candidates: ${es(l)}.`):Re("not_found",`No document found at "${r}". Use /<notebook name>/<document path> for an unambiguous path.`)}async function Vf(e,t,o){const n=wa(o);if(n==="/")throw Re("invalid_path",'Cannot create a document at "/". Use /<notebook name>/<title>.');const r=n.split("/").filter(Boolean),s=r.at(-1);if(!s)throw Re("invalid_path",`Cannot create a document at "${n}".`);await t.reload();const i=(await Hf(e)).find(p=>p.name===r[0]);if(i){const p=r.slice(1,-1),f=p.length===0?"/":`/${p.join("/")}`;let h="/",g;if(f!=="/"){const _=await Xr(e,i,f);if(_.length===0)throw Re("not_found",`Parent document not found at "${Ct(i.name,f)}".`);if(_.length>1)throw Re("ambiguous_path",`Ambiguous parent path "${Ct(i.name,f)}". Candidates: ${es(_)}.`);const w=_[0];h=w.storagePath,g=w.id}const b=nc(f,s);return{notebook:i.id,notebookName:i.name,title:s,parentHPath:f,parentStoragePath:h,parentId:g,hPath:b,canonicalPath:Ct(i.name,b)}}if(r.length===1)throw Re("invalid_path","Root-level create must use /<notebook name>/<title>.");const c=`/${r.slice(0,-1).join("/")}`,l=await Ne(e,t,c,"write");if(l.type!=="document")throw Re("invalid_path",`Parent path "${c}" must resolve to a document folder.`);const u=nc(l.hPath,s);return{notebook:l.notebook,notebookName:l.notebookName,title:s,parentHPath:l.hPath,parentStoragePath:l.storagePath,parentId:l.id,hPath:u,canonicalPath:Ct(l.notebookName,u)}}async function bP(e,t,o){return Vf(e,t,o)}function wP(e,t){let o=0,n=0;for(;;){if(n=e.indexOf(t,n),n===-1)return o;o+=1,n+=t.length}}function kP(e,t,o,n){const r=wP(e,t.old);if(r===0){const a="";throw new Error(`${n} edit #${o+1} did not match any text.${a}`)}if(t.replace_all)return{content:e.split(t.old).join(t.new),replaced:r,replaceAll:!0};const s=e.indexOf(t.old);return{content:`${e.slice(0,s)}${t.new}${e.slice(s+t.old.length)}`,replaced:1,replaceAll:!1}}function _P(e,t,o){let n=e;const r=t.map((s,a)=>{const i=kP(n,s,a,o);return n=i.content,{index:a+1,replaced:i.replaced,replace_all:i.replaceAll}});return{content:n,summary:r}}const vP=/\bdata-av-id=(?:"([^"]+)"|'([^']+)')/i,IP=new Set(["s","av","iframe","widget","query_embed","html","video","audio"]);function ka(e){return!!(e&&IP.has(e))}function SP(e){const t=Array.from(new Set(e.map(o=>o.type).filter(o=>ka(o))));return t.length===0?{}:{nonFidelityWarning:"fs is intentionally limited to pure Markdown-style document operations. This document contains SiYuan-native structures; inspect or modify those blocks with advanced tools instead of fs.",complexBlockTypes:t,recommendedReads:["file.export_md","block.dom"]}}function Zf(e){return e.flatMap(t=>ka(t.type)?[{...t.id?{id:t.id}:{},type:t.type}]:[])}function DP(e){return!!(e.type&&!ka(e.type))}function AP(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"complex_blocks_not_supported_by_fs",message:`fs.${e} is limited to pure Markdown documents and will not modify documents containing SiYuan-native complex blocks.`,path:t,id:o,complexBlocks:n,recommendedTools:["file.export_md","block.dom","block.update","block.append","av"],hint:"Use fs for pure Markdown content only. For database blocks, super blocks, embeds, widgets, HTML/media, or precise native structure changes, inspect with block.dom and edit with the matching advanced tool."}},null,2)}],isError:!0}}function Ft(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function An(e){if(e)return e.split("/").filter(Boolean).at(-1)}function Yf(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Wf(e){const t=e.trim();if(!t)throw new Error("fs path must not be empty.");const n=(t.startsWith("/")?t:`/${t}`).replace(/\/+/g,"/");return n.length>1?n.replace(/\/+$/,""):n}const Qn=[ie,ze];function $e(e){const t=Wf(e);return Qn.find(o=>t===o)??null}function Tn(e){const t=Wf(e);return Qn.find(o=>t.startsWith(`${o}/`))??null}function bt(e){const t=Tn(e);if(t)throw new Error(`${t} is a virtual file and has no children.`)}function Mo(e){if(($e(e)??Tn(e))===ze)throw new Error(`${ze} is a read-only virtual file. Edit user rules in the plugin settings.`)}function TP(e){return{name:e.slice(1),path:e,children:0,virtual:!0}}function PP(e){return{name:e.slice(1),path:e,children:[],virtual:!0}}function EP(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function CP(e,t){const o=Ft(t.name)??Ft(An(t.path))??t.path;return{name:o,path:Yf(e,o),children:t.subFileCount??t.count??0}}async function _a(e,t){return await t.reload(),(await at(e)).notebooks.filter(n=>t.canRead(n.id))}async function RP(e,t){return t.type==="root"?[]:(await Zn(e,t.notebook,t.storagePath)).map(n=>CP(t.canonicalPath,n))}function xP(e,t){const o=Ft(typeof e.name=="string"?e.name:void 0)??Ft(An(typeof e.hPath=="string"?e.hPath:void 0))??Ft(An(typeof e.path=="string"?e.path:void 0))??(typeof e.id=="string"?e.id:"Untitled");return{name:o,path:Yf(t,o)}}async function ts(e,t,o,n,r,s=0,a=new Map){return Array.isArray(t)?Promise.all(t.map(async i=>{const c=i&&typeof i=="object"?i:{},l=xP(c,o);let u=l.name,p=l.path;const f=typeof c.id=="string"?c.id:void 0;if(f)try{let b=a.get(f);b||(b=Vn(e,f),a.set(f,b));const _=await b,w=Ft(An(_));w&&(u=w,p=EP(n,_))}catch{}const h=Array.isArray(c.children)?c.children:[],g={name:u,path:p};return s>=r?g.children=h.length:g.children=await ts(e,h,g.path,n,r,s+1,a),g})):[]}function ko(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.tree)?e.tree:[]}function fn(e){if(!Array.isArray(e))return[];const t=[];for(const o of e){if(!o||typeof o!="object")continue;const n=o;typeof n.id=="string"&&t.push(n.id),Array.isArray(n.children)&&t.push(...fn(n.children))}return t}async function OP(e,t,o){const n=await jn(e,t);for(const r of n)typeof r.id=="string"&&await $p(e,r.id);o.trim().length>0&&await Np(e,"markdown",o,t)}function rc(e){const t=e.match(vP);return(t==null?void 0:t[1])??(t==null?void 0:t[2])}async function Gf(e,t,o){const r=(o??await Ho(e,t)).filter(s=>s.type==="av");return Promise.all(r.map(async s=>{const a=await io(e,s.id),i=typeof a.kramdown=="string"?a.kramdown:"";return{blockID:s.id,...rc(i)?{avID:rc(i)}:{}}}))}function br(e,t,o){const{nextBlockStart:n,...r}=t;if(n===void 0)return{path:e,...r};const s={action:"read",path:e,blockStart:n,blockLimit:t.blockLimit,tokenBudget:t.tokenBudget,...o?{includeBlockIds:!0}:{}};return{path:e,...r,nextWindow:s,nextWindowHint:`Continue with fs(${JSON.stringify(s)}).`}}function Kf(e){return{attributeViews:e,warning:'This document contains database/attribute-view blocks. fs is only a pure Markdown convenience layer and will not safely edit these SiYuan-native structures. Use av(action="get"|"render"|"set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column") for rows, columns, and cells.',avToolHint:{read:'av(action="get", id="<av-id>") or av(action="render", id="<av-id>", blockID="<database-block-id>")',write:'av(action="set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column", avID="<av-id>", ...)'}}}async function NP(e,t,o){const n=await Ho(e,t),r=Zf(n),s=n.filter(DP).map(c=>({id:c.id,type:c.type}));if(s.length===0)throw new Error("fs.replace found no editable non-complex Markdown blocks in this document.");const a=await Promise.all(s.map(async c=>{const[l,u]=await Promise.all([io(e,c.id),Hn(e,c.id)]);return{id:c.id,type:c.type,kramdown:typeof l.kramdown=="string"?l.kramdown:"",dom:typeof u.dom=="string"?u.dom:""}})),i=QD(a,o,"fs.replace");for(const c of i.blocks){const l=c.touchesIndexedInline&&c.type!=="l";await na(e,l?"markdown":"dom",l?c.markdown:c.dom,c.id)}return{summary:i.summary,changedBlockCount:i.blocks.length,changedMarkdown:i.blocks.map(c=>c.markdown).join(`
517
- `),skippedComplexBlocks:r}}async function $P(e,t,o){if(o.type==="document"){const s=ko(await Nt(e,o.notebook,o.storagePath));return[...new Set([o.id,...fn(s)])].map(a=>({id:a,notebookName:o.notebookName}))}if(o.type==="notebook"){const s=ko(await Nt(e,o.notebook,"/"));return[...new Set(fn(s))].map(a=>({id:a,notebookName:o.notebookName}))}const n=await _a(e,t),r=[];for(const s of n){const a=ko(await Nt(e,s.id,"/"));r.push(...[...new Set(fn(a))].map(i=>({id:i,notebookName:s.name})))}return r}function MP(e,t,o){if(t){const r=o?"":"i",s=new RegExp(e,r);return a=>s.test(a)}const n=o?e:e.toLowerCase();return r=>(o?r:r.toLowerCase()).includes(n)}function sn(e,t,o){const n=[];return e.split(/\r?\n/).forEach((r,s)=>{t(r)&&n.push({path:o,line:s+1,text:r.length>300?`${r.slice(0,297)}...`:r})}),n}async function Pn(e){const t=await zs(e);return{content:t.agentSiyuanMemoryText??"",updatedAt:t.agentSiyuanMemoryUpdatedAt??""}}async function os(e){return{content:(await zs(e)).userRulesText??""}}const zP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Iu.parse(o);bt(n.path);const r=$e(n.path);if(r)throw new Error(`${r} is a virtual file and has no children.`);const s=await Ne(e,t,n.path,"read");if(s.type==="root"){const i=await _a(e,t),c=Qn.map(l=>TP(l));for(const l of i){let u=0;try{u=(await Zn(e,l.id,"/")).length}catch{u=0}c.push({name:l.name,path:`/${l.name}`,children:u})}return k({path:"/",items:c})}const a=await Y(t,s.notebook,"read");return a||k({path:s.canonicalPath,items:await RP(e,s)})},FP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Su.parse(o);bt(n.path);const r=$e(n.path);if(r)return k({path:r,tree:[],virtual:!0,maxDepth:n.maxDepth??3});const s=await Ne(e,t,n.path,"read"),a=n.maxDepth??3;if(s.type==="root"){const l=await _a(e,t),u=Qn.map(p=>PP(p));for(const p of l){const f=await Nt(e,p.id,"/");u.push({name:p.name,path:`/${p.name}`,children:await ts(e,ko(f),`/${p.name}`,p.name,a)})}return k({path:"/",tree:u,maxDepth:a})}const i=await Y(t,s.notebook,"read");if(i)return i;const c=await Nt(e,s.notebook,s.storagePath);return k({path:s.canonicalPath,tree:await ts(e,ko(c),s.canonicalPath,s.notebookName,a),maxDepth:a})},qP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Du.parse(o),r={blockStart:n.blockStart,blockLimit:n.blockLimit,tokenBudget:n.tokenBudget,includeBlockIds:n.includeBlockIds};bt(n.path);const s=$e(n.path);if(s===ie){const p=await Pn(e),f=Yi(p.content,r);return k({...br(ie,f,!1),virtual:!0,updatedAt:p.updatedAt||null})}if(s===ze){const p=await os(e),f=Yi(p.content,r);return k({...br(ze,f,!1),virtual:!0})}const a=await Ne(e,t,n.path,"read");if(a.type!=="document")throw new Error(`fs.read requires a document path, got "${n.path}".`);const i=await Y(t,a.notebook,"read");if(i)return i;const c=await Ho(e,a.id),[l,u]=await Promise.all([Sf(e,a.id,r,c),Gf(e,a.id,c)]);return k({...br(a.canonicalPath,l,n.includeBlockIds??!1),...u.length>0?Kf(u):{},...SP(c)})},BP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Au.parse(o);if(Mo(n.path),bt(n.path),$e(n.path)===ie){const f=await Fs(e,n.markdown);return k({success:!0,path:ie,virtual:!0,overwritten:!0,updatedAt:f.agentSiyuanMemoryUpdatedAt||null})}const s=await Vf(e,t,n.path),a=await Y(t,s.notebook,"write");if(a)return a;let i=null;try{const f=await Ne(e,t,s.canonicalPath,"write");i=f.type==="document"?f:null}catch{i=null}if(!i){const f=await Jt(e,bf(n.markdown,s.title),"fs.write"),h=await Fp(e,s.notebook,s.hPath,f);return F(e,k({success:!0,path:s.canonicalPath,id:h,created:!0,...Wt(f)?Oo():{},...Gt(f)?No():{},...Kt(f)?$o():{}}),[{type:"reloadProtyle",id:h},{type:"reloadFiletree"}])}if(!n.overwrite)throw new Error(`Document already exists at "${i.canonicalPath}". Pass overwrite=true to replace its body.`);const c=await Jt(e,n.markdown,"fs.write"),l=await Ho(e,i.id),u=Zf(l);if(u.length>0)return AP("write",i.canonicalPath,i.id,u);const p=await Gf(e,i.id);return await OP(e,i.id,c),F(e,k({success:!0,path:i.canonicalPath,id:i.id,overwritten:!0,...Wt(c)?Oo():{},...Gt(c)?No():{},...Kt(c)?$o():{},...p.length>0?Kf(p):{}}),[{type:"reloadProtyle",id:i.id},{type:"reloadFiletree"}])},LP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Tu.parse(o);if(Mo(n.path),bt(n.path),$e(n.path)===ie){const g=await Pn(e),b=g.content,_=Array.isArray(n.edit)?n.edit:[n.edit],{content:w,summary:P}=_P(b,_,"fs.replace"),D=w!==b;let T=g.updatedAt;return D&&(T=(await Fs(e,w)).agentSiyuanMemoryUpdatedAt),k({success:!0,path:ie,virtual:!0,changed:D,editsApplied:P.length,replacements:P,updatedAt:T||null})}const s=await Ne(e,t,n.path,"write");if(s.type!=="document")throw new Error(`fs.replace requires a document path, got "${n.path}".`);const a=await Y(t,s.notebook,"write");if(a)return a;const i=await wf(e,Array.isArray(n.edit)?n.edit:[n.edit],"fs.replace"),c=await NP(e,s.id,i),{summary:l,changedBlockCount:u,changedMarkdown:p,skippedComplexBlocks:f}=c,h=u>0;return F(e,k({success:!0,path:s.canonicalPath,changed:h,editsApplied:l.length,replacements:l,...f.length>0?{warning:"This document contains SiYuan-native complex blocks. fs.replace edited only matched non-complex Markdown blocks; complex blocks were skipped.",skippedComplexBlocks:f,recommendedTools:["block.dom","block.update","av","file.export_md"]}:{},...Wt(p)?Oo():{},...Gt(p)?No():{},...Kt(p)?$o():{}}),h?[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}]:[])},UP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Pu.parse(o);if(Mo(n.path),bt(n.path),$e(n.path)===ie){const i=await Fs(e,"");return k({success:!0,path:ie,virtual:!0,cleared:!0,updatedAt:i.agentSiyuanMemoryUpdatedAt||null})}const s=await Ne(e,t,n.path,"delete");if(s.type!=="document")throw new Error(`fs.rm requires a document path, got "${n.path}".`);const a=await Y(t,s.notebook,"delete");return a||(await Nr(e,s.id),F(e,k({success:!0,path:s.canonicalPath}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}]))},jP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Eu.parse(o);if(Mo(n.from),Mo(n.to),$e(n.from)===ie||$e(n.to)===ie||Tn(n.from)===ie||Tn(n.to)===ie)throw new Error(`${ie} is a fixed virtual file and cannot be moved or renamed.`);const r=await Ne(e,t,n.from,"write");if(r.type!=="document")throw new Error(`fs.mv source must be a document path, got "${n.from}".`);const s=await bP(e,t,n.to),a=await Y(t,r.notebook,"write");if(a)return a;const i=await Y(t,s.notebook,"write");if(i)return i;try{const c=await Ne(e,t,s.canonicalPath,"write");if(c.type==="document"&&c.id!==r.id)throw new Error(`Destination already exists at "${s.canonicalPath}".`)}catch(c){if(c instanceof Error&&c.message.startsWith("Destination already exists"))throw c}return await Bp(e,[r.id],s.parentId??s.notebook),r.name!==s.title&&await qp(e,r.id,s.title),F(e,k({success:!0,path:r.canonicalPath,movedTo:s.canonicalPath}),[{type:"reloadProtyle",id:r.id},{type:"reloadFiletree"}])},HP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Cu.parse(o);bt(n.path);const r=MP(n.query,n.regex,n.caseSensitive),s=$e(n.path);if(s===ie){const _=await Pn(e),w=sn(_.content,r,ie),P=n.page??1,D=n.pageSize??50,T=Math.max(1,Math.ceil(w.length/D)),A=Math.min(P,T),O=(A-1)*D;return We(w.slice(O,O+D),{total:w.length,page:A,pageSize:D,pageCount:T,hasNextPage:A<T},{path:ie,virtual:!0,updatedAt:_.updatedAt||null,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}if(s===ze){const _=await os(e),w=sn(_.content,r,ze),P=n.page??1,D=n.pageSize??50,T=Math.max(1,Math.ceil(w.length/D)),A=Math.min(P,T),O=(A-1)*D;return We(w.slice(O,O+D),{total:w.length,page:A,pageSize:D,pageCount:T,hasNextPage:A<T},{path:ze,virtual:!0,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}const a=await Ne(e,t,n.path,"read");if(a.type!=="root"){const _=await Y(t,a.notebook,"read");if(_)return _}const i=await $P(e,t,a),c=[];a.type==="root"&&(c.push(...sn((await Pn(e)).content,r,ie)),c.push(...sn((await os(e)).content,r,ze)));for(const _ of i){const w=Wp(await ga(e,_.id)),P=typeof w.content=="string"?w.content:"",D=typeof w.hPath=="string"?w.hPath:`/${_.id}`,T=`/${_.notebookName}${D}`;P.split(/\r?\n/).forEach((A,O)=>{r(A)&&c.push({path:T,line:O+1,text:A.length>300?`${A.slice(0,297)}...`:A})})}const l=new Set,u=c.filter(_=>{const w=`${_.path}\0${_.line}\0${_.text}`;return l.has(w)?!1:(l.add(w),!0)}),p=n.page??1,f=n.pageSize??50,h=Math.max(1,Math.ceil(u.length/f)),g=Math.min(p,h),b=(g-1)*f;return We(u.slice(b,b+f),{total:u.length,page:g,pageSize:f,pageCount:h,hasNextPage:g<h},{path:a.canonicalPath,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})},VP={ls:zP,tree:FP,read:qP,write:BP,replace:LP,rm:UP,mv:jP,search:HP},ZP=[S("ls",Iu,"List direct child documents using human-readable paths."),S("tree",Su,"List a recursive document tree using human-readable paths."),S("read",Du,"Read complete display-block Markdown windows by human-readable path, with outline and continuation metadata."),S("write",Au,"Create a document, stripping a duplicate leading title heading when present; overwrite=true performs a full body replacement."),S("replace",Tu,"Apply exact old/new text replacement edits inside matched non-complex Markdown block DOM without rebuilding the document."),S("rm",Pu,"Delete a document by human-readable path."),S("mv",Eu,"Move or rename a document by human-readable paths."),S("search",Cu,"Search Markdown lines under a human-readable path.")],Jf=De({name:"fs",description:"📂 Simplified filesystem-style document operations.",variants:ZP,actionSchema:a_,aggregateOptions:{guidance:Hc,actionHints:tl},handlers:VP});function YP(e){return Jf.listTools(e)}async function WP(e,t,o,n){return Jf.callTool(e,t,o,n)}const GP="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyEvents.json",Qf="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyStats.json";function zo(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function KP(e){if(!e)return{totalCalls:0,balance:0,updatedAt:0};try{const t=JSON.parse(e),o=zo(t.totalCalls),n=t.balance===void 0?o:zo(t.balance);return{totalCalls:o,balance:n,updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:0,lastAction:typeof t.lastAction=="string"?t.lastAction:void 0}}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function Fo(e){try{return KP(await e.readFile(Qf))}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function Xf(e,t){const o={totalCalls:zo(t.totalCalls),balance:zo(t.balance),updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:Date.now(),...t.lastAction?{lastAction:t.lastAction}:{}};return await e.writeFile(Qf,JSON.stringify(o)),o}async function JP(e,t){const o=await Fo(e);try{return await Xf(e,{totalCalls:o.totalCalls+1,balance:o.balance+1,updatedAt:Date.now(),lastAction:t})}catch{return o}}async function QP(e,t,o){const n=await Fo(e),r=zo(t);if(n.balance<r)throw new Error(`Insufficient mascot balance. Need ${r}, have ${n.balance}.`);return Xf(e,{totalCalls:n.totalCalls,balance:n.balance-r,updatedAt:Date.now(),lastAction:o})}async function sc(e,t){try{const o=JSON.stringify({...t,seq:Date.now(),ts:Date.now()});await e.writeFile(GP,o)}catch{}}const Xn=[{id:"cat-food",label:"Cat Food",cost:5,type:"food",emoji:"🍖"},{id:"milk",label:"Milk",cost:3,type:"drink",emoji:"🥛"},{id:"dried-fish",label:"Dried Fish",cost:4,type:"food",emoji:"🐟"},{id:"can-food",label:"Canned Food",cost:6,type:"food",emoji:"🥫"},{id:"catnip",label:"Catnip",cost:5,type:"snack",emoji:"🌿"},{id:"chicken-leg",label:"Chicken Leg",cost:7,type:"food",emoji:"🍗"},{id:"cheese",label:"Cheese",cost:4,type:"snack",emoji:"🧀"}];Xn[0];Xn[1];function XP(e){return Xn.find(t=>t.id===e)??null}const eE=[S("get_balance",nd,"Get the mascot balance. Every successful MCP tool call earns 1 coin."),S("shop",rd,"List the mascot shop inventory."),S("buy",sd,"Buy one item from the mascot shop.")],eh=De({name:"mascot",description:"🐾 Grouped mascot balance and care operations. Every successful MCP tool call earns 1 coin for the mascot.",variants:eE,actionSchema:f_,aggregateOptions:{guidance:Xc,actionHints:pl},handlers:{get_balance:async({client:e,rawArgs:t})=>{nd.parse(t);const o=await Fo(e);return k({action:"get_balance",balance:o.balance,totalEarned:o.totalCalls})},shop:async({rawArgs:e})=>(rd.parse(e),k({action:"shop",items:Xn})),buy:async({client:e,rawArgs:t})=>{const o=sd.parse(t),n=XP(o.item_id);if(!n)throw new Error(`Unknown mascot shop item: ${o.item_id}.`);const r=await QP(e,n.cost,`buy:${n.id}`);return k({success:!0,action:"buy",item_id:n.id,item:n.label,type:n.type,emoji:n.emoji,cost:n.cost,balance:r.balance,totalEarned:r.totalCalls})}}});function tE(e){return eh.listTools(e)}async function oE(e,t,o,n){return eh.callTool(e,t,o,n)}const th="notebook";function ac(e,t,o,n){const r=e instanceof Error?e.message:String(e);return o?r.includes("permission")?new Error(`Failed to get child documents for notebook "${t}": permission denied by SiYuan. ${r}`):n?new Error(`Failed to get child documents for notebook "${t}": notebook is currently closed or still initializing. ${r}`):new Error(`Failed to get child documents for notebook "${t}" at "/". ${r}`):new Error(`Failed to get child documents: notebook "${t}" does not exist.`)}function nE(e){const t=e instanceof Error?e.message:String(e);return/initializing|kernel still initializing|notebook is currently closed/i.test(t)}async function rE(e,t,o,n){let r=0;for(;r<=o;){r+=1;try{return{children:await Zn(e,t,"/"),attempts:r}}catch(s){if(r>o||!nE(s))return{error:s,attempts:r};await new Promise(a=>setTimeout(a,n))}}return{error:new Error(`Failed to get child documents for notebook "${t}".`),attempts:r}}function sE(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:th,action:"get_child_docs",message:t,reason:"notebook_closed_or_initializing",retryable:!0,suggestedNextAction:"open_notebook_or_retry",notebook:e,retryAttempts:o,retryWindowMs:n,hint:'This usually happens right after notebook(action="close"). Re-open the notebook first, or retry after a short wait.'}},null,2)}],isError:!0}}const aE=async({client:e,rawArgs:t})=>{Ru.parse(t);const o=await at(e);return k(o.notebooks)},iE=async({client:e,rawArgs:t})=>{const o=xu.parse(t),n=await Xv(e,o.name);return o.icon&&(await Up(e,n.notebook.id,o.icon),n.notebook.icon=o.icon),F(e,k({...n.notebook,iconHint:ea("notebook",!!o.icon)}),o.icon?[{type:"reloadIcon"}]:[{type:"reloadFiletree"}])},cE=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ou.parse(o),r=await Y(t,n.notebook,"read");return r||(n.opened?await Jv(e,n.notebook):await Qv(e,n.notebook),F(e,k({success:!0,notebook:n.notebook,opened:n.opened}),[{type:"reloadFiletree"}]))},lE=async({client:e,permMgr:t,rawArgs:o})=>{const n=Nu.parse(o),r=await Y(t,n.notebook,"delete");return r||(await eI(e,n.notebook),F(e,k({success:!0,notebook:n.notebook}),[{type:"reloadFiletree"}]))},uE=async({client:e,permMgr:t,rawArgs:o})=>{const n=$u.parse(o),r=await Y(t,n.notebook,"write");return r||(await tI(e,n.notebook,n.name),F(e,k({success:!0,notebook:n.notebook,name:n.name}),[{type:"reloadFiletree"}]))},dE=async({client:e,permMgr:t,rawArgs:o})=>{const n=Mu.parse(o),r=await Y(t,n.notebook,"read");if(r)return r;const s=await oI(e,n.notebook);return k(s)},pE=async({client:e,permMgr:t,rawArgs:o})=>{const n=zu.parse(o),r=await Y(t,n.notebook,"write");if(r)return r;const s=await nI(e,n.notebook,n.conf);return F(e,k(s),[{type:"reloadFiletree"}])},fE=async({client:e,permMgr:t,rawArgs:o})=>{const n=Fu.parse(o),r=await Y(t,n.notebook,"write");return r||(await Up(e,n.notebook,n.icon),F(e,k({success:!0,notebook:n.notebook,icon:n.icon}),[{type:"reloadIcon"}]))},hE=async({client:e,permMgr:t,rawArgs:o})=>{const n=qu.parse(o);await t.reload();const s=(await at(e)).notebooks.map(i=>({id:i.id,name:i.name,permission:t.get(i.id)}));if(!n.notebook||n.notebook==="all")return k({notebooks:s});const a=s.find(i=>i.id===n.notebook);return a?k({notebook:a}):bo(new Error(`Notebook "${n.notebook}" not found.`),{tool:th,action:"get_permissions",rawArgs:o})},mE=async({client:e,permMgr:t,rawArgs:o})=>{const n=Bu.parse(o);return await t.set(n.notebook,n.permission),F(e,k({success:!0,notebook:n.notebook,permission:n.permission}),[{type:"reloadFiletree"}])},gE=async({client:e,permMgr:t,rawArgs:o})=>{const n=Lu.parse(o),r=2,s=150,a=await Y(t,n.notebook,"read");if(a)return a;const c=(await at(e)).notebooks.find(f=>f.id===n.notebook);if(!c)throw ac(new Error("Notebook not found in lsNotebooks result."),n.notebook,!1,!1);const l=await rE(e,n.notebook,r,s);if(l.error){const f=ac(l.error,n.notebook,!0,!!c.closed);if(c.closed)return sE(n.notebook,f.message,l.attempts,r*s);throw f}const u=l.children??[],p=Xs(u,n.page??1,n.pageSize??50);return We(p.items,p,{notebook:n.notebook})},yE={list:aE,create:iE,set_open_state:cE,remove:lE,rename:uE,get_conf:dE,set_conf:pE,set_icon:fE,get_permissions:hE,set_permission:mE,get_child_docs:gE},bE=[S("list",Ru,"List all notebooks in the workspace."),S("create",xu,"Create a new notebook."),S("set_open_state",Ou,"Set notebook open state (open or close)."),S("remove",Nu,"Remove a notebook."),S("rename",$u,"Rename a notebook."),S("get_conf",Mu,"Get notebook configuration."),S("set_conf",zu,"Set notebook configuration."),S("set_icon",Fu,"Set the icon for a notebook."),S("get_permissions",qu,'Get permission levels for notebooks. Omit notebook or pass "all" to return every notebook; pass a specific notebook ID to return only that notebook.'),S("set_permission",Bu,"Set the permission level for a notebook."),S("get_child_docs",Lu,"Get direct child documents at the notebook root. Returns a paginated { data, total, page, pageSize, pageCount, hasNextPage } payload.")],oh=De({name:"notebook",description:"📚 Grouped notebook operations.",variants:bE,actionSchema:i_,aggregateOptions:{guidance:Vc,actionHints:ol},handlers:yE});function wE(e){return oh.listTools(e)}function kE(e,t,o,n){return oh.callTool(e,t,o,n)}async function _E(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushMsg",n)}async function vE(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushErrMsg",n)}const IE=1,SE=12;function ic(e,t,o,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(o,Math.min(n,Math.trunc(e)))}function DE(e){const t=e.match(/[^.[\]]+/g);if(!t||t.length===0)throw new Error("keyPath must not be empty.");return t.map(o=>/^\d+$/.test(o)?Number(o):o)}function AE(e,t){const o=DE(t);let n=e;for(const r of o){if(typeof r=="number"){if(!Array.isArray(n)||r>=n.length)throw new Error(`Config path not found: ${t}`);n=n[r];continue}if(n===null||typeof n!="object"||!(r in n))throw new Error(`Config path not found: ${t}`);n=n[r]}return n}function En(e,t,o,n){if(e===null)return{type:"null",value:null,truncated:!1};if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return{type:"primitive",value:e,truncated:!1};if(Array.isArray(e))return t>=o?{type:"array",length:e.length,sampleTypes:e.slice(0,n).map(r=>Array.isArray(r)?"array":r===null?"null":typeof r),truncated:e.length>0,omittedItems:Math.max(0,e.length-n)}:{type:"array",length:e.length,items:e.slice(0,n).map(r=>En(r,t+1,o,n)),truncated:e.length>n,omittedItems:Math.max(0,e.length-n)};if(typeof e=="object"){const r=Object.entries(e);return t>=o?{type:"object",keyCount:r.length,keysPreview:r.slice(0,n).map(([s])=>s),truncated:r.length>0,omittedKeys:Math.max(0,r.length-n)}:{type:"object",keyCount:r.length,entries:Object.fromEntries(r.slice(0,n).map(([s,a])=>[s,En(a,t+1,o,n)])),truncated:r.length>n,omittedKeys:Math.max(0,r.length-n)}}return{type:"primitive",value:String(e),truncated:!1}}function TE(e,t,o,n,r){if(t==="get"){if(!o)throw new Error('keyPath is required when mode="get".');const i=AE(e,o);return{mode:t,keyPath:o,value:En(i,0,n,r),hints:["Increase maxDepth or maxItems if you need a larger subtree.",'Use system(action="conf", mode="summary") to inspect sibling keys first.']}}const s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},a=Object.keys(s);return{mode:t,totalTopLevelKeys:a.length,topLevelKeys:a.slice(0,r),truncatedTopLevelKeys:Math.max(0,a.length-r),summary:En(s,0,n,r),hints:['Use system(action="conf", mode="get", keyPath="<path>") to read a single field or subtree.','keyPath supports dot/bracket syntax such as "conf.appearance.mode" or "conf.langs[0]".']}}const PE=async({client:e,rawArgs:t})=>(vp.parse(t),k(await pI(e))),EE=async({client:e,rawArgs:t})=>(Ip.parse(t),k(await fI(e))),CE=async({client:e,rawArgs:t})=>{const o=Sp.parse(t),n=await hI(e),r=o.mode??"summary",s=ic(o.maxDepth,IE,0,5),a=ic(o.maxItems,SE,1,100);return k(TE(n,r,o.keyPath,s,a))},RE=async({client:e,rawArgs:t})=>{const o=Dp.parse(t),n=o.level==="error"?await vE(e,o.msg,o.timeout):await _E(e,o.msg,o.timeout);return k({level:o.level,...n})},xE=async({rawArgs:e})=>{const t=Ap.parse(e);return k(gg(t))},OE=async({client:e,rawArgs:t})=>(Tp.parse(t),k({ok:!0,result:await mI(e)})),NE=async({client:e,rawArgs:t})=>(Pp.parse(t),k({version:await gI(e)})),$E=async({client:e,rawArgs:t})=>{Ep.parse(t);const o=await yI(e);return k({currentTime:o,iso:new Date(o).toISOString()})},ME={workspace_info:PE,network:EE,conf:CE,notify:RE,changelog:xE,perform_sync:OE,get_version:NE,get_current_time:$E},zE=[S("workspace_info",vp,"Get SiYuan workspace metadata. High-risk: exposes the absolute workspace path."),S("network",Ip,"Get current network proxy information."),S("conf",Sp,"Get masked system configuration with summary-first progressive reading."),S("notify",Dp,"Push a notification message."),S("changelog",Ap,"Read the bundled plugin changelog with structured personalization-impact hints."),S("perform_sync",Tp,"Trigger SiYuan sync immediately. High-risk: affects local and remote sync state."),S("get_version",Pp,"Get the SiYuan system version."),S("get_current_time",Ep,"Get the current system time.")],nh=De({name:"system",description:"🖥️ Grouped system and notification operations.",variants:zE,actionSchema:I_,aggregateOptions:{guidance:Jc,actionHints:ul},handlers:ME});function FE(e){return nh.listTools(e)}function qE(e,t,o,n){return nh.callTool(e,t,o,n)}async function BE(e,t={}){const o={...t,app:t.app||"siyuan-mcp-sisyphus"};return e.request("/api/tag/getTag",o)}async function LE(e,t,o){return e.request("/api/tag/renameTag",{oldLabel:t,newLabel:o})}async function UE(e,t){return e.request("/api/tag/removeTag",{label:t})}const jE=[S("list",wp,"List tags in the workspace."),S("rename",kp,"Rename a tag."),S("remove",_p,"Remove a tag.")],rh=De({name:"tag",description:"🏷️ Grouped tag operations.",variants:jE,actionSchema:v_,aggregateOptions:{guidance:Kc,actionHints:ll},handlers:{list:async({client:e,rawArgs:t})=>{const o=wp.parse(t),n=o.query??o.keyword;if(n&&n.trim().length>0){const s=await Rv(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.tags)?a.tags:[];return k({...a,resolvedArgs:{keyword:n},...i.length===0?{warning:"No matching tags were found. If the tag was just created, SiYuan tag indexing may still be catching up; verify the markdown uses #tag# syntax and retry shortly."}:{}})}const r=await BE(e,o);return k(r)},rename:async({client:e,rawArgs:t})=>{const o=kp.parse(t);return await LE(e,o.oldLabel,o.newLabel),F(e,k({success:!0,oldLabel:o.oldLabel,newLabel:o.newLabel}),[{type:"reloadTag"}])},remove:async({client:e,rawArgs:t})=>{const o=_p.parse(t);return await UE(e,o.label),F(e,k({success:!0,label:o.label}),[{type:"reloadTag"}])}}}),HE=rh.listTools,VE=rh.callTool,Xt={fs:{category:"fs",listTools:YP,callTool:WP},notebook:{category:"notebook",listTools:wE,callTool:kE},document:{category:"document",listTools:_T,callTool:vT},block:{category:"block",listTools:$A,callTool:MA},av:{category:"av",listTools:yS,callTool:bS},file:{category:"file",listTools:m0,callTool:g0},feedback:{category:"feedback",listTools:E0,callTool:C0},search:{category:"search",listTools:mD,callTool:gD},tag:{category:"tag",listTools:HE,callTool:VE},system:{category:"system",listTools:FE,callTool:qE},flashcard:{category:"flashcard",listTools:hP,callTool:mP},extension:{category:"extension",prepare:O0,listTools:x0,callTool:M0},mascot:{category:"mascot",listTools:tE,callTool:oE}};function va(e){return Qe.includes(e)?e:null}async function Ia(e,t,o){var n,r;return(r=(n=Xt[e]).prepare)==null?void 0:r.call(n,t[e],o)}const ho="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl",sh="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl.1",ZE=2*1024*1024,cc=2e4;function lc(e){const t=typeof e=="string"?e:"";return t.length<=cc?{text:t,truncated:!1}:{text:t.slice(0,cc),truncated:!0}}function ah(e){return e==="cli"||e==="http"?e:"stdio"}function YE(){return{cli:0,stdio:0,http:0}}function WE(e){return typeof Buffer<"u"?Buffer.byteLength(e,"utf8"):new TextEncoder().encode(e).length}function uc(e){const t=[],o=e.split(/\r?\n/);for(const n of o){const r=n.trim();if(r)try{const s=JSON.parse(r);typeof s.tool=="string"&&typeof s.action=="string"&&typeof s.ts=="number"&&t.push({...s,transport:ah(s.transport)})}catch{}}return t}async function GE(e,t){const o={...t,seq:Date.now(),ts:Date.now()},n=JSON.stringify(o);try{const r=await e.readFile(ho);if(r){const s=`${r}
518
- ${n}`;WE(s)>ZE?(await e.writeFile(sh,r),await e.writeFile(ho,n)):await e.writeFile(ho,s);return}}catch{}try{await e.writeFile(ho,n)}catch{}}function KE(e){if(!e||e.length===0)return"0";const t=e.reduce((o,n)=>{var r;return o+(((r=n.text)==null?void 0:r.length)??0)},0);return t<=200?"0-200":t<=1e3?"200-1K":t<=5e3?"1K-5K":t<=2e4?"5K-20K":"20K+"}function JE(e){try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return;const o=t.error;if(!o||typeof o!="object"||Array.isArray(o))return;const n=o.type,r=o.code,s=typeof n=="string"&&n?n:void 0,a=typeof r=="string"&&r?r:void 0;return a&&(s==="api_error"||s==="internal_error")?a:s??a}catch{return}}function QE(e){if(!e)return;const t=JE(e);if(t)return t;if(e.includes("McpError")){const o=e.match(/McpError\s*\(?([^:)]{1,40})\)?/);return o?`McpError:${o[1]}`:"McpError"}return e.includes("SiYuan API error")?"SiYuanApiError":e.includes("HTTP error")?"HttpError":e.includes("timeout")?"Timeout":e.includes("Unauthorized")||e.includes("unauthorized")?"Unauthorized":/permission denied/i.test(e)?"permission_denied":"UnknownError"}const XE=new Set(["success","id","ids","name","title","label","oldLabel","newLabel","path","paths","from","to","fromID","toID","fromIDs","toIDs","notebook","permission","avID","blockID","keyID","columnID","rowID","srcIDs","count","changed","editsApplied","replacements","created","updated","removed","overwritten","folded","partial","reason","warning","skippedComplexBlocks","recommendedTools"]),eC=new Set(["action","dataType","previousID","nextID","parentID","prepared","materialized","insertedAfter","semantics","sourceAvID","iconHint","showing","contentLength","returnedTotal","returnedPageCount","returnedHasNextPage","kernelMatchedBlockCount","kernelMatchedRootCount","kernelPageCount","kernelHasNextPage","pagingHint","paginationMode","resolvedArgs","totalRows","matchedBlockCount","matchedRootCount","returnedHasNextPage","returnedPageCount","returnedTotal"]),tC=new Set(["markdown","content","blockPath","rootID","root_id","parentID","parent_id","box","ial","sort","sortMode","icon","newFlashcardCount","dueFlashcardCount","flashcardCount"]);function ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function oC(e,t){const o=e.content[0];return{...e,content:[{...o??{type:"text"},type:"text",text:JSON.stringify(t,null,2)}]}}function nC(e){return e.category==="extension"||e.action==="help"||e.category==="system"&&e.action==="conf"}function rC(e){const t=new Set(["type","code","message","fields","hint","notebook","current_permission","required_permission","validActions","validTopics","topic"]);return Object.fromEntries(Object.entries(e).filter(([o])=>t.has(o)))}function sC(e){const t={};for(const o of["id","type","subtype","hPath","path","notebookName"])e[o]!==void 0&&(t[o]=e[o]);return e.plainContent!==void 0?t.plainContent=e.plainContent:e.excerpt!==void 0?t.excerpt=e.excerpt:e.content!==void 0&&(t.content=e.content),Object.keys(t).length>0?t:Sa(e)}function Sa(e){const t={};for(const[o,n]of Object.entries(e))tC.has(o)||(t[o]=er(n));return t}function aC(e){return e.plainContent!==void 0||e.excerpt!==void 0||e.rootID!==void 0||e.root_id!==void 0||e.blockPath!==void 0}function er(e){return Array.isArray(e)?e.map(t=>ft(t)?aC(t)?sC(t):Sa(t):er(t)):ft(e)?ch(e):e}function ih(e){if(ft(e)&&"partialFailure"in e)return{partialFailure:e.partialFailure}}function iC(e,t){const o={};for(const r of XE)e[r]!==void 0&&(o[r]=e[r]);const n=ih(e.uiRefresh);return n!==void 0&&(o.uiRefresh=n),Object.keys(o).length>0?o:e}function ch(e,t){if(ft(e.error))return{error:rC(e.error)};if(e.success===!0)return iC(e);const o={};for(const[n,r]of Object.entries(e)){if(n==="uiRefresh"){const s=ih(r);s!==void 0&&(o.uiRefresh=s);continue}if(n==="nextWindow"&&ft(r)){o.nextWindow=r;continue}eC.has(n)||(o[n]=er(r))}return o}function cC(e,t){if(nC(t))return e;const o=e.content[0];if(!o||o.type!=="text")return e;let n;try{n=JSON.parse(o.text)}catch{return e}const r=Array.isArray(n)?n.map(s=>ft(s)?Sa(s):er(s)):ft(n)?ch(n):n;return oC(e,r)}const lC="telemetryConfig",lh=`/data/storage/petal/siyuan-plugins-mcp-sisyphus/${lC}`;function uh(){return{enabled:!1,lastReportAt:0,reportIntervalHours:24}}function dh(e){const t=uh();if(!e||typeof e!="object"||Array.isArray(e))return t;const o=e,n=typeof o.reportIntervalHours=="number"&&Number.isFinite(o.reportIntervalHours)?Math.max(1,Math.min(168,Math.floor(o.reportIntervalHours))):t.reportIntervalHours,r=typeof o.endpoint=="string"&&o.endpoint.trim().length>0?o.endpoint.trim():void 0;return{enabled:typeof o.enabled=="boolean"?o.enabled:t.enabled,lastReportAt:typeof o.lastReportAt=="number"&&Number.isFinite(o.lastReportAt)?Math.max(0,o.lastReportAt):t.lastReportAt,reportIntervalHours:n,endpoint:r}}async function uC(e){try{const t=await e.readFile(lh);if(t)return dh(JSON.parse(t))}catch{}return uh()}async function dc(e,t){const o=dh(t);try{await e.writeFile(lh,JSON.stringify(o))}catch{}return o}async function dC(e){const t=[];try{const o=await e.readFile(ho);o&&t.push(...uc(o))}catch{}try{const o=await e.readFile(sh);o&&t.push(...uc(o))}catch{}return t}async function pC(e,t){const n=(await dC(e)).filter(p=>p.ts>=t);if(n.length===0)return null;const r=n.length,s=n.filter(p=>p.status==="error").length,a=n.reduce((p,f)=>p+(f.durationMs||0),0),i=new Map,c=new Array(24).fill(0),l=YE();for(const p of n){const f=`${p.tool}/${p.action}`,h=i.get(f);h?(h.count+=1,h.errorCount+=p.status==="error"?1:0,h.totalDuration+=p.durationMs||0):i.set(f,{tool:p.tool,action:p.action,count:1,errorCount:p.status==="error"?1:0,totalDuration:p.durationMs||0});const g=new Date(p.ts).getHours();g>=0&&g<24&&(c[g]+=1),l[ah(p.transport)]+=1}const u=Array.from(i.values()).map(p=>({tool:p.tool,action:p.action,count:p.count,errorCount:p.errorCount,avgDurationMs:p.count>0?Math.round(p.totalDuration/p.count):0})).sort((p,f)=>f.count-p.count);return{v:1,reportedAt:Date.now(),since:t,aggregates:{totalCalls:r,errorCalls:s,errorRate:r>0?Math.round(s/r*1e3)/1e3:0,avgDurationMs:r>0?Math.round(a/r):0,actionBreakdown:u,hourlyDistribution:c,transportDistribution:l},meta:{pluginVersion:process.env.SIYUAN_MCP_PLUGIN_VERSION,nodeVersion:process.version,platform:process.platform}}}async function pc(e){const t=await uC(e);if(!t.enabled||!t.endpoint)return;const o=t.reportIntervalHours*60*60*1e3,n=t.lastReportAt+o;if(Date.now()<n)return;const r=await pC(e,t.lastReportAt||Date.now()-o);if(!r){await dc(e,{...t,lastReportAt:Date.now()});return}try{const s=new AbortController,a=setTimeout(()=>s.abort(),15e3),i=await fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:s.signal});clearTimeout(a),i.ok&&await dc(e,{...t,lastReportAt:Date.now()})}catch{}}function fc(e,t,o,n,r,s,a,i){const c=Vr(n),l=i?zA(i):Vr(a),u=i?i.map(g=>g.text??"").join(""):a??"",p=lc(n),f=lc(u),h=o&&typeof o=="object"?Object.keys(o).filter(g=>g!=="action"):[];return{tool:e,action:t,status:r,durationMs:s,errorCode:r==="error"?QE(a):void 0,paramKeys:h,resultSizeHint:KE(i),transport:ya(),requestChars:c.chars,responseChars:l.chars,requestApproxTokens:c.approxTokens,responseApproxTokens:l.approxTokens,totalApproxTokens:c.approxTokens+l.approxTokens,tokenMode:_f,requestText:p.text,responseText:f.text,requestTextTruncated:p.truncated,responseTextTruncated:f.truncated}}function fC(e){var t;if(e.isError)return{};try{const o=JSON.parse(((t=e.content[0])==null?void 0:t.text)??"{}");return{itemId:typeof o.item_id=="string"?o.item_id:void 0,itemLabel:typeof o.item=="string"?o.item:void 0,itemType:typeof o.type=="string"?o.type:void 0,itemEmoji:typeof o.emoji=="string"?o.emoji:void 0}}catch{return{}}}function hC(e,t){if(t||e.isError)return e;const o=e.content[0];if(!o||o.type!=="text")return e;let n;try{const a=JSON.parse(o.text);if(!a||typeof a!="object"||Array.isArray(a))return e;n=a}catch{return e}const r=n.uiRefresh;if(!r||typeof r!="object"||Array.isArray(r)||"partialFailure"in r)return e;const s={...n};return delete s.uiRefresh,{...e,content:[{...o,text:JSON.stringify(s,null,2)}]}}async function hc(e,t){const o=GE(e,t).catch(()=>{});ya()==="cli"&&await o}async function mC(e,t){var g;const{client:o,category:n,name:r,action:s,args:a}=e,i=e.requestText,c=Date.now(),l=n==="mascot"?await Fo(o):await JP(o,`${r}/${s}`);await sc(o,{tool:r,action:s,status:"running",totalCalls:l.totalCalls,balance:l.balance});let u;try{u=await t()}catch(b){const _=Date.now()-c,w=b instanceof Error?b.message:String(b);throw await hc(o,fc(r,s,a,i,"error",_,w)),pc(o).catch(()=>{}),b}e.slimResponses?u=cC(u,{category:n,action:s}):e.slimResponses===void 0&&(u=hC(u,e.includeUiRefreshMetadata));const p=n==="mascot"?await Fo(o):l,f=n==="mascot"?fC(u):{};await sc(o,{tool:r,action:s,status:u.isError?"error":"success",totalCalls:p.totalCalls,balance:p.balance,...f});const h=Date.now()-c;return await hc(o,fc(r,s,a,i,u.isError?"error":"success",h,(g=u.content[0])==null?void 0:g.text,u.content)),pc(o).catch(()=>{}),u}function gC(e,t,o){var _;const n=yC(t),r=new Map,s=new Set,a=new Set;for(const[w,P]of Object.entries(n)){if(w==="action"||w==="topic")continue;const D=an(w);for(const A of D)r.set(A.toLowerCase(),w);if(_o(P)==="boolean")for(const A of D)s.add(A);else for(const A of D)a.add(A)}for(const w of $_(o)){const P=w.schema??n[w.canonical]??{},D=new Set([...an(w.canonical),...w.aliases.flatMap(an)]);for(const A of D)r.set(A.toLowerCase(),w.canonical);if(_o(P)==="boolean")for(const A of D)s.add(A);else for(const A of D)a.add(A);n[_=w.canonical]??(n[_]=P)}const i=[];for(const w of Object.keys(n))if(!(w==="action"||w==="topic"))for(const P of an(w))i.push(`${P}-json`);const c=[...a,...i],l=[...s,...c],u=kC(e,c,l),p=Tc(u,{boolean:[...s],string:[...a,...i]}),f=vC(u),h={},g=[],b={};for(const[w,P]of Object.entries(p))if(w!=="_"&&w.endsWith("-json")){const D=w.slice(0,-5),T=r.get(D.toLowerCase());if(!T){g.push(`Unknown flag --${w}.`);continue}if(typeof P!="string"||P.length===0)continue;try{b[T]=JSON.parse(P)}catch(A){throw new Error(`--${w} must be valid JSON: ${A instanceof Error?A.message:String(A)}`)}}for(const[w,P]of Object.entries(p)){if(w==="_"||w.endsWith("-json"))continue;const D=r.get(w.toLowerCase());if(!D){g.push(`Unknown flag --${w}; ignored.`);continue}if(D in b||D in h)continue;const T=n[D];_o(T)==="boolean"&&P===!1&&!f.has(w.toLowerCase())||(h[D]=bC(D,P,T))}return p._.length>0&&g.push(`Extra positional arguments ignored: ${p._.join(" ")}`),{args:{...h,...b},warnings:g}}function yC(e){const t={...e.properties??{}},o=e["x-sisyphus-actionSchemas"],n=Array.isArray(o)?o:Array.isArray(e.oneOf)?e.oneOf:Array.isArray(e.anyOf)?e.anyOf:[];for(const r of n){if(!r||typeof r!="object")continue;const s=r.properties;if(!(!s||typeof s!="object"||Array.isArray(s)))for(const[a,i]of Object.entries(s))t[a]??(t[a]=i)}return t}function bC(e,t,o){const n=_o(o);if(n==="array")return Array.isArray(t)?t.map(r=>mc(r,o.items)):typeof t=="string"?t.split(",").map(r=>mc(r.trim(),o.items)):[t];if(n==="number"||n==="integer"){if(typeof t=="number")return t;if(typeof t=="string"){const r=n==="integer"?parseInt(t,10):parseFloat(t);if(Number.isNaN(r))throw new Error(`--${wr(e)} expected a number but got "${t}".`);return r}return t}if(n==="boolean")return typeof t=="boolean"?t:typeof t=="string"?t==="true"||t==="1"||t==="yes":!!t;if(n==="object"){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string")try{return JSON.parse(t)}catch{throw new Error(`--${wr(e)} expects JSON for an object field. Use --${wr(e)}-json '{"..."}'.`)}return t}return typeof t=="string"?t:String(t)}function mc(e,t){if(!t)return e;const o=_o(t);return(o==="number"||o==="integer")&&typeof e=="string"?o==="integer"?parseInt(e,10):parseFloat(e):o==="boolean"&&typeof e=="string"?e==="true"||e==="1"||e==="yes":e}function _o(e){if(!e)return"string";const t=e.type;return Array.isArray(t)?t[0]??"string":typeof t=="string"?t:(e.enum||e.anyOf||e.oneOf,"string")}function an(e){const t=ph(e),o=new Set([e]);return t.length===0?[...o]:(o.add(t.join("-")),o.add(t.join("_")),o.add(wC(t)),[...o])}function ph(e){return e.split(/[_-]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z]{2,})/g,"$1 $2").split(/\s+/)).flatMap(t=>t.match(/[A-Z]+[a-z]*|[a-z]+|[0-9]+/g)??[]).map(t=>t.toLowerCase())}function wC(e){return e.length===0?"":e[0]+e.slice(1).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function wr(e){const t=ph(e);return t.length>0?t.join("-"):e.toLowerCase()}function kC(e,t,o){const n=new Set(t.map(a=>a.toLowerCase())),r=new Set(o.map(a=>a.toLowerCase())),s=[];for(let a=0;a<e.length;a++){const i=e[a],c=fh(i);if(!c||c.hasEquals||c.negated||!n.has(c.key.toLowerCase())){s.push(i);continue}const l=e[a+1];if(l===void 0||l==="--"||_C(l,r)){s.push(i);continue}s.push(`${i}=${l}`),a++}return s}function _C(e,t){const o=fh(e);return!!(o&&t.has(o.key.toLowerCase()))}function fh(e){if(!e.startsWith("-")||e==="-"||e==="--")return null;const t=e.startsWith("--")?2:1,o=e.indexOf("="),n=o===-1?e.slice(t):e.slice(t,o);if(!n)return null;const r=e.startsWith("--")&&n.startsWith("no-"),s=r?n.slice(3):n;return s?{key:s,hasEquals:o!==-1,negated:r}:null}function vC(e){const t=new Set;for(const o of e){if(!o.startsWith("-"))continue;const n=o.indexOf("="),r=n===-1?o.replace(/^-+/,""):o.slice(o.startsWith("--")?2:1,n),s=r.startsWith("no-")?r.slice(3):r;s&&t.add(s.toLowerCase())}return t}class IC{constructor(t={}){se(this,"baseUrl");se(this,"timeout");se(this,"token","");const o=t.baseUrl||process.env.SIYUAN_API_URL||"http://127.0.0.1:6806";this.baseUrl=o.replace(/\/+$/,""),this.timeout=t.timeout||5e3}setToken(t){this.token=t}getBaseUrl(){return this.baseUrl}getAuthHeaders(){const t={Connection:"close"};return this.token&&(t.Authorization=`Token ${this.token}`),t}async fetchWithTimeout(t,o){let s=null;for(let a=0;a<=3;a++){const i=new AbortController,c=setTimeout(()=>i.abort(),this.timeout);try{const u=await fetch(t,{...o,signal:i.signal});if(clearTimeout(c),!u.ok){if(u.status>=400&&u.status<500&&u.status!==429)throw new Error(`HTTP error: ${u.status} ${u.statusText}`);if(await u.arrayBuffer().catch(()=>{}),s=new Error(`HTTP error: ${u.status} ${u.statusText}`),a<3)continue;throw s}return u}catch(u){if(clearTimeout(c),u instanceof Error&&u.name==="AbortError"?s=new Error(`Request timeout after ${this.timeout}ms`):s=u instanceof Error?u:new Error(String(u)),a>=3)throw s}const l=300*(a+1);await new Promise(u=>setTimeout(u,l))}throw s??new Error("Unknown fetch error")}async readRemoteFile(t){return this.fetchWithTimeout(`${this.baseUrl}/api/file/getFile`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify({path:t})})}async readData(t,o){const n=await this.fetchWithTimeout(t,o),r=await n.text();if(r.trim()==="")return null;let s;try{s=JSON.parse(r)}catch{const a=r.length>200?`${r.slice(0,200)}...`:r,i=[n.status,n.statusText].filter(Boolean).join(" ");throw new Error(`Invalid SiYuan API response from ${t}${i?` (HTTP ${i})`:""}: ${a}`)}if(s.code!==0)throw new Error(`SiYuan API error: ${s.code} - ${s.msg}`);return s.data}async readFile(t){return await(await this.readRemoteFile(t)).text()}async readFileBinary(t){const o=await this.readRemoteFile(t);return new Uint8Array(await o.arrayBuffer())}async writeFile(t,o){const n=new FormData,r=new File([o],"content");n.append("path",t),n.append("isDir","false"),n.append("modTime",String(Date.now())),n.append("file",r),await this.requestFormData("/api/file/putFile",n)}async requestFormData(t,o){return this.readData(`${this.baseUrl}${t}`,{method:"POST",headers:this.getAuthHeaders(),body:o})}async request(t,o){return this.readData(`${this.baseUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(o??{})})}}const SC=["none","r","rw","rwd"],gc={none:"none",readonly:"r",write:"rw"},hn="/data/storage/petal/siyuan-plugins-mcp-sisyphus/notebookPermissions",DC=process.env.SIYUAN_MCP_DEBUG_PERMISSIONS==="1";function cn(...e){DC&&console.error("[MCP]",...e)}function hh(e){return typeof e=="string"&&SC.includes(e)}function AC(e){return hh(e)?e:typeof e=="string"&&e in gc?gc[e]:"none"}function TC(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,AC(o)]))}class PC{constructor(t){se(this,"permissions",{});se(this,"client",null);se(this,"loaded",!1);this.client=t??null}async load(){if(this.loaded)return;if(!this.client)throw new Error("[Permissions] No SiYuan client available; cannot load permissions.");let t;try{t=await this.client.readFile(hn)}catch(n){throw cn("Failed to read permissions from API:",n),new Error(`[Permissions] Failed to read permissions from SiYuan API: ${n instanceof Error?n.message:String(n)}`)}if(!t||!t.trim()){this.permissions={},this.loaded=!0,cn("Permissions not found in API, using empty state");return}let o;try{o=JSON.parse(t)}catch(n){throw cn("Failed to parse permissions JSON from API:",n),new Error(`[Permissions] Permissions file at ${hn} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}this.permissions=TC(o),this.loaded=!0,cn("Permissions loaded from API:",Object.keys(this.permissions).length,"entries")}async reload(){this.loaded=!1,await this.load()}async save(){if(!this.client)throw new Error("[Permissions] No SiYuan client available; cannot save permissions.");const t=JSON.stringify(this.permissions,null,2);await this.client.writeFile(hn,t),this.loaded=!0}get(t){const o=this.permissions[t];return hh(o)?o:"r"}async set(t,o){this.permissions[t]=o,await this.save()}getAll(){return{...this.permissions}}canRead(t){return this.get(t)!=="none"}canWrite(t){return["rw","rwd"].includes(this.get(t))}canDelete(t){return this.get(t)==="rwd"}}function tr(e){return!!e._zod}function He(e,t){return tr(e)?Il(e,t):e.safeParse(t)}function mh(e){var o,n;if(!e)return;let t;if(tr(e)?t=(n=(o=e._zod)==null?void 0:o.def)==null?void 0:n.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function EC(e){var r;if(tr(e)){const a=(r=e._zod)==null?void 0:r.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const o=e._def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}const n=e.value;if(n!==void 0)return n}const or="2025-11-25",CC=[or,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lt="io.modelcontextprotocol/related-task",nr="2.0",ae=Xk(e=>e!==null&&(typeof e=="object"||typeof e=="function")),gh=W([d(),E().int()]),yh=d();ue({ttl:E().optional(),pollInterval:E().optional()});const RC=m({ttl:E().optional()}),xC=m({taskId:d()}),Da=ue({progressToken:gh.optional(),[lt]:xC.optional()}),ke=m({_meta:Da.optional()}),Yo=ke.extend({task:RC.optional()}),OC=e=>Yo.safeParse(e).success,de=m({method:d(),params:ke.loose().optional()}),Ae=m({_meta:Da.optional()}),Te=m({method:d(),params:Ae.loose().optional()}),pe=ue({_meta:Da.optional()}),rr=W([d(),E().int()]),bh=m({jsonrpc:y(nr),id:rr,...de.shape}).strict(),ns=e=>bh.safeParse(e).success,wh=m({jsonrpc:y(nr),...Te.shape}).strict(),NC=e=>wh.safeParse(e).success,Aa=m({jsonrpc:y(nr),id:rr,result:pe}).strict(),mo=e=>Aa.safeParse(e).success;var B;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(B||(B={}));const Ta=m({jsonrpc:y(nr),id:rr.optional(),error:m({code:E().int(),message:d(),data:K().optional()})}).strict(),$C=e=>Ta.safeParse(e).success,kr=W([bh,wh,Aa,Ta]);W([Aa,Ta]);const Rt=pe.strict(),MC=Ae.extend({requestId:rr.optional(),reason:d().optional()}),Pa=Te.extend({method:y("notifications/cancelled"),params:MC}),zC=m({src:d(),mimeType:d().optional(),sizes:I(d()).optional(),theme:z(["light","dark"]).optional()}),Wo=m({icons:I(zC).optional()}),eo=m({name:d(),title:d().optional()}),kh=eo.extend({...eo.shape,...Wo.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),FC=Ys(m({applyDefaults:x().optional()}),j(d(),K())),qC=_u(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ys(m({form:FC.optional(),url:ae.optional()}),j(d(),K()).optional())),BC=ue({list:ae.optional(),cancel:ae.optional(),requests:ue({sampling:ue({createMessage:ae.optional()}).optional(),elicitation:ue({create:ae.optional()}).optional()}).optional()}),LC=ue({list:ae.optional(),cancel:ae.optional(),requests:ue({tools:ue({call:ae.optional()}).optional()}).optional()}),UC=m({experimental:j(d(),ae).optional(),sampling:m({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:qC.optional(),roots:m({listChanged:x().optional()}).optional(),tasks:BC.optional(),extensions:j(d(),ae).optional()}),jC=ke.extend({protocolVersion:d(),capabilities:UC,clientInfo:kh}),HC=de.extend({method:y("initialize"),params:jC}),VC=m({experimental:j(d(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:m({listChanged:x().optional()}).optional(),resources:m({subscribe:x().optional(),listChanged:x().optional()}).optional(),tools:m({listChanged:x().optional()}).optional(),tasks:LC.optional(),extensions:j(d(),ae).optional()}),_h=pe.extend({protocolVersion:d(),capabilities:VC,serverInfo:kh,instructions:d().optional()}),vh=Te.extend({method:y("notifications/initialized"),params:Ae.optional()}),ZC=e=>vh.safeParse(e).success,Ea=de.extend({method:y("ping"),params:ke.optional()}),YC=m({progress:E(),total:ee(E()),message:ee(d())}),WC=m({...Ae.shape,...YC.shape,progressToken:gh}),Ca=Te.extend({method:y("notifications/progress"),params:WC}),GC=ke.extend({cursor:yh.optional()}),Go=de.extend({params:GC.optional()}),Ko=pe.extend({nextCursor:yh.optional()}),KC=z(["working","input_required","completed","failed","cancelled"]),Jo=m({taskId:d(),status:KC,ttl:W([E(),fu()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ee(E()),statusMessage:ee(d())}),qo=pe.extend({task:Jo}),JC=Ae.merge(Jo),Cn=Te.extend({method:y("notifications/tasks/status"),params:JC}),Ra=de.extend({method:y("tasks/get"),params:ke.extend({taskId:d()})}),xa=pe.merge(Jo),Oa=de.extend({method:y("tasks/result"),params:ke.extend({taskId:d()})});pe.loose();const Na=Go.extend({method:y("tasks/list")}),$a=Ko.extend({tasks:I(Jo)}),Ma=de.extend({method:y("tasks/cancel"),params:ke.extend({taskId:d()})}),QC=pe.merge(Jo),Ih=m({uri:d(),mimeType:ee(d()),_meta:j(d(),K()).optional()}),Sh=Ih.extend({text:d()}),za=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Dh=Ih.extend({blob:za}),Qo=z(["user","assistant"]),co=m({audience:I(Qo).optional(),priority:E().min(0).max(1).optional(),lastModified:lu({offset:!0}).optional()}),Ah=m({...eo.shape,...Wo.shape,uri:d(),description:ee(d()),mimeType:ee(d()),size:ee(E()),annotations:co.optional(),_meta:ee(ue({}))}),XC=m({...eo.shape,...Wo.shape,uriTemplate:d(),description:ee(d()),mimeType:ee(d()),annotations:co.optional(),_meta:ee(ue({}))}),eR=Go.extend({method:y("resources/list")}),Th=Ko.extend({resources:I(Ah)}),tR=Go.extend({method:y("resources/templates/list")}),Ph=Ko.extend({resourceTemplates:I(XC)}),Fa=ke.extend({uri:d()}),oR=Fa,nR=de.extend({method:y("resources/read"),params:oR}),Eh=pe.extend({contents:I(W([Sh,Dh]))}),Ch=Te.extend({method:y("notifications/resources/list_changed"),params:Ae.optional()}),rR=Fa,sR=de.extend({method:y("resources/subscribe"),params:rR}),aR=Fa,iR=de.extend({method:y("resources/unsubscribe"),params:aR}),cR=Ae.extend({uri:d()}),lR=Te.extend({method:y("notifications/resources/updated"),params:cR}),uR=m({name:d(),description:ee(d()),required:ee(x())}),dR=m({...eo.shape,...Wo.shape,description:ee(d()),arguments:ee(I(uR)),_meta:ee(ue({}))}),pR=Go.extend({method:y("prompts/list")}),Rh=Ko.extend({prompts:I(dR)}),fR=ke.extend({name:d(),arguments:j(d(),d()).optional()}),hR=de.extend({method:y("prompts/get"),params:fR}),qa=m({type:y("text"),text:d(),annotations:co.optional(),_meta:j(d(),K()).optional()}),Ba=m({type:y("image"),data:za,mimeType:d(),annotations:co.optional(),_meta:j(d(),K()).optional()}),La=m({type:y("audio"),data:za,mimeType:d(),annotations:co.optional(),_meta:j(d(),K()).optional()}),mR=m({type:y("tool_use"),name:d(),id:d(),input:j(d(),K()),_meta:j(d(),K()).optional()}),gR=m({type:y("resource"),resource:W([Sh,Dh]),annotations:co.optional(),_meta:j(d(),K()).optional()}),yR=Ah.extend({type:y("resource_link")}),Ua=W([qa,Ba,La,yR,gR]),bR=m({role:Qo,content:Ua}),xh=pe.extend({description:d().optional(),messages:I(bR)}),Oh=Te.extend({method:y("notifications/prompts/list_changed"),params:Ae.optional()}),wR=m({title:d().optional(),readOnlyHint:x().optional(),destructiveHint:x().optional(),idempotentHint:x().optional(),openWorldHint:x().optional()}),kR=m({taskSupport:z(["required","optional","forbidden"]).optional()}),Nh=m({...eo.shape,...Wo.shape,description:d().optional(),inputSchema:m({type:y("object"),properties:j(d(),ae).optional(),required:I(d()).optional()}).catchall(K()),outputSchema:m({type:y("object"),properties:j(d(),ae).optional(),required:I(d()).optional()}).catchall(K()).optional(),annotations:wR.optional(),execution:kR.optional(),_meta:j(d(),K()).optional()}),_R=Go.extend({method:y("tools/list")}),$h=Ko.extend({tools:I(Nh)}),sr=pe.extend({content:I(Ua).default([]),structuredContent:j(d(),K()).optional(),isError:x().optional()});sr.or(pe.extend({toolResult:K()}));const vR=Yo.extend({name:d(),arguments:j(d(),K()).optional()}),IR=de.extend({method:y("tools/call"),params:vR}),Mh=Te.extend({method:y("notifications/tools/list_changed"),params:Ae.optional()}),SR=m({autoRefresh:x().default(!0),debounceMs:E().int().nonnegative().default(300)}),zh=z(["debug","info","notice","warning","error","critical","alert","emergency"]),DR=ke.extend({level:zh}),AR=de.extend({method:y("logging/setLevel"),params:DR}),TR=Ae.extend({level:zh,logger:d().optional(),data:K()}),PR=Te.extend({method:y("notifications/message"),params:TR}),ER=m({name:d().optional()}),CR=m({hints:I(ER).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),RR=m({mode:z(["auto","required","none"]).optional()}),xR=m({type:y("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:I(Ua).default([]),structuredContent:m({}).loose().optional(),isError:x().optional(),_meta:j(d(),K()).optional()}),OR=gu("type",[qa,Ba,La]),Rn=gu("type",[qa,Ba,La,mR,xR]),NR=m({role:Qo,content:W([Rn,I(Rn)]),_meta:j(d(),K()).optional()}),$R=Yo.extend({messages:I(NR),modelPreferences:CR.optional(),systemPrompt:d().optional(),includeContext:z(["none","thisServer","allServers"]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:I(d()).optional(),metadata:ae.optional(),tools:I(Nh).optional(),toolChoice:RR.optional()}),Fh=de.extend({method:y("sampling/createMessage"),params:$R}),qh=pe.extend({model:d(),stopReason:ee(z(["endTurn","stopSequence","maxTokens"]).or(d())),role:Qo,content:OR}),Bh=pe.extend({model:d(),stopReason:ee(z(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Qo,content:W([Rn,I(Rn)])}),MR=m({type:y("boolean"),title:d().optional(),description:d().optional(),default:x().optional()}),zR=m({type:y("string"),title:d().optional(),description:d().optional(),minLength:E().optional(),maxLength:E().optional(),format:z(["email","uri","date","date-time"]).optional(),default:d().optional()}),FR=m({type:z(["number","integer"]),title:d().optional(),description:d().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),qR=m({type:y("string"),title:d().optional(),description:d().optional(),enum:I(d()),default:d().optional()}),BR=m({type:y("string"),title:d().optional(),description:d().optional(),oneOf:I(m({const:d(),title:d()})),default:d().optional()}),LR=m({type:y("string"),title:d().optional(),description:d().optional(),enum:I(d()),enumNames:I(d()).optional(),default:d().optional()}),UR=W([qR,BR]),jR=m({type:y("array"),title:d().optional(),description:d().optional(),minItems:E().optional(),maxItems:E().optional(),items:m({type:y("string"),enum:I(d())}),default:I(d()).optional()}),HR=m({type:y("array"),title:d().optional(),description:d().optional(),minItems:E().optional(),maxItems:E().optional(),items:m({anyOf:I(m({const:d(),title:d()}))}),default:I(d()).optional()}),VR=W([jR,HR]),ZR=W([LR,UR,VR]),YR=W([ZR,MR,zR,FR]),WR=Yo.extend({mode:y("form").optional(),message:d(),requestedSchema:m({type:y("object"),properties:j(d(),YR),required:I(d()).optional()})}),GR=Yo.extend({mode:y("url"),message:d(),elicitationId:d(),url:d().url()}),KR=W([WR,GR]),Lh=de.extend({method:y("elicitation/create"),params:KR}),JR=Ae.extend({elicitationId:d()}),QR=Te.extend({method:y("notifications/elicitation/complete"),params:JR}),Uh=pe.extend({action:z(["accept","decline","cancel"]),content:_u(e=>e===null?void 0:e,j(d(),W([d(),E(),x(),I(d())])).optional())}),XR=m({type:y("ref/resource"),uri:d()}),ex=m({type:y("ref/prompt"),name:d()}),tx=ke.extend({ref:W([ex,XR]),argument:m({name:d(),value:d()}),context:m({arguments:j(d(),d()).optional()}).optional()}),ox=de.extend({method:y("completion/complete"),params:tx}),jh=pe.extend({completion:ue({values:I(d()).max(100),total:ee(E().int()),hasMore:ee(x())})}),nx=m({uri:d().startsWith("file://"),name:d().optional(),_meta:j(d(),K()).optional()}),rx=de.extend({method:y("roots/list"),params:ke.optional()}),sx=pe.extend({roots:I(nx)}),ax=Te.extend({method:y("notifications/roots/list_changed"),params:Ae.optional()});W([Ea,HC,ox,AR,hR,pR,eR,tR,nR,sR,iR,IR,_R,Ra,Oa,Na,Ma]);W([Pa,Ca,vh,ax,Cn]);W([Rt,qh,Bh,Uh,sx,xa,$a,qo]);W([Ea,Fh,Lh,rx,Ra,Oa,Na,Ma]);W([Pa,Ca,PR,lR,Ch,Mh,Oh,Cn,QR]);W([Rt,_h,jh,xh,Rh,Th,Ph,Eh,sr,$h,xa,$a,qo]);class M extends Error{constructor(t,o,n){super(`MCP error ${t}: ${o}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,o,n){if(t===B.UrlElicitationRequired&&n){const r=n;if(r.elicitations)return new ix(r.elicitations,o)}return new M(t,o,n)}}class ix extends M{constructor(t,o=`URL elicitation${t.length>1?"s":""} required`){super(B.UrlElicitationRequired,o,{elicitations:t})}get elicitations(){var t;return((t=this.data)==null?void 0:t.elicitations)??[]}}function it(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yc(e){const t=mh(e),o=t==null?void 0:t.method;if(!o)throw new Error("Schema is missing a method literal");const n=EC(o);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function bc(e,t){const o=He(e,t);if(!o.success)throw o.error;return o.data}const cx=6e4;class lx{constructor(t){this._options=t,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(Pa,o=>{this._oncancel(o)}),this.setNotificationHandler(Ca,o=>{this._onprogress(o)}),this.setRequestHandler(Ea,o=>({})),this._taskStore=t==null?void 0:t.taskStore,this._taskMessageQueue=t==null?void 0:t.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ra,async(o,n)=>{const r=await this._taskStore.getTask(o.params.taskId,n.sessionId);if(!r)throw new M(B.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Oa,async(o,n)=>{const r=async()=>{var i;const s=o.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(c.type==="response"||c.type==="error"){const l=c.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),c.type==="response")p(l);else{const f=l,h=new M(f.error.code,f.error.message,f.error.data);p(h)}else{const f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await((i=this._transport)==null?void 0:i.send(c.message,{relatedRequestId:n.requestId}))}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new M(B.InvalidParams,`Task not found: ${s}`);if(!it(a.status))return await this._waitForTaskUpdate(s,n.signal),await r();if(it(a.status)){const c=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...c,_meta:{...c._meta,[lt]:{taskId:s}}}}return await r()};return await r()}),this.setRequestHandler(Na,async(o,n)=>{var r;try{const{tasks:s,nextCursor:a}=await this._taskStore.listTasks((r=o.params)==null?void 0:r.cursor,n.sessionId);return{tasks:s,nextCursor:a,_meta:{}}}catch(s){throw new M(B.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Ma,async(o,n)=>{try{const r=await this._taskStore.getTask(o.params.taskId,n.sessionId);if(!r)throw new M(B.InvalidParams,`Task not found: ${o.params.taskId}`);if(it(r.status))throw new M(B.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(o.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(o.params.taskId);const s=await this._taskStore.getTask(o.params.taskId,n.sessionId);if(!s)throw new M(B.InvalidParams,`Task not found after cancellation: ${o.params.taskId}`);return{_meta:{},...s}}catch(r){throw r instanceof M?r:new M(B.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;const o=this._requestHandlerAbortControllers.get(t.params.requestId);o==null||o.abort(t.params.reason)}_setupTimeout(t,o,n,r,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(r,o),startTime:Date.now(),timeout:o,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:r})}_resetTimeout(t){const o=this._timeoutInfo.get(t);if(!o)return!1;const n=Date.now()-o.startTime;if(o.maxTotalTimeout&&n>=o.maxTotalTimeout)throw this._timeoutInfo.delete(t),M.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:o.maxTotalTimeout,totalElapsed:n});return clearTimeout(o.timeoutId),o.timeoutId=setTimeout(o.onTimeout,o.timeout),!0}_cleanupTimeout(t){const o=this._timeoutInfo.get(t);o&&(clearTimeout(o.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var s,a,i;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=t;const o=(s=this.transport)==null?void 0:s.onclose;this._transport.onclose=()=>{o==null||o(),this._onclose()};const n=(a=this.transport)==null?void 0:a.onerror;this._transport.onerror=c=>{n==null||n(c),this._onerror(c)};const r=(i=this._transport)==null?void 0:i.onmessage;this._transport.onmessage=(c,l)=>{r==null||r(c,l),mo(c)||$C(c)?this._onresponse(c):ns(c)?this._onrequest(c,l):NC(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var n;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const o=M.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,(n=this.onclose)==null||n.call(this);for(const r of t.values())r(o)}_onerror(t){var o;(o=this.onerror)==null||o.call(this,t)}_onnotification(t){const o=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;o!==void 0&&Promise.resolve().then(()=>o(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,o){var u,p,f,h;const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,r=this._transport,s=(f=(p=(u=t.params)==null?void 0:u._meta)==null?void 0:p[lt])==null?void 0:f.taskId;if(n===void 0){const g={jsonrpc:"2.0",id:t.id,error:{code:B.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},r==null?void 0:r.sessionId).catch(b=>this._onerror(new Error(`Failed to enqueue error response: ${b}`))):r==null||r.send(g).catch(b=>this._onerror(new Error(`Failed to send an error response: ${b}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=OC(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,r==null?void 0:r.sessionId):void 0,l={signal:a.signal,sessionId:r==null?void 0:r.sessionId,_meta:(h=t.params)==null?void 0:h._meta,sendNotification:async g=>{if(a.signal.aborted)return;const b={relatedRequestId:t.id};s&&(b.relatedTask={taskId:s}),await this.notification(g,b)},sendRequest:async(g,b,_)=>{var D;if(a.signal.aborted)throw new M(B.ConnectionClosed,"Request was cancelled");const w={..._,relatedRequestId:t.id};s&&!w.relatedTask&&(w.relatedTask={taskId:s});const P=((D=w.relatedTask)==null?void 0:D.taskId)??s;return P&&c&&await c.updateTaskStatus(P,"input_required"),await this.request(g,b,w)},authInfo:o==null?void 0:o.authInfo,requestId:t.id,requestInfo:o==null?void 0:o.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:i==null?void 0:i.ttl,closeSSEStream:o==null?void 0:o.closeSSEStream,closeStandaloneSSEStream:o==null?void 0:o.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async g=>{if(a.signal.aborted)return;const b={result:g,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:b,timestamp:Date.now()},r==null?void 0:r.sessionId):await(r==null?void 0:r.send(b))},async g=>{if(a.signal.aborted)return;const b={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(g.code)?g.code:B.InternalError,message:g.message??"Internal error",...g.data!==void 0&&{data:g.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:b,timestamp:Date.now()},r==null?void 0:r.sessionId):await(r==null?void 0:r.send(b))}).catch(g=>this._onerror(new Error(`Failed to send response: ${g}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:o,...n}=t.params,r=Number(o),s=this._progressHandlers.get(r);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(r),i=this._timeoutInfo.get(r);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(c){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(c);return}s(n)}_onresponse(t){const o=Number(t.id),n=this._requestResolvers.get(o);if(n){if(this._requestResolvers.delete(o),mo(t))n(t);else{const a=new M(t.error.code,t.error.message,t.error.data);n(a)}return}const r=this._responseHandlers.get(o);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(o),this._cleanupTimeout(o);let s=!1;if(mo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,o))}}if(s||this._progressHandlers.delete(o),mo(t))r(t);else{const a=M.fromError(t.error.code,t.error.message,t.error.data);r(a)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)==null?void 0:t.close())}async*requestStream(t,o,n){var a,i;const{task:r}=n??{};if(!r){try{yield{type:"result",result:await this.request(t,o,n)}}catch(c){yield{type:"error",error:c instanceof M?c:new M(B.InternalError,String(c))}}return}let s;try{const c=await this.request(t,qo,n);if(c.task)s=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new M(B.InternalError,"Task creation did not return a task");for(;;){const l=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:l},it(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},o,n)}:l.status==="failed"?yield{type:"error",error:new M(B.InternalError,`Task ${s} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new M(B.InternalError,`Task ${s} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},o,n)};return}const u=l.pollInterval??((a=this._options)==null?void 0:a.defaultTaskPollInterval)??1e3;await new Promise(p=>setTimeout(p,u)),(i=n==null?void 0:n.signal)==null||i.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof M?c:new M(B.InternalError,String(c))}}}request(t,o,n){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:c}=n??{};return new Promise((l,u)=>{var P,D,T,A,O;const p=C=>{u(C)};if(!this._transport){p(new Error("Not connected"));return}if(((P=this._options)==null?void 0:P.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(C){p(C);return}(D=n==null?void 0:n.signal)==null||D.throwIfAborted();const f=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:f};n!=null&&n.onprogress&&(this._progressHandlers.set(f,n.onprogress),h.params={...t.params,_meta:{...((T=t.params)==null?void 0:T._meta)||{},progressToken:f}}),i&&(h.params={...h.params,task:i}),c&&(h.params={...h.params,_meta:{...((A=h.params)==null?void 0:A._meta)||{},[lt]:c}});const g=C=>{var Z;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(Z=this._transport)==null||Z.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(C)}},{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a}).catch(_e=>this._onerror(new Error(`Failed to send cancellation: ${_e}`)));const L=C instanceof M?C:new M(B.RequestTimeout,String(C));u(L)};this._responseHandlers.set(f,C=>{var L;if(!((L=n==null?void 0:n.signal)!=null&&L.aborted)){if(C instanceof Error)return u(C);try{const Z=He(o,C.result);Z.success?l(Z.data):u(Z.error)}catch(Z){u(Z)}}}),(O=n==null?void 0:n.signal)==null||O.addEventListener("abort",()=>{var C;g((C=n==null?void 0:n.signal)==null?void 0:C.reason)});const b=(n==null?void 0:n.timeout)??cx,_=()=>g(M.fromError(B.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(f,b,n==null?void 0:n.maxTotalTimeout,_,(n==null?void 0:n.resetTimeoutOnProgress)??!1);const w=c==null?void 0:c.taskId;if(w){const C=L=>{const Z=this._responseHandlers.get(f);Z?Z(L):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,C),this._enqueueTaskMessage(w,{type:"request",message:h,timestamp:Date.now()}).catch(L=>{this._cleanupTimeout(f),u(L)})}else this._transport.send(h,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a}).catch(C=>{this._cleanupTimeout(f),u(C)})})}async getTask(t,o){return this.request({method:"tasks/get",params:t},xa,o)}async getTaskResult(t,o,n){return this.request({method:"tasks/result",params:t},o,n)}async listTasks(t,o){return this.request({method:"tasks/list",params:t},$a,o)}async cancelTask(t,o){return this.request({method:"tasks/cancel",params:t},QC,o)}async notification(t,o){var i,c,l,u;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=(i=o==null?void 0:o.relatedTask)==null?void 0:i.taskId;if(n){const p={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...((c=t.params)==null?void 0:c._meta)||{},[lt]:o.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:p,timestamp:Date.now()});return}if((((l=this._options)==null?void 0:l.debouncedNotificationMethods)??[]).includes(t.method)&&!t.params&&!(o!=null&&o.relatedRequestId)&&!(o!=null&&o.relatedTask)){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var f,h;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let p={...t,jsonrpc:"2.0"};o!=null&&o.relatedTask&&(p={...p,params:{...p.params,_meta:{...((f=p.params)==null?void 0:f._meta)||{},[lt]:o.relatedTask}}}),(h=this._transport)==null||h.send(p,o).catch(g=>this._onerror(g))});return}let a={...t,jsonrpc:"2.0"};o!=null&&o.relatedTask&&(a={...a,params:{...a.params,_meta:{...((u=a.params)==null?void 0:u._meta)||{},[lt]:o.relatedTask}}}),await this._transport.send(a,o)}setRequestHandler(t,o){const n=yc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(r,s)=>{const a=bc(t,r);return Promise.resolve(o(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,o){const n=yc(t);this._notificationHandlers.set(n,r=>{const s=bc(t,r);return Promise.resolve(o(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const o=this._taskProgressTokens.get(t);o!==void 0&&(this._progressHandlers.delete(o),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,o,n){var s;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const r=(s=this._options)==null?void 0:s.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,o,n,r)}async _clearTaskQueue(t,o){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,o);for(const r of n)if(r.type==="request"&&ns(r.message)){const s=r.message.id,a=this._requestResolvers.get(s);a?(a(new M(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,o){var r,s;let n=((r=this._options)==null?void 0:r.defaultTaskPollInterval)??1e3;try{const a=await((s=this._taskStore)==null?void 0:s.getTask(t));a!=null&&a.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,i)=>{if(o.aborted){i(new M(B.InvalidRequest,"Request cancelled"));return}const c=setTimeout(a,n);o.addEventListener("abort",()=>{clearTimeout(c),i(new M(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,o){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async r=>{if(!t)throw new Error("No request provided");return await n.createTask(r,t.id,{method:t.method,params:t.params},o)},getTask:async r=>{const s=await n.getTask(r,o);if(!s)throw new M(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(r,s,a)=>{await n.storeTaskResult(r,s,a,o);const i=await n.getTask(r,o);if(i){const c=Cn.parse({method:"notifications/tasks/status",params:i});await this.notification(c),it(i.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>n.getTaskResult(r,o),updateTaskStatus:async(r,s,a)=>{const i=await n.getTask(r,o);if(!i)throw new M(B.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(it(i.status))throw new M(B.InvalidParams,`Cannot update task "${r}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(r,s,a,o);const c=await n.getTask(r,o);if(c){const l=Cn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),it(c.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>n.listTasks(r,o)}}}function wc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ux(e,t){const o={...e};for(const n in t){const r=n,s=t[r];if(s===void 0)continue;const a=o[r];wc(a)&&wc(s)?o[r]={...a,...s}:o[r]=s}return o}class Hh{constructor(t){}getValidator(t){return o=>({valid:!0,data:o,errorMessage:void 0})}}const dx=new Hh;class px{constructor(t){this._client=t}async*callToolStream(t,o=sr,n){const r=this._client,s={...n,task:(n==null?void 0:n.task)??(r.isToolTask(t.name)?{}:void 0)},a=r.requestStream({method:"tools/call",params:t},o,s),i=r.getToolOutputValidator(t.name);for await(const c of a){if(c.type==="result"&&i){const l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new M(B.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const u=i(l.structuredContent);if(!u.valid){yield{type:"error",error:new M(B.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof M){yield{type:"error",error:u};return}yield{type:"error",error:new M(B.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(t,o){return this._client.getTask({taskId:t},o)}async getTaskResult(t,o,n){return this._client.getTaskResult({taskId:t},o,n)}async listTasks(t,o){return this._client.listTasks(t?{cursor:t}:void 0,o)}async cancelTask(t,o){return this._client.cancelTask({taskId:t},o)}requestStream(t,o,n){return this._client.requestStream(t,o,n)}}function mn(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const o=t,n=e.properties;for(const r of Object.keys(n)){const s=n[r];o[r]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(o[r]=s.default),o[r]!==void 0&&mn(s,o[r])}}if(Array.isArray(e.anyOf))for(const o of e.anyOf)typeof o!="boolean"&&mn(o,t);if(Array.isArray(e.oneOf))for(const o of e.oneOf)typeof o!="boolean"&&mn(o,t)}}function fx(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,o=e.url!==void 0;return{supportsFormMode:t||!t&&!o,supportsUrlMode:o}}class hx extends lx{constructor(t,o){super(o),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=(o==null?void 0:o.capabilities)??{},this._jsonSchemaValidator=(o==null?void 0:o.jsonSchemaValidator)??new Hh,o!=null&&o.listChanged&&(this._pendingListChangedConfig=o.listChanged)}_setupListChangedHandlers(t){var o,n,r,s,a,i;t.tools&&((n=(o=this._serverCapabilities)==null?void 0:o.tools)!=null&&n.listChanged)&&this._setupListChangedHandler("tools",Mh,t.tools,async()=>(await this.listTools()).tools),t.prompts&&((s=(r=this._serverCapabilities)==null?void 0:r.prompts)!=null&&s.listChanged)&&this._setupListChangedHandler("prompts",Oh,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&((i=(a=this._serverCapabilities)==null?void 0:a.resources)!=null&&i.listChanged)&&this._setupListChangedHandler("resources",Ch,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new px(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ux(this._capabilities,t)}setRequestHandler(t,o){var i;const n=mh(t),r=n==null?void 0:n.method;if(!r)throw new Error("Schema is missing a method literal");let s;if(tr(r)){const c=r,l=(i=c._zod)==null?void 0:i.def;s=(l==null?void 0:l.value)??c.value}else{const c=r,l=c._def;s=(l==null?void 0:l.value)??c.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const c=async(l,u)=>{var D,T;const p=He(Lh,l);if(!p.success){const A=p.error instanceof Error?p.error.message:String(p.error);throw new M(B.InvalidParams,`Invalid elicitation request: ${A}`)}const{params:f}=p.data;f.mode=f.mode??"form";const{supportsFormMode:h,supportsUrlMode:g}=fx(this._capabilities.elicitation);if(f.mode==="form"&&!h)throw new M(B.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!g)throw new M(B.InvalidParams,"Client does not support URL-mode elicitation requests");const b=await Promise.resolve(o(l,u));if(f.task){const A=He(qo,b);if(!A.success){const O=A.error instanceof Error?A.error.message:String(A.error);throw new M(B.InvalidParams,`Invalid task creation result: ${O}`)}return A.data}const _=He(Uh,b);if(!_.success){const A=_.error instanceof Error?_.error.message:String(_.error);throw new M(B.InvalidParams,`Invalid elicitation result: ${A}`)}const w=_.data,P=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&w.action==="accept"&&w.content&&P&&(T=(D=this._capabilities.elicitation)==null?void 0:D.form)!=null&&T.applyDefaults)try{mn(P,w.content)}catch{}return w};return super.setRequestHandler(t,c)}if(a==="sampling/createMessage"){const c=async(l,u)=>{const p=He(Fh,l);if(!p.success){const w=p.error instanceof Error?p.error.message:String(p.error);throw new M(B.InvalidParams,`Invalid sampling request: ${w}`)}const{params:f}=p.data,h=await Promise.resolve(o(l,u));if(f.task){const w=He(qo,h);if(!w.success){const P=w.error instanceof Error?w.error.message:String(w.error);throw new M(B.InvalidParams,`Invalid task creation result: ${P}`)}return w.data}const b=f.tools||f.toolChoice?Bh:qh,_=He(b,h);if(!_.success){const w=_.error instanceof Error?_.error.message:String(_.error);throw new M(B.InvalidParams,`Invalid sampling result: ${w}`)}return _.data};return super.setRequestHandler(t,c)}return super.setRequestHandler(t,o)}assertCapability(t,o){var n;if(!((n=this._serverCapabilities)!=null&&n[t]))throw new Error(`Server does not support ${t} (required for ${o})`)}async connect(t,o){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:or,capabilities:this._capabilities,clientInfo:this._clientInfo}},_h,o);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!CC.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var o,n,r,s,a;switch(t){case"logging/setLevel":if(!((o=this._serverCapabilities)!=null&&o.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!((n=this._serverCapabilities)!=null&&n.prompts))throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((r=this._serverCapabilities)!=null&&r.resources))throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!((s=this._serverCapabilities)!=null&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!((a=this._serverCapabilities)!=null&&a.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var o;switch(t){case"notifications/roots/list_changed":if(!((o=this._capabilities.roots)!=null&&o.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){var o,n;(n=(o=this._serverCapabilities)==null?void 0:o.tasks)==null||n.requests}assertTaskHandlerCapability(t){var o;this._capabilities&&((o=this._capabilities.tasks)==null||o.requests,void 0)}async ping(t){return this.request({method:"ping"},Rt,t)}async complete(t,o){return this.request({method:"completion/complete",params:t},jh,o)}async setLoggingLevel(t,o){return this.request({method:"logging/setLevel",params:{level:t}},Rt,o)}async getPrompt(t,o){return this.request({method:"prompts/get",params:t},xh,o)}async listPrompts(t,o){return this.request({method:"prompts/list",params:t},Rh,o)}async listResources(t,o){return this.request({method:"resources/list",params:t},Th,o)}async listResourceTemplates(t,o){return this.request({method:"resources/templates/list",params:t},Ph,o)}async readResource(t,o){return this.request({method:"resources/read",params:t},Eh,o)}async subscribeResource(t,o){return this.request({method:"resources/subscribe",params:t},Rt,o)}async unsubscribeResource(t,o){return this.request({method:"resources/unsubscribe",params:t},Rt,o)}async callTool(t,o=sr,n){if(this.isToolTaskRequired(t.name))throw new M(B.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const r=await this.request({method:"tools/call",params:t},o,n),s=this.getToolOutputValidator(t.name);if(s){if(!r.structuredContent&&!r.isError)throw new M(B.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(r.structuredContent)try{const a=s(r.structuredContent);if(!a.valid)throw new M(B.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof M?a:new M(B.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return r}isToolTask(t){var o,n,r,s;return(s=(r=(n=(o=this._serverCapabilities)==null?void 0:o.tasks)==null?void 0:n.requests)==null?void 0:r.tools)!=null&&s.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){var o;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of t){if(n.outputSchema){const s=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,s)}const r=(o=n.execution)==null?void 0:o.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(n.name),r==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,o){const n=await this.request({method:"tools/list",params:t},$h,o);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,o,n,r){const s=SR.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:c}=n,l=async()=>{if(!a){c(null,null);return}try{const p=await r();c(null,p)}catch(p){const f=p instanceof Error?p:new Error(String(p));c(f,null)}},u=()=>{if(i){const p=this._listChangedDebounceTimers.get(t);p&&clearTimeout(p);const f=setTimeout(l,i);this._listChangedDebounceTimers.set(t,f)}else l()};this.setNotificationHandler(o,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function rs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function mx(e=fetch,t){return t?async(o,n)=>{const r={...t,...n,headers:n!=null&&n.headers?{...rs(t.headers),...rs(n.headers)}:t.headers};return e(o,r)}:e}let ja;ja=globalThis.crypto;async function gx(e){return(await ja).getRandomValues(new Uint8Array(e))}async function yx(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",o=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const r=await gx(e-n.length);for(const s of r)s<o&&(n+=t[s%t.length])}return n}async function bx(e){return await yx(e)}async function wx(e){const t=await(await ja).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function kx(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await bx(e),o=await wx(t);return{code_verifier:t,code_challenge:o}}const le=uk().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:q.custom,message:"URL must be parseable",fatal:!0}),_g}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),_x=ue({resource:d().url(),authorization_servers:I(le).optional(),jwks_uri:d().url().optional(),scopes_supported:I(d()).optional(),bearer_methods_supported:I(d()).optional(),resource_signing_alg_values_supported:I(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:x().optional(),authorization_details_types_supported:I(d()).optional(),dpop_signing_alg_values_supported:I(d()).optional(),dpop_bound_access_tokens_required:x().optional()}),Vh=ue({issuer:d(),authorization_endpoint:le,token_endpoint:le,registration_endpoint:le.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),service_documentation:le.optional(),revocation_endpoint:le.optional(),revocation_endpoint_auth_methods_supported:I(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:I(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:I(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:I(d()).optional(),code_challenge_methods_supported:I(d()).optional(),client_id_metadata_document_supported:x().optional()}),vx=ue({issuer:d(),authorization_endpoint:le,token_endpoint:le,userinfo_endpoint:le.optional(),jwks_uri:le,registration_endpoint:le.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),acr_values_supported:I(d()).optional(),subject_types_supported:I(d()),id_token_signing_alg_values_supported:I(d()),id_token_encryption_alg_values_supported:I(d()).optional(),id_token_encryption_enc_values_supported:I(d()).optional(),userinfo_signing_alg_values_supported:I(d()).optional(),userinfo_encryption_alg_values_supported:I(d()).optional(),userinfo_encryption_enc_values_supported:I(d()).optional(),request_object_signing_alg_values_supported:I(d()).optional(),request_object_encryption_alg_values_supported:I(d()).optional(),request_object_encryption_enc_values_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),display_values_supported:I(d()).optional(),claim_types_supported:I(d()).optional(),claims_supported:I(d()).optional(),service_documentation:d().optional(),claims_locales_supported:I(d()).optional(),ui_locales_supported:I(d()).optional(),claims_parameter_supported:x().optional(),request_parameter_supported:x().optional(),request_uri_parameter_supported:x().optional(),require_request_uri_registration:x().optional(),op_policy_uri:le.optional(),op_tos_uri:le.optional(),client_id_metadata_document_supported:x().optional()}),Ix=m({...vx.shape,...Vh.pick({code_challenge_methods_supported:!0}).shape}),Sx=m({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:o_().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Dx=m({error:d(),error_description:d().optional(),error_uri:d().optional()}),kc=le.optional().or(y("").transform(()=>{})),Ax=m({redirect_uris:I(le),token_endpoint_auth_method:d().optional(),grant_types:I(d()).optional(),response_types:I(d()).optional(),client_name:d().optional(),client_uri:le.optional(),logo_uri:kc,scope:d().optional(),contacts:I(d()).optional(),tos_uri:kc,policy_uri:d().optional(),jwks_uri:le.optional(),jwks:Ck().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),Tx=m({client_id:d(),client_secret:d().optional(),client_id_issued_at:E().optional(),client_secret_expires_at:E().optional()}).strip(),Px=Ax.merge(Tx);m({error:d(),error_description:d().optional()}).strip();m({token:d(),token_type_hint:d().optional()}).strip();function Ex(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Cx({requestedResource:e,configuredResource:t}){const o=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(o.origin!==n.origin||o.pathname.length<n.pathname.length)return!1;const r=o.pathname.endsWith("/")?o.pathname:o.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return r.startsWith(s)}class ce extends Error{constructor(t,o){super(t),this.errorUri=o,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class ss extends ce{}ss.errorCode="invalid_request";class xn extends ce{}xn.errorCode="invalid_client";class On extends ce{}On.errorCode="invalid_grant";class Nn extends ce{}Nn.errorCode="unauthorized_client";class as extends ce{}as.errorCode="unsupported_grant_type";class is extends ce{}is.errorCode="invalid_scope";class cs extends ce{}cs.errorCode="access_denied";class to extends ce{}to.errorCode="server_error";class ls extends ce{}ls.errorCode="temporarily_unavailable";class us extends ce{}us.errorCode="unsupported_response_type";class ds extends ce{}ds.errorCode="unsupported_token_type";class ps extends ce{}ps.errorCode="invalid_token";class fs extends ce{}fs.errorCode="method_not_allowed";class hs extends ce{}hs.errorCode="too_many_requests";class $n extends ce{}$n.errorCode="invalid_client_metadata";class ms extends ce{}ms.errorCode="insufficient_scope";class gs extends ce{}gs.errorCode="invalid_target";const Rx={[ss.errorCode]:ss,[xn.errorCode]:xn,[On.errorCode]:On,[Nn.errorCode]:Nn,[as.errorCode]:as,[is.errorCode]:is,[cs.errorCode]:cs,[to.errorCode]:to,[ls.errorCode]:ls,[us.errorCode]:us,[ds.errorCode]:ds,[ps.errorCode]:ps,[fs.errorCode]:fs,[hs.errorCode]:hs,[$n.errorCode]:$n,[ms.errorCode]:ms,[gs.errorCode]:gs};class vt extends Error{constructor(t){super(t??"Unauthorized")}}function xx(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const _r="code",vr="S256";function Ox(e,t){const o=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&xx(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?o?"client_secret_basic":"none":o&&t.includes("client_secret_basic")?"client_secret_basic":o&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":o?"client_secret_post":"none"}function Nx(e,t,o,n){const{client_id:r,client_secret:s}=t;switch(e){case"client_secret_basic":$x(r,s,o);return;case"client_secret_post":Mx(r,s,n);return;case"none":zx(r,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function $x(e,t,o){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);o.set("Authorization",`Basic ${n}`)}function Mx(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}function zx(e,t){t.set("client_id",e)}async function Zh(e){const t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{const n=Dx.parse(JSON.parse(o)),{error:r,error_description:s,error_uri:a}=n,i=Rx[r]||to;return new i(s||"",a)}catch(n){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${o}`;return new to(r)}}async function ln(e,t){var o,n;try{return await Ir(e,t)}catch(r){if(r instanceof xn||r instanceof Nn)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"all")),await Ir(e,t);if(r instanceof On)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Ir(e,t);throw r}}async function Ir(e,{serverUrl:t,authorizationCode:o,scope:n,resourceMetadataUrl:r,fetchFn:s}){var D,T,A,O,C;const a=await((D=e.discoveryState)==null?void 0:D.call(e));let i,c,l,u=r;if(!u&&(a!=null&&a.resourceMetadataUrl)&&(u=new URL(a.resourceMetadataUrl)),a!=null&&a.authorizationServerUrl){if(c=a.authorizationServerUrl,i=a.resourceMetadata,l=a.authorizationServerMetadata??await Wh(c,{fetchFn:s}),!i)try{i=await Yh(t,{resourceMetadataUrl:u},s)}catch{}(l!==a.authorizationServerMetadata||i!==a.resourceMetadata)&&await((T=e.saveDiscoveryState)==null?void 0:T.call(e,{authorizationServerUrl:String(c),resourceMetadataUrl:u==null?void 0:u.toString(),resourceMetadata:i,authorizationServerMetadata:l}))}else{const L=await Hx(t,{resourceMetadataUrl:u,fetchFn:s});c=L.authorizationServerUrl,l=L.authorizationServerMetadata,i=L.resourceMetadata,await((A=e.saveDiscoveryState)==null?void 0:A.call(e,{authorizationServerUrl:String(c),resourceMetadataUrl:u==null?void 0:u.toString(),resourceMetadata:i,authorizationServerMetadata:l}))}const p=await qx(t,e,i),f=n||((O=i==null?void 0:i.scopes_supported)==null?void 0:O.join(" "))||e.clientMetadata.scope;let h=await Promise.resolve(e.clientInformation());if(!h){if(o!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const L=(l==null?void 0:l.client_id_metadata_document_supported)===!0,Z=e.clientMetadataUrl;if(Z&&!Fx(Z))throw new $n(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Z}`);if(L&&Z)h={client_id:Z},await((C=e.saveClientInformation)==null?void 0:C.call(e,h));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const Za=await Gx(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:s});await e.saveClientInformation(Za),h=Za}}const g=!e.redirectUrl;if(o!==void 0||g){const L=await Wx(e,c,{metadata:l,resource:p,authorizationCode:o,fetchFn:s});return await e.saveTokens(L),"AUTHORIZED"}const b=await e.tokens();if(b!=null&&b.refresh_token)try{const L=await Yx(c,{metadata:l,clientInformation:h,refreshToken:b.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(L),"AUTHORIZED"}catch(L){if(!(!(L instanceof ce)||L instanceof to))throw L}const _=e.state?await e.state():void 0,{authorizationUrl:w,codeVerifier:P}=await Vx(c,{metadata:l,clientInformation:h,state:_,redirectUrl:e.redirectUrl,scope:f,resource:p});return await e.saveCodeVerifier(P),await e.redirectToAuthorization(w),"REDIRECT"}function Fx(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function qx(e,t,o){const n=Ex(e);if(t.validateResourceURL)return await t.validateResourceURL(n,o==null?void 0:o.resource);if(o){if(!Cx({requestedResource:n,configuredResource:o.resource}))throw new Error(`Protected resource ${o.resource} does not match expected ${n} (or origin)`);return new URL(o.resource)}}function _c(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[o,n]=t.split(" ");if(o.toLowerCase()!=="bearer"||!n)return{};const r=Sr(e,"resource_metadata")||void 0;let s;if(r)try{s=new URL(r)}catch{}const a=Sr(e,"scope")||void 0,i=Sr(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Sr(e,t){const o=e.headers.get("WWW-Authenticate");if(!o)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),r=o.match(n);return r?r[1]||r[2]:null}async function Yh(e,t,o=fetch){var r,s;const n=await Ux(e,"oauth-protected-resource",o,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!n||n.status===404)throw await((r=n==null?void 0:n.body)==null?void 0:r.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await((s=n.body)==null?void 0:s.cancel()),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return _x.parse(await n.json())}async function Ha(e,t,o=fetch){try{return await o(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Ha(e,void 0,o):void 0;throw n}}function Bx(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function vc(e,t,o=fetch){return await Ha(e,{"MCP-Protocol-Version":t},o)}function Lx(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Ux(e,t,o,n){const r=new URL(e),s=(n==null?void 0:n.protocolVersion)??or;let a;if(n!=null&&n.metadataUrl)a=new URL(n.metadataUrl);else{const c=Bx(t,r.pathname);a=new URL(c,(n==null?void 0:n.metadataServerUrl)??r),a.search=r.search}let i=await vc(a,s,o);if(!(n!=null&&n.metadataUrl)&&Lx(i,r.pathname)){const c=new URL(`/.well-known/${t}`,r);i=await vc(c,s,o)}return i}function jx(e){const t=typeof e=="string"?new URL(e):e,o=t.pathname!=="/",n=[];if(!o)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),n.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function Wh(e,{fetchFn:t=fetch,protocolVersion:o=or}={}){var s;const n={"MCP-Protocol-Version":o,Accept:"application/json"},r=jx(e);for(const{url:a,type:i}of r){const c=await Ha(a,n,t);if(c){if(!c.ok){if(await((s=c.body)==null?void 0:s.cancel()),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?Vh.parse(await c.json()):Ix.parse(await c.json())}}}async function Hx(e,t){let o,n;try{o=await Yh(e,{resourceMetadataUrl:t==null?void 0:t.resourceMetadataUrl},t==null?void 0:t.fetchFn),o.authorization_servers&&o.authorization_servers.length>0&&(n=o.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const r=await Wh(n,{fetchFn:t==null?void 0:t.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:r,resourceMetadata:o}}async function Vx(e,{metadata:t,clientInformation:o,redirectUrl:n,scope:r,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(_r))throw new Error(`Incompatible auth server: does not support response type ${_r}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(vr))throw new Error(`Incompatible auth server: does not support code challenge method ${vr}`)}else i=new URL("/authorize",e);const c=await kx(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",_r),i.searchParams.set("client_id",o.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",vr),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),r&&i.searchParams.set("scope",r),r!=null&&r.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}function Zx(e,t,o){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(o)})}async function Gh(e,{metadata:t,tokenRequestParams:o,clientInformation:n,addClientAuthentication:r,resource:s,fetchFn:a}){const i=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&o.set("resource",s.href),r)await r(c,o,i,t);else if(n){const u=(t==null?void 0:t.token_endpoint_auth_methods_supported)??[],p=Ox(n,u);Nx(p,n,c,o)}const l=await(a??fetch)(i,{method:"POST",headers:c,body:o});if(!l.ok)throw await Zh(l);return Sx.parse(await l.json())}async function Yx(e,{metadata:t,clientInformation:o,refreshToken:n,resource:r,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await Gh(e,{metadata:t,tokenRequestParams:i,clientInformation:o,addClientAuthentication:s,resource:r,fetchFn:a});return{refresh_token:n,...c}}async function Wx(e,t,{metadata:o,resource:n,authorizationCode:r,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const l=await e.codeVerifier();i=Zx(r,l,e.redirectUrl)}const c=await e.clientInformation();return Gh(t,{metadata:o,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Gx(e,{metadata:t,clientMetadata:o,scope:n,fetchFn:r}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const a=await(r??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o,...n!==void 0?{scope:n}:{}})});if(!a.ok)throw await Zh(a);return Px.parse(await a.json())}class Ic extends Error{constructor(t,o){super(t),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}}function Dr(e){}function Kx(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Dr,onError:o=Dr,onRetry:n=Dr,onComment:r}=e;let s="",a=!0,i,c="",l="";function u(b){const _=a?b.replace(/^\xEF\xBB\xBF/,""):b,[w,P]=Jx(`${s}${_}`);for(const D of w)p(D);s=P,a=!1}function p(b){if(b===""){h();return}if(b.startsWith(":")){r&&r(b.slice(b.startsWith(": ")?2:1));return}const _=b.indexOf(":");if(_!==-1){const w=b.slice(0,_),P=b[_+1]===" "?2:1,D=b.slice(_+P);f(w,D,b);return}f(b,"",b)}function f(b,_,w){switch(b){case"event":l=_;break;case"data":c=`${c}${_}
519
- `;break;case"id":i=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):o(new Ic(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:o(new Ic(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:_,line:w}));break}}function h(){c.length>0&&t({id:i,event:l||void 0,data:c.endsWith(`
520
- `)?c.slice(0,-1):c}),i=void 0,c="",l=""}function g(b={}){s&&b.consume&&p(s),a=!0,i=void 0,c="",l="",s=""}return{feed:u,reset:g}}function Jx(e){const t=[];let o="",n=0;for(;n<e.length;){const r=e.indexOf("\r",n),s=e.indexOf(`
511
+ `.trim())}async function nD(e,t,o,n){const r=await $v(e,t,o,n);if(GS(r)&&(Array.isArray(r.backlinks)||Array.isArray(r.backmentions)))return{backlinks:Array.isArray(r.backlinks)?r.backlinks:[],backmentions:Array.isArray(r.backmentions)?r.backmentions:[]};const[s,a]=await Promise.all([oD(e,t,o,n),nf(e,t,o,n)]);return{backlinks:s,backmentions:a,fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}async function rD(e,t,o,n){const r=await Mv(e,t,o,n);return r&&typeof r=="object"&&Array.isArray(r.backmentions)?{backmentions:r.backmentions}:{backmentions:await nf(e,t,o,n),fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}const sD="search";function aD(e){return typeof e=="string"&&e.trim().length>0}function wr(e,t){return aD(t)?t:e}function sn(e){const t=Object.entries(e).filter(([,o])=>o!==void 0);return t.length===0?{}:{resolvedArgs:Object.fromEntries(t)}}function pa(e,t){return t?{showing:t.showing,truncated:t.truncated,hint:t.hint}:{showing:e,truncated:!1}}function po(e){return Array.isArray(e)?jS(e):[]}function iD(e){let t=e.types?DS(e.types):e.types;return e.typeShortcodes&&e.typeShortcodes.length>0&&(t={...SS(e.typeShortcodes),...t}),t}function cD(e){return e.parentId?Math.min((e.pageSize??32)*3,128):e.pageSize}function lD(e,t){if(!Array.isArray(e.blocks))return;const o=t;e.blocks=e.blocks.filter(n=>n.rootID===o||n.root_id===o||n.parent_id===o||n.parentID===o),e.matchedBlockCount=e.blocks.length,e.parentIdFilter=o}function uD(e,t){Array.isArray(e.blocks)&&(e.blocks=e.blocks.filter(o=>{const r=(typeof o.tag=="string"?o.tag.trim():"").length>0;return t?r:!r}),e.matchedBlockCount=e.blocks.length)}function kr(e){const t=TS(e.methodName,e.method);return{...t!==void 0?{method:t}:{},...t!==void 0?{methodName:AS(t)}:{}}}function dD(e,t,o,n){const r=Array.isArray(e.blocks)?e.blocks:[],s=t.page??1,a=t.pageSize??32,i=ea(r,20,`Use page/pageSize parameters to paginate. Current page: ${s}.`),c=r.length,l=typeof o.pageCount=="number"?o.pageCount:1,u=typeof e.filteredOutBlockCount=="number"?e.filteredOutBlockCount:0,p=u>0||!!t.parentId||t.hasTags!==void 0,h={total:p?c:typeof o.matchedBlockCount=="number"?o.matchedBlockCount:c,page:s,pageSize:a,pageCount:p?1:l,hasNextPage:p?!1:s<l},{blocks:g,pageCount:b,..._}=e;return We(i.items,h,{..._,...ut(u),...pa(c,i.meta),returnedTotal:c,returnedPageCount:1,returnedHasNextPage:!1,...o.matchedBlockCount!==void 0?{kernelMatchedBlockCount:o.matchedBlockCount}:{},...o.matchedRootCount!==void 0?{kernelMatchedRootCount:o.matchedRootCount}:{},kernelPageCount:l,kernelHasNextPage:s<l,...p?{paginationMode:"post_filtered_window",pagingHint:"kernel* pagination fields describe the raw SiYuan search page before permission and parent/tag post-filtering."}:{},...t.parentId&&c===0?{warning:"No matching blocks were found in the requested document subtree. If the content was just created or updated, SiYuan full-text indexing may still be catching up; retry shortly."}:{},...n?{resolvedArgs:n}:{}})}function pD(e,t,o){const n=ea(e,50,"Add LIMIT and OFFSET to your SQL for pagination."),r=e.length;return k({data:n.items,total:r,totalRows:r,...pa(r,n.meta),...ut(t),...o?{resolvedArgs:o}:{}})}function fD(e,t,o,n){const r=ea(t,20,"Use page/pageSize parameters to paginate asset content results."),s=t.length;return k({...e,assetContents:r.items,data:r.items,total:s,...pa(s,r.meta),...ut(o),...n?{resolvedArgs:n}:{}})}const hD={fulltext:async({client:e,permMgr:t,rawArgs:o})=>{const n=fp.parse(o);if(n.parentId){const{denied:f}=await N(e,t,n.parentId,"read");if(f)return f}const r=kr(n),s=qr(n.sortBy,n.orderBy),a=await Ov(e,{query:n.query,method:r.method,types:iD(n),paths:n.paths,groupBy:n.groupBy,orderBy:s,page:n.page,pageSize:cD(n)}),c=Fi(a,t),l={...c,blocks:po(Array.isArray(c.blocks)?c.blocks:[])};n.parentId&&lD(l,n.parentId),n.hasTags!==void 0&&uD(l,n.hasTags),Array.isArray(l.blocks)&&(l.blocks=await VS(e,l.blocks));const p=n.methodName!==void 0||n.sortBy!==void 0?sn({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:Ni(s)}:{}}).resolvedArgs:void 0;return dD(l,n,{matchedBlockCount:typeof a.matchedBlockCount=="number"?a.matchedBlockCount:void 0,matchedRootCount:typeof a.matchedRootCount=="number"?a.matchedRootCount:void 0,pageCount:typeof a.pageCount=="number"?a.pageCount:void 0},p)},query_sql:async({client:e,permMgr:t,rawArgs:o})=>{const n=hp.parse(o),r=wr(n.stmt,n.sql);try{eD(r??"")}catch(l){return wo(l,{tool:sD,action:"query_sql",rawArgs:o})}const s=await st(e,r??""),a=Array.isArray(s)?s:[],i=await hn(e,a,t),c=n.sql!==void 0?sn({stmt:r}).resolvedArgs:void 0;return pD(i.items,i.removedCount,c)},get_backlinks:async({client:e,permMgr:t,rawArgs:o})=>{const n=mp.parse(o),r=wr(n.refTreeID,n.scopeRootId),s=n.mode??"both",{denied:a}=await N(e,t,n.id,"read");if(a)return a;try{const i=s!=="mentions"?await nD(e,n.id,n.keyword,r):{},c=s!=="links"?await rD(e,n.id,n.keyword,r):{},l={...i,...c},u=mn(l,t);return k({...u,mode:s,backlinks:s!=="mentions"?po(Array.isArray(u.backlinks)?u.backlinks:[]):[],backmentions:s!=="links"?po(Array.isArray(u.backmentions)?u.backmentions:[]):[],...l.sourcePayloadMissing?{sourcePayloadMissing:!0}:{},...l.fallbackQuery?{fallbackQuery:l.fallbackQuery}:{},...l.resultConfidence?{resultConfidence:l.resultConfidence}:{},...n.scopeRootId!==void 0?{resolvedArgs:{refTreeID:r}}:{},...l.fallbackUsed?{warning:"SiYuan returned no backlink/backmention payload; SQL fallback results are shown."}:{}})}catch(i){if(YS(i))return k({backlinks:[],backmentions:[],warning:"SiYuan rejected part of the backlink/backmention query due to restricted notebooks; restricted results were omitted.",partial:!0,reason:"permission_filtered",permissionSummary:ut(1).permissionSummary});throw i}},search_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=gp.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await zv(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.blocks)?a.blocks:[],c=await hn(e,i,t),l=po(c.items);return k({...a,blocks:l,data:l,total:l.length,showing:l.length,truncated:!1,...ut(c.removedCount)})},find_replace:async({client:e,permMgr:t,rawArgs:o})=>{const n=yp.parse(o);for(const i of n.ids){const{denied:c}=await N(e,t,i,"write");if(c)return c}if(Array.isArray(n.paths))for(const i of n.paths){const c=await No(e,i);if(!c)continue;const l=await Y(t,c,"write");if(l)return l}const r=kr(n),s=qr(n.sortBy,n.orderBy);await Fv(e,{k:n.k,r:n.r,ids:n.ids,...n.paths?{paths:n.paths}:{},...n.types?{types:n.types}:{},...r.method!==void 0?{method:r.method}:{},...s!==void 0?{orderBy:s}:{},...n.groupBy!==void 0?{groupBy:n.groupBy}:{},...n.replaceTypes?{replaceTypes:n.replaceTypes}:{}});const a=n.methodName!==void 0||n.sortBy!==void 0;return k({success:!0,replaced:!0,ids:n.ids,k:n.k,r:n.r,...n.paths?{paths:n.paths}:{},...a?{resolvedArgs:sn({...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:Ni(s)}:{}}).resolvedArgs}:{}})},search_assets:async({client:e,rawArgs:t})=>{const o=bp.parse(t),n=wr(o.k,o.query)??"",r=await qv(e,n,o.exts);return o.query===void 0?k(r):k({...r&&typeof r=="object"&&!Array.isArray(r)?r:{data:r},resolvedArgs:{query:n}})},fulltext_asset_content:async({client:e,permMgr:t,rawArgs:o})=>{const n=wp.parse(o);if(n.assetId){const p=await Lv(e,n.assetId,n.query??"",n.queryMethod??0);return k(p)}const r=kr(n),s=xS(n.sortBy,n.orderBy),a=await Bv(e,{query:n.query,...n.types?{types:n.types}:{},...r.method!==void 0?{method:r.method}:{},...s!==void 0?{orderBy:s}:{},...n.page!==void 0?{page:n.page}:{},...n.pageSize!==void 0?{pageSize:n.pageSize}:{}}),i=a&&typeof a=="object"?a:{},c=Array.isArray(i.assetContents)?i.assetContents:[],l=await hn(e,c,t),u=n.methodName!==void 0||n.sortBy!==void 0;return fD(i,l.items,l.removedCount,u?sn({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:OS(s)}:{}}).resolvedArgs:void 0)},list_invalid_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=kp.parse(o),r=await Uv(e,n.page,n.pageSize),a=Fi(r??{},t),i=Array.isArray(a.blocks)?a.blocks:[],c=po(i);return k({...a,blocks:c,data:c,total:c.length,showing:c.length,truncated:!1,...ut(typeof a.filteredOutBlockCount=="number"?a.filteredOutBlockCount:0)})}},mD="search",gD=[S("fulltext",fp,"Full-text search across all blocks."),S("query_sql",hp,"Execute a read-only SQL query against the database."),S("get_backlinks",mp,"Find documents/blocks that link to or mention the given block."),S("search_refs",gp,"Search blocks that reference a given block or document."),S("find_replace",yp,"Find and replace text in documents or blocks."),S("search_assets",bp,"Search asset files by filename."),S("fulltext_asset_content",wp,"Full-text search indexed asset contents."),S("list_invalid_refs",kp,"List invalid block references.")],rf=De({name:mD,description:"🔍 Grouped search and query operations.",variants:gD,actionSchema:I_,aggregateOptions:{guidance:ll,actionHints:ul,guidanceInlineLimit:5},handlers:hD});function yD(e){return rf.listTools(e)}async function bD(e,t,o,n){return rf.callTool(e,t,o,n)}const wD=/\n?\{:\s*(?=[^}]*\bid\s*=)([^}]*)\}\s*$/s,sf=/<span\b(?=[^>]*\bdata-type=(?:"[^"]*\bblock-ref\b[^"]*"|'[^']*\bblock-ref\b[^']*'))([^>]*)>([\s\S]*?)<\/span>/gi,kD=/<span\b(?=[^>]*\bdata-type=(?:"[^"]*\btag\b[^"]*"|'[^']*\btag\b[^']*'))([^>]*)>([\s\S]*?)<\/span>/gi,_D=/^<span\b(?=[^>]*\bdata-type=(?:"[^"]*\bblock-ref\b[^"]*"|'[^']*\bblock-ref\b[^']*'))([^>]*)>([\s\S]*?)<\/span>$/i,vD=/^<span\b(?=[^>]*\bdata-type=(?:"[^"]*\btag\b[^"]*"|'[^']*\btag\b[^']*'))([^>]*)>([\s\S]*?)<\/span>$/i,Wt=/\sdata-id=(?:"([^"]+)"|'([^']+)')/i,af=/\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])(.*?)\2\)\)/g,Li=/\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])(.*?)\2\)\)/,ID=/^\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])(.*?)\2\)$/,cf=/\(\(([0-9]{14}-[a-z0-9]{7})\)\)/,SD=/\[[^\]]+\]\(siyuan:\/\/blocks\/[0-9]{14}-[a-z0-9]{7}\)/i,DD=/\[\^\d+\]|^\[\^\d+\]:/m,TD=/#([^#\s][^#\n]*?)#/g,Bi=/#([^#\s][^#\n]*?)#/,lf=/\sdata-type=(?:"[^"]*\b(?:tag|block-ref)\b[^"]*"|'[^']*\b(?:tag|block-ref)\b[^']*')/i,AD=/^<\s*(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\b/i,PD=/[\u200B\u200C\u200D\u2060\uFEFF]/,uf=/[\u200B\u200C\u200D\u2060\uFEFF]/g,Ui=/^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)(.*)$/,CD=/^(\s*(?:>\s*)*)(`{3,}|~{3,}|\$\$).*$/,df=/^\s*\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,pf=/^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*/,ED=/^(\s*(?:>\s*)+)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,RD=/^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,xD=/^(\s*(?:>\s*)+(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*/,OD=/^(\s*(?:>\s*)+(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)\{:\s*(?=[^}]*\bid\s*=)[^}]*\}\s*$/,ND=/^\s*(?:>\s*)+$/,$D="siyuan://blocks Markdown links are allowed, but SiYuan treats them as mentions, not backlinks. Use ((id '完整标题')) when you need a real backlink.",MD="Footnote-style references like [^1] are allowed, but they create footnotes or note markers, not SiYuan backlinks. Use ((id '完整标题')) when you need a real backlink.",zD="Naked block references like ((id)) are allowed and normalized before writing. If the target anchor cannot be resolved, MCP uses the block ID as fallback anchor text; pass ((id '完整标题')) when exact readable text matters.";function Gt(e){return SD.test(e)}function Kt(e){return DD.test(e)}function $o(){return{warning:"siyuan://blocks Markdown links create mentions, not backlinks.",hint:$D}}function Mo(){return{warning:"Footnote-style references create footnotes or note markers, not backlinks.",hint:MD}}function Jt(e){return/\(\(([0-9]{14}-[a-z0-9]{7})\s+(['"])\1\2\)\)/.test(e)}function zo(){return{warning:"Some naked block references used the block ID as fallback anchor text.",hint:zD}}function Ke(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function tt(e){return e.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(t,o)=>{const n=o.toLowerCase();if(n==="amp")return"&";if(n==="lt")return"<";if(n==="gt")return">";if(n==="quot")return'"';if(n==="apos")return"'";if(n==="nbsp")return" ";if(n.startsWith("#x")){const r=Number.parseInt(n.slice(2),16);return Number.isFinite(r)?String.fromCodePoint(r):t}if(n.startsWith("#")){const r=Number.parseInt(n.slice(1),10);return Number.isFinite(r)?String.fromCodePoint(r):t}return t})}function fa(e){const t=e.match(wD);return t?{content:Ur(e.slice(0,t.index).trimEnd()),ial:t[0].trim()}:{content:Ur(e.trimEnd()),ial:""}}function FD(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Ur(e){return e.replace(af,(t,o,n,r)=>`((${o} '${FD(r)}'))`)}function qD(e){return e.replace(sf,(t,o,n)=>{var a,i;const r=((a=o.match(Wt))==null?void 0:a[1])??((i=o.match(Wt))==null?void 0:i[2]);if(!r)return t;const s=tt(n.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim().replace(/\\/g,"\\\\").replace(/'/g,"\\'");return s?`((${r} '${s}'))`:t})}function LD(e){return e.replace(kD,(t,o,n)=>{const r=tt(n.replace(/<[^>]+>/g,"")).replace(uf,"").replace(/\s+/g," ").trim();return r?r.startsWith("#")&&r.endsWith("#")?r:`#${r}#`:t})}function ha(e,t){const o=e.match(CD);if(!o)return t;const n=o[2];if(!n)return t;const r=n[0],s=n.length;return t?r===t.marker&&s>=t.length?null:t:{marker:r,length:s}}function BD(e,t){if(t!=="l")return e.trimEnd();const o=[];let n=null;for(const r of e.split(/\r?\n/)){const s=n!==null;if(n=ha(r,n),s||s!==(n!==null)){o.push(r);continue}const i=r.replace(pf,"$1");df.test(i)||o.push(i)}return o.join(`
512
+ `).trimEnd()}function UD(e,t){if(t!=="b"&&t!=="callout"&&t!=="s")return e.trimEnd();const o=[];let n=null,r=!1;for(const s of e.split(/\r?\n/)){const a=n!==null;if(n=ha(s,n),a||a!==(n!==null)){o.push(s);continue}if(df.test(s)){r=!1;continue}if(ED.test(s)){r=!0;continue}if(!(r&&ND.test(s))){if(RD.test(s)||OD.test(s)){r=!1;continue}r=!1,o.push(s.replace(pf,"$1").replace(xD,"$1"))}}return o.join(`
513
+ `).trimEnd()}function jD(e){const t=[];let o=null;for(const n of e.split(/\r?\n/)){const r=o!==null;o=ha(n,o);const s=r!==(o!==null);t.push(r||s?n:n.replace(uf,""))}return t.join(`
514
+ `).trimEnd()}function ma(e){const t=fa(e.kramdown),o=LD(qD(t.content));return jD(UD(BD(o,e.type),e.type))}function HD(e,t){return ma({kramdown:e,type:t})}function ff(e,t){const o=e.trimEnd();return t.ial?`${o}
515
+ ${t.ial}`:o}function hf(e,t){let o=0,n=0;for(;;){if(n=e.indexOf(t,n),n===-1)return o;o+=1,n+=t.length}}function jr(e,t){const o=hf(e,t.old);if(o===0)return{content:e,replaced:0,replaceAll:!!t.replace_all};if(t.replace_all)return{content:e.split(t.old).join(t.new),replaced:o,replaceAll:!0};const n=e.indexOf(t.old);return{content:`${e.slice(0,n)}${t.new}${e.slice(n+t.old.length)}`,replaced:1,replaceAll:!1}}function VD(e){if(/[\r\n]/.test(e.old)||/[\r\n]/.test(e.new))return null;const t=e.old.match(Ui);if(!t)return null;const o=e.new.match(Ui);return o&&o[1]!==t[1]?null:{...e,old:t[2]??"",new:o?o[2]??"":e.new}}function ZD(e,t,o){if(o==="l"){const r=VD(t);if(r){const s=jr(e,r);if(s.replaced>0)return{edit:r,...s}}}const n=jr(e,t);return{edit:t,...n}}function YD(e){return Ke(e).replace(/\n/g,"<br>")}function WD(e,t,o){const n=t.old.match(ID);if(!n)return null;const r=n[1],s=n[3];let a=0;return{dom:e.replace(sf,(c,l,u)=>{var h,g;if(a>=o)return c;const p=((h=l.match(Wt))==null?void 0:h[1])??((g=l.match(Wt))==null?void 0:g[2]),f=tt(u.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim();return p!==r||f!==s?c:(a+=1,Qn(t.new))}),replaced:a}}function En(e,t,o,n){for(const r of t)PD.test(r)||e.push({value:r,start:o,end:n})}function ji(e,t,o){let n=0;for(;n<t.length;){if(t[n]==="&"){const r=t.indexOf(";",n+1);if(r!==-1){const s=t.slice(n,r+1),a=tt(s);if(a!==s){En(e,a,o+n,o+r+1),n=r+1;continue}}}En(e,t[n],o+n,o+n+1),n+=1}}function Hi(e,t,o){const r=e.slice(o).match(t);return(r==null?void 0:r.index)===void 0?-1:o+r.index}function Vi(e,t){const o=e.indexOf(">",t);if(o===-1)return-1;let n=1,r=o+1;for(;r<e.length;){const s=Hi(e,/<\s*span\b[^>]*>/i,r),a=Hi(e,/<\s*\/\s*span\s*>/i,r);if(a===-1)return-1;if(s!==-1&&s<a){n+=1;const c=e.indexOf(">",s);if(c===-1)return-1;r=c+1;continue}n-=1;const i=e.indexOf(">",a);if(i===-1)return-1;if(n===0)return i+1;r=i+1}return-1}function GD(e){var n,r;const t=e.match(_D);if(t){const s=t[1]??"",a=t[2]??"",i=((n=s.match(Wt))==null?void 0:n[1])??((r=s.match(Wt))==null?void 0:r[2]),c=tt(a.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim();return i&&c?`((${i} '${c}'))`:null}const o=e.match(vD);if(o){const s=tt((o[2]??"").replace(/<[^>]+>/g,"")).trim();return s.startsWith("#")&&s.endsWith("#")?s:`#${s}#`}return null}function mf(e){const t=[];let o=0;for(;o<e.length;){const n=e.indexOf("<",o),r=n===-1?e.length:n;if(r>o&&ji(t,e.slice(o,r),o),n===-1)break;const s=e.indexOf(">",n);if(s===-1)break;const a=e.slice(n,s+1);if(lf.test(a)&&/^<\s*span\b/i.test(a)){const i=Vi(e,n);if(i!==-1){const c=e.slice(n,i),l=GD(c);if(l){En(t,l,n,i),o=i;continue}}}if(/^<\s*br\b/i.test(a)&&En(t,`
516
+ `,n,s+1),/^<\s*span\b/i.test(a)){const i=Vi(e,n);if(i!==-1){const c=e.slice(n,i),l=c.indexOf(">")+1,u=c.lastIndexOf("</span>");if(l>0&&u>=l){const p=c.slice(l,u),f=[];ji(f,p.replace(/<[^>]+>/g,""),n+l);for(const h of f)t.push({value:h.value,start:n,end:i});o=i;continue}}}o=s+1}return t}function KD(e,t,o){var s,a;let n=e,r=0;for(;r<o;){const i=mf(n),l=i.map(h=>h.value).join("").indexOf(t.old);if(l===-1)break;const u=l+t.old.length-1,p=(s=i[l])==null?void 0:s.start,f=(a=i[u])==null?void 0:a.end;if(p===void 0||f===void 0)break;n=`${n.slice(0,p)}${Qn(t.new)}${n.slice(f)}`,r+=1}return{dom:n,replaced:r}}function JD(e,t){const n=mf(e).map(a=>a.value).join(""),r=n.length>240?`${n.slice(0,240)}...`:n,s=t.old.length>160?`${t.old.slice(0,160)}...`:t.old;return` DOM logical text preview: ${JSON.stringify(r)}. Old preview: ${JSON.stringify(s)}.`}function QD(e,t,o,n){if(o<=0)return{segment:e,replaced:0};if(n&&/^#[^#\s][^#\n]*#$/.test(t.old))return{segment:e,replaced:0};const r=tt(e),s=hf(r,t.old);if(s===0)return{segment:e,replaced:0};const a=Math.min(s,o);let i="",c=0,l=0;for(;c<a;){const u=r.indexOf(t.old,l);if(u===-1)break;i+=Ke(r.slice(l,u)),i+=n?YD(t.new):Qn(t.new),l=u+t.old.length,c+=1}return i+=Ke(r.slice(l)),{segment:i,replaced:c}}function gf(e,t){if(/^<\s*\/\s*[^>]+>/.test(e)){t.pop();return}/^<\s*[!?]/.test(e)||/\/\s*>$/.test(e)||AD.test(e)||t.push(lf.test(e))}function yf(e,t,o,n,r){const s=WD(e,t,o);if(s)return s;let a="",i=0,c=0;const l=[];for(;i<e.length;){const u=e.indexOf("<",i),p=u===-1?e.length:u;if(p>i){const g=e.slice(i,p),b=QD(g,t,o===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:o-c,l.some(Boolean));a+=b.segment,c+=b.replaced}if(u===-1)break;const f=e.indexOf(">",u);if(f===-1)throw new Error(`${n} cannot safely update DOM for edit #${r+1}: malformed block DOM.`);const h=e.slice(u,f+1);if(a+=h,gf(h,l),i=f+1,c>=o)return a+=e.slice(i),{dom:a,replaced:c}}return c>0?{dom:a,replaced:c}:KD(e,t,o)}function bf(e,t,o,n,r,s){if(n!==o)throw new Error(`${e} cannot safely map edit #${t+1} from kramdown to DOM. The match may cross unsupported inline formatting; narrow the old text or use block.update/fs.write for a full block rewrite. Expected ${o} DOM replacement(s), got ${n}.${JD(r,s)}`)}function wf(e,t,o){if(/\{:\s*[^}]*\bid=/.test(e.old)||/\{:\s*[^}]*\bid=/.test(e.new))throw new Error(`${t} edit #${o+1} appears to modify block IAL metadata. Use block(action="set_attrs") for attributes and keep content replacements inside the block body.`)}function XD(e,t,o,n){const r=fa(e);let s=r.content,a=t;const i=[];o.forEach((l,u)=>{wf(l,n,u);const p=jr(s,l);if(p.replaced===0){const h=" block.replace only searches the content body of the single block identified by id; it does not include child blocks, sibling blocks, the whole document, or block IAL metadata.";throw new Error(`${n} edit #${u+1} did not match any text.${h}`)}const f=yf(a,l,p.replaceAll?Number.POSITIVE_INFINITY:1,n,u);bf(n,u,p.replaced,f.replaced,a,l),s=p.content,a=f.dom,i.push({index:u+1,replaced:p.replaced,replace_all:p.replaceAll})});const c=ff(s,r);return kf(c),{kramdown:c,markdown:s,dom:a,summary:i}}function Hr(e){return Li.test(e.old)||Li.test(e.new)||Bi.test(e.old)||Bi.test(e.new)}function eT(e,t,o){const n=e.map(a=>({id:a.id,parsed:fa(a.kramdown),editableContent:ma(a),dom:a.dom,type:a.type})),r=new Map,s=[];return t.forEach((a,i)=>{wf(a,o,i);let c=0;for(const l of n){if(!a.replace_all&&c>0)break;const u=l.editableContent,p=ZD(l.editableContent,a,l.type);if(p.replaced===0)continue;const f=yf(l.dom,p.edit,p.replaceAll?Number.POSITIVE_INFINITY:1,o,i);if(bf(o,i,p.replaced,f.replaced,l.dom,p.edit),l.editableContent=p.content,l.dom=f.dom,c+=p.replaced,p.content!==u){const h=ff(l.editableContent,l.parsed);kf(h);const g=r.get(l.id);r.set(l.id,{id:l.id,kramdown:h,markdown:l.editableContent,dom:l.dom,type:l.type,touchesIndexedInline:!!(g!=null&&g.touchesIndexedInline)||Hr(a)||Hr(p.edit)})}}if(c===0)throw new Error(`${o} edit #${i+1} did not match any text in editable document blocks. Cross-block replacements are not allowed because they would require rebuilding blocks.`);s.push({index:i+1,replaced:c,replace_all:!!a.replace_all})}),{blocks:[...r.values()],summary:s}}function kf(e){if(cf.test(e))throw new Error("Refusing to write naked block references like ((id)). Use ((id '完整标题')) so the anchor text is explicit.")}function Vr(e,t,o={}){if(!o.allowNakedBlockRefs&&cf.test(e))throw new Error(`${t} refuses naked block references like ((id)). Use ((id '完整标题')) so the anchor text is explicit.`)}function Zi(e){let t="",o=0;for(const n of e.matchAll(TD)){t+=Ke(e.slice(o,n.index));const r=n[0],s=n[1];t+=`<span data-type="tag">${Ke(s)}</span>`,o=(n.index??0)+r.length}return t+=Ke(e.slice(o)),t}function Qn(e){let t="",o=0;for(const n of e.matchAll(af)){t+=Zi(e.slice(o,n.index));const r=n[1],s=n[3];t+=`<span data-type="block-ref" data-subtype="s" data-id="${Ke(r)}">${Ke(s)}</span>`,o=(n.index??0)+n[0].length}return t+=Zi(e.slice(o)),t.replace(/\n/g,"<br>")}function tT(e,t){Vr(e,t);let o="",n=0;const r=[];for(;n<e.length;){const s=e.indexOf("<",n),a=s===-1?e.length:s;if(a>n){const l=e.slice(n,a);o+=r.some(Boolean)?l:Qn(tt(l))}if(s===-1)break;const i=e.indexOf(">",s);if(i===-1)throw new Error(`${t} cannot safely normalize DOM: malformed block DOM.`);const c=e.slice(s,i+1);o+=c,gf(c,r),n=i+1}return o}function _f(e,t){var i;const o=t==null?void 0:t.trim(),n=e.replace(/^\uFEFF/,""),r=((i=n.match(/^\s*/))==null?void 0:i[0])??"",s=n.slice(r.length);if(!o)return e;const a=new RegExp(`^#\\s+${oT(o)}(?:\\s*\\r?\\n|\\s*$)`);return a.test(s)?`${r}${s.replace(a,"").replace(/^\r?\n+/,"")}`:e}function oT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Yi=/\(\(([0-9]{14}-[a-z0-9]{7})\)\)/g;function nT(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function rT(e){return e.replace(/\{:\s*[^}]*\}/g,"").replace(/^#{1,6}\s+/,"").replace(/^\s*(?:[-*+]|\d+[.)])\s+/,"").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\(\(([0-9]{14}-[a-z0-9]{7})\s+'([^']+)'\)\)/g,"$2").replace(/[*_~`=]/g,"").replace(/\s+/g," ").trim()}function Wi(e){return e.split(/\r?\n/).map(t=>rT(t)).find(t=>t.length>0)??""}async function sT(e,t){try{const o=await co(e,t),n=typeof o.kramdown=="string"?Wi(HD(o.kramdown)):"";if(n)return n}catch{}try{const o=await Fp(e,t);if(o&&typeof o=="object"){const n=o;for(const r of["content","fcontent","name","markdown"]){const s=n[r];if(typeof s=="string"){const a=Wi(s);if(a)return a}}}}catch{}return t}async function Qt(e,t,o){const n=Ur(t);Vr(n,o,{allowNakedBlockRefs:!0});const r=[...new Set([...n.matchAll(Yi)].map(i=>i[1]))];if(r.length===0)return n;const s=new Map;await Promise.all(r.map(async i=>{s.set(i,await sT(e,i))}));const a=n.replace(Yi,(i,c)=>{const l=s.get(c);return`((${c} '${nT(l??c)}'))`});return Vr(a,o),a}async function vf(e,t,o){return Promise.all(t.map(async n=>({...n,old:await Qt(e,n.old,o),new:await Qt(e,n.new,o)})))}async function Zr(e,t){if(typeof e.request=="function")try{const o=await e.request("/api/query/sql",{stmt:`SELECT type FROM blocks WHERE id = '${String(t).replace(/\0/g,"").replace(/'/g,"''")}' LIMIT 1`}),n=Array.isArray(o)?o[0]:void 0;return n&&typeof n=="object"&&typeof n.type=="string"?n.type:void 0}catch{return}}function Yr(e){return{databaseBlock:!0,warning:`${e} operated on a database/attribute-view block container. To read or edit database rows, columns, or cells, use av(action="get"|"render"|"add_rows"|"remove_rows"|"add_column"|"remove_column"|"set_cells") with the attribute view ID instead of editing the block as markdown.`,avToolHint:{read:'av(action="get", id="<av-id>") or av(action="render", id="<av-id>", blockID="<database-block-id>")',write:'av(action="set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column", avID="<av-id>", ...)'}}}function Xn(e,t){return{...e,...Gt(t)?$o():{},...Kt(t)?Mo():{},...Jt(t)?zo():{}}}function ga(e){return Gt(e)||Kt(e)||Jt(e)}function er(e){return Xn({},e)}function aT(e){return typeof e!="string"?!1:e!=="d"}function iT(e){if(!e||typeof e!="object")return{};const t=e;return{...typeof t.id=="string"?{id:t.id}:{},...typeof t.type=="string"?{type:t.type}:{},...typeof t.subtype=="string"?{subtype:t.subtype}:{},...typeof t.content=="string"?{content:t.content}:{},...typeof t.path=="string"?{path:t.path}:{}}}async function cT(e,t){const o=jo(),n=new Map;let r=!1;for(const s of t){s&&typeof s=="object"&&aT(s.type)&&(r=!0);const a=await Ho(e,s,o);if(!(a!=null&&a.documentId)||!a.notebook||!a.path)continue;let i=n.get(a.documentId);if(!i){let c,l;try{const u=await dt(e,a.documentId);c=u.name,l=u.hPath}catch{c=void 0,l=void 0}i={documentId:a.documentId,notebook:a.notebook,path:a.path,...l?{hPath:l}:{},...c?{name:c}:{},updatedBlockCount:0,sampleBlocks:[]},n.set(a.documentId,i)}i.updatedBlockCount+=1,i.sampleBlocks.length<3&&i.sampleBlocks.push(iT(s))}return{documents:[...n.values()],containsLowLevelBlocks:r}}function ya(e,t){const o=Array.isArray(e)?e[0]:e,n=o&&typeof o=="object"&&Array.isArray(o.doOperations)?o.doOperations[0]:void 0,r=typeof(n==null?void 0:n.id)=="string"?n.id:void 0,s=typeof(n==null?void 0:n.parentID)=="string"?n.parentID:t.parentID,a=typeof(n==null?void 0:n.previousID)=="string"?n.previousID:t.previousID,i=typeof(n==null?void 0:n.nextID)=="string"?n.nextID:t.nextID,c={action:t.action,...r?{id:r}:{},...s?{parentID:s}:{},...a?{previousID:a}:{},...i?{nextID:i}:{},dataType:t.dataType};for(const[l,u]of Object.entries(t))["action","dataType","parentID","previousID","nextID"].includes(l)||(c[l]=u);return xe(c)}function lT(e,t){const o={success:!0,id:t.id,dataType:t.dataType};for(const[n,r]of Object.entries(t))["id","dataType","data"].includes(n)||(o[n]=r);if(t.dataType==="markdown"&&(o.markdown=da(t.data)),Object.assign(o,er(t.data)),e&&typeof e=="object"&&!Array.isArray(e)){const n=e.updated;n!==void 0&&(o.updated=n)}return t.dataType==="markdown"&&/[\r\n]/.test(t.data)&&(o.warning="block(update) is best for single-block replacement. Multi-line markdown may be truncated to the first line by SiYuan; use block(append), block(prepend), or block(insert) when you need multiple blocks or tables."),k(o)}function uT(e){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:"block",action:"insert",message:'Invalid arguments for block(action="insert").',fields:[{path:`blocks[${e}].previousID`,message:"Provide nextID, previousID, or parentID for each block, or set a batch-level parentID/previousID/nextID."}]}},null,2)}],isError:!0}}async function dT(e,t,o){return Promise.all(t.map(async n=>({...n,data:await yt(e,n.dataType,n.data,"block.insert"),nextID:n.nextID??o.nextID,previousID:n.previousID??o.previousID,parentID:n.parentID??o.parentID})))}async function yt(e,t,o,n){return t==="dom"?tT(o,n):Qt(e,o,n)}async function pT(e,t){return Promise.all(t.map(async o=>({...o,data:await yt(e,o.dataType,o.data,"block.update")})))}function fT(e){const t=Array.isArray(e)?e:[e],o=[];for(const n of t){if(!n||typeof n!="object")continue;const r=n.doOperations;if(Array.isArray(r))for(const s of r){if(!s||typeof s!="object")continue;const a=s.id;typeof a=="string"&&a.length>0&&!o.includes(a)&&o.push(a)}}return o}function hT(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:"block",action:"insert",reason:"empty_transaction_result",message:`SiYuan accepted insert for ${e} block(s), but returned no created block IDs.`,hint:"Check that each item includes nextID, previousID, or parentID, or provide one batch-level parentID/previousID/nextID, then retry. MCP now rejects no-op insert responses instead of reporting success.",transactions:t}},null,2)}],isError:!0}}const mT=async({client:e,permMgr:t,rawArgs:o})=>{const n=md.parse(o);if(n.blocks){const c=await dT(e,n.blocks,{parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),l=new Set;for(const[f,h]of c.entries()){const g=h.nextID||h.previousID||h.parentID;if(!g)return uT(f);const{denied:b,context:_}=await N(e,t,g,"write");if(b)return b;l.add(_.documentId)}const u=await Pv(e,c),p=fT(u);return p.length===0?hT(c.length,u):F(e,k({success:!0,action:"insert",count:c.length,createdBlockIDs:p,transactions:u,...c.some(f=>ga(f.data))?er(c.map(f=>f.data).join(`
517
+ `)):{}}),[...l].map(f=>({type:"reloadProtyle",id:f})))}const r=n.nextID||n.previousID||n.parentID;let s;if(r){const{denied:c,context:l}=await N(e,t,r,"write");if(c)return c;s=l.documentId}const a=await yt(e,n.dataType,n.data,"block.insert"),i=await wv(e,n.dataType,a,n.nextID,n.previousID,n.parentID);return F(e,ya(i,Xn({action:"insert",dataType:n.dataType,parentID:n.parentID,previousID:n.previousID,nextID:n.nextID},a)),s?[{type:"reloadProtyle",id:s}]:[])},gT=async({client:e,permMgr:t,rawArgs:o})=>{const n=gd.parse(o),{denied:r,context:s}=await N(e,t,n.parentID,"write");if(r)return r;const a=await yt(e,n.dataType,n.data,"block.prepend"),i=await kv(e,n.dataType,a,n.parentID);return F(e,ya(i,Xn({action:"prepend",dataType:n.dataType,parentID:n.parentID},a)),[{type:"reloadProtyle",id:s.documentId}])},yT=async({client:e,permMgr:t,rawArgs:o})=>{const n=yd.parse(o),{denied:r,context:s}=await N(e,t,n.parentID,"write");if(r)return r;const a=await yt(e,n.dataType,n.data,"block.append"),i=await Mp(e,n.dataType,a,n.parentID);return F(e,ya(i,Xn({action:"append",dataType:n.dataType,parentID:n.parentID},a)),[{type:"reloadProtyle",id:s.documentId}])},bT=async({client:e,permMgr:t,rawArgs:o})=>{const n=bd.parse(o);if(n.items){const l=await pT(e,n.items),u=new Set,p=[];for(const h of l){const{denied:g,context:b}=await N(e,t,h.id,"write");if(g)return g;await Zr(e,h.id)==="av"&&p.push(h.id),u.add(b.documentId)}const f=await Cv(e,l);return F(e,k({success:!0,action:"update",count:n.items.length,transactions:f,...l.some(h=>ga(h.data))?er(l.map(h=>h.data).join(`
518
+ `)):{},...p.length>0?{databaseBlockIds:p,...Yr("block.update")}:{}}),[...u].map(h=>({type:"reloadProtyle",id:h})))}const{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a=await Zr(e,n.id)==="av",i=await yt(e,n.dataType,n.data,"block.update"),c=await sa(e,n.dataType,i,n.id);return F(e,lT(c,{id:n.id,dataType:n.dataType,data:i,...a?Yr("block.update"):{}}),[{type:"reloadProtyle",id:s.documentId}])},wT=async({client:e,permMgr:t,rawArgs:o})=>{const n=wd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a=Qp(await co(e,n.id)),i=typeof a.kramdown=="string"?a.kramdown:"",c=await Gn(e,n.id),l=typeof c.dom=="string"?c.dom:"",u=await vf(e,Array.isArray(n.edit)?n.edit:[n.edit],"block.replace"),{kramdown:p,markdown:f,dom:h,summary:g}=XD(i,l,u,"block.replace"),b=p!==i;if(b){const _=u.some(Hr);await sa(e,_?"markdown":"dom",_?f:h,n.id)}return F(e,k({success:!0,action:"replace",id:n.id,changed:b,editsApplied:g.length,replacements:g,...ga(p)?er(p):{}}),b?[{type:"reloadProtyle",id:s.documentId}]:[])},kT=async({client:e,permMgr:t,rawArgs:o})=>{const n=kd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"delete");if(r)return r;const a=await Zr(e,n.id)==="av";return await zp(e,n.id),F(e,k({success:!0,id:n.id,...a?Yr("block.delete"):{}}),[{type:"reloadProtyle",id:s.documentId}])},_T=async({client:e,permMgr:t,rawArgs:o})=>{const n=_d.parse(o),r=n.ids??[n.id],s=new Set;for(const u of r){const p=await N(e,t,u,"write");if(p.denied)return p.denied;s.add(p.context.documentId)}if(n.parentID){const u=await N(e,t,n.parentID,"write");if(u.denied)return u.denied}if(n.previousID){const u=await N(e,t,n.previousID,"write");if(u.denied)return u.denied}const a=[],i=[...r].reverse();for(const u of i)a.push(await _v(e,u,n.previousID,n.parentID));const c=n.ids?a:a[0],l=[...s].map(u=>({type:"reloadProtyle",id:u}));if(n.parentID){const u=await N(e,t,n.parentID,"write");if(u.denied)return u.denied;l.push({type:"reloadProtyle",id:u.context.documentId})}if(n.previousID){const u=await N(e,t,n.previousID,"write");if(u.denied)return u.denied;l.push({type:"reloadProtyle",id:u.context.documentId})}return F(e,xe({...n.ids?{ids:n.ids,finalOrder:n.ids,apiCallOrder:i,count:n.ids.length}:{id:n.id},...n.previousID?{previousID:n.previousID}:{},...n.parentID?{parentID:n.parentID}:{}},c),l)},vT=async({client:e,permMgr:t,rawArgs:o})=>{const n=vd.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");return r||(n.folded?await vv(e,n.id):await Iv(e,n.id),F(e,k({success:!0,id:n.id,folded:n.folded}),[{type:"reloadProtyle",id:s.documentId}]))},IT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Id.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=Qp(await co(e,n.id));return k(s)},ST=async({client:e,permMgr:t,rawArgs:o})=>{const n=Sd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Wn(e,n.id),a=Array.isArray(s)?s:[],i=ta(a,n.page??1,n.pageSize??50);return We(i.items,i,{...i.truncated?{hint:'Use page/pageSize to paginate. For focused reads, use block(action="get_kramdown") or search(action="query_sql") with a parent_id filter.'}:{}})},DT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Dd.parse(o),r=await N(e,t,n.fromID,"write");if(r.denied)return r.denied;const s=await N(e,t,n.toID,"write");return s.denied?s.denied:(await Sv(e,n.fromID,n.toID,n.refIDs),F(e,k({success:!0,fromID:n.fromID,toID:n.toID}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId}]))},TT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Td.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");return r||(await Oe(e,[{doOperations:[{action:"setAttrs",id:n.id,data:JSON.stringify(n.attrs)}],undoOperations:[]}]),F(e,k({success:!0,id:n.id,attrs:n.attrs}),[{type:"reloadProtyle",id:s.documentId}]))},AT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ad.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await qp(e,n.id);return k(s)},PT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Pd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Fp(e,n.id);return k(s)},CT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Cd.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Dv(e,n.id,n.excludeTypes);return k(s)},ET=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ed.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=await Gn(e,n.id);return k(s)},RT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Rd.parse(o),r=await Tv(e),s=Array.isArray(r)?r:[],a=await hn(e,s,t),i=typeof n.count=="number"?n.count:void 0,c=typeof i=="number"?a.items.slice(0,i):a.items,l=await cT(e,c);return k({documents:l.documents,documentCount:l.documents.length,count:c.length,containsLowLevelBlocks:l.containsLowLevelBlocks,grouping:"document",primaryView:"documents",items:c,hint:"documents is the user-facing summary grouped by root document; items remains the raw recent block stream for advanced consumers.",...a.removedCount>0?{partial:!0,filteredOutCount:a.removedCount,reason:"permission_filtered"}:{}})},xT=async({client:e,permMgr:t,rawArgs:o})=>{const n=xd.parse(o);for(const s of n.ids){const{denied:a}=await N(e,t,s,"read");if(a)return a}const r=await Av(e,n.ids);return k(r)},OT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Od.parse(o),r=await Y(t,n.notebook,"write");if(r)return r;const s=await yt(e,n.dataType,n.data,"block.add_to_daily_note"),a=n.position==="append"?await Ev(e,n.notebook,n.dataType,s):await Rv(e,n.notebook,n.dataType,s);return F(e,k({success:!0,action:"add_to_daily_note",notebook:n.notebook,dataType:n.dataType,position:n.position,transactions:a}),[{type:"reloadFiletree"}])},NT=async({client:e,permMgr:t,rawArgs:o})=>{const n=Nd.parse(o),r=n.ids??[n.id];for(const a of r){const{denied:i}=await N(e,t,a,"read");if(i)return i}const s=await xv(e,r,n.refCount??!1,n.av??!1);return k(s)},$T={insert:mT,prepend:gT,append:yT,update:bT,replace:wT,delete:kT,move:_T,set_fold_state:vT,get_kramdown:IT,get_children:ST,transfer_references:DT,set_attrs:TT,get_attrs:AT,info:PT,breadcrumb:CT,dom:ET,recent_updated:RT,word_count:xT,add_to_daily_note:OT,docs_info:NT},MT=[S("insert",md,"Insert one or more blocks at the specified position."),S("prepend",gd,"Insert a block at the beginning of a parent."),S("append",yd,"Insert a block at the end of a parent."),S("update",bd,"Update one or more blocks."),S("replace",wd,"Apply exact old/new text replacement edits inside one block body and patch the original DOM."),S("delete",kd,"Delete a block by ID."),S("move",_d,"Move a block to a new position."),S("set_fold_state",vd,"Set the fold state of a foldable block."),S("get_kramdown",Id,"Get block content in kramdown format."),S("get_children",Sd,"Get child blocks of a parent with pagination support."),S("transfer_references",Dd,"Transfer block references from one block to another."),S("set_attrs",Td,"Set block attributes."),S("get_attrs",Ad,"Get block attributes."),S("info",Pd,"Get block position and root document metadata."),S("breadcrumb",Cd,"Get the breadcrumb path for a block."),S("dom",Ed,"Get rendered DOM for a block."),S("recent_updated",Rd,"Get recently updated blocks."),S("word_count",xd,"Get word-count statistics for blocks."),S("add_to_daily_note",Od,"Add a block to today's daily note, creating the note if needed."),S("docs_info",Nd,"Get document info for one or more documents.")],If=De({name:"block",description:"🧱 Grouped block operations.",variants:MT,actionSchema:p_,aggregateOptions:{guidance:Gc,actionHints:al,propertyDescriptionOverrides:{parentID:"Parent block or document ID. With prepend/append, a document ID targets the document head or tail; a block ID targets that block's child list.",previousID:'Sibling block ID to position after. For block(action="move"), provide previousID, parentID, or both to describe the destination. Successful moves return a structured success object.'}},handlers:$T}),zT=If.listTools,FT=If.callTool,Sf="approx_context_v1";function Wr(e){return Math.ceil(Math.max(0,e)/4)}function Gr(e){const t=typeof e=="string"?e:"";return{chars:t.length,approxTokens:Wr(t.length)}}function qT(e){const t=(e??[]).map(o=>o.text??"").join("");return Gr(t)}const LT=50,BT=2e3,UT=new Set(["l","b","callout","s","t","table","tb","av","code","c","math","m","html","iframe","widget","query_embed"]);function jT(e){if(!e)return;const t=e.trim();if(!t)return;const o=t.toLowerCase();return o.startsWith("node")?o.includes("paragraph")?"p":o.includes("heading")?"h":o.includes("listitem")?"i":o.includes("list")?"l":o.includes("blockquote")?"b":o.includes("callout")?"callout":o.includes("superblock")?"s":o.includes("table")?"t":o.includes("codeblock")?"c":o.includes("mathblock")?"m":o.includes("attributeview")?"av":o.includes("htmlblock")?"html":o.includes("iframe")?"iframe":o.includes("widget")?"widget":o.includes("video")?"video":o.includes("audio")?"audio":o.includes("blockqueryembed")?"query_embed":o.includes("thematicbreak")?"tb":t:t}function HT(e){if(!e||typeof e!="object")return null;const t=e,o=typeof t.id=="string"?t.id:"";return o?{id:o,type:jT(typeof t.type=="string"?t.type:void 0),subtype:typeof t.subtype=="string"?t.subtype:void 0}:null}function VT(e){return!!(e.type&&UT.has(e.type))}async function Df(e,t,o,n){const r=await Wn(e,t);for(const s of r){const a=HT(s);a&&(n.has(a.id)||(n.add(a.id),o.push(a),VT(a)||await Df(e,a.id,o,n)))}}async function Zo(e,t){const o=[];return await Df(e,t,o,new Set([t])),o}function ZT(e,t){var r;const o=(r=e.subtype)==null?void 0:r.match(/^h([1-6])$/i);if(o)return Number(o[1]);const n=t.match(/^\s{0,3}(#{1,6})\s+/);return n==null?void 0:n[1].length}function YT(e){var n;const o=(e.split(/\r?\n/,1)[0]??"").match(/^\s{0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$/);return((n=o==null?void 0:o[1])==null?void 0:n.trim())||void 0}function WT(e,t,o){const n=[];return e.forEach((r,s)=>{if(r.type!=="h")return;const a=t[s]??"",i=ZT(r,a),c=YT(a);!i||!c||n.push({blockIndex:s,level:i,title:c,...o?{id:r.id}:{}})}),n}function Tf(e,t,o){const n=o.blockStart??0,r=o.blockLimit??LT,s=o.tokenBudget??BT,a=o.includeBlockIds??!1,i=e.length,c=[],l=[];let u=0,p=0;if(n<i){const b=Math.min(i,n+r);for(let _=n;_<b;_+=1){const w=t[_]??"",P=w.length>0&&c.length>0?2:0,D=p+P+w.length,A=Wr(D)>s;if(w.length>0&&A&&c.length>0)break;if(u+=1,a){const T=e[_];l.push({blockIndex:_,id:T.id,...T.type?{type:T.type}:{},...T.subtype?{subtype:T.subtype}:{}})}w.length>0&&(c.push(w),p=D)}}const f=Wr(p),h=n+u,g=h<i;return{content:c.join(`
519
+
520
+ `),outline:WT(e,t,a),blockStart:n,blockLimit:r,returnedBlocks:u,totalBlocks:i,tokenBudget:s,estimatedTokens:f,tokenMode:Sf,truncated:g,hasNextWindow:g,...g?{nextBlockStart:h}:{},...f>s?{budgetExceeded:!0}:{},...a?{blockRefs:l}:{}}}function GT(e){const t=[];let o=null;for(const n of e.split(/\r?\n/)){const r=n.match(/^\s{0,3}(`{3,}|~{3,})/);if(r){const a=r[1][0];o?a===o.marker&&r[1].length>=o.length&&(o=null):o={marker:a,length:r[1].length};continue}if(o)continue;const s=n.match(/^\s{0,3}(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);s&&t.push({blockIndex:0,level:s[1].length,title:s[2].trim()})}return t}function Gi(e,t={}){const o=e.length>0?[{id:"synthetic",type:"p"}]:[];return{...Tf(o,e.length>0?[e]:[],{...t,includeBlockIds:!1}),outline:GT(e)}}async function Af(e,t,o={},n){const r=n??await Zo(e,t),s=await Promise.all(r.map(async a=>{const i=await co(e,a.id);return ma({kramdown:typeof i.kramdown=="string"?i.kramdown:"",type:a.type})}));return Tf(r,s,o)}const _r=[120,240],KT=["path","hpath"];function JT(e){return e==="/"||/\.sy(?:\/|$)/.test(e)}async function Pf(e,t,o){await Oe(e,[{doOperations:[{action:"setAttrs",id:t,data:JSON.stringify(o)}],undoOperations:[]}])}function QT(e){return e instanceof Error&&/SiYuan API error:\s*-1\s*-\s*indexing/i.test(e.message)}async function Cf(e,t){let o;for(let r=0;r<=_r.length;r+=1)try{return await Kn(e,t)}catch(s){if(!QT(s)||r===_r.length){o=s;break}o=s,await Vo(_r[r])}const n=o instanceof Error?o.message:String(o);throw new Error(`Failed to resolve hierarchical path for document "${t}" because SiYuan indexing is still catching up. Retry shortly after create. Last error: ${n}`)}function an(e){const t=typeof e.path=="object"?e.path.notebook:e.notebook,o=typeof e.path=="object"?e.path.path:e.path;return{humanPath:{notebookName:e.notebookName??e.notebook,hPath:e.hPath},idPath:{id:e.id,ids:e.ids,notebook:t,path:o}}}function XT(e){const t=e.trim();if(!t)throw new Error("Cover source must not be empty.");const o=/^https?:\/\//i.test(t),n=t.startsWith("/assets/");if(!o&&!n)throw new Error("Cover source must be an http(s) URL or a SiYuan asset path starting with /assets/.");const r=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return{source:t,titleImg:`background-image:url("${r}");`}}function eA(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function tA(e){return e.split("/").filter(Boolean).at(-1)}function oA(e){return/(?:^|\/)\d{14}-[a-z0-9]{7}\.sy$/i.test(e)}async function vr(e,t,o){const n=await jp(e,o,t);return n.length>0?n:(await st(e,["SELECT id FROM blocks",`WHERE box = '${we(t)}'`,`AND hpath = '${we(o)}'`,"AND type = 'd'","ORDER BY updated DESC"].join(" "))).map(s=>s&&typeof s=="object"?s.id:void 0).filter(s=>typeof s=="string"&&s.length>0)}async function nA(e,t,o){const n=o==="/"?"/":o.replace(/\/+$/,"");return oA(n)?aa(e,t,n):n}function Kr(e,t,o=0){return Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object")return n;const r=n;if(o>=t&&Array.isArray(r.children)&&r.children.length>0){const{children:s,...a}=r;return{...a,childCount:s.length,childrenTruncated:!0}}return Array.isArray(r.children)?{...r,children:Kr(r.children,t,o+1)}:r}):e}async function Jr(e,t,o=new Map){return Array.isArray(t)?Promise.all(t.map(async n=>{if(!n||typeof n!="object")return n;const r=n,s={...r},a=typeof r.id=="string"?r.id:void 0;if(a&&(r.name===void 0||r.icon===void 0))try{let i=o.get(a);i||(i=Ct(e,a),o.set(a,i));const c=await i;s.name===void 0&&c.name&&(s.name=c.name.replace(/\.sy$/,"")),s.icon===void 0&&c.icon&&(s.icon=c.icon)}catch{}return Array.isArray(r.children)&&(s.children=await Jr(e,r.children,o)),s})):t}function rA(e,t){if(Array.isArray(e))return mn({backmentions:e},t).backmentions;if(!e||typeof e!="object")return e;const o=e;return Array.isArray(o.files)?{...o,files:mn({backmentions:o.files},t).backmentions}:Array.isArray(o.docs)?{...o,docs:mn({backmentions:o.docs},t).backmentions}:e}async function sA(e,t,o,n){if(Array.isArray(t)){const s=await br(e,t,o,n);return{data:s.items,permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}if(!t||typeof t!="object")return{data:t,permissionFilteredOutCount:0,pathFilteredOutCount:0};const r=t;if(Array.isArray(r.files)){const s=await br(e,r.files,o,n);return{data:{...r,files:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}if(Array.isArray(r.docs)){const s=await br(e,r.docs,o,n);return{data:{...r,docs:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}return{data:rA(t,o),permissionFilteredOutCount:0,pathFilteredOutCount:0}}const aA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Hu.parse(o);if(await t.reload(),!t.canWrite(n.notebook))return na(n.notebook,t.get(n.notebook),"write");const r=n.parentPath?await nA(e,n.notebook,n.parentPath):void 0,s=n.path??eA(r,n.title),a=await Qt(e,_f(n.markdown??"",n.title??tA(s)),"document.create"),i=await Lp(e,n.notebook,s,a);return n.icon&&await Pf(e,i,{icon:n.icon}),F(e,k({success:!0,notebook:n.notebook,path:s,...Gt(a)?$o():{},...Kt(a)?Mo():{},...Jt(a)?zo():{},...n.parentPath?{parentPath:n.parentPath}:{},...r&&r!==n.parentPath?{resolvedParentPath:r}:{},...n.title?{title:n.title}:{},id:i,iconHint:oa("document",!!n.icon)}),n.icon?[{type:"reloadIcon"}]:[{type:"reloadProtyle",id:i},{type:"reloadFiletree"}])},iA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Vu.parse(o),r=n.hpath??n.hPath,s=new Set(n.include??KT),a={source:n.id?{id:n.id}:n.path?{notebook:n.notebook,path:n.path}:{notebook:n.notebook}};if(n.id){const{denied:p,context:f}=await N(e,t,n.id,"read");if(p)return p;a.id=n.id,a.notebook=f.notebook,a.path=f.path,s.has("path")&&(a.path=await ko(e,n.id)),a.hPath=await Cf(e,n.id),s.has("docInfo")&&(a.docInfo=await Ct(e,n.id));const h=await Lr(e,f.notebook);return h&&(a.notebookName=h),k(an(a))}const i=await Y(t,n.notebook,"read");if(i)return i;const c=await Lr(e,n.notebook);if(n.path){if(a.notebook=n.notebook,c&&(a.notebookName=c),a.path=n.path,!JT(n.path)){const f=await vr(e,n.notebook,n.path),h=f[0];return a.source={type:"hpath",notebook:n.notebook,hPath:n.path,providedAs:"path"},a.hPath=n.path,a.interpretedPathAs="hpath",a.hint="document.lookup path expects a storage path such as /20240318112233-abc123.sy. Human-readable paths should be passed as hpath; this call was interpreted as hpath for compatibility.",(s.has("ids")||s.has("id"))&&(a.ids=f,s.has("id")&&(a.id=h)),h&&(a.path=await ko(e,h)),h&&s.has("docInfo")&&(a.docInfo=await Ct(e,h)),k(an(a))}const p=await aa(e,n.notebook,n.path);if(a.hPath=p,s.has("id")||s.has("ids")){const f=await vr(e,n.notebook,p??n.path);a.ids=f,s.has("id")&&(a.id=f[0])}return s.has("docInfo")&&typeof a.id=="string"&&(a.docInfo=await Ct(e,a.id)),k(an(a))}const l=await vr(e,n.notebook,r);a.notebook=n.notebook,c&&(a.notebookName=c),a.hPath=r,(s.has("ids")||s.has("id"))&&(a.ids=l,s.has("id")&&(a.id=l[0]));const u=l[0];if(u){const{denied:p}=await N(e,t,u,"read");if(p)return p;a.path=await ko(e,u)}if(u&&s.has("docInfo")){const{denied:p}=await N(e,t,u,"read");if(p)return p;a.docInfo=await Ct(e,u)}return k(an(a))},cA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Zu.parse(o);if(n.id){const{denied:r,context:s}=await N(e,t,n.id,"write");return r||(await Bp(e,n.id,n.title),F(e,k({success:!0,id:n.id,title:n.title}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await Y(t,n.notebook,"write");if(r)return r}return await jv(e,n.notebook,n.path,n.title),F(e,k({success:!0,notebook:n.notebook,path:n.path,title:n.title}),[{type:"reloadFiletree"}])},lA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Yu.parse(o);if(n.ids){const r=[];for(const s of n.ids){const{denied:a,context:i}=await N(e,t,s,"delete");if(a)return a;r.push(i.documentId)}for(const s of n.ids)await Fr(e,s);return F(e,k({success:!0,ids:n.ids,count:n.ids.length}),[...r.map(s=>({type:"reloadProtyle",id:s})),{type:"reloadFiletree"}])}if(n.paths){for(const r of n.paths){const s=await No(e,r);if(!s)throw new Error(`Unable to resolve notebook for storage path "${r}" while checking permissions.`);const a=await Y(t,s,"delete");if(a)return a}return await Jv(e,n.paths),F(e,k({success:!0,paths:n.paths,count:n.paths.length}),[{type:"reloadFiletree"}])}if(n.id){const{denied:r,context:s}=await N(e,t,n.id,"delete");return r||(await Fr(e,n.id),F(e,k({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await Y(t,n.notebook,"delete");if(r)return r}return await Hv(e,n.notebook,n.path),F(e,k({success:!0,notebook:n.notebook,path:n.path}),[{type:"reloadFiletree"}])},uA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Wu.parse(o);if(n.toNotebook){const r=await Y(t,n.toNotebook,"write");if(r)return r}if(n.toID){const r=await hI(e,n.toID),s=await Y(t,r,"write");if(s)return s}if(n.fromIDs){const r=[];for(const s of n.fromIDs){const{denied:a,context:i}=await N(e,t,s,"write");if(a)return a;r.push(i.documentId)}return await Up(e,n.fromIDs,n.toID),F(e,k({success:!0,fromIDs:n.fromIDs,toID:n.toID}),[...r.map(s=>({type:"reloadProtyle",id:s})),{type:"reloadFiletree"}])}for(const r of n.fromPaths){const s=await No(e,r);if(!s)throw new Error(`Unable to resolve source notebook for storage path "${r}" while checking permissions.`);const a=await Y(t,s,"write");if(a)return a}return await Vv(e,n.fromPaths,n.toNotebook,n.toPath),F(e,k({success:!0,fromPaths:n.fromPaths,toNotebook:n.toNotebook,toPath:n.toPath}),[{type:"reloadFiletree"}])},dA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Gu.parse(o),{denied:r,context:s}=await N(e,t,n.id,"read");if(r)return r;const a=await Wn(e,s.documentId);return k(a)},pA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ku.parse(o),{denied:r,context:s}=await N(e,t,n.id,"read");if(r)return r;const a=await Jn(e,s.notebook,s.path);return k(a)},fA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ju.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a={},i={success:!0,id:n.id},c=[];if(n.attrs.icon!==void 0&&(a.icon=n.attrs.icon,i.icon=n.attrs.icon,c.push({type:"reloadIcon"},{type:"reloadFiletree"})),n.attrs.cover!==void 0){const l=n.attrs.cover;if(!l)a["title-img"]="",i.clearedCover=!0;else{const u=XT(l);a["title-img"]=u.titleImg,i.cover=u.source,i.titleImg=u.titleImg}c.push({type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"})}return await Pf(e,n.id,a),F(e,k(i),c)},hA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Qu.parse(o),r=await Y(t,n.notebook,"read");if(r)return r;const s=n.maxDepth??3,a=await $t(e,n.notebook,n.path),i='Use maxDepth to control tree depth. Use document(action="list_tree") with a deeper path to expand specific subtrees.';if(a&&typeof a=="object"&&Array.isArray(a.tree)){const l=await Jr(e,a.tree);return k({...a,tree:Kr(l,s),maxDepth:s,depthHint:i})}const c=await Jr(e,a);return k({tree:Kr(c,s),maxDepth:s,depthHint:i})},mA=async({client:e,permMgr:t,rawArgs:o})=>{const n=Xu.parse(o),r=await Y(t,n.notebook,"read");if(r)return r;const s=await Yv(e,n.query),a=await sA(e,s,t,n.path),i=a.permissionFilteredOutCount+a.pathFilteredOutCount;return k({...a.data&&typeof a.data=="object"&&!Array.isArray(a.data)?a.data:{docs:a.data},...n.path?{path:n.path,pathApplied:!0}:{},...a.permissionFilteredOutCount>0?{partial:!0,reason:"permission_filtered"}:{},...i>0?{filteredOutCount:i}:{},...a.pathFilteredOutCount>0?{pathFilteredOutCount:a.pathFilteredOutCount}:{}})},gA=async({client:e,permMgr:t,rawArgs:o})=>{const n=ed.parse(o),{denied:r,context:s}=await N(e,t,n.id,"read");if(r)return r;const a=await Lr(e,s.notebook);if(n.mode==="html"){const p=await Wv(e,n.id,0,n.size);return k({id:n.id,mode:"html",notebook:s.notebook,...a?{notebookName:a}:{},...p&&typeof p=="object"?p:{content:p}})}const i=await Af(e,n.id,{blockStart:n.blockStart,blockLimit:n.blockLimit,tokenBudget:n.tokenBudget,includeBlockIds:n.includeBlockIds}),{nextBlockStart:c,...l}=i,u=c===void 0?void 0:{action:"get_doc",id:n.id,mode:"markdown",blockStart:c,blockLimit:i.blockLimit,tokenBudget:i.tokenBudget,...n.includeBlockIds?{includeBlockIds:!0}:{}};return k({id:n.id,mode:"markdown",notebook:s.notebook,...a?{notebookName:a}:{},hPath:await Cf(e,n.id),...l,...u?{nextWindow:u,nextWindowHint:`Continue with document(${JSON.stringify(u)}).`}:{}})},yA=async({client:e,permMgr:t,rawArgs:o})=>{const n=td.parse(o),r=await Y(t,n.notebook,"write");if(r)return r;const s=await Gv(e,n.notebook,n.app);let a;try{a=await Kn(e,s.id)}catch{a=void 0}return F(e,k({success:!0,notebook:n.notebook,...s,...a?{hPath:a}:{},iconHint:oa("document")}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}])},bA=async({client:e,permMgr:t,rawArgs:o})=>{const n=od.parse(o),{denied:r,context:s}=await N(e,t,n.id,"write");if(r)return r;const a=await Kv(e,n.id);return F(e,k({success:!0,sourceID:n.id,...a}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}])},wA=async({client:e,permMgr:t,rawArgs:o})=>{const n=nd.parse(o),r=await N(e,t,n.headingID,"write");if(r.denied)return r.denied;const s=await Y(t,n.targetNotebook,"write");return s||(await Qv(e,n.headingID,n.targetNotebook,n.targetPath,n.previousPath),F(e,k({success:!0,headingID:n.headingID,targetNotebook:n.targetNotebook,...n.targetPath?{targetPath:n.targetPath}:{},...n.previousPath?{previousPath:n.previousPath}:{}}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadFiletree"}]))},kA=async({client:e,permMgr:t,rawArgs:o})=>{const n=rd.parse(o),r=await N(e,t,n.srcID,"write");if(r.denied)return r.denied;const s=await N(e,t,n.targetID,"write");if(s.denied)return s.denied;const a=await Xv(e,n.srcID,n.targetID,n.after??!1);return F(e,k({success:!0,srcID:n.srcID,targetID:n.targetID,after:n.after??!1,...a}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId},{type:"reloadFiletree"}])},_A={create:aA,lookup:iA,rename:cA,remove:lA,move:uA,get_child_blocks:dA,get_child_docs:pA,set_attr:fA,list_tree:hA,search_docs:mA,get_doc:gA,create_daily_note:yA,duplicate:bA,heading_to_doc:wA,doc_to_heading:kA},vA=[S("create",Hu,"Create a new document. Prefer path for child documents; parentPath + title also accepts a human-readable parent path or a storage path ending in .sy."),S("lookup",Vu,"Look up document IDs, storage paths, human-readable paths, and document metadata from one document reference."),S("rename",Zu,"Rename a document"),S("remove",Yu,"Delete a document"),S("move",Wu,"Move a document to another location"),S("get_child_blocks",Gu,"Get top-level blocks of a document"),S("get_child_docs",Ku,"Get child documents"),S("set_attr",Ju,"Set document metadata such as icon and cover image."),S("list_tree",Qu,"Get document tree"),S("search_docs",Xu,"Search documents by title"),S("get_doc",ed,"Read document Markdown in complete block windows, or return the current HTML view."),S("create_daily_note",td,"Create or open today's daily note"),S("duplicate",od,"Duplicate a document"),S("heading_to_doc",nd,"Convert a heading to a separate document"),S("doc_to_heading",rd,"Merge a document into another as a heading")],Ef=De({name:"document",description:"📝 Grouped document operations.",variants:vA,actionSchema:d_,aggregateOptions:{guidance:Wc,actionHints:sl,propertyDescriptionOverrides:{path:'Path value. For action="create", use a human-readable target path such as /Inbox/Weekly Note. For action="lookup" and path-based rename/remove/move, use a storage path returned by document(action="lookup", id=..., include=["path"]); use hpath for human-readable lookup.',parentPath:'Parent path for title-based creation. Accepts a human-readable parent path such as /Inbox or a storage path ending in .sy returned by document(action="lookup").',fromPaths:'Source storage paths returned by document(action="lookup").',toPath:'Target storage path. Use the storage path of an existing destination document returned by document(action="lookup").'}},handlers:_A});function IA(e){return Ef.listTools(e)}async function SA(e,t,o,n){return Ef.callTool(e,t,o,n)}async function DA(e,t,o,n){const r=new FormData,s=new File([o],n);return r.append("assetsDirPath",t),r.append("file[]",s,n),e.requestFormData("/api/asset/upload",r)}async function ba(e,t){const o={id:t};return e.request("/api/export/exportMdContent",o)}async function TA(e,t,o){const n={paths:t,name:o};return e.request("/api/export/exportResources",n)}async function AA(e){return e.request("/api/asset/getUnusedAssets",{})}async function PA(e,t){return e.request("/api/asset/getDocAssets",{id:t})}async function CA(e,t){return e.request("/api/asset/getDocImageAssets",{id:t})}async function EA(e,t){return e.request("/api/asset/getImageOCRText",t?{path:t}:{})}async function RA(e){return e.request("/api/asset/removeUnusedAssets",{})}async function xA(e,t,o){return e.request("/api/asset/renameAsset",{oldPath:t,newName:o})}async function OA(e,t){return e.request("/api/asset/deleteAsset",{path:t})}function kt(e){const t=new Error(e);return t.reason="invalid_template_path",t}function NA(e){const t=e.trim();if(!t)throw kt("Template path is required.");if(/[\0?#]/.test(t))throw kt("Template path must not contain null bytes, query strings, or hash fragments.");const o=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/"),n=o.toLowerCase(),r="/data/templates/",s=n.lastIndexOf(r);let a;if(s>=0)a=o.slice(s+r.length);else{const c=o.replace(/^\/+/,""),l=c.toLowerCase();if(l.startsWith("data/templates/"))a=c.slice(15);else if(l.startsWith("templates/"))a=c.slice(10);else{if(/^[a-z]:\//i.test(o))throw kt("Template path must be inside data/templates; arbitrary drive paths are not allowed.");if(!o.startsWith("/"))a=c;else throw kt("Template path must be inside data/templates or use the /templates/ static route.")}}a=a.replace(/^\/+/,"").replace(/\/{2,}/g,"/");const i=a.split("/");if(i.length===0||i.some(c=>!c||c==="."||c==="..")||a.startsWith("../")||a.includes("/../")||a.includes(":"))throw kt("Template path must not traverse directories.");if(!a.toLowerCase().endsWith(".md"))throw kt("Template source reading only supports Markdown .md files.");return a}function Yo(e){const t=NA(e),o=`/templates/${t.split("/").map(encodeURIComponent).join("/")}`;return{path:e.trim().replace(/\\/g,"/"),relativePath:t,staticPath:o,workspacePath:`/data/templates/${t}`}}function pt(e,t){const o=new Error(e);return o.reason=t,o}function $A(e){const t=e.trim().replace(/\.md$/i,"");if(!t)throw pt("Template name is required.","invalid_template_name");if(/[\0?#/\\:]/.test(t)||t==="."||t==="..")throw pt("Template name must be a root template name without slashes, drive markers, query strings, or hash fragments.","invalid_template_name");return t}function MA(e){return e.replace(/\.md$/i,"")}function zA(e){try{const t=Yo(e.path);return{path:e.path,content:e.content,relativePath:t.relativePath}}catch{return null}}async function Rf(e,t=""){const o={k:t},n=await e.request("/api/search/searchTemplate",o);return{templates:Array.isArray(n==null?void 0:n.templates)?n.templates:[],k:typeof(n==null?void 0:n.k)=="string"?n.k:t}}async function Wo(e,t){const o=Yo(t),n=[...new Set([MA(o.relativePath),""])];for(const r of n){const a=(await Rf(e,r)).templates.map(zA).find(i=>!!i&&i.relativePath===o.relativePath);if(a)return a}throw pt(`Template not found: ${o.relativePath}`,"template_not_found")}async function FA(e,t,o,n){const r={id:t,path:o,...n!==void 0?{preview:n}:{}};return e.request("/api/template/render",r)}async function qA(e,t){const o={template:t};return e.request("/api/template/renderSprig",o)}async function xf(e,t,o){const n=Yo(t);try{await e.writeFile(n.workspacePath,o)}catch(r){const s=r instanceof Error?r.message:String(r);throw pt(`Failed to write template [${n.relativePath}]: ${s}`,"template_write_failed")}return{path:n.workspacePath,relativePath:n.relativePath,totalChars:o.length}}async function LA(e,t){const o=await Wo(e,t);try{await e.request("/api/search/removeTemplate",{path:o.path})}catch(n){const r=n instanceof Error?n.message:String(n);throw pt(`Failed to delete template [${o.relativePath}]: ${r}`,"template_delete_failed")}return{path:o.path,relativePath:o.relativePath}}async function BA(e,t,o,n=!1){const r=$A(o),s={id:t,name:r,overwrite:n};try{await e.request("/api/template/docSaveAsTemplate",s)}catch(a){const i=a instanceof Error?a.message:String(a);throw/SiYuan API error:\s*1\b/.test(i)?pt(`Template already exists: ${r}.md`,"template_exists"):pt(`Failed to save document as template [${r}]: ${i}`,"template_write_failed")}return{id:t,name:r,relativePath:`${r}.md`}}async function UA(e,t){const o=Yo(t),n=await fetch(`${e.getBaseUrl()}${o.staticPath}`,{method:"GET",headers:e.getAuthHeaders()});if(!n.ok){const r=`Failed to read template source [${o.relativePath}]: HTTP ${n.status} ${n.statusText}`,s=new Error(r);throw s.reason=n.status===404?"template_not_found":"template_source_unavailable",s}return{path:o.path,relativePath:o.relativePath,markdown:await n.text()}}const jA="file",Qr=10;function HA(e){const t=e.trim().replace(/\\/g,"/");if(!t)return"";const o=t.replace(/^\/+/,""),n=o.startsWith("data/")?o:o.startsWith("assets/")?`data/${o}`:o;return(n.startsWith("/")?n:`/${n}`).replace(/\/{2,}/g,"/")}function VA(e){return[...new Set(e.map(HA).filter(Boolean))]}function ZA(e){return U.isAbsolute(e)?e:U.resolve(process.cwd(),e)}function YA(e){return U.isAbsolute(e)?e:U.resolve(process.cwd(),e)}function WA(e){return e instanceof Error&&/is not in workspace/i.test(e.message)}function Be(e,t,o,n,r){const s=t instanceof Error?t.message:String(t);return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:jA,action:e,message:s,reason:o,...r??{},hint:n}},null,2)}],isError:!0}}function ot(e){return e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"?e.reason:"template_source_unavailable"}function GA(e){return ot(e)==="template_not_found"}function Of(e){return U.basename(e).replace(/\.md$/i,"")}function KA(e){const t=Yo(e.path);return{path:e.path,relativePath:t.relativePath,name:Of(t.relativePath),content:e.content,readArgs:{action:"read_template",path:e.path},renderArgsTemplate:{action:"render",engine:"template",id:"<doc-id>",path:e.path}}}function Xr(e,t,o){return{path:e,relativePath:t,name:Of(t),...typeof o=="number"?{totalChars:o}:{},readArgs:{action:"read_template",path:e},renderArgsTemplate:{action:"render",engine:"template",id:"<doc-id>",path:e}}}async function Nf(e,t,o,n){try{const r=await Wo(e,t);return Xr(r.path,r.relativePath,n)}catch{return Xr(o,t,n)}}const JA=(e,t)=>async({client:o,rawArgs:n})=>{const r=Gd.parse(n),s=YA(r.localFilePath);if(!H.existsSync(s))throw new Error(`Local file does not exist: ${s}`);const a=H.statSync(s);if(!a.isFile())throw new Error(`Local file path must point to a regular file: ${s}`);if(a.size>t&&r.confirmLargeFile!==!0)return k({success:!1,requiresConfirmation:!0,reason:"file_too_large",localFilePath:s,fileSizeBytes:a.size,thresholdBytes:t,thresholdMB:e,message:`File exceeds the large-upload safety threshold (${e} MB). Stop the current operation and ask the user for explicit confirmation before retrying with confirmLargeFile=true.`});const i=U.basename(s),c=H.readFileSync(s),l=await DA(o,r.assetsDirPath,c,i);return k({...l,localFilePath:s,uploadedFileName:i,...a.size>t?{largeFileConfirmed:!0}:{}})},QA=async({client:e,permMgr:t,rawArgs:o})=>{const n=op.parse(o);if(n.engine==="sprig"){const s=await qA(e,n.template);return k(s)}const{denied:r}=await N(e,t,n.id,"read");if(r)return r;try{const s=await FA(e,n.id,n.path,n.preview);return k(s)}catch(s){if(WA(s))return Be("render",s,"path_not_in_workspace",'The template path must point to a file inside the SiYuan workspace, not an arbitrary local path such as /tmp/... or your repo checkout. Use file(action="list_templates") to resolve a valid template path.',{workspacePathRequired:!0});throw s}},XA=async({client:e,rawArgs:t})=>{const o=Kd.parse(t),n=o.query??"",r=await Rf(e,n),s=(Array.isArray(r.templates)?r.templates:[]).map(KA),a=ta(s,o.page??1,o.pageSize??20);return We(a.items,a,{query:r.k,showing:a.showing,truncated:a.truncated})},e0=async({client:e,rawArgs:t})=>{const o=Jd.parse(t);try{const n=await UA(e,o.path),r=n.markdown.length,s=o.offset??0,a=o.limit??8e3,i=n.markdown.slice(s,s+a),c=s+i.length,l=c<r;return k({path:n.path,relativePath:n.relativePath,markdown:i,totalChars:r,offset:s,limit:a,truncated:l,...l?{nextOffset:c}:{}})}catch(n){return Be("read_template",n,ot(n),'Use file(action="list_templates") to resolve a valid Markdown template path. If you only need rendered output, use file(action="render", engine="template").')}},t0=async({client:e,rawArgs:t})=>{const o=Qd.parse(t);if(o.overwrite!==!0)try{const n=await Wo(e,o.path);return Be("create_template",new Error(`Template already exists: ${n.relativePath}`),"template_exists","Pass overwrite=true to replace the existing template, or choose a different template path.",{path:n.path,relativePath:n.relativePath})}catch(n){if(!GA(n))return Be("create_template",n,ot(n),'Use a Markdown template path under data/templates, such as "reports/monthly.md".')}try{const n=await xf(e,o.path,o.markdown),r=await Nf(e,n.relativePath,n.path,n.totalChars);return k({success:!0,...r})}catch(n){return Be("create_template",n,ot(n),'Use a Markdown template path under data/templates, such as "reports/monthly.md".')}},o0=async({client:e,rawArgs:t})=>{const o=Xd.parse(t);let n;try{n=await Wo(e,o.path)}catch(r){return Be("update_template",r,ot(r),'Use file(action="list_templates") to resolve an existing Markdown template before updating it.')}try{const r=await xf(e,n.relativePath,o.markdown),s=await Nf(e,r.relativePath,n.path,r.totalChars);return k({success:!0,...s})}catch(r){return Be("update_template",r,ot(r),"The template was found, but writing the replacement Markdown failed.")}},n0=async({client:e,rawArgs:t})=>{const o=ep.parse(t);try{const n=await LA(e,o.path);return k({success:!0,...n})}catch(n){return Be("delete_template",n,ot(n),'Use file(action="list_templates") to resolve an existing Markdown template before deleting it.')}},r0=async({client:e,permMgr:t,rawArgs:o})=>{const n=tp.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;try{const s=await BA(e,n.id,n.name,n.overwrite??!1);let a;try{const i=await Wo(e,s.relativePath);a=Xr(i.path,i.relativePath)}catch{a=void 0}return k({success:!0,id:s.id,name:s.name,...a?{template:a}:{}})}catch(s){return Be("save_doc_as_template",s,ot(s),"Use a root-level template name without slashes. Pass overwrite=true to replace an existing template.")}},s0=async({client:e,permMgr:t,rawArgs:o})=>{const n=np.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=Jp(await ba(e,n.id));return k(s)},a0=async({client:e,rawArgs:t})=>{const o=rp.parse(t),n=VA(o.paths);if(n.length===0)throw new Error("export_resources requires at least one non-empty resource path.");let r;try{r=await TA(e,n,o.name)}catch(s){const a=s instanceof Error?s.message:String(s);throw new Error(`Failed to export resources. original_paths=${JSON.stringify(o.paths)} normalized_paths=${JSON.stringify(n)} cause=${a}`)}if(o.outputPath){const s=ZA(o.outputPath),a=await e.readFileBinary(r.path);return H.mkdirSync(U.dirname(s),{recursive:!0}),H.writeFileSync(s,a),k({...r,outputPath:s,bytes:a.byteLength})}return k(r)},i0=async({client:e,rawArgs:t})=>{sp.parse(t);const o=await AA(e);return k({assets:o,count:Array.isArray(o)?o.length:void 0})},c0=async({client:e,permMgr:t,rawArgs:o})=>{const n=ap.parse(o),{denied:r}=await N(e,t,n.id,"read");if(r)return r;const s=n.assetType==="image"?await CA(e,n.id):await PA(e,n.id);return k({id:n.id,assetType:n.assetType??"all",assets:s,count:Array.isArray(s)?s.length:void 0})},l0=async({client:e,rawArgs:t})=>{const o=ip.parse(t),n=await EA(e,o.path);return k({path:o.path??null,...n})},u0=async({client:e,rawArgs:t})=>{cp.parse(t);const o=await RA(e);return k({success:!0,...o&&typeof o=="object"&&!Array.isArray(o)?o:{result:o}})},d0=async({client:e,rawArgs:t})=>{const o=lp.parse(t),n=await xA(e,o.oldPath,o.newName);return k({success:!0,oldPath:o.oldPath,newName:o.newName,...n})},p0=async({client:e,rawArgs:t})=>{const o=up.parse(t),n=await OA(e,o.path);return k({success:!0,path:o.path,...n&&typeof n=="object"&&!Array.isArray(n)?n:{}})},f0=async({client:e,rawArgs:t})=>{var D;const o=dp.parse(t),n=await ba(e,o.id),r=typeof n.content=="string"?n.content:"",a=((D=(typeof n.hPath=="string"?n.hPath:"").split("/").filter(Boolean).pop())==null?void 0:D.replace(/\.sy$/,""))||o.id,i=o.id.slice(-7),c=`${a}-${i}`,l=process.env.USERPROFILE||process.env.HOME||"",u=o.outputDir?U.resolve(o.outputDir):U.join(l,"siyuan-extracted"),p=!o.outputDir,f=U.join(u,c),h=U.join(f,"assets");H.existsSync(u)&&H.rmSync(u,{recursive:!0,force:!0}),H.mkdirSync(h,{recursive:!0});const g=U.join(f,`${a}.md`);H.writeFileSync(g,r,"utf-8");const b=[...r.matchAll(/\]\(assets\/([^\s)"']+)(?:\s+"[^"]*")?\)/g)],_=[`${a}.md`];let w=0,P=0;for(const A of b){const T=A[1],O=U.join(h,T);try{H.mkdirSync(U.dirname(O),{recursive:!0});const E=await e.readFileBinary(`data/assets/${T}`);H.writeFileSync(O,E),_.push(`assets/${T}`),w++}catch{P++}}return k({outputRoot:u,defaultOutputDirUsed:p,extractedDir:f,docMdFile:`${a}.md`,extractedAssetCount:w,skippedAssetCount:P,structure:_,hint:p?"No outputDir was provided, so extract_doc used the default ~/siyuan-extracted/ output root. Pass outputDir explicitly when you need a specific location such as /private/tmp.":"extract_doc wrote to the explicit outputDir root."})};function h0(e,t){return{upload_asset:JA(e,t),list_templates:XA,read_template:e0,create_template:t0,update_template:o0,delete_template:n0,save_doc_as_template:r0,render:QA,export_md:s0,export_resources:a0,list_unused_assets:i0,get_doc_assets:c0,get_image_ocr_text:l0,remove_unused_assets:u0,rename_asset:d0,delete_asset:p0,extract_doc:f0}}const m0=[S("upload_asset",Gd,"Read a local file and upload it to the specified assets directory."),S("list_templates",Kd,"List or search SiYuan workspace templates available under data/templates."),S("read_template",Jd,"Read a Markdown template source through SiYuan’s authenticated template route."),S("create_template",Qd,"Create a Markdown template under data/templates through SiYuan’s workspace file API."),S("update_template",Xd,"Replace an existing Markdown template under data/templates."),S("delete_template",ep,"Delete an existing Markdown template under data/templates."),S("save_doc_as_template",tp,"Save an existing SiYuan document as a root-level template."),S("render",op,"Render a SiYuan workspace template (.action{.title}) or an inline Sprig template ({{...}})."),S("export_md",np,"Export document content as Markdown."),S("export_resources",rp,"Export resources as a ZIP archive."),S("list_unused_assets",sp,"List unused asset files."),S("get_doc_assets",ap,"List assets directly referenced by the current document tree. Use extract_doc for complete document asset inspection."),S("get_image_ocr_text",ip,"Get stored OCR text for an image asset."),S("remove_unused_assets",cp,"Remove all unused asset files."),S("rename_asset",lp,"Rename an asset file."),S("delete_asset",up,"Delete an asset file."),S("extract_doc",dp,"Export a document and all referenced assets into a self-contained uncompressed folder. Prefer this over export_resources when you need to inspect attachment content.")];function $f(e,t){return De({name:"file",description:"📁 Grouped file and asset operations.",variants:m0,actionSchema:h_,aggregateOptions:{guidance:Jc,actionHints:cl},handlers:h0(e,t)})}const g0=$f(Qr,Qr*1024*1024);function y0(e){return g0.listTools(e)}async function b0(e,t,o,n){const r="uploadLargeFileThresholdMB"in o&&typeof o.uploadLargeFileThresholdMB=="number"?o.uploadLargeFileThresholdMB:Qr,s=r*1024*1024;return $f(r,s).callTool(e,t,o,n)}function wa(){const e=(process.env.SIYUAN_MCP_TRANSPORT??"").toLowerCase();return e==="cli"||e==="http"?e:"stdio"}const Mf="Uq2KRv7t",w0="https://f-api.wps.cn/ksform/api/v3/campaign",k0=`https://f.wps.cn/ksform/w/write/${Mf}`,_0="0.5.1",_t={description:"v5nhl6",impact:"bbev5x",suggestion:"6wxpgj",source:"8dcnsl",agent:"fu27dr",pluginVersion:"yl3by8"},v0={settings:{value:"用户"},cli:{value:"CLI"},stdio:{value:"STDIO"},http:{value:"HTTP"}},zf="无";function gn(e){return(e==null?void 0:e.trim())||zf}function Dt(e){return{type:"input",strValue:e,isManualInput:!0}}function I0(e){const t=v0[e];return Dt(t.value)}function S0(e,t,o,n="input"){const r=e!=null&&e.questionMap?Object.entries(e.questionMap):[],s=r.find(([,i])=>{var c;return i.title===t&&i.type===n&&((c=i.baseInfo)==null?void 0:c.delete)!==!0});if(s)return s[0];const a=r.find(([,i])=>{var c;return i.title===t&&((c=i.baseInfo)==null?void 0:c.delete)!==!0});return(a==null?void 0:a[0])??o}function D0(e){const t=(e??"").trim().toLowerCase();if(t==="settings"||t==="user"||t==="用户")return"settings";if(t==="cli")return"cli";if(t==="http")return"http";if(t==="stdio")return"stdio";const o=wa();return o==="cli"||o==="http"?o:"stdio"}function T0(e){const t=gn(e);return t!==zf?t:"0.5.1".trim()?"0.5.1".trim():_0}function A0(e,t){var u,p,f,h;const o=(h=(f=(p=(u=t==null?void 0:t.setting)==null?void 0:u.baseSetting)==null?void 0:p.commitConfig)==null?void 0:f.options)==null?void 0:h[0];if(!(t!=null&&t.token))throw new Error("Feedback form metadata did not include a submit token.");if(!(o!=null&&o.id))throw new Error("Feedback form metadata did not include a submit option.");const n=e.description.trim(),r=gn(e.impact),s=gn(e.suggestion),a=gn(e.agent),i=T0(e.pluginVersion),c=D0(e.source),l=S0(t,"来源",_t.source);return{answerJson:{answers:{[_t.description]:Dt(n),[_t.impact]:Dt(r),[_t.suggestion]:Dt(s),[l]:I0(c),[_t.agent]:Dt(a),[_t.pluginVersion]:Dt(i)},answersProperty:{commitInfo:{optionId:o.id,optionText:""}},consumeTime:2},phoneNumber:"",editVersion:t.editVersion??1,token:t.token,channel:c}}function Ki(e){return{Accept:"application/json, text/plain, */*",Origin:"https://f.wps.cn",Referer:k0,"User-Agent":"siyuan-plugin-mcp-sisyphus feedback",...e}}async function Ji(e,t){const o=await e.text();let n;try{n=JSON.parse(o)}catch{const r=o.length>200?`${o.slice(0,200)}...`:o;throw new Error(`${t} returned invalid JSON: ${r}`)}return n}async function Qi(e,t){const o=await e.text(),n=o.length>300?`${o.slice(0,300)}...`:o;return new Error(`${t} failed: HTTP ${e.status}${n?` ${n}`:""}`)}async function P0(e,t=fetch){var u,p,f,h,g,b;const o=e.description.trim();if(!o)throw new Error("Feedback description is required.");const n=`${w0}/${Mf}`,r=await t(n,{method:"GET",headers:Ki()});if(!r.ok)throw await Qi(r,"Feedback metadata request");const s=await Ji(r,"Feedback metadata request");if(s.code!==0||!s.data)throw new Error(`Feedback metadata request failed: ${s.result||s.code}`);if((p=(u=s.data.setting)==null?void 0:u.baseSetting)!=null&&p.checkLogin)throw new Error("Feedback form currently requires WPS login.");const a=`sisyphus${Math.random().toString(36).slice(2)}`,i=A0({...e,description:o},s.data),c=await t(n,{method:"POST",headers:Ki({"Content-Type":"application/json",Cookie:`csrf=${a}`}),body:JSON.stringify({...i,csrfmiddlewaretoken:a})});if(!c.ok)throw await Qi(c,"Feedback submit");const l=await Ji(c,"Feedback submit");if(l.code!==0)throw new Error(`Feedback submit failed: ${l.result||l.code}`);return{success:!0,aid:(f=l.data)==null?void 0:f.aid,answerShareId:(g=(h=l.data)==null?void 0:h.answerShare)==null?void 0:g.asid,createdTs:(b=l.data)==null?void 0:b.createdTs}}const C0="feedback",E0=[S("submit",cd,"Submit plain-text GitHub Issue-style feedback to the developer.")],Ff=De({name:C0,description:"💬 Submit plain-text GitHub Issue-style feedback, suggestions, or experience reports to the plugin developer.",variants:E0,actionSchema:y_,aggregateOptions:{guidance:ol,actionHints:ml},handlers:{submit:async({rawArgs:e})=>{const t=cd.parse(e),o=await P0({description:t.description,impact:t.impact,suggestion:t.suggestion,agent:t.agent,source:t.source});return k({action:"submit",...o})}}});function R0(e){return Ff.listTools(e)}async function x0(e,t,o,n){return Ff.callTool(e,t,o,n)}const qf=["Bridge tools exposed through the official SiYuan /mcp endpoint.","Plugin tools are included by default; native SiYuan tools are included only when includeNativeTools is enabled.",'Use action="list" to inspect discovery status. Every exposed tool keeps its official name as the action.',"Pass downstream parameters inside arguments={...}. Tools without readOnlyHint=true may mutate data and require explicit user confirmation."].join(" "),tr=new Set(["help","list"]);function Ce(e,t=!1){return{content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}],...t?{isError:!0}:{}}}function ka(e,t){return e.source==="plugin"||t.includeNativeTools}function Xt(e,t){return!e.enabled||!t?[]:or(t.bridge.getTools(),e)}function or(e,t){const o=new Set(t.blockedTools);return e.filter(n=>ka(n,t)&&!o.has(n.name)&&!tr.has(n.name))}function es(e,t){return Array.isArray(e)?e.map(o=>es(o,t)):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([o,n])=>o==="$ref"&&typeof n=="string"&&n.startsWith("#")?[o,`${t}${n.slice(1)}`]:[o,es(n,t)]))}function O0(e,t){const o=e.readOnlyHint?"Declared read-only by the official MCP registry.":"May modify data or trigger side effects. Explicit user confirmation is required before calling.",n=e.schemaDegraded?" The original input schema was invalid and has been degraded to a generic object.":"";return{type:"object",title:e.title||e.name,description:`${e.description||e.name} ${o}${n}`,source:e.source,readOnlyHint:e.readOnlyHint,...e.effectScope?{effectScope:e.effectScope}:{},properties:{action:{type:"string",const:e.name,description:`Official SiYuan MCP tool name: ${e.name}`},arguments:es(e.inputSchema,`#/oneOf/${t}/properties/arguments`)},required:["action","arguments"],additionalProperties:!1}}function N0(e,t){if(!e.enabled)return[];const o=Xt(e,t),n=["help","list",...o.map(s=>s.name)],r=[{type:"object",title:"Extension help",properties:{action:{type:"string",const:"help"},topic:{type:"string",description:"Optional official MCP tool name."}},required:["action"],additionalProperties:!1},{type:"object",title:"List official MCP tools",properties:{action:{type:"string",const:"list"},refresh:{type:"boolean",description:"Refresh the official SiYuan MCP registry before returning the list."}},required:["action"],additionalProperties:!1},...o.map((s,a)=>O0(s,a+2))];return[{name:"extension",description:[qf,`Currently exposed actions: ${n.join(", ")}.`].join(`
521
+
522
+ `),inputSchema:{type:"object",properties:{action:{type:"string",enum:n,description:"Use list or an exposed official MCP tool name."},arguments:{type:"object",description:"Arguments forwarded unchanged to the selected official MCP tool.",additionalProperties:!0},refresh:{type:"boolean"},topic:{type:"string"}},required:["action"],oneOf:r}}]}async function $0(e,t){if(!e.enabled||!t)return;const o=t.bridge.getSnapshot();if(o.lastAttemptAt)return Et(e,t,o.tools)&&await _o(t),o;if(t.discoveryMode==="background")return Et(e,t,o.tools),t.discoveryPromise||(t.discoveryPromise=t.bridge.refresh().then(async r=>(Et(e,t,r.tools)&&await _o(t),r)).finally(()=>{t.discoveryPromise=void 0})),o;const n=await t.bridge.refresh();return Et(e,t,n.tools)&&await _o(t),n}function Et(e,t,o=t.bridge.getTools()){const n=JSON.stringify(or(o,e)),r=t.exposedToolsFingerprint!==n;return t.exposedToolsFingerprint=n,r}async function _o(e){var t;try{await((t=e.notifyToolListChanged)==null?void 0:t.call(e))}catch{}}function M0(e,t){const o=new Set(t.blockedTools),n=or(e.tools,t),r=e.tools.reduce((s,a)=>(s[a.source]+=1,s),{plugin:0,native:0});return{connected:e.connected,supported:e.supported,siyuanVersion:e.siyuanVersion,minSupportedVersion:e.minSupportedVersion,lastSuccessfulRefreshAt:e.lastSuccessfulRefreshAt,lastAttemptAt:e.lastAttemptAt,error:e.error,changed:e.changed,discoveredCount:e.tools.length,discoveredBySource:r,nativeToolsEnabled:t.includeNativeTools,exposedCount:n.length,schemaBytes:JSON.stringify(n.map(s=>s.inputSchema)).length,tools:e.tools.map(s=>({name:s.name,title:s.title,description:s.description,source:s.source,readOnlyHint:s.readOnlyHint,effectScope:s.effectScope,schemaDegraded:s.schemaDegraded,blocked:o.has(s.name),sourceEnabled:ka(s,t),reservedActionConflict:tr.has(s.name),exposed:n.some(a=>a.name===s.name)})),hint:e.error?"Official MCP tools require SiYuan 3.7.0+, an administrator session, and a valid API token.":t.includeNativeTools?'Plugin and native SiYuan tools are exposed. Call extension(action="<official tool name>", arguments={...}).':"Plugin tools are exposed. Enable includeNativeTools in settings to expose native SiYuan tools."}}function z0(e,t,o){const n=o==null?void 0:o.bridge.getTools().find(r=>r.name===e);if(e&&n){const r=ka(n,t),s=tr.has(n.name);return Ce({tool:n.name,title:n.title,description:n.description,source:n.source,readOnlyHint:n.readOnlyHint,requiresConfirmation:!n.readOnlyHint,effectScope:n.effectScope,blocked:t.blockedTools.includes(n.name),sourceEnabled:r,reservedActionConflict:s,exposed:r&&!s&&!t.blockedTools.includes(n.name),schemaDegraded:n.schemaDegraded,inputSchema:n.inputSchema,call:{action:n.name,arguments:{}}})}return Ce({tool:"extension",description:qf,actions:{list:{parameters:{refresh:"boolean, optional"},description:"Inspect or refresh official MCP tool discovery."},"<official tool name>":{parameters:{arguments:"object, required"},description:"Forward one call to the selected official MCP tool. Calls are never retried."}},includeNativeTools:t.includeNativeTools,discoveredTools:(o==null?void 0:o.bridge.getTools().map(r=>({name:r.name,source:r.source,exposed:Xt(t,o).some(s=>s.name===r.name)})))??[]})}async function F0(e,t,o,n,r){const s=typeof(t==null?void 0:t.action)=="string"?t.action:"";if(s==="help")return z0(typeof(t==null?void 0:t.topic)=="string"?t.topic:void 0,o,r);if(!r)return Ce("Official MCP bridge runtime is unavailable.",!0);if(s==="list"){const c=r.bridge.getSnapshot(),l=(t==null?void 0:t.refresh)===!0||!c.lastAttemptAt?await r.bridge.refresh({forceVersionCheck:(t==null?void 0:t.refresh)===!0}):c;return Et(o,r,l.tools)&&await _o(r),Ce(M0(l,o))}if(!s)return Ce('extension.action is required. Use action="list" to inspect available official MCP tools.',!0);if(o.blockedTools.includes(s))return Ce(`Official MCP tool "${s}" is blocked in Sisyphus settings.`,!0);let a=Xt(o,r).find(c=>c.name===s);if(!a){const c=await r.bridge.refresh();Et(o,r,c.tools)&&await _o(r),a=or(c.tools,o).find(l=>l.name===s)}if(!a){const c=r.bridge.getTools().find(l=>l.name===s);return(c==null?void 0:c.source)==="native"&&!o.includeNativeTools?Ce(`Native SiYuan MCP tool "${s}" is disabled. Enable extension.includeNativeTools in Sisyphus settings first.`,!0):tr.has(s)?Ce(`Official MCP tool "${s}" conflicts with a reserved extension action and cannot be exposed.`,!0):Ce(`Unknown official MCP tool "${s}". Use extension(action="list", refresh=true) to inspect current tools.`,!0)}const i=t==null?void 0:t.arguments;return i===null||typeof i!="object"||Array.isArray(i)?Ce("extension.arguments must be an object.",!0):r.bridge.callTool(s,i)}async function Lf(e){return e.request("/api/riff/getRiffDecks",{})}async function Xi(e,t,o){return e.request("/api/riff/getRiffDueCards",{deckID:t??"",...o!==void 0?{reviewedCards:o}:{}})}async function q0(e,t,o){return e.request("/api/riff/getNotebookRiffDueCards",{notebook:t,...o!==void 0?{reviewedCards:o}:{}})}async function L0(e,t,o){return e.request("/api/riff/getTreeRiffDueCards",{rootID:t,...o!==void 0?{reviewedCards:o}:{}})}async function B0(e,t,o,n,r){return e.request("/api/riff/reviewRiffCard",{deckID:t,cardID:o,rating:n,...r!==void 0?{reviewedCards:r}:{}})}async function U0(e,t,o){return e.request("/api/riff/skipReviewRiffCard",{deckID:t,cardID:o})}async function j0(e,t,o){return e.request("/api/riff/addRiffCards",{deckID:t,blockIDs:o})}async function H0(e,t,o){return e.request("/api/riff/removeRiffCards",{deckID:t,blockIDs:o})}async function ec(e,t,o,n){return e.request("/api/riff/getRiffCards",{id:t,page:o,...n!==void 0?{pageSize:n}:{}})}async function V0(e,t){return e.request("/api/riff/getRiffCardsByBlockIDs",{blockIDs:t})}const Ze="20230218211946-2kw8jgx",tc="custom-riff-decks",Z0="Built-in Deck",Y0=5,W0=300,oc=6,G0=300;function K0(e){return typeof e=="string"?["new","0"].includes(e.toLowerCase()):e===0}function J0(e){return typeof e=="string"?["old","1","review"].includes(e.toLowerCase()):e===1}function Q0(e,t){return t==="due"?e:t==="new"?e.filter(o=>K0(o.state)):e.filter(o=>J0(o.state))}function Bf(e){return e===""?Ze:e}function X0(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function eP(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.id=="string"&&t.id.length>0)return t.id;if(typeof t.deckID=="string"&&t.deckID.length>0)return t.deckID}async function Uf(e,t){const o=await qp(e,t);return o&&typeof o=="object"?o:{}}async function tP(e,t){for(const o of t)if((await Uf(e,o)).type==="doc")throw new Error(`Block "${o}" is a document block and cannot be turned into a flashcard. Pass a content block ID such as a paragraph or heading instead.`)}async function jf(e,t,o){if(t===Ze)return;const n=await Lf(e);if(!Array.isArray(n)||!n.some(r=>eP(r)===t))throw new Error(`flashcard/${o} requires an existing deckID. Deck "${t}" was not found.`)}async function oP(e,t,o,n){for(const r of t){const s=await Uf(e,r);if(!X0(s[tc]).includes(o))throw new Error(`flashcard/${n} did not persist a valid deck binding for block "${r}". Expected ${tc} to include "${o}".`)}}function nP(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:[]}function rP(e){return typeof e.id=="string"&&e.id.length>0?e.id:typeof e.blockID=="string"&&e.blockID.length>0?e.blockID:void 0}function nc(e){return!e||typeof e!="object"?!1:typeof e.riffCardID=="string"&&e.riffCardID.length>0?!0:!!e.riffCard}async function Hf(e,t,o,n){const r=new Set(t);for(let s=0;s<oc;s+=1){const a=await V0(e,t),i=new Map;for(const l of nP(a)){const u=rP(l);u&&i.set(u,l)}if([...r].every(l=>{const u=i.get(l);return o==="present"?nc(u):!nc(u)}))return;s<oc-1&&await Vo(G0)}throw new Error(o==="present"?`flashcard/${n} did not create readable riff card records for blocks: ${t.join(", ")}`:`flashcard/${n} did not fully remove readable riff card records for blocks: ${t.join(", ")}`)}function Vf(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:Array.isArray(e==null?void 0:e.cards)?e.cards:[]}function sP(e){return(!e.type||e.type==="")&&typeof e.content=="string"&&e.content.includes("不存在符合条件的内容块")}function aP(e){return e.length>0&&e.some(sP)}async function iP(e,t,o,n){let r=await ec(e,t,o,n);for(let s=1;s<Y0;s+=1){if(!aP(Vf(r)))return r;await Vo(W0),r=await ec(e,t,o,n)}return r}const cP=async({client:e,rawArgs:t})=>{const o=ld.parse(t),r=(o.scope==="all"?await Xi(e,"",o.reviewedCards):o.scope==="deck"?await Xi(e,o.deckID,o.reviewedCards):o.scope==="notebook"?await q0(e,o.notebook,o.reviewedCards):await L0(e,o.rootID,o.reviewedCards))??{};return k({...r,action:"list_cards",scope:o.scope,filter:o.filter,...o.deckID?{deckID:o.deckID}:{},...o.notebook?{notebook:o.notebook}:{},...o.rootID?{rootID:o.rootID}:{},...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},cards:Q0(Array.isArray(r.cards)?r.cards:[],o.filter)})},lP=async({client:e,rawArgs:t})=>{ud.parse(t);const o=await Lf(e),n=Array.isArray(o)?[...o]:[];return n.some(s=>{if(!s||typeof s!="object")return!1;const a=s;return a.id===Ze||a.deckID===Ze})||n.unshift({id:Ze,deckID:Ze,name:Z0,builtin:!0}),k({action:"get_decks",decks:n})},uP=async({client:e,rawArgs:t})=>{const o=hd.parse(t),n=await iP(e,o.deckID,o.page??1,o.pageSize);return k({action:"get_cards",deckID:o.deckID,page:o.page??1,...o.pageSize!==void 0?{pageSize:o.pageSize}:{},cards:Vf(n),total:n==null?void 0:n.total,pageCount:n==null?void 0:n.pageCount})},dP=async({client:e,rawArgs:t})=>{const o=dd.parse(t);if(o.deckID==="")throw new Error("flashcard/review_card requires a concrete deckID. Use flashcard/get_cards first to resolve the card deck, then retry.");if(o.skip===!0){const r=await U0(e,o.deckID,o.cardID);return k({action:"review_card",skip:!0,deckID:o.deckID,cardID:o.cardID,result:r})}const n=await B0(e,o.deckID,o.cardID,o.rating,o.reviewedCards);return k({action:"review_card",deckID:o.deckID,cardID:o.cardID,rating:o.rating,...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},result:n})},pP=async({client:e,rawArgs:t})=>{const o=pd.parse(t),n=Bf(o.deckID);await tP(e,o.blockIDs),await jf(e,n,"create_card");const r=o.mode??"full",s=await j0(e,n,o.blockIDs);return await oP(e,o.blockIDs,n,"create_card"),n===Ze&&await Hf(e,o.blockIDs,"present","create_card"),k({action:"create_card",mode:r,deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:s})},fP=async({client:e,rawArgs:t})=>{const o=fd.parse(t),n=Bf(o.deckID);await jf(e,n,"remove_card");const r=await H0(e,n,o.blockIDs);return n===Ze&&await Hf(e,o.blockIDs,"absent","remove_card"),k({action:"remove_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})},hP={list_cards:cP,get_decks:lP,get_cards:uP,review_card:dP,create_card:pP,remove_card:fP},mP=[S("list_cards",ld,"List due flashcards and optionally filter to new/old cards."),S("get_decks",ud,"Get flashcard deck definitions."),S("get_cards",hd,"List all cards in a deck with pagination (not limited to due cards)."),S("review_card",dd,"Submit a review result or skip one flashcard."),S("create_card",pd,"Turn existing blocks into flashcards or attach existing blocks to a deck."),S("remove_card",fd,"Remove existing blocks from a flashcard deck.")],Zf=De({name:"flashcard",description:"🃏 Grouped flashcard review and deck operations.",variants:mP,actionSchema:m_,aggregateOptions:{guidance:el,actionHints:fl},handlers:hP}),gP=Zf.listTools,yP=Zf.callTool;function _a(e){const t=e.trim();if(!t)throw new Error("fs path must not be empty.");const n=(t.startsWith("/")?t:`/${t}`).replace(/\/+/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function bP(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function rc(e){return e.split("/").filter(Boolean).at(-1)??""}function sc(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Rt(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function wP(e,t,o){return o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t)}async function Yf(e){return(await at(e)).notebooks.map(o=>({id:o.id,name:o.name,closed:o.closed}))}async function ts(e,t,o){let n;try{n=await jp(e,o,t.id)}catch{n=[]}const r=await st(e,["SELECT id","FROM blocks","WHERE type = 'd'",`AND box = '${we(t.id)}'`,`AND hpath = '${we(o)}'`,"LIMIT 100"].join(" ")).catch(()=>[]);for(const i of r)i&&typeof i=="object"&&typeof i.id=="string"&&n.push(i.id);const s=[...new Set(n)],a=[];for(const i of s){const c=await ko(e,i),l=await Kn(e,i).catch(()=>o),u=_a(l),p=rc(u)||bP(rc(c.path))||i;a.push({type:"document",id:i,notebook:c.notebook||t.id,notebookName:t.name,hPath:u,storagePath:c.path,canonicalPath:Rt(t.name,u),name:p})}return a}function os(e){return e.map(t=>t.canonicalPath).join(", ")}function Re(e,t){const o=new Error(t);return Object.assign(o,{code:e}),o}async function Ne(e,t,o,n="read"){const r=_a(o);if(r==="/")return{type:"root",canonicalPath:"/"};await t.reload();const s=await Yf(e),a=r.split("/").filter(Boolean),i=a[0],c=s.find(u=>u.name===i);if(c){const u=a.length===1?"/":`/${a.slice(1).join("/")}`;if(u==="/")return{type:"notebook",notebook:c.id,notebookName:c.name,hPath:"/",storagePath:"/",canonicalPath:Rt(c.name,"/")};const p=await ts(e,c,u);if(p.length===0)throw Re("not_found",`No document found at "${r}".`);if(p.length>1)throw Re("ambiguous_path",`Ambiguous fs path "${r}". Candidates: ${os(p)}.`);return p[0]}const l=[];for(const u of s)if(wP(t,u.id,n))try{l.push(...await ts(e,u,r))}catch{}if(l.length===1)return l[0];throw l.length>1?Re("ambiguous_path",`Ambiguous fs path "${r}". Candidates: ${os(l)}.`):Re("not_found",`No document found at "${r}". Use /<notebook name>/<document path> for an unambiguous path.`)}async function Wf(e,t,o){const n=_a(o);if(n==="/")throw Re("invalid_path",'Cannot create a document at "/". Use /<notebook name>/<title>.');const r=n.split("/").filter(Boolean),s=r.at(-1);if(!s)throw Re("invalid_path",`Cannot create a document at "${n}".`);await t.reload();const i=(await Yf(e)).find(p=>p.name===r[0]);if(i){const p=r.slice(1,-1),f=p.length===0?"/":`/${p.join("/")}`;let h="/",g;if(f!=="/"){const _=await ts(e,i,f);if(_.length===0)throw Re("not_found",`Parent document not found at "${Rt(i.name,f)}".`);if(_.length>1)throw Re("ambiguous_path",`Ambiguous parent path "${Rt(i.name,f)}". Candidates: ${os(_)}.`);const w=_[0];h=w.storagePath,g=w.id}const b=sc(f,s);return{notebook:i.id,notebookName:i.name,title:s,parentHPath:f,parentStoragePath:h,parentId:g,hPath:b,canonicalPath:Rt(i.name,b)}}if(r.length===1)throw Re("invalid_path","Root-level create must use /<notebook name>/<title>.");const c=`/${r.slice(0,-1).join("/")}`,l=await Ne(e,t,c,"write");if(l.type!=="document")throw Re("invalid_path",`Parent path "${c}" must resolve to a document folder.`);const u=sc(l.hPath,s);return{notebook:l.notebook,notebookName:l.notebookName,title:s,parentHPath:l.hPath,parentStoragePath:l.storagePath,parentId:l.id,hPath:u,canonicalPath:Rt(l.notebookName,u)}}async function kP(e,t,o){return Wf(e,t,o)}function _P(e,t){let o=0,n=0;for(;;){if(n=e.indexOf(t,n),n===-1)return o;o+=1,n+=t.length}}function vP(e,t,o,n){const r=_P(e,t.old);if(r===0){const a="";throw new Error(`${n} edit #${o+1} did not match any text.${a}`)}if(t.replace_all)return{content:e.split(t.old).join(t.new),replaced:r,replaceAll:!0};const s=e.indexOf(t.old);return{content:`${e.slice(0,s)}${t.new}${e.slice(s+t.old.length)}`,replaced:1,replaceAll:!1}}function IP(e,t,o){let n=e;const r=t.map((s,a)=>{const i=vP(n,s,a,o);return n=i.content,{index:a+1,replaced:i.replaced,replace_all:i.replaceAll}});return{content:n,summary:r}}const SP=/\bdata-av-id=(?:"([^"]+)"|'([^']+)')/i,DP=new Set(["s","av","iframe","widget","query_embed","html","video","audio"]);function va(e){return!!(e&&DP.has(e))}function TP(e){const t=Array.from(new Set(e.map(o=>o.type).filter(o=>va(o))));return t.length===0?{}:{nonFidelityWarning:"fs is intentionally limited to pure Markdown-style document operations. This document contains SiYuan-native structures; inspect or modify those blocks with advanced tools instead of fs.",complexBlockTypes:t,recommendedReads:["file.export_md","block.dom"]}}function Gf(e){return e.flatMap(t=>va(t.type)?[{...t.id?{id:t.id}:{},type:t.type}]:[])}function AP(e){return!!(e.type&&!va(e.type))}function PP(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"complex_blocks_not_supported_by_fs",message:`fs.${e} is limited to pure Markdown documents and will not modify documents containing SiYuan-native complex blocks.`,path:t,id:o,complexBlocks:n,recommendedTools:["file.export_md","block.dom","block.update","block.append","av"],hint:"Use fs for pure Markdown content only. For database blocks, super blocks, embeds, widgets, HTML/media, or precise native structure changes, inspect with block.dom and edit with the matching advanced tool."}},null,2)}],isError:!0}}function qt(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Rn(e){if(e)return e.split("/").filter(Boolean).at(-1)}function Kf(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Jf(e){const t=e.trim();if(!t)throw new Error("fs path must not be empty.");const n=(t.startsWith("/")?t:`/${t}`).replace(/\/+/g,"/");return n.length>1?n.replace(/\/+$/,""):n}const nr=[ie,ze];function $e(e){const t=Jf(e);return nr.find(o=>t===o)??null}function xn(e){const t=Jf(e);return nr.find(o=>t.startsWith(`${o}/`))??null}function bt(e){const t=xn(e);if(t)throw new Error(`${t} is a virtual file and has no children.`)}function Fo(e){if(($e(e)??xn(e))===ze)throw new Error(`${ze} is a read-only virtual file. Edit user rules in the plugin settings.`)}function CP(e){return{name:e.slice(1),path:e,children:0,virtual:!0}}function EP(e){return{name:e.slice(1),path:e,children:[],virtual:!0}}function RP(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function xP(e,t){const o=qt(t.name)??qt(Rn(t.path))??t.path;return{name:o,path:Kf(e,o),children:t.subFileCount??t.count??0}}async function Ia(e,t){return await t.reload(),(await at(e)).notebooks.filter(n=>t.canRead(n.id))}async function OP(e,t){return t.type==="root"?[]:(await Jn(e,t.notebook,t.storagePath)).map(n=>xP(t.canonicalPath,n))}function NP(e,t){const o=qt(typeof e.name=="string"?e.name:void 0)??qt(Rn(typeof e.hPath=="string"?e.hPath:void 0))??qt(Rn(typeof e.path=="string"?e.path:void 0))??(typeof e.id=="string"?e.id:"Untitled");return{name:o,path:Kf(t,o)}}async function ns(e,t,o,n,r,s=0,a=new Map){return Array.isArray(t)?Promise.all(t.map(async i=>{const c=i&&typeof i=="object"?i:{},l=NP(c,o);let u=l.name,p=l.path;const f=typeof c.id=="string"?c.id:void 0;if(f)try{let b=a.get(f);b||(b=Kn(e,f),a.set(f,b));const _=await b,w=qt(Rn(_));w&&(u=w,p=RP(n,_))}catch{}const h=Array.isArray(c.children)?c.children:[],g={name:u,path:p};return s>=r?g.children=h.length:g.children=await ns(e,h,g.path,n,r,s+1,a),g})):[]}function vo(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.tree)?e.tree:[]}function yn(e){if(!Array.isArray(e))return[];const t=[];for(const o of e){if(!o||typeof o!="object")continue;const n=o;typeof n.id=="string"&&t.push(n.id),Array.isArray(n.children)&&t.push(...yn(n.children))}return t}async function $P(e,t,o){const n=await Wn(e,t);for(const r of n)typeof r.id=="string"&&await zp(e,r.id);o.trim().length>0&&await Mp(e,"markdown",o,t)}function ac(e){const t=e.match(SP);return(t==null?void 0:t[1])??(t==null?void 0:t[2])}async function Qf(e,t,o){const r=(o??await Zo(e,t)).filter(s=>s.type==="av");return Promise.all(r.map(async s=>{const a=await co(e,s.id),i=typeof a.kramdown=="string"?a.kramdown:"";return{blockID:s.id,...ac(i)?{avID:ac(i)}:{}}}))}function Ir(e,t,o){const{nextBlockStart:n,...r}=t;if(n===void 0)return{path:e,...r};const s={action:"read",path:e,blockStart:n,blockLimit:t.blockLimit,tokenBudget:t.tokenBudget,...o?{includeBlockIds:!0}:{}};return{path:e,...r,nextWindow:s,nextWindowHint:`Continue with fs(${JSON.stringify(s)}).`}}function Xf(e){return{attributeViews:e,warning:'This document contains database/attribute-view blocks. fs is only a pure Markdown convenience layer and will not safely edit these SiYuan-native structures. Use av(action="get"|"render"|"set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column") for rows, columns, and cells.',avToolHint:{read:'av(action="get", id="<av-id>") or av(action="render", id="<av-id>", blockID="<database-block-id>")',write:'av(action="set_cells"|"add_rows"|"remove_rows"|"add_column"|"remove_column", avID="<av-id>", ...)'}}}async function MP(e,t,o){const n=await Zo(e,t),r=Gf(n),s=n.filter(AP).map(c=>({id:c.id,type:c.type}));if(s.length===0)throw new Error("fs.replace found no editable non-complex Markdown blocks in this document.");const a=await Promise.all(s.map(async c=>{const[l,u]=await Promise.all([co(e,c.id),Gn(e,c.id)]);return{id:c.id,type:c.type,kramdown:typeof l.kramdown=="string"?l.kramdown:"",dom:typeof u.dom=="string"?u.dom:""}})),i=eT(a,o,"fs.replace");for(const c of i.blocks){const l=c.touchesIndexedInline&&c.type!=="l";await sa(e,l?"markdown":"dom",l?c.markdown:c.dom,c.id)}return{summary:i.summary,changedBlockCount:i.blocks.length,changedMarkdown:i.blocks.map(c=>c.markdown).join(`
523
+ `),skippedComplexBlocks:r}}async function zP(e,t,o){if(o.type==="document"){const s=vo(await $t(e,o.notebook,o.storagePath));return[...new Set([o.id,...yn(s)])].map(a=>({id:a,notebookName:o.notebookName}))}if(o.type==="notebook"){const s=vo(await $t(e,o.notebook,"/"));return[...new Set(yn(s))].map(a=>({id:a,notebookName:o.notebookName}))}const n=await Ia(e,t),r=[];for(const s of n){const a=vo(await $t(e,s.id,"/"));r.push(...[...new Set(yn(a))].map(i=>({id:i,notebookName:s.name})))}return r}function FP(e,t,o){if(t){const r=o?"":"i",s=new RegExp(e,r);return a=>s.test(a)}const n=o?e:e.toLowerCase();return r=>(o?r:r.toLowerCase()).includes(n)}function cn(e,t,o){const n=[];return e.split(/\r?\n/).forEach((r,s)=>{t(r)&&n.push({path:o,line:s+1,text:r.length>300?`${r.slice(0,297)}...`:r})}),n}async function On(e){const t=await qs(e);return{content:t.agentSiyuanMemoryText??"",updatedAt:t.agentSiyuanMemoryUpdatedAt??""}}async function rs(e){return{content:(await qs(e)).userRulesText??""}}const qP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Du.parse(o);bt(n.path);const r=$e(n.path);if(r)throw new Error(`${r} is a virtual file and has no children.`);const s=await Ne(e,t,n.path,"read");if(s.type==="root"){const i=await Ia(e,t),c=nr.map(l=>CP(l));for(const l of i){let u=0;try{u=(await Jn(e,l.id,"/")).length}catch{u=0}c.push({name:l.name,path:`/${l.name}`,children:u})}return k({path:"/",items:c})}const a=await Y(t,s.notebook,"read");return a||k({path:s.canonicalPath,items:await OP(e,s)})},LP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Tu.parse(o);bt(n.path);const r=$e(n.path);if(r)return k({path:r,tree:[],virtual:!0,maxDepth:n.maxDepth??3});const s=await Ne(e,t,n.path,"read"),a=n.maxDepth??3;if(s.type==="root"){const l=await Ia(e,t),u=nr.map(p=>EP(p));for(const p of l){const f=await $t(e,p.id,"/");u.push({name:p.name,path:`/${p.name}`,children:await ns(e,vo(f),`/${p.name}`,p.name,a)})}return k({path:"/",tree:u,maxDepth:a})}const i=await Y(t,s.notebook,"read");if(i)return i;const c=await $t(e,s.notebook,s.storagePath);return k({path:s.canonicalPath,tree:await ns(e,vo(c),s.canonicalPath,s.notebookName,a),maxDepth:a})},BP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Au.parse(o),r={blockStart:n.blockStart,blockLimit:n.blockLimit,tokenBudget:n.tokenBudget,includeBlockIds:n.includeBlockIds};bt(n.path);const s=$e(n.path);if(s===ie){const p=await On(e),f=Gi(p.content,r);return k({...Ir(ie,f,!1),virtual:!0,updatedAt:p.updatedAt||null})}if(s===ze){const p=await rs(e),f=Gi(p.content,r);return k({...Ir(ze,f,!1),virtual:!0})}const a=await Ne(e,t,n.path,"read");if(a.type!=="document")throw new Error(`fs.read requires a document path, got "${n.path}".`);const i=await Y(t,a.notebook,"read");if(i)return i;const c=await Zo(e,a.id),[l,u]=await Promise.all([Af(e,a.id,r,c),Qf(e,a.id,c)]);return k({...Ir(a.canonicalPath,l,n.includeBlockIds??!1),...u.length>0?Xf(u):{},...TP(c)})},UP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Pu.parse(o);if(Fo(n.path),bt(n.path),$e(n.path)===ie){const f=await Ls(e,n.markdown);return k({success:!0,path:ie,virtual:!0,overwritten:!0,updatedAt:f.agentSiyuanMemoryUpdatedAt||null})}const s=await Wf(e,t,n.path),a=await Y(t,s.notebook,"write");if(a)return a;let i=null;try{const f=await Ne(e,t,s.canonicalPath,"write");i=f.type==="document"?f:null}catch{i=null}if(!i){const f=await Qt(e,_f(n.markdown,s.title),"fs.write"),h=await Lp(e,s.notebook,s.hPath,f);return F(e,k({success:!0,path:s.canonicalPath,id:h,created:!0,...Gt(f)?$o():{},...Kt(f)?Mo():{},...Jt(f)?zo():{}}),[{type:"reloadProtyle",id:h},{type:"reloadFiletree"}])}if(!n.overwrite)throw new Error(`Document already exists at "${i.canonicalPath}". Pass overwrite=true to replace its body.`);const c=await Qt(e,n.markdown,"fs.write"),l=await Zo(e,i.id),u=Gf(l);if(u.length>0)return PP("write",i.canonicalPath,i.id,u);const p=await Qf(e,i.id);return await $P(e,i.id,c),F(e,k({success:!0,path:i.canonicalPath,id:i.id,overwritten:!0,...Gt(c)?$o():{},...Kt(c)?Mo():{},...Jt(c)?zo():{},...p.length>0?Xf(p):{}}),[{type:"reloadProtyle",id:i.id},{type:"reloadFiletree"}])},jP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Cu.parse(o);if(Fo(n.path),bt(n.path),$e(n.path)===ie){const g=await On(e),b=g.content,_=Array.isArray(n.edit)?n.edit:[n.edit],{content:w,summary:P}=IP(b,_,"fs.replace"),D=w!==b;let A=g.updatedAt;return D&&(A=(await Ls(e,w)).agentSiyuanMemoryUpdatedAt),k({success:!0,path:ie,virtual:!0,changed:D,editsApplied:P.length,replacements:P,updatedAt:A||null})}const s=await Ne(e,t,n.path,"write");if(s.type!=="document")throw new Error(`fs.replace requires a document path, got "${n.path}".`);const a=await Y(t,s.notebook,"write");if(a)return a;const i=await vf(e,Array.isArray(n.edit)?n.edit:[n.edit],"fs.replace"),c=await MP(e,s.id,i),{summary:l,changedBlockCount:u,changedMarkdown:p,skippedComplexBlocks:f}=c,h=u>0;return F(e,k({success:!0,path:s.canonicalPath,changed:h,editsApplied:l.length,replacements:l,...f.length>0?{warning:"This document contains SiYuan-native complex blocks. fs.replace edited only matched non-complex Markdown blocks; complex blocks were skipped.",skippedComplexBlocks:f,recommendedTools:["block.dom","block.update","av","file.export_md"]}:{},...Gt(p)?$o():{},...Kt(p)?Mo():{},...Jt(p)?zo():{}}),h?[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}]:[])},HP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Eu.parse(o);if(Fo(n.path),bt(n.path),$e(n.path)===ie){const i=await Ls(e,"");return k({success:!0,path:ie,virtual:!0,cleared:!0,updatedAt:i.agentSiyuanMemoryUpdatedAt||null})}const s=await Ne(e,t,n.path,"delete");if(s.type!=="document")throw new Error(`fs.rm requires a document path, got "${n.path}".`);const a=await Y(t,s.notebook,"delete");return a||(await Fr(e,s.id),F(e,k({success:!0,path:s.canonicalPath}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}]))},VP=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ru.parse(o);if(Fo(n.from),Fo(n.to),$e(n.from)===ie||$e(n.to)===ie||xn(n.from)===ie||xn(n.to)===ie)throw new Error(`${ie} is a fixed virtual file and cannot be moved or renamed.`);const r=await Ne(e,t,n.from,"write");if(r.type!=="document")throw new Error(`fs.mv source must be a document path, got "${n.from}".`);const s=await kP(e,t,n.to),a=await Y(t,r.notebook,"write");if(a)return a;const i=await Y(t,s.notebook,"write");if(i)return i;try{const c=await Ne(e,t,s.canonicalPath,"write");if(c.type==="document"&&c.id!==r.id)throw new Error(`Destination already exists at "${s.canonicalPath}".`)}catch(c){if(c instanceof Error&&c.message.startsWith("Destination already exists"))throw c}return await Up(e,[r.id],s.parentId??s.notebook),r.name!==s.title&&await Bp(e,r.id,s.title),F(e,k({success:!0,path:r.canonicalPath,movedTo:s.canonicalPath}),[{type:"reloadProtyle",id:r.id},{type:"reloadFiletree"}])},ZP=async({client:e,permMgr:t,rawArgs:o})=>{const n=xu.parse(o);bt(n.path);const r=FP(n.query,n.regex,n.caseSensitive),s=$e(n.path);if(s===ie){const _=await On(e),w=cn(_.content,r,ie),P=n.page??1,D=n.pageSize??50,A=Math.max(1,Math.ceil(w.length/D)),T=Math.min(P,A),O=(T-1)*D;return We(w.slice(O,O+D),{total:w.length,page:T,pageSize:D,pageCount:A,hasNextPage:T<A},{path:ie,virtual:!0,updatedAt:_.updatedAt||null,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}if(s===ze){const _=await rs(e),w=cn(_.content,r,ze),P=n.page??1,D=n.pageSize??50,A=Math.max(1,Math.ceil(w.length/D)),T=Math.min(P,A),O=(T-1)*D;return We(w.slice(O,O+D),{total:w.length,page:T,pageSize:D,pageCount:A,hasNextPage:T<A},{path:ze,virtual:!0,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}const a=await Ne(e,t,n.path,"read");if(a.type!=="root"){const _=await Y(t,a.notebook,"read");if(_)return _}const i=await zP(e,t,a),c=[];a.type==="root"&&(c.push(...cn((await On(e)).content,r,ie)),c.push(...cn((await rs(e)).content,r,ze)));for(const _ of i){const w=Jp(await ba(e,_.id)),P=typeof w.content=="string"?w.content:"",D=typeof w.hPath=="string"?w.hPath:`/${_.id}`,A=`/${_.notebookName}${D}`;P.split(/\r?\n/).forEach((T,O)=>{r(T)&&c.push({path:A,line:O+1,text:T.length>300?`${T.slice(0,297)}...`:T})})}const l=new Set,u=c.filter(_=>{const w=`${_.path}\0${_.line}\0${_.text}`;return l.has(w)?!1:(l.add(w),!0)}),p=n.page??1,f=n.pageSize??50,h=Math.max(1,Math.ceil(u.length/f)),g=Math.min(p,h),b=(g-1)*f;return We(u.slice(b,b+f),{total:u.length,page:g,pageSize:f,pageCount:h,hasNextPage:g<h},{path:a.canonicalPath,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})},YP={ls:qP,tree:LP,read:BP,write:UP,replace:jP,rm:HP,mv:VP,search:ZP},WP=[S("ls",Du,"List direct child documents using human-readable paths."),S("tree",Tu,"List a recursive document tree using human-readable paths."),S("read",Au,"Read complete display-block Markdown windows by human-readable path, with outline and continuation metadata."),S("write",Pu,"Create a document, stripping a duplicate leading title heading when present; overwrite=true performs a full body replacement."),S("replace",Cu,"Apply exact old/new text replacement edits inside matched non-complex Markdown block DOM without rebuilding the document."),S("rm",Eu,"Delete a document by human-readable path."),S("mv",Ru,"Move or rename a document by human-readable paths."),S("search",xu,"Search Markdown lines under a human-readable path.")],eh=De({name:"fs",description:"📂 Simplified filesystem-style document operations.",variants:WP,actionSchema:l_,aggregateOptions:{guidance:Zc,actionHints:nl},handlers:YP});function GP(e){return eh.listTools(e)}async function KP(e,t,o,n){return eh.callTool(e,t,o,n)}const JP="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyEvents.json",th="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyStats.json";function qo(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function QP(e){if(!e)return{totalCalls:0,balance:0,updatedAt:0};try{const t=JSON.parse(e),o=qo(t.totalCalls),n=t.balance===void 0?o:qo(t.balance);return{totalCalls:o,balance:n,updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:0,lastAction:typeof t.lastAction=="string"?t.lastAction:void 0}}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function Lo(e){try{return QP(await e.readFile(th))}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function oh(e,t){const o={totalCalls:qo(t.totalCalls),balance:qo(t.balance),updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:Date.now(),...t.lastAction?{lastAction:t.lastAction}:{}};return await e.writeFile(th,JSON.stringify(o)),o}async function XP(e,t){const o=await Lo(e);try{return await oh(e,{totalCalls:o.totalCalls+1,balance:o.balance+1,updatedAt:Date.now(),lastAction:t})}catch{return o}}async function eC(e,t,o){const n=await Lo(e),r=qo(t);if(n.balance<r)throw new Error(`Insufficient mascot balance. Need ${r}, have ${n.balance}.`);return oh(e,{totalCalls:n.totalCalls,balance:n.balance-r,updatedAt:Date.now(),lastAction:o})}async function ic(e,t){try{const o=JSON.stringify({...t,seq:Date.now(),ts:Date.now()});await e.writeFile(JP,o)}catch{}}const rr=[{id:"cat-food",label:"Cat Food",cost:5,type:"food",emoji:"🍖"},{id:"milk",label:"Milk",cost:3,type:"drink",emoji:"🥛"},{id:"dried-fish",label:"Dried Fish",cost:4,type:"food",emoji:"🐟"},{id:"can-food",label:"Canned Food",cost:6,type:"food",emoji:"🥫"},{id:"catnip",label:"Catnip",cost:5,type:"snack",emoji:"🌿"},{id:"chicken-leg",label:"Chicken Leg",cost:7,type:"food",emoji:"🍗"},{id:"cheese",label:"Cheese",cost:4,type:"snack",emoji:"🧀"}];rr[0];rr[1];function tC(e){return rr.find(t=>t.id===e)??null}const oC=[S("get_balance",sd,"Get the mascot balance. Every successful MCP tool call earns 1 coin."),S("shop",ad,"List the mascot shop inventory."),S("buy",id,"Buy one item from the mascot shop.")],nh=De({name:"mascot",description:"🐾 Grouped mascot balance and care operations. Every successful MCP tool call earns 1 coin for the mascot.",variants:oC,actionSchema:g_,aggregateOptions:{guidance:tl,actionHints:hl},handlers:{get_balance:async({client:e,rawArgs:t})=>{sd.parse(t);const o=await Lo(e);return k({action:"get_balance",balance:o.balance,totalEarned:o.totalCalls})},shop:async({rawArgs:e})=>(ad.parse(e),k({action:"shop",items:rr})),buy:async({client:e,rawArgs:t})=>{const o=id.parse(t),n=tC(o.item_id);if(!n)throw new Error(`Unknown mascot shop item: ${o.item_id}.`);const r=await eC(e,n.cost,`buy:${n.id}`);return k({success:!0,action:"buy",item_id:n.id,item:n.label,type:n.type,emoji:n.emoji,cost:n.cost,balance:r.balance,totalEarned:r.totalCalls})}}});function nC(e){return nh.listTools(e)}async function rC(e,t,o,n){return nh.callTool(e,t,o,n)}const rh="notebook";function cc(e,t,o,n){const r=e instanceof Error?e.message:String(e);return o?r.includes("permission")?new Error(`Failed to get child documents for notebook "${t}": permission denied by SiYuan. ${r}`):n?new Error(`Failed to get child documents for notebook "${t}": notebook is currently closed or still initializing. ${r}`):new Error(`Failed to get child documents for notebook "${t}" at "/". ${r}`):new Error(`Failed to get child documents: notebook "${t}" does not exist.`)}function sC(e){const t=e instanceof Error?e.message:String(e);return/initializing|kernel still initializing|notebook is currently closed/i.test(t)}async function aC(e,t,o,n){let r=0;for(;r<=o;){r+=1;try{return{children:await Jn(e,t,"/"),attempts:r}}catch(s){if(r>o||!sC(s))return{error:s,attempts:r};await new Promise(a=>setTimeout(a,n))}}return{error:new Error(`Failed to get child documents for notebook "${t}".`),attempts:r}}function iC(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:rh,action:"get_child_docs",message:t,reason:"notebook_closed_or_initializing",retryable:!0,suggestedNextAction:"open_notebook_or_retry",notebook:e,retryAttempts:o,retryWindowMs:n,hint:'This usually happens right after notebook(action="close"). Re-open the notebook first, or retry after a short wait.'}},null,2)}],isError:!0}}const cC=async({client:e,rawArgs:t})=>{Ou.parse(t);const o=await at(e);return k(o.notebooks)},lC=async({client:e,rawArgs:t})=>{const o=Nu.parse(t),n=await oI(e,o.name);return o.icon&&(await Hp(e,n.notebook.id,o.icon),n.notebook.icon=o.icon),F(e,k({...n.notebook,iconHint:oa("notebook",!!o.icon)}),o.icon?[{type:"reloadIcon"}]:[{type:"reloadFiletree"}])},uC=async({client:e,permMgr:t,rawArgs:o})=>{const n=$u.parse(o),r=await Y(t,n.notebook,"read");return r||(n.opened?await eI(e,n.notebook):await tI(e,n.notebook),F(e,k({success:!0,notebook:n.notebook,opened:n.opened}),[{type:"reloadFiletree"}]))},dC=async({client:e,permMgr:t,rawArgs:o})=>{const n=Mu.parse(o),r=await Y(t,n.notebook,"delete");return r||(await nI(e,n.notebook),F(e,k({success:!0,notebook:n.notebook}),[{type:"reloadFiletree"}]))},pC=async({client:e,permMgr:t,rawArgs:o})=>{const n=zu.parse(o),r=await Y(t,n.notebook,"write");return r||(await rI(e,n.notebook,n.name),F(e,k({success:!0,notebook:n.notebook,name:n.name}),[{type:"reloadFiletree"}]))},fC=async({client:e,permMgr:t,rawArgs:o})=>{const n=Fu.parse(o),r=await Y(t,n.notebook,"read");if(r)return r;const s=await sI(e,n.notebook);return k(s)},hC=async({client:e,permMgr:t,rawArgs:o})=>{const n=qu.parse(o),r=await Y(t,n.notebook,"write");if(r)return r;const s=await aI(e,n.notebook,n.conf);return F(e,k(s),[{type:"reloadFiletree"}])},mC=async({client:e,permMgr:t,rawArgs:o})=>{const n=Lu.parse(o),r=await Y(t,n.notebook,"write");return r||(await Hp(e,n.notebook,n.icon),F(e,k({success:!0,notebook:n.notebook,icon:n.icon}),[{type:"reloadIcon"}]))},gC=async({client:e,permMgr:t,rawArgs:o})=>{const n=Bu.parse(o);await t.reload();const s=(await at(e)).notebooks.map(i=>({id:i.id,name:i.name,permission:t.get(i.id)}));if(!n.notebook||n.notebook==="all")return k({notebooks:s});const a=s.find(i=>i.id===n.notebook);return a?k({notebook:a}):wo(new Error(`Notebook "${n.notebook}" not found.`),{tool:rh,action:"get_permissions",rawArgs:o})},yC=async({client:e,permMgr:t,rawArgs:o})=>{const n=Uu.parse(o);return await t.set(n.notebook,n.permission),F(e,k({success:!0,notebook:n.notebook,permission:n.permission}),[{type:"reloadFiletree"}])},bC=async({client:e,permMgr:t,rawArgs:o})=>{const n=ju.parse(o),r=2,s=150,a=await Y(t,n.notebook,"read");if(a)return a;const c=(await at(e)).notebooks.find(f=>f.id===n.notebook);if(!c)throw cc(new Error("Notebook not found in lsNotebooks result."),n.notebook,!1,!1);const l=await aC(e,n.notebook,r,s);if(l.error){const f=cc(l.error,n.notebook,!0,!!c.closed);if(c.closed)return iC(n.notebook,f.message,l.attempts,r*s);throw f}const u=l.children??[],p=ta(u,n.page??1,n.pageSize??50);return We(p.items,p,{notebook:n.notebook})},wC={list:cC,create:lC,set_open_state:uC,remove:dC,rename:pC,get_conf:fC,set_conf:hC,set_icon:mC,get_permissions:gC,set_permission:yC,get_child_docs:bC},kC=[S("list",Ou,"List all notebooks in the workspace."),S("create",Nu,"Create a new notebook."),S("set_open_state",$u,"Set notebook open state (open or close)."),S("remove",Mu,"Remove a notebook."),S("rename",zu,"Rename a notebook."),S("get_conf",Fu,"Get notebook configuration."),S("set_conf",qu,"Set notebook configuration."),S("set_icon",Lu,"Set the icon for a notebook."),S("get_permissions",Bu,'Get permission levels for notebooks. Omit notebook or pass "all" to return every notebook; pass a specific notebook ID to return only that notebook.'),S("set_permission",Uu,"Set the permission level for a notebook."),S("get_child_docs",ju,"Get direct child documents at the notebook root. Returns a paginated { data, total, page, pageSize, pageCount, hasNextPage } payload.")],sh=De({name:"notebook",description:"📚 Grouped notebook operations.",variants:kC,actionSchema:u_,aggregateOptions:{guidance:Yc,actionHints:rl},handlers:wC});function _C(e){return sh.listTools(e)}function vC(e,t,o,n){return sh.callTool(e,t,o,n)}async function IC(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushMsg",n)}async function SC(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushErrMsg",n)}const DC=1,TC=12;function lc(e,t,o,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(o,Math.min(n,Math.trunc(e)))}function AC(e){const t=e.match(/[^.[\]]+/g);if(!t||t.length===0)throw new Error("keyPath must not be empty.");return t.map(o=>/^\d+$/.test(o)?Number(o):o)}function PC(e,t){const o=AC(t);let n=e;for(const r of o){if(typeof r=="number"){if(!Array.isArray(n)||r>=n.length)throw new Error(`Config path not found: ${t}`);n=n[r];continue}if(n===null||typeof n!="object"||!(r in n))throw new Error(`Config path not found: ${t}`);n=n[r]}return n}function Nn(e,t,o,n){if(e===null)return{type:"null",value:null,truncated:!1};if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return{type:"primitive",value:e,truncated:!1};if(Array.isArray(e))return t>=o?{type:"array",length:e.length,sampleTypes:e.slice(0,n).map(r=>Array.isArray(r)?"array":r===null?"null":typeof r),truncated:e.length>0,omittedItems:Math.max(0,e.length-n)}:{type:"array",length:e.length,items:e.slice(0,n).map(r=>Nn(r,t+1,o,n)),truncated:e.length>n,omittedItems:Math.max(0,e.length-n)};if(typeof e=="object"){const r=Object.entries(e);return t>=o?{type:"object",keyCount:r.length,keysPreview:r.slice(0,n).map(([s])=>s),truncated:r.length>0,omittedKeys:Math.max(0,r.length-n)}:{type:"object",keyCount:r.length,entries:Object.fromEntries(r.slice(0,n).map(([s,a])=>[s,Nn(a,t+1,o,n)])),truncated:r.length>n,omittedKeys:Math.max(0,r.length-n)}}return{type:"primitive",value:String(e),truncated:!1}}function CC(e,t,o,n,r){if(t==="get"){if(!o)throw new Error('keyPath is required when mode="get".');const i=PC(e,o);return{mode:t,keyPath:o,value:Nn(i,0,n,r),hints:["Increase maxDepth or maxItems if you need a larger subtree.",'Use system(action="conf", mode="summary") to inspect sibling keys first.']}}const s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},a=Object.keys(s);return{mode:t,totalTopLevelKeys:a.length,topLevelKeys:a.slice(0,r),truncatedTopLevelKeys:Math.max(0,a.length-r),summary:Nn(s,0,n,r),hints:['Use system(action="conf", mode="get", keyPath="<path>") to read a single field or subtree.','keyPath supports dot/bracket syntax such as "conf.appearance.mode" or "conf.langs[0]".']}}const EC=async({client:e,rawArgs:t})=>(Sp.parse(t),k(await mI(e))),RC=async({client:e,rawArgs:t})=>(Dp.parse(t),k(await gI(e))),xC=async({client:e,rawArgs:t})=>{const o=Tp.parse(t),n=await yI(e),r=o.mode??"summary",s=lc(o.maxDepth,DC,0,5),a=lc(o.maxItems,TC,1,100);return k(CC(n,r,o.keyPath,s,a))},OC=async({client:e,rawArgs:t})=>{const o=Ap.parse(t),n=o.level==="error"?await SC(e,o.msg,o.timeout):await IC(e,o.msg,o.timeout);return k({level:o.level,...n})},NC=async({rawArgs:e})=>{const t=Pp.parse(e);return k(wg(t))},$C=async({client:e,rawArgs:t})=>(Cp.parse(t),k({ok:!0,result:await bI(e)})),MC=async({client:e,rawArgs:t})=>(Ep.parse(t),k({version:await Zp(e)})),zC=async({client:e,rawArgs:t})=>{Rp.parse(t);const o=await wI(e);return k({currentTime:o,iso:new Date(o).toISOString()})},FC={workspace_info:EC,network:RC,conf:xC,notify:OC,changelog:NC,perform_sync:$C,get_version:MC,get_current_time:zC},qC=[S("workspace_info",Sp,"Get SiYuan workspace metadata. High-risk: exposes the absolute workspace path."),S("network",Dp,"Get current network proxy information."),S("conf",Tp,"Get masked system configuration with summary-first progressive reading."),S("notify",Ap,"Push a notification message."),S("changelog",Pp,"Read the bundled plugin changelog with structured personalization-impact hints."),S("perform_sync",Cp,"Trigger SiYuan sync immediately. High-risk: affects local and remote sync state."),S("get_version",Ep,"Get the SiYuan system version."),S("get_current_time",Rp,"Get the current system time.")],ah=De({name:"system",description:"🖥️ Grouped system and notification operations.",variants:qC,actionSchema:T_,aggregateOptions:{guidance:Xc,actionHints:pl},handlers:FC});function LC(e){return ah.listTools(e)}function BC(e,t,o,n){return ah.callTool(e,t,o,n)}async function UC(e,t={}){const o={...t,app:t.app||"siyuan-mcp-sisyphus"};return e.request("/api/tag/getTag",o)}async function jC(e,t,o){return e.request("/api/tag/renameTag",{oldLabel:t,newLabel:o})}async function HC(e,t){return e.request("/api/tag/removeTag",{label:t})}const VC=[S("list",_p,"List tags in the workspace."),S("rename",vp,"Rename a tag."),S("remove",Ip,"Remove a tag.")],ih=De({name:"tag",description:"🏷️ Grouped tag operations.",variants:VC,actionSchema:D_,aggregateOptions:{guidance:Qc,actionHints:dl},handlers:{list:async({client:e,rawArgs:t})=>{const o=_p.parse(t),n=o.query??o.keyword;if(n&&n.trim().length>0){const s=await Nv(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.tags)?a.tags:[];return k({...a,resolvedArgs:{keyword:n},...i.length===0?{warning:"No matching tags were found. If the tag was just created, SiYuan tag indexing may still be catching up; verify the markdown uses #tag# syntax and retry shortly."}:{}})}const r=await UC(e,o);return k(r)},rename:async({client:e,rawArgs:t})=>{const o=vp.parse(t);return await jC(e,o.oldLabel,o.newLabel),F(e,k({success:!0,oldLabel:o.oldLabel,newLabel:o.newLabel}),[{type:"reloadTag"}])},remove:async({client:e,rawArgs:t})=>{const o=Ip.parse(t);return await HC(e,o.label),F(e,k({success:!0,label:o.label}),[{type:"reloadTag"}])}}}),ZC=ih.listTools,YC=ih.callTool,eo={fs:{category:"fs",listTools:GP,callTool:KP},notebook:{category:"notebook",listTools:_C,callTool:vC},document:{category:"document",listTools:IA,callTool:SA},block:{category:"block",listTools:zT,callTool:FT},av:{category:"av",listTools:wS,callTool:kS},file:{category:"file",listTools:y0,callTool:b0},feedback:{category:"feedback",listTools:R0,callTool:x0},search:{category:"search",listTools:yD,callTool:bD},tag:{category:"tag",listTools:ZC,callTool:YC},system:{category:"system",listTools:LC,callTool:BC},flashcard:{category:"flashcard",listTools:gP,callTool:yP},extension:{category:"extension",prepare:$0,listTools:N0,callTool:F0},mascot:{category:"mascot",listTools:nC,callTool:rC}};function Sa(e){return Qe.includes(e)?e:null}async function Da(e,t,o){var n,r;return(r=(n=eo[e]).prepare)==null?void 0:r.call(n,t[e],o)}const mo="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl",ch="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl.1",WC=2*1024*1024,uc=2e4;function dc(e){const t=typeof e=="string"?e:"";return t.length<=uc?{text:t,truncated:!1}:{text:t.slice(0,uc),truncated:!0}}function lh(e){return e==="cli"||e==="http"?e:"stdio"}function GC(){return{cli:0,stdio:0,http:0}}function KC(e){return typeof Buffer<"u"?Buffer.byteLength(e,"utf8"):new TextEncoder().encode(e).length}function pc(e){const t=[],o=e.split(/\r?\n/);for(const n of o){const r=n.trim();if(r)try{const s=JSON.parse(r);typeof s.tool=="string"&&typeof s.action=="string"&&typeof s.ts=="number"&&t.push({...s,transport:lh(s.transport)})}catch{}}return t}async function JC(e,t){const o={...t,seq:Date.now(),ts:Date.now()},n=JSON.stringify(o);try{const r=await e.readFile(mo);if(r){const s=`${r}
524
+ ${n}`;KC(s)>WC?(await e.writeFile(ch,r),await e.writeFile(mo,n)):await e.writeFile(mo,s);return}}catch{}try{await e.writeFile(mo,n)}catch{}}function QC(e){if(!e||e.length===0)return"0";const t=e.reduce((o,n)=>{var r;return o+(((r=n.text)==null?void 0:r.length)??0)},0);return t<=200?"0-200":t<=1e3?"200-1K":t<=5e3?"1K-5K":t<=2e4?"5K-20K":"20K+"}function XC(e){try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return;const o=t.error;if(!o||typeof o!="object"||Array.isArray(o))return;const n=o.type,r=o.code,s=typeof n=="string"&&n?n:void 0,a=typeof r=="string"&&r?r:void 0;return a&&(s==="api_error"||s==="internal_error")?a:s??a}catch{return}}function eE(e){if(!e)return;const t=XC(e);if(t)return t;if(e.includes("McpError")){const o=e.match(/McpError\s*\(?([^:)]{1,40})\)?/);return o?`McpError:${o[1]}`:"McpError"}return e.includes("SiYuan API error")?"SiYuanApiError":e.includes("HTTP error")?"HttpError":e.includes("timeout")?"Timeout":e.includes("Unauthorized")||e.includes("unauthorized")?"Unauthorized":/permission denied/i.test(e)?"permission_denied":"UnknownError"}const tE=new Set(["success","id","ids","name","title","label","oldLabel","newLabel","path","paths","from","to","fromID","toID","fromIDs","toIDs","notebook","permission","avID","blockID","keyID","columnID","rowID","srcIDs","count","changed","editsApplied","replacements","created","updated","removed","overwritten","folded","partial","reason","warning","skippedComplexBlocks","recommendedTools"]),oE=new Set(["action","dataType","previousID","nextID","parentID","prepared","materialized","insertedAfter","semantics","sourceAvID","iconHint","showing","contentLength","returnedTotal","returnedPageCount","returnedHasNextPage","kernelMatchedBlockCount","kernelMatchedRootCount","kernelPageCount","kernelHasNextPage","pagingHint","paginationMode","resolvedArgs","totalRows","matchedBlockCount","matchedRootCount","returnedHasNextPage","returnedPageCount","returnedTotal"]),nE=new Set(["markdown","content","blockPath","rootID","root_id","parentID","parent_id","box","ial","sort","sortMode","icon","newFlashcardCount","dueFlashcardCount","flashcardCount"]);function ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rE(e,t){const o=e.content[0];return{...e,content:[{...o??{type:"text"},type:"text",text:JSON.stringify(t,null,2)}]}}function sE(e){return e.category==="extension"||e.action==="help"||e.category==="system"&&e.action==="conf"}function aE(e){const t=new Set(["type","code","message","fields","hint","notebook","current_permission","required_permission","validActions","validTopics","topic"]);return Object.fromEntries(Object.entries(e).filter(([o])=>t.has(o)))}function iE(e){const t={};for(const o of["id","type","subtype","hPath","path","notebookName"])e[o]!==void 0&&(t[o]=e[o]);return e.plainContent!==void 0?t.plainContent=e.plainContent:e.excerpt!==void 0?t.excerpt=e.excerpt:e.content!==void 0&&(t.content=e.content),Object.keys(t).length>0?t:Ta(e)}function Ta(e){const t={};for(const[o,n]of Object.entries(e))nE.has(o)||(t[o]=sr(n));return t}function cE(e){return e.plainContent!==void 0||e.excerpt!==void 0||e.rootID!==void 0||e.root_id!==void 0||e.blockPath!==void 0}function sr(e){return Array.isArray(e)?e.map(t=>ft(t)?cE(t)?iE(t):Ta(t):sr(t)):ft(e)?dh(e):e}function uh(e){if(ft(e)&&"partialFailure"in e)return{partialFailure:e.partialFailure}}function lE(e,t){const o={};for(const r of tE)e[r]!==void 0&&(o[r]=e[r]);const n=uh(e.uiRefresh);return n!==void 0&&(o.uiRefresh=n),Object.keys(o).length>0?o:e}function dh(e,t){if(ft(e.error))return{error:aE(e.error)};if(e.success===!0)return lE(e);const o={};for(const[n,r]of Object.entries(e)){if(n==="uiRefresh"){const s=uh(r);s!==void 0&&(o.uiRefresh=s);continue}if(n==="nextWindow"&&ft(r)){o.nextWindow=r;continue}oE.has(n)||(o[n]=sr(r))}return o}function uE(e,t){if(sE(t))return e;const o=e.content[0];if(!o||o.type!=="text")return e;let n;try{n=JSON.parse(o.text)}catch{return e}const r=Array.isArray(n)?n.map(s=>ft(s)?Ta(s):sr(s)):ft(n)?dh(n):n;return rE(e,r)}const dE="telemetryConfig",ph=`/data/storage/petal/siyuan-plugins-mcp-sisyphus/${dE}`;function fh(){return{enabled:!1,lastReportAt:0,reportIntervalHours:24}}function hh(e){const t=fh();if(!e||typeof e!="object"||Array.isArray(e))return t;const o=e,n=typeof o.reportIntervalHours=="number"&&Number.isFinite(o.reportIntervalHours)?Math.max(1,Math.min(168,Math.floor(o.reportIntervalHours))):t.reportIntervalHours,r=typeof o.endpoint=="string"&&o.endpoint.trim().length>0?o.endpoint.trim():void 0;return{enabled:typeof o.enabled=="boolean"?o.enabled:t.enabled,lastReportAt:typeof o.lastReportAt=="number"&&Number.isFinite(o.lastReportAt)?Math.max(0,o.lastReportAt):t.lastReportAt,reportIntervalHours:n,endpoint:r}}async function pE(e){try{const t=await e.readFile(ph);if(t)return hh(JSON.parse(t))}catch{}return fh()}async function fc(e,t){const o=hh(t);try{await e.writeFile(ph,JSON.stringify(o))}catch{}return o}async function fE(e){const t=[];try{const o=await e.readFile(mo);o&&t.push(...pc(o))}catch{}try{const o=await e.readFile(ch);o&&t.push(...pc(o))}catch{}return t}async function hE(e,t){const n=(await fE(e)).filter(p=>p.ts>=t);if(n.length===0)return null;const r=n.length,s=n.filter(p=>p.status==="error").length,a=n.reduce((p,f)=>p+(f.durationMs||0),0),i=new Map,c=new Array(24).fill(0),l=GC();for(const p of n){const f=`${p.tool}/${p.action}`,h=i.get(f);h?(h.count+=1,h.errorCount+=p.status==="error"?1:0,h.totalDuration+=p.durationMs||0):i.set(f,{tool:p.tool,action:p.action,count:1,errorCount:p.status==="error"?1:0,totalDuration:p.durationMs||0});const g=new Date(p.ts).getHours();g>=0&&g<24&&(c[g]+=1),l[lh(p.transport)]+=1}const u=Array.from(i.values()).map(p=>({tool:p.tool,action:p.action,count:p.count,errorCount:p.errorCount,avgDurationMs:p.count>0?Math.round(p.totalDuration/p.count):0})).sort((p,f)=>f.count-p.count);return{v:1,reportedAt:Date.now(),since:t,aggregates:{totalCalls:r,errorCalls:s,errorRate:r>0?Math.round(s/r*1e3)/1e3:0,avgDurationMs:r>0?Math.round(a/r):0,actionBreakdown:u,hourlyDistribution:c,transportDistribution:l},meta:{pluginVersion:process.env.SIYUAN_MCP_PLUGIN_VERSION,nodeVersion:process.version,platform:process.platform}}}async function hc(e){const t=await pE(e);if(!t.enabled||!t.endpoint)return;const o=t.reportIntervalHours*60*60*1e3,n=t.lastReportAt+o;if(Date.now()<n)return;const r=await hE(e,t.lastReportAt||Date.now()-o);if(!r){await fc(e,{...t,lastReportAt:Date.now()});return}try{const s=new AbortController,a=setTimeout(()=>s.abort(),15e3),i=await fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:s.signal});clearTimeout(a),i.ok&&await fc(e,{...t,lastReportAt:Date.now()})}catch{}}function mc(e,t,o,n,r,s,a,i){const c=Gr(n),l=i?qT(i):Gr(a),u=i?i.map(g=>g.text??"").join(""):a??"",p=dc(n),f=dc(u),h=o&&typeof o=="object"?Object.keys(o).filter(g=>g!=="action"):[];return{tool:e,action:t,status:r,durationMs:s,errorCode:r==="error"?eE(a):void 0,paramKeys:h,resultSizeHint:QC(i),transport:wa(),requestChars:c.chars,responseChars:l.chars,requestApproxTokens:c.approxTokens,responseApproxTokens:l.approxTokens,totalApproxTokens:c.approxTokens+l.approxTokens,tokenMode:Sf,requestText:p.text,responseText:f.text,requestTextTruncated:p.truncated,responseTextTruncated:f.truncated}}function mE(e){var t;if(e.isError)return{};try{const o=JSON.parse(((t=e.content[0])==null?void 0:t.text)??"{}");return{itemId:typeof o.item_id=="string"?o.item_id:void 0,itemLabel:typeof o.item=="string"?o.item:void 0,itemType:typeof o.type=="string"?o.type:void 0,itemEmoji:typeof o.emoji=="string"?o.emoji:void 0}}catch{return{}}}function gE(e,t){if(t||e.isError)return e;const o=e.content[0];if(!o||o.type!=="text")return e;let n;try{const a=JSON.parse(o.text);if(!a||typeof a!="object"||Array.isArray(a))return e;n=a}catch{return e}const r=n.uiRefresh;if(!r||typeof r!="object"||Array.isArray(r)||"partialFailure"in r)return e;const s={...n};return delete s.uiRefresh,{...e,content:[{...o,text:JSON.stringify(s,null,2)}]}}async function gc(e,t){const o=JC(e,t).catch(()=>{});wa()==="cli"&&await o}async function yE(e,t){var g;const{client:o,category:n,name:r,action:s,args:a}=e,i=e.requestText,c=Date.now(),l=n==="mascot"?await Lo(o):await XP(o,`${r}/${s}`);await ic(o,{tool:r,action:s,status:"running",totalCalls:l.totalCalls,balance:l.balance});let u;try{u=await t()}catch(b){const _=Date.now()-c,w=b instanceof Error?b.message:String(b);throw await gc(o,mc(r,s,a,i,"error",_,w)),hc(o).catch(()=>{}),b}e.slimResponses?u=uE(u,{category:n,action:s}):e.slimResponses===void 0&&(u=gE(u,e.includeUiRefreshMetadata));const p=n==="mascot"?await Lo(o):l,f=n==="mascot"?mE(u):{};await ic(o,{tool:r,action:s,status:u.isError?"error":"success",totalCalls:p.totalCalls,balance:p.balance,...f});const h=Date.now()-c;return await gc(o,mc(r,s,a,i,u.isError?"error":"success",h,(g=u.content[0])==null?void 0:g.text,u.content)),hc(o).catch(()=>{}),u}function bE(e,t,o){var _;const n=wE(t),r=new Map,s=new Set,a=new Set;for(const[w,P]of Object.entries(n)){if(w==="action"||w==="topic")continue;const D=ln(w);for(const T of D)r.set(T.toLowerCase(),w);if(Io(P)==="boolean")for(const T of D)s.add(T);else for(const T of D)a.add(T)}for(const w of F_(o)){const P=w.schema??n[w.canonical]??{},D=new Set([...ln(w.canonical),...w.aliases.flatMap(ln)]);for(const T of D)r.set(T.toLowerCase(),w.canonical);if(Io(P)==="boolean")for(const T of D)s.add(T);else for(const T of D)a.add(T);n[_=w.canonical]??(n[_]=P)}const i=[];for(const w of Object.keys(n))if(!(w==="action"||w==="topic"))for(const P of ln(w))i.push(`${P}-json`);const c=[...a,...i],l=[...s,...c],u=vE(e,c,l),p=Cc(u,{boolean:[...s],string:[...a,...i]}),f=SE(u),h={},g=[],b={};for(const[w,P]of Object.entries(p))if(w!=="_"&&w.endsWith("-json")){const D=w.slice(0,-5),A=r.get(D.toLowerCase());if(!A){g.push(`Unknown flag --${w}.`);continue}if(typeof P!="string"||P.length===0)continue;try{b[A]=JSON.parse(P)}catch(T){throw new Error(`--${w} must be valid JSON: ${T instanceof Error?T.message:String(T)}`)}}for(const[w,P]of Object.entries(p)){if(w==="_"||w.endsWith("-json"))continue;const D=r.get(w.toLowerCase());if(!D){g.push(`Unknown flag --${w}; ignored.`);continue}if(D in b||D in h)continue;const A=n[D];Io(A)==="boolean"&&P===!1&&!f.has(w.toLowerCase())||(h[D]=kE(D,P,A))}return p._.length>0&&g.push(`Extra positional arguments ignored: ${p._.join(" ")}`),{args:{...h,...b},warnings:g}}function wE(e){const t={...e.properties??{}},o=e["x-sisyphus-actionSchemas"],n=Array.isArray(o)?o:Array.isArray(e.oneOf)?e.oneOf:Array.isArray(e.anyOf)?e.anyOf:[];for(const r of n){if(!r||typeof r!="object")continue;const s=r.properties;if(!(!s||typeof s!="object"||Array.isArray(s)))for(const[a,i]of Object.entries(s))t[a]??(t[a]=i)}return t}function kE(e,t,o){const n=Io(o);if(n==="array")return Array.isArray(t)?t.map(r=>yc(r,o.items)):typeof t=="string"?t.split(",").map(r=>yc(r.trim(),o.items)):[t];if(n==="number"||n==="integer"){if(typeof t=="number")return t;if(typeof t=="string"){const r=n==="integer"?parseInt(t,10):parseFloat(t);if(Number.isNaN(r))throw new Error(`--${Sr(e)} expected a number but got "${t}".`);return r}return t}if(n==="boolean")return typeof t=="boolean"?t:typeof t=="string"?t==="true"||t==="1"||t==="yes":!!t;if(n==="object"){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string")try{return JSON.parse(t)}catch{throw new Error(`--${Sr(e)} expects JSON for an object field. Use --${Sr(e)}-json '{"..."}'.`)}return t}return typeof t=="string"?t:String(t)}function yc(e,t){if(!t)return e;const o=Io(t);return(o==="number"||o==="integer")&&typeof e=="string"?o==="integer"?parseInt(e,10):parseFloat(e):o==="boolean"&&typeof e=="string"?e==="true"||e==="1"||e==="yes":e}function Io(e){if(!e)return"string";const t=e.type;return Array.isArray(t)?t[0]??"string":typeof t=="string"?t:(e.enum||e.anyOf||e.oneOf,"string")}function ln(e){const t=mh(e),o=new Set([e]);return t.length===0?[...o]:(o.add(t.join("-")),o.add(t.join("_")),o.add(_E(t)),[...o])}function mh(e){return e.split(/[_-]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z]{2,})/g,"$1 $2").split(/\s+/)).flatMap(t=>t.match(/[A-Z]+[a-z]*|[a-z]+|[0-9]+/g)??[]).map(t=>t.toLowerCase())}function _E(e){return e.length===0?"":e[0]+e.slice(1).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Sr(e){const t=mh(e);return t.length>0?t.join("-"):e.toLowerCase()}function vE(e,t,o){const n=new Set(t.map(a=>a.toLowerCase())),r=new Set(o.map(a=>a.toLowerCase())),s=[];for(let a=0;a<e.length;a++){const i=e[a],c=gh(i);if(!c||c.hasEquals||c.negated||!n.has(c.key.toLowerCase())){s.push(i);continue}const l=e[a+1];if(l===void 0||l==="--"||IE(l,r)){s.push(i);continue}s.push(`${i}=${l}`),a++}return s}function IE(e,t){const o=gh(e);return!!(o&&t.has(o.key.toLowerCase()))}function gh(e){if(!e.startsWith("-")||e==="-"||e==="--")return null;const t=e.startsWith("--")?2:1,o=e.indexOf("="),n=o===-1?e.slice(t):e.slice(t,o);if(!n)return null;const r=e.startsWith("--")&&n.startsWith("no-"),s=r?n.slice(3):n;return s?{key:s,hasEquals:o!==-1,negated:r}:null}function SE(e){const t=new Set;for(const o of e){if(!o.startsWith("-"))continue;const n=o.indexOf("="),r=n===-1?o.replace(/^-+/,""):o.slice(o.startsWith("--")?2:1,n),s=r.startsWith("no-")?r.slice(3):r;s&&t.add(s.toLowerCase())}return t}class DE{constructor(t={}){ee(this,"baseUrl");ee(this,"timeout");ee(this,"token","");const o=t.baseUrl||process.env.SIYUAN_API_URL||"http://127.0.0.1:6806";this.baseUrl=o.replace(/\/+$/,""),this.timeout=t.timeout||5e3}setToken(t){this.token=t}getBaseUrl(){return this.baseUrl}getAuthHeaders(){const t={Connection:"close"};return this.token&&(t.Authorization=`Token ${this.token}`),t}async fetchWithTimeout(t,o){let s=null;for(let a=0;a<=3;a++){const i=new AbortController,c=setTimeout(()=>i.abort(),this.timeout);try{const u=await fetch(t,{...o,signal:i.signal});if(clearTimeout(c),!u.ok){if(u.status>=400&&u.status<500&&u.status!==429)throw new Error(`HTTP error: ${u.status} ${u.statusText}`);if(await u.arrayBuffer().catch(()=>{}),s=new Error(`HTTP error: ${u.status} ${u.statusText}`),a<3)continue;throw s}return u}catch(u){if(clearTimeout(c),u instanceof Error&&u.name==="AbortError"?s=new Error(`Request timeout after ${this.timeout}ms`):s=u instanceof Error?u:new Error(String(u)),a>=3)throw s}const l=300*(a+1);await new Promise(u=>setTimeout(u,l))}throw s??new Error("Unknown fetch error")}async readRemoteFile(t){return this.fetchWithTimeout(`${this.baseUrl}/api/file/getFile`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify({path:t})})}async readData(t,o){const n=await this.fetchWithTimeout(t,o),r=await n.text();if(r.trim()==="")return null;let s;try{s=JSON.parse(r)}catch{const a=r.length>200?`${r.slice(0,200)}...`:r,i=[n.status,n.statusText].filter(Boolean).join(" ");throw new Error(`Invalid SiYuan API response from ${t}${i?` (HTTP ${i})`:""}: ${a}`)}if(s.code!==0)throw new Error(`SiYuan API error: ${s.code} - ${s.msg}`);return s.data}async readFile(t){return await(await this.readRemoteFile(t)).text()}async readFileBinary(t){const o=await this.readRemoteFile(t);return new Uint8Array(await o.arrayBuffer())}async writeFile(t,o){const n=new FormData,r=new File([o],"content");n.append("path",t),n.append("isDir","false"),n.append("modTime",String(Date.now())),n.append("file",r),await this.requestFormData("/api/file/putFile",n)}async requestFormData(t,o){return this.readData(`${this.baseUrl}${t}`,{method:"POST",headers:this.getAuthHeaders(),body:o})}async request(t,o){return this.readData(`${this.baseUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(o??{})})}}const TE=["none","r","rw","rwd"],bc={none:"none",readonly:"r",write:"rw"},bn="/data/storage/petal/siyuan-plugins-mcp-sisyphus/notebookPermissions",AE=process.env.SIYUAN_MCP_DEBUG_PERMISSIONS==="1";function un(...e){AE&&console.error("[MCP]",...e)}function yh(e){return typeof e=="string"&&TE.includes(e)}function PE(e){return yh(e)?e:typeof e=="string"&&e in bc?bc[e]:"none"}function CE(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,PE(o)]))}class EE{constructor(t){ee(this,"permissions",{});ee(this,"client",null);ee(this,"loaded",!1);this.client=t??null}async load(){if(this.loaded)return;if(!this.client)throw new Error("[Permissions] No SiYuan client available; cannot load permissions.");let t;try{t=await this.client.readFile(bn)}catch(n){throw un("Failed to read permissions from API:",n),new Error(`[Permissions] Failed to read permissions from SiYuan API: ${n instanceof Error?n.message:String(n)}`)}if(!t||!t.trim()){this.permissions={},this.loaded=!0,un("Permissions not found in API, using empty state");return}let o;try{o=JSON.parse(t)}catch(n){throw un("Failed to parse permissions JSON from API:",n),new Error(`[Permissions] Permissions file at ${bn} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}this.permissions=CE(o),this.loaded=!0,un("Permissions loaded from API:",Object.keys(this.permissions).length,"entries")}async reload(){this.loaded=!1,await this.load()}async save(){if(!this.client)throw new Error("[Permissions] No SiYuan client available; cannot save permissions.");const t=JSON.stringify(this.permissions,null,2);await this.client.writeFile(bn,t),this.loaded=!0}get(t){const o=this.permissions[t];return yh(o)?o:"r"}async set(t,o){this.permissions[t]=o,await this.save()}getAll(){return{...this.permissions}}canRead(t){return this.get(t)!=="none"}canWrite(t){return["rw","rwd"].includes(this.get(t))}canDelete(t){return this.get(t)==="rwd"}}function ar(e){return!!e._zod}function He(e,t){return ar(e)?Dl(e,t):e.safeParse(t)}function bh(e){var o,n;if(!e)return;let t;if(ar(e)?t=(n=(o=e._zod)==null?void 0:o.def)==null?void 0:n.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function RE(e){var r;if(ar(e)){const a=(r=e._zod)==null?void 0:r.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const o=e._def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}const n=e.value;if(n!==void 0)return n}const ir="2025-11-25",xE=[ir,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lt="io.modelcontextprotocol/related-task",cr="2.0",ae=o_(e=>e!==null&&(typeof e=="object"||typeof e=="function")),wh=W([d(),C().int()]),kh=d();ue({ttl:C().optional(),pollInterval:C().optional()});const OE=m({ttl:C().optional()}),NE=m({taskId:d()}),Aa=ue({progressToken:wh.optional(),[lt]:NE.optional()}),ke=m({_meta:Aa.optional()}),Go=ke.extend({task:OE.optional()}),$E=e=>Go.safeParse(e).success,de=m({method:d(),params:ke.loose().optional()}),Te=m({_meta:Aa.optional()}),Ae=m({method:d(),params:Te.loose().optional()}),pe=ue({_meta:Aa.optional()}),lr=W([d(),C().int()]),_h=m({jsonrpc:y(cr),id:lr,...de.shape}).strict(),ss=e=>_h.safeParse(e).success,vh=m({jsonrpc:y(cr),...Ae.shape}).strict(),ME=e=>vh.safeParse(e).success,Pa=m({jsonrpc:y(cr),id:lr,result:pe}).strict(),go=e=>Pa.safeParse(e).success;var L;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(L||(L={}));const Ca=m({jsonrpc:y(cr),id:lr.optional(),error:m({code:C().int(),message:d(),data:K().optional()})}).strict(),zE=e=>Ca.safeParse(e).success,Dr=W([_h,vh,Pa,Ca]);W([Pa,Ca]);const xt=pe.strict(),FE=Te.extend({requestId:lr.optional(),reason:d().optional()}),Ea=Ae.extend({method:y("notifications/cancelled"),params:FE}),qE=m({src:d(),mimeType:d().optional(),sizes:I(d()).optional(),theme:z(["light","dark"]).optional()}),Ko=m({icons:I(qE).optional()}),to=m({name:d(),title:d().optional()}),Ih=to.extend({...to.shape,...Ko.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),LE=Gs(m({applyDefaults:x().optional()}),j(d(),K())),BE=Iu(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Gs(m({form:LE.optional(),url:ae.optional()}),j(d(),K()).optional())),UE=ue({list:ae.optional(),cancel:ae.optional(),requests:ue({sampling:ue({createMessage:ae.optional()}).optional(),elicitation:ue({create:ae.optional()}).optional()}).optional()}),jE=ue({list:ae.optional(),cancel:ae.optional(),requests:ue({tools:ue({call:ae.optional()}).optional()}).optional()}),HE=m({experimental:j(d(),ae).optional(),sampling:m({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:BE.optional(),roots:m({listChanged:x().optional()}).optional(),tasks:UE.optional(),extensions:j(d(),ae).optional()}),VE=ke.extend({protocolVersion:d(),capabilities:HE,clientInfo:Ih}),ZE=de.extend({method:y("initialize"),params:VE}),YE=m({experimental:j(d(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:m({listChanged:x().optional()}).optional(),resources:m({subscribe:x().optional(),listChanged:x().optional()}).optional(),tools:m({listChanged:x().optional()}).optional(),tasks:jE.optional(),extensions:j(d(),ae).optional()}),Sh=pe.extend({protocolVersion:d(),capabilities:YE,serverInfo:Ih,instructions:d().optional()}),Dh=Ae.extend({method:y("notifications/initialized"),params:Te.optional()}),WE=e=>Dh.safeParse(e).success,Ra=de.extend({method:y("ping"),params:ke.optional()}),GE=m({progress:C(),total:te(C()),message:te(d())}),KE=m({...Te.shape,...GE.shape,progressToken:wh}),xa=Ae.extend({method:y("notifications/progress"),params:KE}),JE=ke.extend({cursor:kh.optional()}),Jo=de.extend({params:JE.optional()}),Qo=pe.extend({nextCursor:kh.optional()}),QE=z(["working","input_required","completed","failed","cancelled"]),Xo=m({taskId:d(),status:QE,ttl:W([C(),mu()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:te(C()),statusMessage:te(d())}),Bo=pe.extend({task:Xo}),XE=Te.merge(Xo),$n=Ae.extend({method:y("notifications/tasks/status"),params:XE}),Oa=de.extend({method:y("tasks/get"),params:ke.extend({taskId:d()})}),Na=pe.merge(Xo),$a=de.extend({method:y("tasks/result"),params:ke.extend({taskId:d()})});pe.loose();const Ma=Jo.extend({method:y("tasks/list")}),za=Qo.extend({tasks:I(Xo)}),Fa=de.extend({method:y("tasks/cancel"),params:ke.extend({taskId:d()})}),eR=pe.merge(Xo),Th=m({uri:d(),mimeType:te(d()),_meta:j(d(),K()).optional()}),Ah=Th.extend({text:d()}),qa=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ph=Th.extend({blob:qa}),en=z(["user","assistant"]),lo=m({audience:I(en).optional(),priority:C().min(0).max(1).optional(),lastModified:du({offset:!0}).optional()}),Ch=m({...to.shape,...Ko.shape,uri:d(),description:te(d()),mimeType:te(d()),size:te(C()),annotations:lo.optional(),_meta:te(ue({}))}),tR=m({...to.shape,...Ko.shape,uriTemplate:d(),description:te(d()),mimeType:te(d()),annotations:lo.optional(),_meta:te(ue({}))}),oR=Jo.extend({method:y("resources/list")}),Eh=Qo.extend({resources:I(Ch)}),nR=Jo.extend({method:y("resources/templates/list")}),Rh=Qo.extend({resourceTemplates:I(tR)}),La=ke.extend({uri:d()}),rR=La,sR=de.extend({method:y("resources/read"),params:rR}),xh=pe.extend({contents:I(W([Ah,Ph]))}),Oh=Ae.extend({method:y("notifications/resources/list_changed"),params:Te.optional()}),aR=La,iR=de.extend({method:y("resources/subscribe"),params:aR}),cR=La,lR=de.extend({method:y("resources/unsubscribe"),params:cR}),uR=Te.extend({uri:d()}),dR=Ae.extend({method:y("notifications/resources/updated"),params:uR}),pR=m({name:d(),description:te(d()),required:te(x())}),fR=m({...to.shape,...Ko.shape,description:te(d()),arguments:te(I(pR)),_meta:te(ue({}))}),hR=Jo.extend({method:y("prompts/list")}),Nh=Qo.extend({prompts:I(fR)}),mR=ke.extend({name:d(),arguments:j(d(),d()).optional()}),gR=de.extend({method:y("prompts/get"),params:mR}),Ba=m({type:y("text"),text:d(),annotations:lo.optional(),_meta:j(d(),K()).optional()}),Ua=m({type:y("image"),data:qa,mimeType:d(),annotations:lo.optional(),_meta:j(d(),K()).optional()}),ja=m({type:y("audio"),data:qa,mimeType:d(),annotations:lo.optional(),_meta:j(d(),K()).optional()}),yR=m({type:y("tool_use"),name:d(),id:d(),input:j(d(),K()),_meta:j(d(),K()).optional()}),bR=m({type:y("resource"),resource:W([Ah,Ph]),annotations:lo.optional(),_meta:j(d(),K()).optional()}),wR=Ch.extend({type:y("resource_link")}),Ha=W([Ba,Ua,ja,wR,bR]),kR=m({role:en,content:Ha}),$h=pe.extend({description:d().optional(),messages:I(kR)}),Mh=Ae.extend({method:y("notifications/prompts/list_changed"),params:Te.optional()}),_R=m({title:d().optional(),readOnlyHint:x().optional(),destructiveHint:x().optional(),idempotentHint:x().optional(),openWorldHint:x().optional()}),vR=m({taskSupport:z(["required","optional","forbidden"]).optional()}),zh=m({...to.shape,...Ko.shape,description:d().optional(),inputSchema:m({type:y("object"),properties:j(d(),ae).optional(),required:I(d()).optional()}).catchall(K()),outputSchema:m({type:y("object"),properties:j(d(),ae).optional(),required:I(d()).optional()}).catchall(K()).optional(),annotations:_R.optional(),execution:vR.optional(),_meta:j(d(),K()).optional()}),IR=Jo.extend({method:y("tools/list")}),Fh=Qo.extend({tools:I(zh)}),ur=pe.extend({content:I(Ha).default([]),structuredContent:j(d(),K()).optional(),isError:x().optional()});ur.or(pe.extend({toolResult:K()}));const SR=Go.extend({name:d(),arguments:j(d(),K()).optional()}),DR=de.extend({method:y("tools/call"),params:SR}),qh=Ae.extend({method:y("notifications/tools/list_changed"),params:Te.optional()}),TR=m({autoRefresh:x().default(!0),debounceMs:C().int().nonnegative().default(300)}),Lh=z(["debug","info","notice","warning","error","critical","alert","emergency"]),AR=ke.extend({level:Lh}),PR=de.extend({method:y("logging/setLevel"),params:AR}),CR=Te.extend({level:Lh,logger:d().optional(),data:K()}),ER=Ae.extend({method:y("notifications/message"),params:CR}),RR=m({name:d().optional()}),xR=m({hints:I(RR).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),OR=m({mode:z(["auto","required","none"]).optional()}),NR=m({type:y("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:I(Ha).default([]),structuredContent:m({}).loose().optional(),isError:x().optional(),_meta:j(d(),K()).optional()}),$R=bu("type",[Ba,Ua,ja]),Mn=bu("type",[Ba,Ua,ja,yR,NR]),MR=m({role:en,content:W([Mn,I(Mn)]),_meta:j(d(),K()).optional()}),zR=Go.extend({messages:I(MR),modelPreferences:xR.optional(),systemPrompt:d().optional(),includeContext:z(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:I(d()).optional(),metadata:ae.optional(),tools:I(zh).optional(),toolChoice:OR.optional()}),Bh=de.extend({method:y("sampling/createMessage"),params:zR}),Uh=pe.extend({model:d(),stopReason:te(z(["endTurn","stopSequence","maxTokens"]).or(d())),role:en,content:$R}),jh=pe.extend({model:d(),stopReason:te(z(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:en,content:W([Mn,I(Mn)])}),FR=m({type:y("boolean"),title:d().optional(),description:d().optional(),default:x().optional()}),qR=m({type:y("string"),title:d().optional(),description:d().optional(),minLength:C().optional(),maxLength:C().optional(),format:z(["email","uri","date","date-time"]).optional(),default:d().optional()}),LR=m({type:z(["number","integer"]),title:d().optional(),description:d().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),BR=m({type:y("string"),title:d().optional(),description:d().optional(),enum:I(d()),default:d().optional()}),UR=m({type:y("string"),title:d().optional(),description:d().optional(),oneOf:I(m({const:d(),title:d()})),default:d().optional()}),jR=m({type:y("string"),title:d().optional(),description:d().optional(),enum:I(d()),enumNames:I(d()).optional(),default:d().optional()}),HR=W([BR,UR]),VR=m({type:y("array"),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({type:y("string"),enum:I(d())}),default:I(d()).optional()}),ZR=m({type:y("array"),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({anyOf:I(m({const:d(),title:d()}))}),default:I(d()).optional()}),YR=W([VR,ZR]),WR=W([jR,HR,YR]),GR=W([WR,FR,qR,LR]),KR=Go.extend({mode:y("form").optional(),message:d(),requestedSchema:m({type:y("object"),properties:j(d(),GR),required:I(d()).optional()})}),JR=Go.extend({mode:y("url"),message:d(),elicitationId:d(),url:d().url()}),QR=W([KR,JR]),Hh=de.extend({method:y("elicitation/create"),params:QR}),XR=Te.extend({elicitationId:d()}),ex=Ae.extend({method:y("notifications/elicitation/complete"),params:XR}),Vh=pe.extend({action:z(["accept","decline","cancel"]),content:Iu(e=>e===null?void 0:e,j(d(),W([d(),C(),x(),I(d())])).optional())}),tx=m({type:y("ref/resource"),uri:d()}),ox=m({type:y("ref/prompt"),name:d()}),nx=ke.extend({ref:W([ox,tx]),argument:m({name:d(),value:d()}),context:m({arguments:j(d(),d()).optional()}).optional()}),rx=de.extend({method:y("completion/complete"),params:nx}),Zh=pe.extend({completion:ue({values:I(d()).max(100),total:te(C().int()),hasMore:te(x())})}),sx=m({uri:d().startsWith("file://"),name:d().optional(),_meta:j(d(),K()).optional()}),ax=de.extend({method:y("roots/list"),params:ke.optional()}),ix=pe.extend({roots:I(sx)}),cx=Ae.extend({method:y("notifications/roots/list_changed"),params:Te.optional()});W([Ra,ZE,rx,PR,gR,hR,oR,nR,sR,iR,lR,DR,IR,Oa,$a,Ma,Fa]);W([Ea,xa,Dh,cx,$n]);W([xt,Uh,jh,Vh,ix,Na,za,Bo]);W([Ra,Bh,Hh,ax,Oa,$a,Ma,Fa]);W([Ea,xa,ER,dR,Oh,qh,Mh,$n,ex]);W([xt,Sh,Zh,$h,Nh,Eh,Rh,xh,ur,Fh,Na,za,Bo]);class M extends Error{constructor(t,o,n){super(`MCP error ${t}: ${o}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,o,n){if(t===L.UrlElicitationRequired&&n){const r=n;if(r.elicitations)return new lx(r.elicitations,o)}return new M(t,o,n)}}class lx extends M{constructor(t,o=`URL elicitation${t.length>1?"s":""} required`){super(L.UrlElicitationRequired,o,{elicitations:t})}get elicitations(){var t;return((t=this.data)==null?void 0:t.elicitations)??[]}}function it(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wc(e){const t=bh(e),o=t==null?void 0:t.method;if(!o)throw new Error("Schema is missing a method literal");const n=RE(o);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function kc(e,t){const o=He(e,t);if(!o.success)throw o.error;return o.data}const ux=6e4;class dx{constructor(t){this._options=t,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(Ea,o=>{this._oncancel(o)}),this.setNotificationHandler(xa,o=>{this._onprogress(o)}),this.setRequestHandler(Ra,o=>({})),this._taskStore=t==null?void 0:t.taskStore,this._taskMessageQueue=t==null?void 0:t.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Oa,async(o,n)=>{const r=await this._taskStore.getTask(o.params.taskId,n.sessionId);if(!r)throw new M(L.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler($a,async(o,n)=>{const r=async()=>{var i;const s=o.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(c.type==="response"||c.type==="error"){const l=c.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),c.type==="response")p(l);else{const f=l,h=new M(f.error.code,f.error.message,f.error.data);p(h)}else{const f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await((i=this._transport)==null?void 0:i.send(c.message,{relatedRequestId:n.requestId}))}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new M(L.InvalidParams,`Task not found: ${s}`);if(!it(a.status))return await this._waitForTaskUpdate(s,n.signal),await r();if(it(a.status)){const c=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...c,_meta:{...c._meta,[lt]:{taskId:s}}}}return await r()};return await r()}),this.setRequestHandler(Ma,async(o,n)=>{var r;try{const{tasks:s,nextCursor:a}=await this._taskStore.listTasks((r=o.params)==null?void 0:r.cursor,n.sessionId);return{tasks:s,nextCursor:a,_meta:{}}}catch(s){throw new M(L.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Fa,async(o,n)=>{try{const r=await this._taskStore.getTask(o.params.taskId,n.sessionId);if(!r)throw new M(L.InvalidParams,`Task not found: ${o.params.taskId}`);if(it(r.status))throw new M(L.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(o.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(o.params.taskId);const s=await this._taskStore.getTask(o.params.taskId,n.sessionId);if(!s)throw new M(L.InvalidParams,`Task not found after cancellation: ${o.params.taskId}`);return{_meta:{},...s}}catch(r){throw r instanceof M?r:new M(L.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;const o=this._requestHandlerAbortControllers.get(t.params.requestId);o==null||o.abort(t.params.reason)}_setupTimeout(t,o,n,r,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(r,o),startTime:Date.now(),timeout:o,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:r})}_resetTimeout(t){const o=this._timeoutInfo.get(t);if(!o)return!1;const n=Date.now()-o.startTime;if(o.maxTotalTimeout&&n>=o.maxTotalTimeout)throw this._timeoutInfo.delete(t),M.fromError(L.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:o.maxTotalTimeout,totalElapsed:n});return clearTimeout(o.timeoutId),o.timeoutId=setTimeout(o.onTimeout,o.timeout),!0}_cleanupTimeout(t){const o=this._timeoutInfo.get(t);o&&(clearTimeout(o.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var s,a,i;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=t;const o=(s=this.transport)==null?void 0:s.onclose;this._transport.onclose=()=>{o==null||o(),this._onclose()};const n=(a=this.transport)==null?void 0:a.onerror;this._transport.onerror=c=>{n==null||n(c),this._onerror(c)};const r=(i=this._transport)==null?void 0:i.onmessage;this._transport.onmessage=(c,l)=>{r==null||r(c,l),go(c)||zE(c)?this._onresponse(c):ss(c)?this._onrequest(c,l):ME(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var n;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const o=M.fromError(L.ConnectionClosed,"Connection closed");this._transport=void 0,(n=this.onclose)==null||n.call(this);for(const r of t.values())r(o)}_onerror(t){var o;(o=this.onerror)==null||o.call(this,t)}_onnotification(t){const o=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;o!==void 0&&Promise.resolve().then(()=>o(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,o){var u,p,f,h;const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,r=this._transport,s=(f=(p=(u=t.params)==null?void 0:u._meta)==null?void 0:p[lt])==null?void 0:f.taskId;if(n===void 0){const g={jsonrpc:"2.0",id:t.id,error:{code:L.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},r==null?void 0:r.sessionId).catch(b=>this._onerror(new Error(`Failed to enqueue error response: ${b}`))):r==null||r.send(g).catch(b=>this._onerror(new Error(`Failed to send an error response: ${b}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=$E(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,r==null?void 0:r.sessionId):void 0,l={signal:a.signal,sessionId:r==null?void 0:r.sessionId,_meta:(h=t.params)==null?void 0:h._meta,sendNotification:async g=>{if(a.signal.aborted)return;const b={relatedRequestId:t.id};s&&(b.relatedTask={taskId:s}),await this.notification(g,b)},sendRequest:async(g,b,_)=>{var D;if(a.signal.aborted)throw new M(L.ConnectionClosed,"Request was cancelled");const w={..._,relatedRequestId:t.id};s&&!w.relatedTask&&(w.relatedTask={taskId:s});const P=((D=w.relatedTask)==null?void 0:D.taskId)??s;return P&&c&&await c.updateTaskStatus(P,"input_required"),await this.request(g,b,w)},authInfo:o==null?void 0:o.authInfo,requestId:t.id,requestInfo:o==null?void 0:o.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:i==null?void 0:i.ttl,closeSSEStream:o==null?void 0:o.closeSSEStream,closeStandaloneSSEStream:o==null?void 0:o.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async g=>{if(a.signal.aborted)return;const b={result:g,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:b,timestamp:Date.now()},r==null?void 0:r.sessionId):await(r==null?void 0:r.send(b))},async g=>{if(a.signal.aborted)return;const b={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(g.code)?g.code:L.InternalError,message:g.message??"Internal error",...g.data!==void 0&&{data:g.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:b,timestamp:Date.now()},r==null?void 0:r.sessionId):await(r==null?void 0:r.send(b))}).catch(g=>this._onerror(new Error(`Failed to send response: ${g}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:o,...n}=t.params,r=Number(o),s=this._progressHandlers.get(r);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(r),i=this._timeoutInfo.get(r);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(c){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(c);return}s(n)}_onresponse(t){const o=Number(t.id),n=this._requestResolvers.get(o);if(n){if(this._requestResolvers.delete(o),go(t))n(t);else{const a=new M(t.error.code,t.error.message,t.error.data);n(a)}return}const r=this._responseHandlers.get(o);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(o),this._cleanupTimeout(o);let s=!1;if(go(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,o))}}if(s||this._progressHandlers.delete(o),go(t))r(t);else{const a=M.fromError(t.error.code,t.error.message,t.error.data);r(a)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)==null?void 0:t.close())}async*requestStream(t,o,n){var a,i;const{task:r}=n??{};if(!r){try{yield{type:"result",result:await this.request(t,o,n)}}catch(c){yield{type:"error",error:c instanceof M?c:new M(L.InternalError,String(c))}}return}let s;try{const c=await this.request(t,Bo,n);if(c.task)s=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new M(L.InternalError,"Task creation did not return a task");for(;;){const l=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:l},it(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},o,n)}:l.status==="failed"?yield{type:"error",error:new M(L.InternalError,`Task ${s} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new M(L.InternalError,`Task ${s} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},o,n)};return}const u=l.pollInterval??((a=this._options)==null?void 0:a.defaultTaskPollInterval)??1e3;await new Promise(p=>setTimeout(p,u)),(i=n==null?void 0:n.signal)==null||i.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof M?c:new M(L.InternalError,String(c))}}}request(t,o,n){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:c}=n??{};return new Promise((l,u)=>{var P,D,A,T,O;const p=E=>{u(E)};if(!this._transport){p(new Error("Not connected"));return}if(((P=this._options)==null?void 0:P.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(E){p(E);return}(D=n==null?void 0:n.signal)==null||D.throwIfAborted();const f=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:f};n!=null&&n.onprogress&&(this._progressHandlers.set(f,n.onprogress),h.params={...t.params,_meta:{...((A=t.params)==null?void 0:A._meta)||{},progressToken:f}}),i&&(h.params={...h.params,task:i}),c&&(h.params={...h.params,_meta:{...((T=h.params)==null?void 0:T._meta)||{},[lt]:c}});const g=E=>{var Z;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(Z=this._transport)==null||Z.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(E)}},{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a}).catch(_e=>this._onerror(new Error(`Failed to send cancellation: ${_e}`)));const B=E instanceof M?E:new M(L.RequestTimeout,String(E));u(B)};this._responseHandlers.set(f,E=>{var B;if(!((B=n==null?void 0:n.signal)!=null&&B.aborted)){if(E instanceof Error)return u(E);try{const Z=He(o,E.result);Z.success?l(Z.data):u(Z.error)}catch(Z){u(Z)}}}),(O=n==null?void 0:n.signal)==null||O.addEventListener("abort",()=>{var E;g((E=n==null?void 0:n.signal)==null?void 0:E.reason)});const b=(n==null?void 0:n.timeout)??ux,_=()=>g(M.fromError(L.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(f,b,n==null?void 0:n.maxTotalTimeout,_,(n==null?void 0:n.resetTimeoutOnProgress)??!1);const w=c==null?void 0:c.taskId;if(w){const E=B=>{const Z=this._responseHandlers.get(f);Z?Z(B):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,E),this._enqueueTaskMessage(w,{type:"request",message:h,timestamp:Date.now()}).catch(B=>{this._cleanupTimeout(f),u(B)})}else this._transport.send(h,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a}).catch(E=>{this._cleanupTimeout(f),u(E)})})}async getTask(t,o){return this.request({method:"tasks/get",params:t},Na,o)}async getTaskResult(t,o,n){return this.request({method:"tasks/result",params:t},o,n)}async listTasks(t,o){return this.request({method:"tasks/list",params:t},za,o)}async cancelTask(t,o){return this.request({method:"tasks/cancel",params:t},eR,o)}async notification(t,o){var i,c,l,u;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=(i=o==null?void 0:o.relatedTask)==null?void 0:i.taskId;if(n){const p={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...((c=t.params)==null?void 0:c._meta)||{},[lt]:o.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:p,timestamp:Date.now()});return}if((((l=this._options)==null?void 0:l.debouncedNotificationMethods)??[]).includes(t.method)&&!t.params&&!(o!=null&&o.relatedRequestId)&&!(o!=null&&o.relatedTask)){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var f,h;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let p={...t,jsonrpc:"2.0"};o!=null&&o.relatedTask&&(p={...p,params:{...p.params,_meta:{...((f=p.params)==null?void 0:f._meta)||{},[lt]:o.relatedTask}}}),(h=this._transport)==null||h.send(p,o).catch(g=>this._onerror(g))});return}let a={...t,jsonrpc:"2.0"};o!=null&&o.relatedTask&&(a={...a,params:{...a.params,_meta:{...((u=a.params)==null?void 0:u._meta)||{},[lt]:o.relatedTask}}}),await this._transport.send(a,o)}setRequestHandler(t,o){const n=wc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(r,s)=>{const a=kc(t,r);return Promise.resolve(o(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,o){const n=wc(t);this._notificationHandlers.set(n,r=>{const s=kc(t,r);return Promise.resolve(o(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const o=this._taskProgressTokens.get(t);o!==void 0&&(this._progressHandlers.delete(o),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,o,n){var s;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const r=(s=this._options)==null?void 0:s.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,o,n,r)}async _clearTaskQueue(t,o){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,o);for(const r of n)if(r.type==="request"&&ss(r.message)){const s=r.message.id,a=this._requestResolvers.get(s);a?(a(new M(L.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,o){var r,s;let n=((r=this._options)==null?void 0:r.defaultTaskPollInterval)??1e3;try{const a=await((s=this._taskStore)==null?void 0:s.getTask(t));a!=null&&a.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,i)=>{if(o.aborted){i(new M(L.InvalidRequest,"Request cancelled"));return}const c=setTimeout(a,n);o.addEventListener("abort",()=>{clearTimeout(c),i(new M(L.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,o){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async r=>{if(!t)throw new Error("No request provided");return await n.createTask(r,t.id,{method:t.method,params:t.params},o)},getTask:async r=>{const s=await n.getTask(r,o);if(!s)throw new M(L.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(r,s,a)=>{await n.storeTaskResult(r,s,a,o);const i=await n.getTask(r,o);if(i){const c=$n.parse({method:"notifications/tasks/status",params:i});await this.notification(c),it(i.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>n.getTaskResult(r,o),updateTaskStatus:async(r,s,a)=>{const i=await n.getTask(r,o);if(!i)throw new M(L.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(it(i.status))throw new M(L.InvalidParams,`Cannot update task "${r}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(r,s,a,o);const c=await n.getTask(r,o);if(c){const l=$n.parse({method:"notifications/tasks/status",params:c});await this.notification(l),it(c.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>n.listTasks(r,o)}}}function _c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function px(e,t){const o={...e};for(const n in t){const r=n,s=t[r];if(s===void 0)continue;const a=o[r];_c(a)&&_c(s)?o[r]={...a,...s}:o[r]=s}return o}class Yh{constructor(t){}getValidator(t){return o=>({valid:!0,data:o,errorMessage:void 0})}}const fx=new Yh;class hx{constructor(t){this._client=t}async*callToolStream(t,o=ur,n){const r=this._client,s={...n,task:(n==null?void 0:n.task)??(r.isToolTask(t.name)?{}:void 0)},a=r.requestStream({method:"tools/call",params:t},o,s),i=r.getToolOutputValidator(t.name);for await(const c of a){if(c.type==="result"&&i){const l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new M(L.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const u=i(l.structuredContent);if(!u.valid){yield{type:"error",error:new M(L.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof M){yield{type:"error",error:u};return}yield{type:"error",error:new M(L.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(t,o){return this._client.getTask({taskId:t},o)}async getTaskResult(t,o,n){return this._client.getTaskResult({taskId:t},o,n)}async listTasks(t,o){return this._client.listTasks(t?{cursor:t}:void 0,o)}async cancelTask(t,o){return this._client.cancelTask({taskId:t},o)}requestStream(t,o,n){return this._client.requestStream(t,o,n)}}function wn(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const o=t,n=e.properties;for(const r of Object.keys(n)){const s=n[r];o[r]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(o[r]=s.default),o[r]!==void 0&&wn(s,o[r])}}if(Array.isArray(e.anyOf))for(const o of e.anyOf)typeof o!="boolean"&&wn(o,t);if(Array.isArray(e.oneOf))for(const o of e.oneOf)typeof o!="boolean"&&wn(o,t)}}function mx(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,o=e.url!==void 0;return{supportsFormMode:t||!t&&!o,supportsUrlMode:o}}class gx extends dx{constructor(t,o){super(o),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=(o==null?void 0:o.capabilities)??{},this._jsonSchemaValidator=(o==null?void 0:o.jsonSchemaValidator)??new Yh,o!=null&&o.listChanged&&(this._pendingListChangedConfig=o.listChanged)}_setupListChangedHandlers(t){var o,n,r,s,a,i;t.tools&&((n=(o=this._serverCapabilities)==null?void 0:o.tools)!=null&&n.listChanged)&&this._setupListChangedHandler("tools",qh,t.tools,async()=>(await this.listTools()).tools),t.prompts&&((s=(r=this._serverCapabilities)==null?void 0:r.prompts)!=null&&s.listChanged)&&this._setupListChangedHandler("prompts",Mh,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&((i=(a=this._serverCapabilities)==null?void 0:a.resources)!=null&&i.listChanged)&&this._setupListChangedHandler("resources",Oh,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new hx(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=px(this._capabilities,t)}setRequestHandler(t,o){var i;const n=bh(t),r=n==null?void 0:n.method;if(!r)throw new Error("Schema is missing a method literal");let s;if(ar(r)){const c=r,l=(i=c._zod)==null?void 0:i.def;s=(l==null?void 0:l.value)??c.value}else{const c=r,l=c._def;s=(l==null?void 0:l.value)??c.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const c=async(l,u)=>{var D,A;const p=He(Hh,l);if(!p.success){const T=p.error instanceof Error?p.error.message:String(p.error);throw new M(L.InvalidParams,`Invalid elicitation request: ${T}`)}const{params:f}=p.data;f.mode=f.mode??"form";const{supportsFormMode:h,supportsUrlMode:g}=mx(this._capabilities.elicitation);if(f.mode==="form"&&!h)throw new M(L.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!g)throw new M(L.InvalidParams,"Client does not support URL-mode elicitation requests");const b=await Promise.resolve(o(l,u));if(f.task){const T=He(Bo,b);if(!T.success){const O=T.error instanceof Error?T.error.message:String(T.error);throw new M(L.InvalidParams,`Invalid task creation result: ${O}`)}return T.data}const _=He(Vh,b);if(!_.success){const T=_.error instanceof Error?_.error.message:String(_.error);throw new M(L.InvalidParams,`Invalid elicitation result: ${T}`)}const w=_.data,P=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&w.action==="accept"&&w.content&&P&&(A=(D=this._capabilities.elicitation)==null?void 0:D.form)!=null&&A.applyDefaults)try{wn(P,w.content)}catch{}return w};return super.setRequestHandler(t,c)}if(a==="sampling/createMessage"){const c=async(l,u)=>{const p=He(Bh,l);if(!p.success){const w=p.error instanceof Error?p.error.message:String(p.error);throw new M(L.InvalidParams,`Invalid sampling request: ${w}`)}const{params:f}=p.data,h=await Promise.resolve(o(l,u));if(f.task){const w=He(Bo,h);if(!w.success){const P=w.error instanceof Error?w.error.message:String(w.error);throw new M(L.InvalidParams,`Invalid task creation result: ${P}`)}return w.data}const b=f.tools||f.toolChoice?jh:Uh,_=He(b,h);if(!_.success){const w=_.error instanceof Error?_.error.message:String(_.error);throw new M(L.InvalidParams,`Invalid sampling result: ${w}`)}return _.data};return super.setRequestHandler(t,c)}return super.setRequestHandler(t,o)}assertCapability(t,o){var n;if(!((n=this._serverCapabilities)!=null&&n[t]))throw new Error(`Server does not support ${t} (required for ${o})`)}async connect(t,o){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:ir,capabilities:this._capabilities,clientInfo:this._clientInfo}},Sh,o);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!xE.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var o,n,r,s,a;switch(t){case"logging/setLevel":if(!((o=this._serverCapabilities)!=null&&o.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!((n=this._serverCapabilities)!=null&&n.prompts))throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((r=this._serverCapabilities)!=null&&r.resources))throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!((s=this._serverCapabilities)!=null&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!((a=this._serverCapabilities)!=null&&a.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var o;switch(t){case"notifications/roots/list_changed":if(!((o=this._capabilities.roots)!=null&&o.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){var o,n;(n=(o=this._serverCapabilities)==null?void 0:o.tasks)==null||n.requests}assertTaskHandlerCapability(t){var o;this._capabilities&&((o=this._capabilities.tasks)==null||o.requests,void 0)}async ping(t){return this.request({method:"ping"},xt,t)}async complete(t,o){return this.request({method:"completion/complete",params:t},Zh,o)}async setLoggingLevel(t,o){return this.request({method:"logging/setLevel",params:{level:t}},xt,o)}async getPrompt(t,o){return this.request({method:"prompts/get",params:t},$h,o)}async listPrompts(t,o){return this.request({method:"prompts/list",params:t},Nh,o)}async listResources(t,o){return this.request({method:"resources/list",params:t},Eh,o)}async listResourceTemplates(t,o){return this.request({method:"resources/templates/list",params:t},Rh,o)}async readResource(t,o){return this.request({method:"resources/read",params:t},xh,o)}async subscribeResource(t,o){return this.request({method:"resources/subscribe",params:t},xt,o)}async unsubscribeResource(t,o){return this.request({method:"resources/unsubscribe",params:t},xt,o)}async callTool(t,o=ur,n){if(this.isToolTaskRequired(t.name))throw new M(L.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const r=await this.request({method:"tools/call",params:t},o,n),s=this.getToolOutputValidator(t.name);if(s){if(!r.structuredContent&&!r.isError)throw new M(L.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(r.structuredContent)try{const a=s(r.structuredContent);if(!a.valid)throw new M(L.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof M?a:new M(L.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return r}isToolTask(t){var o,n,r,s;return(s=(r=(n=(o=this._serverCapabilities)==null?void 0:o.tasks)==null?void 0:n.requests)==null?void 0:r.tools)!=null&&s.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){var o;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of t){if(n.outputSchema){const s=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,s)}const r=(o=n.execution)==null?void 0:o.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(n.name),r==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,o){const n=await this.request({method:"tools/list",params:t},Fh,o);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,o,n,r){const s=TR.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:c}=n,l=async()=>{if(!a){c(null,null);return}try{const p=await r();c(null,p)}catch(p){const f=p instanceof Error?p:new Error(String(p));c(f,null)}},u=()=>{if(i){const p=this._listChangedDebounceTimers.get(t);p&&clearTimeout(p);const f=setTimeout(l,i);this._listChangedDebounceTimers.set(t,f)}else l()};this.setNotificationHandler(o,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function as(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function yx(e=fetch,t){return t?async(o,n)=>{const r={...t,...n,headers:n!=null&&n.headers?{...as(t.headers),...as(n.headers)}:t.headers};return e(o,r)}:e}let Va;Va=globalThis.crypto;async function bx(e){return(await Va).getRandomValues(new Uint8Array(e))}async function wx(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",o=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const r=await bx(e-n.length);for(const s of r)s<o&&(n+=t[s%t.length])}return n}async function kx(e){return await wx(e)}async function _x(e){const t=await(await Va).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function vx(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await kx(e),o=await _x(t);return{code_verifier:t,code_challenge:o}}const le=fk().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:q.custom,message:"URL must be parseable",fatal:!0}),Sg}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ix=ue({resource:d().url(),authorization_servers:I(le).optional(),jwks_uri:d().url().optional(),scopes_supported:I(d()).optional(),bearer_methods_supported:I(d()).optional(),resource_signing_alg_values_supported:I(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:x().optional(),authorization_details_types_supported:I(d()).optional(),dpop_signing_alg_values_supported:I(d()).optional(),dpop_bound_access_tokens_required:x().optional()}),Wh=ue({issuer:d(),authorization_endpoint:le,token_endpoint:le,registration_endpoint:le.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),service_documentation:le.optional(),revocation_endpoint:le.optional(),revocation_endpoint_auth_methods_supported:I(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:I(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:I(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:I(d()).optional(),code_challenge_methods_supported:I(d()).optional(),client_id_metadata_document_supported:x().optional()}),Sx=ue({issuer:d(),authorization_endpoint:le,token_endpoint:le,userinfo_endpoint:le.optional(),jwks_uri:le,registration_endpoint:le.optional(),scopes_supported:I(d()).optional(),response_types_supported:I(d()),response_modes_supported:I(d()).optional(),grant_types_supported:I(d()).optional(),acr_values_supported:I(d()).optional(),subject_types_supported:I(d()),id_token_signing_alg_values_supported:I(d()),id_token_encryption_alg_values_supported:I(d()).optional(),id_token_encryption_enc_values_supported:I(d()).optional(),userinfo_signing_alg_values_supported:I(d()).optional(),userinfo_encryption_alg_values_supported:I(d()).optional(),userinfo_encryption_enc_values_supported:I(d()).optional(),request_object_signing_alg_values_supported:I(d()).optional(),request_object_encryption_alg_values_supported:I(d()).optional(),request_object_encryption_enc_values_supported:I(d()).optional(),token_endpoint_auth_methods_supported:I(d()).optional(),token_endpoint_auth_signing_alg_values_supported:I(d()).optional(),display_values_supported:I(d()).optional(),claim_types_supported:I(d()).optional(),claims_supported:I(d()).optional(),service_documentation:d().optional(),claims_locales_supported:I(d()).optional(),ui_locales_supported:I(d()).optional(),claims_parameter_supported:x().optional(),request_parameter_supported:x().optional(),request_uri_parameter_supported:x().optional(),require_request_uri_registration:x().optional(),op_policy_uri:le.optional(),op_tos_uri:le.optional(),client_id_metadata_document_supported:x().optional()}),Dx=m({...Sx.shape,...Wh.pick({code_challenge_methods_supported:!0}).shape}),Tx=m({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:s_().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Ax=m({error:d(),error_description:d().optional(),error_uri:d().optional()}),vc=le.optional().or(y("").transform(()=>{})),Px=m({redirect_uris:I(le),token_endpoint_auth_method:d().optional(),grant_types:I(d()).optional(),response_types:I(d()).optional(),client_name:d().optional(),client_uri:le.optional(),logo_uri:vc,scope:d().optional(),contacts:I(d()).optional(),tos_uri:vc,policy_uri:d().optional(),jwks_uri:le.optional(),jwks:Ok().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),Cx=m({client_id:d(),client_secret:d().optional(),client_id_issued_at:C().optional(),client_secret_expires_at:C().optional()}).strip(),Ex=Px.merge(Cx);m({error:d(),error_description:d().optional()}).strip();m({token:d(),token_type_hint:d().optional()}).strip();function Rx(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function xx({requestedResource:e,configuredResource:t}){const o=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(o.origin!==n.origin||o.pathname.length<n.pathname.length)return!1;const r=o.pathname.endsWith("/")?o.pathname:o.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return r.startsWith(s)}class ce extends Error{constructor(t,o){super(t),this.errorUri=o,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class is extends ce{}is.errorCode="invalid_request";class zn extends ce{}zn.errorCode="invalid_client";class Fn extends ce{}Fn.errorCode="invalid_grant";class qn extends ce{}qn.errorCode="unauthorized_client";class cs extends ce{}cs.errorCode="unsupported_grant_type";class ls extends ce{}ls.errorCode="invalid_scope";class us extends ce{}us.errorCode="access_denied";class oo extends ce{}oo.errorCode="server_error";class ds extends ce{}ds.errorCode="temporarily_unavailable";class ps extends ce{}ps.errorCode="unsupported_response_type";class fs extends ce{}fs.errorCode="unsupported_token_type";class hs extends ce{}hs.errorCode="invalid_token";class ms extends ce{}ms.errorCode="method_not_allowed";class gs extends ce{}gs.errorCode="too_many_requests";class Ln extends ce{}Ln.errorCode="invalid_client_metadata";class ys extends ce{}ys.errorCode="insufficient_scope";class bs extends ce{}bs.errorCode="invalid_target";const Ox={[is.errorCode]:is,[zn.errorCode]:zn,[Fn.errorCode]:Fn,[qn.errorCode]:qn,[cs.errorCode]:cs,[ls.errorCode]:ls,[us.errorCode]:us,[oo.errorCode]:oo,[ds.errorCode]:ds,[ps.errorCode]:ps,[fs.errorCode]:fs,[hs.errorCode]:hs,[ms.errorCode]:ms,[gs.errorCode]:gs,[Ln.errorCode]:Ln,[ys.errorCode]:ys,[bs.errorCode]:bs};class vt extends Error{constructor(t){super(t??"Unauthorized")}}function Nx(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Tr="code",Ar="S256";function $x(e,t){const o=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Nx(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?o?"client_secret_basic":"none":o&&t.includes("client_secret_basic")?"client_secret_basic":o&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":o?"client_secret_post":"none"}function Mx(e,t,o,n){const{client_id:r,client_secret:s}=t;switch(e){case"client_secret_basic":zx(r,s,o);return;case"client_secret_post":Fx(r,s,n);return;case"none":qx(r,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function zx(e,t,o){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);o.set("Authorization",`Basic ${n}`)}function Fx(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}function qx(e,t){t.set("client_id",e)}async function Gh(e){const t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{const n=Ax.parse(JSON.parse(o)),{error:r,error_description:s,error_uri:a}=n,i=Ox[r]||oo;return new i(s||"",a)}catch(n){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${o}`;return new oo(r)}}async function dn(e,t){var o,n;try{return await Pr(e,t)}catch(r){if(r instanceof zn||r instanceof qn)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"all")),await Pr(e,t);if(r instanceof Fn)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Pr(e,t);throw r}}async function Pr(e,{serverUrl:t,authorizationCode:o,scope:n,resourceMetadataUrl:r,fetchFn:s}){var D,A,T,O,E;const a=await((D=e.discoveryState)==null?void 0:D.call(e));let i,c,l,u=r;if(!u&&(a!=null&&a.resourceMetadataUrl)&&(u=new URL(a.resourceMetadataUrl)),a!=null&&a.authorizationServerUrl){if(c=a.authorizationServerUrl,i=a.resourceMetadata,l=a.authorizationServerMetadata??await Jh(c,{fetchFn:s}),!i)try{i=await Kh(t,{resourceMetadataUrl:u},s)}catch{}(l!==a.authorizationServerMetadata||i!==a.resourceMetadata)&&await((A=e.saveDiscoveryState)==null?void 0:A.call(e,{authorizationServerUrl:String(c),resourceMetadataUrl:u==null?void 0:u.toString(),resourceMetadata:i,authorizationServerMetadata:l}))}else{const B=await Zx(t,{resourceMetadataUrl:u,fetchFn:s});c=B.authorizationServerUrl,l=B.authorizationServerMetadata,i=B.resourceMetadata,await((T=e.saveDiscoveryState)==null?void 0:T.call(e,{authorizationServerUrl:String(c),resourceMetadataUrl:u==null?void 0:u.toString(),resourceMetadata:i,authorizationServerMetadata:l}))}const p=await Bx(t,e,i),f=n||((O=i==null?void 0:i.scopes_supported)==null?void 0:O.join(" "))||e.clientMetadata.scope;let h=await Promise.resolve(e.clientInformation());if(!h){if(o!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const B=(l==null?void 0:l.client_id_metadata_document_supported)===!0,Z=e.clientMetadataUrl;if(Z&&!Lx(Z))throw new Ln(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Z}`);if(B&&Z)h={client_id:Z},await((E=e.saveClientInformation)==null?void 0:E.call(e,h));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const Wa=await Jx(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:s});await e.saveClientInformation(Wa),h=Wa}}const g=!e.redirectUrl;if(o!==void 0||g){const B=await Kx(e,c,{metadata:l,resource:p,authorizationCode:o,fetchFn:s});return await e.saveTokens(B),"AUTHORIZED"}const b=await e.tokens();if(b!=null&&b.refresh_token)try{const B=await Gx(c,{metadata:l,clientInformation:h,refreshToken:b.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(B),"AUTHORIZED"}catch(B){if(!(!(B instanceof ce)||B instanceof oo))throw B}const _=e.state?await e.state():void 0,{authorizationUrl:w,codeVerifier:P}=await Yx(c,{metadata:l,clientInformation:h,state:_,redirectUrl:e.redirectUrl,scope:f,resource:p});return await e.saveCodeVerifier(P),await e.redirectToAuthorization(w),"REDIRECT"}function Lx(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Bx(e,t,o){const n=Rx(e);if(t.validateResourceURL)return await t.validateResourceURL(n,o==null?void 0:o.resource);if(o){if(!xx({requestedResource:n,configuredResource:o.resource}))throw new Error(`Protected resource ${o.resource} does not match expected ${n} (or origin)`);return new URL(o.resource)}}function Ic(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[o,n]=t.split(" ");if(o.toLowerCase()!=="bearer"||!n)return{};const r=Cr(e,"resource_metadata")||void 0;let s;if(r)try{s=new URL(r)}catch{}const a=Cr(e,"scope")||void 0,i=Cr(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Cr(e,t){const o=e.headers.get("WWW-Authenticate");if(!o)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),r=o.match(n);return r?r[1]||r[2]:null}async function Kh(e,t,o=fetch){var r,s;const n=await Hx(e,"oauth-protected-resource",o,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!n||n.status===404)throw await((r=n==null?void 0:n.body)==null?void 0:r.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await((s=n.body)==null?void 0:s.cancel()),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Ix.parse(await n.json())}async function Za(e,t,o=fetch){try{return await o(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Za(e,void 0,o):void 0;throw n}}function Ux(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Sc(e,t,o=fetch){return await Za(e,{"MCP-Protocol-Version":t},o)}function jx(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Hx(e,t,o,n){const r=new URL(e),s=(n==null?void 0:n.protocolVersion)??ir;let a;if(n!=null&&n.metadataUrl)a=new URL(n.metadataUrl);else{const c=Ux(t,r.pathname);a=new URL(c,(n==null?void 0:n.metadataServerUrl)??r),a.search=r.search}let i=await Sc(a,s,o);if(!(n!=null&&n.metadataUrl)&&jx(i,r.pathname)){const c=new URL(`/.well-known/${t}`,r);i=await Sc(c,s,o)}return i}function Vx(e){const t=typeof e=="string"?new URL(e):e,o=t.pathname!=="/",n=[];if(!o)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),n.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function Jh(e,{fetchFn:t=fetch,protocolVersion:o=ir}={}){var s;const n={"MCP-Protocol-Version":o,Accept:"application/json"},r=Vx(e);for(const{url:a,type:i}of r){const c=await Za(a,n,t);if(c){if(!c.ok){if(await((s=c.body)==null?void 0:s.cancel()),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?Wh.parse(await c.json()):Dx.parse(await c.json())}}}async function Zx(e,t){let o,n;try{o=await Kh(e,{resourceMetadataUrl:t==null?void 0:t.resourceMetadataUrl},t==null?void 0:t.fetchFn),o.authorization_servers&&o.authorization_servers.length>0&&(n=o.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const r=await Jh(n,{fetchFn:t==null?void 0:t.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:r,resourceMetadata:o}}async function Yx(e,{metadata:t,clientInformation:o,redirectUrl:n,scope:r,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Tr))throw new Error(`Incompatible auth server: does not support response type ${Tr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ar))throw new Error(`Incompatible auth server: does not support code challenge method ${Ar}`)}else i=new URL("/authorize",e);const c=await vx(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",Tr),i.searchParams.set("client_id",o.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Ar),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),r&&i.searchParams.set("scope",r),r!=null&&r.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}function Wx(e,t,o){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(o)})}async function Qh(e,{metadata:t,tokenRequestParams:o,clientInformation:n,addClientAuthentication:r,resource:s,fetchFn:a}){const i=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&o.set("resource",s.href),r)await r(c,o,i,t);else if(n){const u=(t==null?void 0:t.token_endpoint_auth_methods_supported)??[],p=$x(n,u);Mx(p,n,c,o)}const l=await(a??fetch)(i,{method:"POST",headers:c,body:o});if(!l.ok)throw await Gh(l);return Tx.parse(await l.json())}async function Gx(e,{metadata:t,clientInformation:o,refreshToken:n,resource:r,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await Qh(e,{metadata:t,tokenRequestParams:i,clientInformation:o,addClientAuthentication:s,resource:r,fetchFn:a});return{refresh_token:n,...c}}async function Kx(e,t,{metadata:o,resource:n,authorizationCode:r,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const l=await e.codeVerifier();i=Wx(r,l,e.redirectUrl)}const c=await e.clientInformation();return Qh(t,{metadata:o,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Jx(e,{metadata:t,clientMetadata:o,scope:n,fetchFn:r}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const a=await(r??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o,...n!==void 0?{scope:n}:{}})});if(!a.ok)throw await Gh(a);return Ex.parse(await a.json())}class Dc extends Error{constructor(t,o){super(t),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}}function Er(e){}function Qx(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Er,onError:o=Er,onRetry:n=Er,onComment:r}=e;let s="",a=!0,i,c="",l="";function u(b){const _=a?b.replace(/^\xEF\xBB\xBF/,""):b,[w,P]=Xx(`${s}${_}`);for(const D of w)p(D);s=P,a=!1}function p(b){if(b===""){h();return}if(b.startsWith(":")){r&&r(b.slice(b.startsWith(": ")?2:1));return}const _=b.indexOf(":");if(_!==-1){const w=b.slice(0,_),P=b[_+1]===" "?2:1,D=b.slice(_+P);f(w,D,b);return}f(b,"",b)}function f(b,_,w){switch(b){case"event":l=_;break;case"data":c=`${c}${_}
525
+ `;break;case"id":i=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):o(new Dc(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:o(new Dc(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:_,line:w}));break}}function h(){c.length>0&&t({id:i,event:l||void 0,data:c.endsWith(`
526
+ `)?c.slice(0,-1):c}),i=void 0,c="",l=""}function g(b={}){s&&b.consume&&p(s),a=!0,i=void 0,c="",l="",s=""}return{feed:u,reset:g}}function Xx(e){const t=[];let o="",n=0;for(;n<e.length;){const r=e.indexOf("\r",n),s=e.indexOf(`
521
527
  `,n);let a=-1;if(r!==-1&&s!==-1?a=Math.min(r,s):r!==-1?r===e.length-1?a=-1:a=r:s!==-1&&(a=s),a===-1){o=e.slice(n);break}else{const i=e.slice(n,a);t.push(i),n=a+1,e[n-1]==="\r"&&e[n]===`
522
- `&&n++}}return[t,o]}class Qx extends TransformStream{constructor({onError:t,onRetry:o,onComment:n}={}){let r;super({start(s){r=Kx({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:o,onComment:n})},transform(s){r.feed(s)}})}}const Xx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class It extends Error{constructor(t,o){super(`Streamable HTTP error: ${o}`),this.code=t}}class eO{constructor(t,o){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=o==null?void 0:o.requestInit,this._authProvider=o==null?void 0:o.authProvider,this._fetch=o==null?void 0:o.fetch,this._fetchWithInit=mx(o==null?void 0:o.fetch,o==null?void 0:o.requestInit),this._sessionId=o==null?void 0:o.sessionId,this._reconnectionOptions=(o==null?void 0:o.reconnectionOptions)??Xx}async _authThenStart(){var o;if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await ln(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(o=this.onerror)==null||o.call(this,n),n}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var n;const t={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(t.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const o=rs((n=this._requestInit)==null?void 0:n.headers);return new Headers({...t,...o})}async _startOrAuthSse(t){var n,r,s;const{resumptionToken:o}=t;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);const i=await(this._fetch??fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)==null?void 0:n.signal});if(!i.ok){if(await((r=i.body)==null?void 0:r.cancel()),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new It(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,t,!0)}catch(a){throw(s=this.onerror)==null||s.call(this,a),a}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const o=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(o*Math.pow(n,t),r)}_scheduleReconnection(t,o=0){var s;const n=this._reconnectionOptions.maxRetries;if(o>=n){(s=this.onerror)==null||s.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const r=this._getNextReconnectionDelay(o);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)==null||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,o+1)})},r)}_handleSseStream(t,o,n){if(!t)return;const{onresumptiontoken:r,replayMessageId:s}=o;let a,i=!1,c=!1;(async()=>{var u,p,f,h;try{const g=t.pipeThrough(new TextDecoderStream).pipeThrough(new Qx({onRetry:w=>{this._serverRetryMs=w}})).getReader();for(;;){const{value:w,done:P}=await g.read();if(P)break;if(w.id&&(a=w.id,i=!0,r==null||r(w.id)),!!w.data&&(!w.event||w.event==="message"))try{const D=kr.parse(JSON.parse(w.data));mo(D)&&(c=!0,s!==void 0&&(D.id=s)),(u=this.onmessage)==null||u.call(this,D)}catch(D){(p=this.onerror)==null||p.call(this,D)}}(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:s},0)}catch(g){if((f=this.onerror)==null||f.call(this,new Error(`SSE stream disconnected: ${g}`)),(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:s},0)}catch(w){(h=this.onerror)==null||h.call(this,new Error(`Failed to reconnect: ${w instanceof Error?w.message:String(w)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new vt("No auth provider");if(await ln(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){var t,o;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)==null||t.abort(),(o=this.onclose)==null||o.call(this)}async send(t,o){var n,r,s,a,i,c;try{const{resumptionToken:l,onresumptiontoken:u}=o||{};if(l){this._startOrAuthSse({resumptionToken:l,replayMessageId:ns(t)?t.id:void 0}).catch(P=>{var D;return(D=this.onerror)==null?void 0:D.call(this,P)});return}const p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");const f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(t),signal:(n=this._abortController)==null?void 0:n.signal},h=await(this._fetch??fetch)(this._url,f),g=h.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!h.ok){const P=await h.text().catch(()=>null);if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:D,scope:T}=_c(h);if(this._resourceMetadataUrl=D,this._scope=T,await ln(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new vt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(h.status===403&&this._authProvider){const{resourceMetadataUrl:D,scope:T,error:A}=_c(h);if(A==="insufficient_scope"){const O=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===O)throw new It(403,"Server returned 403 after trying upscoping");if(T&&(this._scope=T),D&&(this._resourceMetadataUrl=D),this._lastUpscopingHeader=O??void 0,await ln(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new vt;return this.send(t)}}throw new It(h.status,`Error POSTing to endpoint: ${P}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){await((r=h.body)==null?void 0:r.cancel()),ZC(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(P=>{var D;return(D=this.onerror)==null?void 0:D.call(this,P)});return}const _=(Array.isArray(t)?t:[t]).filter(P=>"method"in P&&"id"in P&&P.id!==void 0).length>0,w=h.headers.get("content-type");if(_)if(w!=null&&w.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:u},!1);else if(w!=null&&w.includes("application/json")){const P=await h.json(),D=Array.isArray(P)?P.map(T=>kr.parse(T)):[kr.parse(P)];for(const T of D)(s=this.onmessage)==null||s.call(this,T)}else throw await((a=h.body)==null?void 0:a.cancel()),new It(-1,`Unexpected content type: ${w}`);else await((i=h.body)==null?void 0:i.cancel())}catch(l){throw(c=this.onerror)==null||c.call(this,l),l}}get sessionId(){return this._sessionId}async terminateSession(){var t,o,n;if(this._sessionId)try{const r=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:r,signal:(t=this._abortController)==null?void 0:t.signal},a=await(this._fetch??fetch)(this._url,s);if(await((o=a.body)==null?void 0:o.cancel()),!a.ok&&a.status!==405)throw new It(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)==null||n.call(this,r),r}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,o){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:o==null?void 0:o.onresumptiontoken})}}const tO="plugin__siyuan_plugins_mcp_sisyphus__",Kh=m({name:d(),title:d().optional(),description:d().optional(),inputSchema:K().optional(),outputSchema:K().optional(),source:d().optional(),readOnlyHint:x().optional(),effectScope:d().optional()}).passthrough(),oO=m({tools:I(Kh),nextCursor:d().optional()}).passthrough();function ys(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nO(e){if(!ys(e))return{schema:{type:"object",additionalProperties:!0},degraded:!0};const t=e.type,o=Array.isArray(e.oneOf)||Array.isArray(e.anyOf)||Array.isArray(e.allOf)||typeof e.$ref=="string";return t!==void 0&&t!=="object"?{schema:{type:"object",additionalProperties:!0},degraded:!0}:t===void 0&&!o&&!ys(e.properties)?{schema:{type:"object",additionalProperties:!0},degraded:!0}:{schema:t===void 0&&!o?{...e,type:"object"}:{...e},degraded:!1}}function rO(e){const t=new Map;for(const o of e){const n=Kh.safeParse(o);if(!n.success)continue;const r=n.data,s=r.source?r.source:"native";if(s!=="plugin"&&s!=="native"||r.name.startsWith(tO))continue;const a=nO(r.inputSchema);t.set(r.name,{name:r.name,title:r.title,description:r.description,inputSchema:a.schema,outputSchema:ys(r.outputSchema)?r.outputSchema:void 0,source:s,readOnlyHint:r.readOnlyHint===!0,effectScope:r.effectScope,schemaDegraded:a.degraded})}return[...t.values()].sort((o,n)=>o.name.localeCompare(n.name))}function Ar(e){return e instanceof Error?e.message:String(e)}function Sc(e){return JSON.stringify(e.map(t=>({name:t.name,title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,source:t.source,readOnlyHint:t.readOnlyHint,effectScope:t.effectScope,schemaDegraded:t.schemaDegraded})))}class sO{constructor(t,o={}){se(this,"siyuanClient");se(this,"fetchImpl");se(this,"client");se(this,"transport");se(this,"connecting");se(this,"cachedTools",[]);se(this,"connected",!1);se(this,"lastSuccessfulRefreshAt");se(this,"lastAttemptAt");se(this,"lastError");this.siyuanClient=t,this.fetchImpl=o.fetch}getTools(){return this.cachedTools.map(t=>({...t,inputSchema:{...t.inputSchema},outputSchema:t.outputSchema?{...t.outputSchema}:void 0}))}getSnapshot(t=!1){return{tools:this.getTools(),connected:this.connected,lastSuccessfulRefreshAt:this.lastSuccessfulRefreshAt,lastAttemptAt:this.lastAttemptAt,error:this.lastError,changed:t}}async refresh(){this.lastAttemptAt=new Date().toISOString();const t=Sc(this.cachedTools);try{const o=await this.listToolsOnce();return this.commitRefresh(o,t)}catch{await this.resetConnection()}try{const o=await this.listToolsOnce();return this.commitRefresh(o,t)}catch(o){return this.connected=!1,this.lastError=Ar(o),this.getSnapshot(!1)}}async callTool(t,o){try{await this.ensureConnected()}catch(n){return this.connected=!1,{content:[{type:"text",text:`Official SiYuan MCP is unavailable before dispatch: ${Ar(n)}`}],isError:!0}}try{const n=await this.client.callTool({name:t,arguments:o});return{content:n.content.map(r=>r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:{type:"text",text:JSON.stringify(r)}),isError:n.isError}}catch(n){return this.connected=!1,this.lastError=Ar(n),{content:[{type:"text",text:[`Official MCP tool call failed after dispatch: ${this.lastError}`,"Execution status is unknown. Inspect the target plugin state before deciding whether to retry."].join(`
523
- `)}],isError:!0}}}async close(){await this.resetConnection()}async listToolsOnce(){await this.ensureConnected();const t=[];let o;do{const n={method:"tools/list",params:o?{cursor:o}:{}},r=await this.client.request(n,oO,{timeout:5e3});t.push(...r.tools),o=r.nextCursor}while(o);return rO(t)}commitRefresh(t,o){return this.cachedTools=t,this.connected=!0,this.lastError=void 0,this.lastSuccessfulRefreshAt=new Date().toISOString(),this.getSnapshot(o!==Sc(t))}async ensureConnected(){if(!(this.connected&&this.client&&this.transport)){if(this.connecting)return this.connecting;this.connecting=(async()=>{const t={...this.siyuanClient.getAuthHeaders()};delete t.Connection;const o=new eO(new URL(`${this.siyuanClient.getBaseUrl()}/mcp`),{requestInit:{headers:t},fetch:this.fetchImpl,reconnectionOptions:{maxReconnectionDelay:1e3,initialReconnectionDelay:250,reconnectionDelayGrowFactor:1,maxRetries:0}}),n=new hx({name:"siyuan-sisyphus-extension-bridge",version:"1.0.0"},{capabilities:{},jsonSchemaValidator:dx});try{await n.connect(o,{timeout:5e3})}catch(r){throw await o.close().catch(()=>{}),r}this.client=n,this.transport=o,this.connected=!0})();try{await this.connecting}finally{this.connecting=void 0}}}async resetConnection(){const t=this.transport;this.client=void 0,this.transport=void 0,this.connected=!1,t&&await t.close().catch(()=>{})}}const Xo="siyuan-plugins-mcp-sisyphus",Jh=`/data/plugins/${Xo}/plugin.json`;function Tr(){return[`This CLI requires the SiYuan plugin "${Xo}".`,"Install and enable the plugin in SiYuan first, then open the plugin settings panel and configure permissions before retrying."].join(" ")}function aO(e){const t=e?` Details: ${e}`:"";return[`The required SiYuan plugin "${Xo}" appears to be installed, but its settings are not ready yet.`,"Enable the plugin in SiYuan, open its settings panel once, and save/configure notebook permissions before retrying."].join(" ")+t}function Dc(e){const t=e instanceof Error?e.message:String(e);return/HTTP error:\s*(401|403|5\d\d)\b/i.test(t)||/unauthorized/i.test(t)||/forbidden/i.test(t)||/timeout/i.test(t)||/fetch failed/i.test(t)||/network/i.test(t)||/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT/i.test(t)}function iO(e){try{return JSON.parse(e)}catch(t){throw new Error(`Found "${Xo}" at ${Jh}, but its plugin.json is invalid JSON: ${t instanceof Error?t.message:String(t)}`)}}async function cO(e){let t="";try{t=await e.readFile(Jh)}catch(n){throw Dc(n)?n:new Error(Tr())}if(!t.trim())throw new Error(Tr());if(iO(t).name!==Xo)throw new Error(Tr());try{await e.readFile(hn)}catch(n){throw Dc(n)?n:new Error(aO(n instanceof Error?n.message:String(n)))}}async function Va(e,t={}){const o=no(e.configPath),n=hm(o,{cliUrl:e.url,cliToken:e.token,profile:e.profile});mm(n);const r=new IC({baseUrl:n.apiUrl});n.token&&r.setToken(n.token),await cO(r);const s=await lO(r),a=new PC(r);t.loadPermissions!==!1&&await a.load();const i={bridge:new sO(r)};return{client:r,toolConfig:s,permMgr:a,officialMcpRuntime:i}}async function lO(e){try{const t=await e.readFile(So);if(!t)return Ao();const o=JSON.parse(t);return Uc(o,{source:`SiYuan API file "${So}"`}),Ms(o)}catch{return Ao()}}async function uO(e){const{tool:t,action:o,rest:n}=e;if(!t||!o)throw new Error("runDispatch requires both tool and action.");const r=va(t);if(!r)throw wO(t);const s=ro(r,o),a=zn[r];if(r!=="extension"&&!a.includes(s)&&s!=="help")throw Ac(r,s);const i=process.env.SIYUAN_MCP_TRANSPORT;process.env.SIYUAN_MCP_TRANSPORT="cli";try{const{client:c,toolConfig:l,permMgr:u,officialMcpRuntime:p}=await Va(e);if(!l[r].enabled)return Io({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const f=Xt[r];if(r==="extension"){await Ia(r,l,p);const O=Qt(l.extension,p).map(C=>C.name);if(!a.includes(s)&&s!=="help"&&!O.includes(s))throw Ac(r,s,O)}const h=bO(r,l,p),g=dO(r,s,n),{args:b,warnings:_}=gC(g,h,{category:r,action:s});if(_.length>0&&e.debug)for(const O of _)process.stderr.write(`[warn] ${O}
524
- `);const w={action:s,...b},P=[$,t,o,...n].join(" ").trim(),D=async O=>{const C=O===void 0?w:{...w,page:O};return mC({client:c,category:r,name:t,action:s,args:C,requestText:r==="extension"?[$,t,s].join(" "):P,slimResponses:l.debug.slimResponses&&!e.debug},()=>f.callTool(c,C,l[r],u,p))},T=await D(),A=Io(T,{json:e.json,debug:e.debug});return A!==0||e.json||await hO(T,D,{json:e.json,debug:e.debug}),A}catch(c){return Ye(c,{debug:e.debug}),1}finally{i===void 0?delete process.env.SIYUAN_MCP_TRANSPORT:process.env.SIYUAN_MCP_TRANSPORT=i}}function dO(e,t,o){const n=o.filter(r=>!r.startsWith("-"));if(n.length===0)return o;if(e==="fs"){if(["ls","tree","read","rm"].includes(t))return po(o,"path",n[0]);if(t==="search")return po(po(o,"path",n[0]),"query",n[1]);if(t==="mv")return po(po(o,"from",n[0]),"to",n[1])}return o}function po(e,t,o){return!o||pO(e,t)?e:[`--${t}`,o,...fO(e,o)]}function pO(e,t){const o=new Set([t,t.replace(/_/g,"-"),t.replace(/-/g,"_")]);return e.some(n=>{if(!n.startsWith("-"))return!1;const r=n.replace(/^-+/,"").split("=")[0];return o.has(r)})}function fO(e,t){let o=!1;return e.filter(n=>!o&&n===t&&!n.startsWith("-")?(o=!0,!1):!0)}async function hO(e,t,o){var i,c;if(!mO())return;let n=Ja(e);if(!n||n.pageCount<=1)return;const r=process.stdin,s=process.stdout,a=!!r.isRaw;try{for((i=r.setRawMode)==null||i.call(r,!0),r.resume();n.pageCount>1;){s.write(`
525
- Paging: Enter/n next, p previous, q quit › `);const l=await yO();if(s.write(`
526
- `),l===""||l==="\x1B"||l.toLowerCase()==="q")return;const u=gO(l,n.page,n.pageCount);if(u===null)continue;const p=await t(u);Io(p,o);const f=Ja(p);if(!f)return;n=f}}finally{(c=r.setRawMode)==null||c.call(r,a),r.pause()}}function mO(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function gO(e,t,o){const n=e.toLowerCase();return(e==="\r"||e===`
527
- `||n==="n")&&t<o?t+1:n==="p"&&t>1?t-1:null}function yO(){return new Promise(e=>{process.stdin.once("data",t=>{e(String(t))})})}function bO(e,t,o){const r=Xt[e].listTools(t[e],o)[0];if(!r)throw new Error(`Tool "${e}" has no aggregated descriptor — this is a bug.`);return r.inputSchema}function wO(e){const t=Qe.join(", ");return new Error(`Unknown tool "${e}". Available tools: ${t}. Try "${$} list".`)}function Ac(e,t,o=[]){const n=[...zn[e],...o].join(", ");return new Error(`Unknown action "${t}" for tool "${e}". Available actions: ${n}. Try "${$} help ${e}".`)}class kO{constructor(){se(this,"rl");se(this,"closed",!1);this.rl=nm.createInterface({input:process.stdin,output:process.stdout}),this.rl.once("close",()=>{this.closed=!0})}ask(t){return this.closed?Promise.resolve(""):new Promise(o=>{let n=!1;const r=()=>{n||(n=!0,o(""))};this.rl.once("close",r),this.rl.question(t,s=>{n||(n=!0,this.rl.off("close",r),o(s.trim()))})})}close(){this.closed||this.rl.close()}}async function _O(e){const t=Cc(e??ws()),o=no(e),n=ht(o),r=new kO;try{Je("SiYuan CLI setup"),ve("Path",t),ve("Tip","Press Enter to accept the default shown in brackets."),process.stdout.write(`
528
- `);const s=await r.ask("Profile name [default]: ")||"default";if(n.profiles[s]){const p=(await r.ask(`Profile "${s}" already exists. Overwrite it? [y/N] `)).toLowerCase();if(p!=="y"&&p!=="yes"){ge("warning","Aborted. Existing profile was kept.");return}}const a=await r.ask("SiYuan API URL [http://127.0.0.1:6806]: ")||"http://127.0.0.1:6806",i=await r.ask("SiYuan API token (find it in SiYuan > Settings > About): "),c=(await r.ask(`Make "${s}" the active profile? [Y/n] `)).toLowerCase(),u=Rc(o,s,{apiUrl:a,token:i},{makeCurrent:!c||c==="y"||c==="yes"});ks(u,e),process.stdout.write(`
528
+ `&&n++}}return[t,o]}class eO extends TransformStream{constructor({onError:t,onRetry:o,onComment:n}={}){let r;super({start(s){r=Qx({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:o,onComment:n})},transform(s){r.feed(s)}})}}const tO={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class It extends Error{constructor(t,o){super(`Streamable HTTP error: ${o}`),this.code=t}}class oO{constructor(t,o){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=o==null?void 0:o.requestInit,this._authProvider=o==null?void 0:o.authProvider,this._fetch=o==null?void 0:o.fetch,this._fetchWithInit=yx(o==null?void 0:o.fetch,o==null?void 0:o.requestInit),this._sessionId=o==null?void 0:o.sessionId,this._reconnectionOptions=(o==null?void 0:o.reconnectionOptions)??tO}async _authThenStart(){var o;if(!this._authProvider)throw new vt("No auth provider");let t;try{t=await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(o=this.onerror)==null||o.call(this,n),n}if(t!=="AUTHORIZED")throw new vt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var n;const t={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(t.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const o=as((n=this._requestInit)==null?void 0:n.headers);return new Headers({...t,...o})}async _startOrAuthSse(t){var n,r,s;const{resumptionToken:o}=t;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),o&&a.set("last-event-id",o);const i=await(this._fetch??fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)==null?void 0:n.signal});if(!i.ok){if(await((r=i.body)==null?void 0:r.cancel()),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new It(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,t,!0)}catch(a){throw(s=this.onerror)==null||s.call(this,a),a}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const o=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(o*Math.pow(n,t),r)}_scheduleReconnection(t,o=0){var s;const n=this._reconnectionOptions.maxRetries;if(o>=n){(s=this.onerror)==null||s.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const r=this._getNextReconnectionDelay(o);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)==null||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,o+1)})},r)}_handleSseStream(t,o,n){if(!t)return;const{onresumptiontoken:r,replayMessageId:s}=o;let a,i=!1,c=!1;(async()=>{var u,p,f,h;try{const g=t.pipeThrough(new TextDecoderStream).pipeThrough(new eO({onRetry:w=>{this._serverRetryMs=w}})).getReader();for(;;){const{value:w,done:P}=await g.read();if(P)break;if(w.id&&(a=w.id,i=!0,r==null||r(w.id)),!!w.data&&(!w.event||w.event==="message"))try{const D=Dr.parse(JSON.parse(w.data));go(D)&&(c=!0,s!==void 0&&(D.id=s)),(u=this.onmessage)==null||u.call(this,D)}catch(D){(p=this.onerror)==null||p.call(this,D)}}(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:s},0)}catch(g){if((f=this.onerror)==null||f.call(this,new Error(`SSE stream disconnected: ${g}`)),(n||i)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:s},0)}catch(w){(h=this.onerror)==null||h.call(this,new Error(`Failed to reconnect: ${w instanceof Error?w.message:String(w)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new vt("No auth provider");if(await dn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new vt("Failed to authorize")}async close(){var t,o;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)==null||t.abort(),(o=this.onclose)==null||o.call(this)}async send(t,o){var n,r,s,a,i,c;try{const{resumptionToken:l,onresumptiontoken:u}=o||{};if(l){this._startOrAuthSse({resumptionToken:l,replayMessageId:ss(t)?t.id:void 0}).catch(P=>{var D;return(D=this.onerror)==null?void 0:D.call(this,P)});return}const p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");const f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(t),signal:(n=this._abortController)==null?void 0:n.signal},h=await(this._fetch??fetch)(this._url,f),g=h.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!h.ok){const P=await h.text().catch(()=>null);if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:D,scope:A}=Ic(h);if(this._resourceMetadataUrl=D,this._scope=A,await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new vt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(h.status===403&&this._authProvider){const{resourceMetadataUrl:D,scope:A,error:T}=Ic(h);if(T==="insufficient_scope"){const O=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===O)throw new It(403,"Server returned 403 after trying upscoping");if(A&&(this._scope=A),D&&(this._resourceMetadataUrl=D),this._lastUpscopingHeader=O??void 0,await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new vt;return this.send(t)}}throw new It(h.status,`Error POSTing to endpoint: ${P}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){await((r=h.body)==null?void 0:r.cancel()),WE(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(P=>{var D;return(D=this.onerror)==null?void 0:D.call(this,P)});return}const _=(Array.isArray(t)?t:[t]).filter(P=>"method"in P&&"id"in P&&P.id!==void 0).length>0,w=h.headers.get("content-type");if(_)if(w!=null&&w.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:u},!1);else if(w!=null&&w.includes("application/json")){const P=await h.json(),D=Array.isArray(P)?P.map(A=>Dr.parse(A)):[Dr.parse(P)];for(const A of D)(s=this.onmessage)==null||s.call(this,A)}else throw await((a=h.body)==null?void 0:a.cancel()),new It(-1,`Unexpected content type: ${w}`);else await((i=h.body)==null?void 0:i.cancel())}catch(l){throw(c=this.onerror)==null||c.call(this,l),l}}get sessionId(){return this._sessionId}async terminateSession(){var t,o,n;if(this._sessionId)try{const r=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:r,signal:(t=this._abortController)==null?void 0:t.signal},a=await(this._fetch??fetch)(this._url,s);if(await((o=a.body)==null?void 0:o.cancel()),!a.ok&&a.status!==405)throw new It(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)==null||n.call(this,r),r}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,o){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:o==null?void 0:o.onresumptiontoken})}}const kn="3.7.0";function Tc(e){const t=e.trim().match(/^v?(\d+)\.(\d+)\.(\d+)/i);if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}function nO(e){const t=Tc(e),o=Tc(kn);if(!t)return!1;for(let n=0;n<o.length;n+=1){if(t[n]>o[n])return!0;if(t[n]<o[n])return!1}return!0}const rO="plugin__siyuan_plugins_mcp_sisyphus__",Xh=m({name:d(),title:d().optional(),description:d().optional(),inputSchema:K().optional(),outputSchema:K().optional(),source:d().optional(),readOnlyHint:x().optional(),effectScope:d().optional()}).passthrough(),sO=m({tools:I(Xh),nextCursor:d().optional()}).passthrough();function ws(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function aO(e){if(!ws(e))return{schema:{type:"object",additionalProperties:!0},degraded:!0};const t=e.type,o=Array.isArray(e.oneOf)||Array.isArray(e.anyOf)||Array.isArray(e.allOf)||typeof e.$ref=="string";return t!==void 0&&t!=="object"?{schema:{type:"object",additionalProperties:!0},degraded:!0}:t===void 0&&!o&&!ws(e.properties)?{schema:{type:"object",additionalProperties:!0},degraded:!0}:{schema:t===void 0&&!o?{...e,type:"object"}:{...e},degraded:!1}}function iO(e){const t=new Map;for(const o of e){const n=Xh.safeParse(o);if(!n.success)continue;const r=n.data,s=r.source?r.source:"native";if(s!=="plugin"&&s!=="native"||r.name.startsWith(rO))continue;const a=aO(r.inputSchema);t.set(r.name,{name:r.name,title:r.title,description:r.description,inputSchema:a.schema,outputSchema:ws(r.outputSchema)?r.outputSchema:void 0,source:s,readOnlyHint:r.readOnlyHint===!0,effectScope:r.effectScope,schemaDegraded:a.degraded})}return[...t.values()].sort((o,n)=>o.name.localeCompare(n.name))}function pn(e){return e instanceof Error?e.message:String(e)}function fn(e){return JSON.stringify(e.map(t=>({name:t.name,title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,source:t.source,readOnlyHint:t.readOnlyHint,effectScope:t.effectScope,schemaDegraded:t.schemaDegraded})))}class cO{constructor(t,o={}){ee(this,"siyuanClient");ee(this,"fetchImpl");ee(this,"getSiYuanVersion");ee(this,"client");ee(this,"transport");ee(this,"connecting");ee(this,"cachedTools",[]);ee(this,"connected",!1);ee(this,"lastSuccessfulRefreshAt");ee(this,"lastAttemptAt");ee(this,"lastError");ee(this,"versionChecked",!1);ee(this,"supported");ee(this,"siyuanVersion");this.siyuanClient=t,this.fetchImpl=o.fetch,this.getSiYuanVersion=o.getSiYuanVersion??(()=>Zp(this.siyuanClient))}getTools(){return this.cachedTools.map(t=>({...t,inputSchema:{...t.inputSchema},outputSchema:t.outputSchema?{...t.outputSchema}:void 0}))}getSnapshot(t=!1){return{tools:this.getTools(),connected:this.connected,supported:this.supported,siyuanVersion:this.siyuanVersion,minSupportedVersion:kn,lastSuccessfulRefreshAt:this.lastSuccessfulRefreshAt,lastAttemptAt:this.lastAttemptAt,error:this.lastError,changed:t}}async refresh(t={}){this.lastAttemptAt=new Date().toISOString();const o=fn(this.cachedTools);if(!await this.checkSupport(t.forceVersionCheck===!0))return await this.resetConnection(),this.cachedTools=[],this.getSnapshot(o!==fn(this.cachedTools));try{const r=await this.listToolsOnce();return this.commitRefresh(r,o)}catch{await this.resetConnection()}try{const r=await this.listToolsOnce();return this.commitRefresh(r,o)}catch(r){return this.connected=!1,this.lastError=pn(r),this.cachedTools=[],this.getSnapshot(o!==fn(this.cachedTools))}}async callTool(t,o){if(!await this.checkSupport())return{content:[{type:"text",text:this.lastError||`Official SiYuan MCP requires SiYuan ${kn} or newer.`}],isError:!0};try{await this.ensureConnected()}catch(n){return this.connected=!1,{content:[{type:"text",text:`Official SiYuan MCP is unavailable before dispatch: ${pn(n)}`}],isError:!0}}try{const n=await this.client.callTool({name:t,arguments:o});return{content:n.content.map(r=>r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:{type:"text",text:JSON.stringify(r)}),isError:n.isError}}catch(n){return this.connected=!1,this.lastError=pn(n),{content:[{type:"text",text:[`Official MCP tool call failed after dispatch: ${this.lastError}`,"Execution status is unknown. Inspect the target plugin state before deciding whether to retry."].join(`
529
+ `)}],isError:!0}}}async close(){await this.resetConnection()}async listToolsOnce(){await this.ensureConnected();const t=[];let o;do{const n={method:"tools/list",params:o?{cursor:o}:{}},r=await this.client.request(n,sO,{timeout:5e3});t.push(...r.tools),o=r.nextCursor}while(o);return iO(t)}commitRefresh(t,o){return this.cachedTools=t,this.connected=!0,this.lastError=void 0,this.lastSuccessfulRefreshAt=new Date().toISOString(),this.getSnapshot(o!==fn(t))}async checkSupport(t=!1){if(this.versionChecked&&!t)return this.supported===!0;this.versionChecked=!0;try{const o=await this.getSiYuanVersion();return this.siyuanVersion=o,this.supported=nO(o),this.supported?(this.lastError=void 0,!0):(this.lastError=`SiYuan ${o} does not support the official MCP endpoint. Version ${kn} or newer is required for extension tools.`,!1)}catch(o){return this.supported=void 0,this.lastError=`Unable to determine SiYuan version through /api/system/version: ${pn(o)}`,!1}}async ensureConnected(){if(!(this.connected&&this.client&&this.transport)){if(this.connecting)return this.connecting;this.connecting=(async()=>{const t={...this.siyuanClient.getAuthHeaders()};delete t.Connection;const o=new oO(new URL(`${this.siyuanClient.getBaseUrl()}/mcp`),{requestInit:{headers:t},fetch:this.fetchImpl,reconnectionOptions:{maxReconnectionDelay:1e3,initialReconnectionDelay:250,reconnectionDelayGrowFactor:1,maxRetries:0}}),n=new gx({name:"siyuan-sisyphus-extension-bridge",version:"1.0.0"},{capabilities:{},jsonSchemaValidator:fx});try{await n.connect(o,{timeout:5e3})}catch(r){throw await o.close().catch(()=>{}),r}this.client=n,this.transport=o,this.connected=!0})();try{await this.connecting}finally{this.connecting=void 0}}}async resetConnection(){const t=this.transport;this.client=void 0,this.transport=void 0,this.connected=!1,t&&await t.close().catch(()=>{})}}const tn="siyuan-plugins-mcp-sisyphus",em=`/data/plugins/${tn}/plugin.json`;function Rr(){return[`This CLI requires the SiYuan plugin "${tn}".`,"Install and enable the plugin in SiYuan first, then open the plugin settings panel and configure permissions before retrying."].join(" ")}function lO(e){const t=e?` Details: ${e}`:"";return[`The required SiYuan plugin "${tn}" appears to be installed, but its settings are not ready yet.`,"Enable the plugin in SiYuan, open its settings panel once, and save/configure notebook permissions before retrying."].join(" ")+t}function Ac(e){const t=e instanceof Error?e.message:String(e);return/HTTP error:\s*(401|403|5\d\d)\b/i.test(t)||/unauthorized/i.test(t)||/forbidden/i.test(t)||/timeout/i.test(t)||/fetch failed/i.test(t)||/network/i.test(t)||/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT/i.test(t)}function uO(e){try{return JSON.parse(e)}catch(t){throw new Error(`Found "${tn}" at ${em}, but its plugin.json is invalid JSON: ${t instanceof Error?t.message:String(t)}`)}}async function dO(e){let t="";try{t=await e.readFile(em)}catch(n){throw Ac(n)?n:new Error(Rr())}if(!t.trim())throw new Error(Rr());if(uO(t).name!==tn)throw new Error(Rr());try{await e.readFile(bn)}catch(n){throw Ac(n)?n:new Error(lO(n instanceof Error?n.message:String(n)))}}async function Ya(e,t={}){const o=ro(e.configPath),n=ym(o,{cliUrl:e.url,cliToken:e.token,profile:e.profile});bm(n);const r=new DE({baseUrl:n.apiUrl});n.token&&r.setToken(n.token),await dO(r);const s=await pO(r),a=new EE(r);t.loadPermissions!==!1&&await a.load();const i={bridge:new cO(r),discoveryMode:"blocking"};return{client:r,toolConfig:s,permMgr:a,officialMcpRuntime:i}}async function pO(e){try{const t=await e.readFile(To);if(!t)return Po();const o=JSON.parse(t);return Hc(o,{source:`SiYuan API file "${To}"`}),Fs(o)}catch{return Po()}}async function fO(e){const{tool:t,action:o,rest:n}=e;if(!t||!o)throw new Error("runDispatch requires both tool and action.");const r=Sa(t);if(!r)throw vO(t);const s=so(r,o),a=Un[r];if(r!=="extension"&&!a.includes(s)&&s!=="help")throw Pc(r,s);const i=process.env.SIYUAN_MCP_TRANSPORT;process.env.SIYUAN_MCP_TRANSPORT="cli";try{const{client:c,toolConfig:l,permMgr:u,officialMcpRuntime:p}=await Ya(e);if(!l[r].enabled)return Do({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const f=eo[r];if(r==="extension"){await Da(r,l,p);const O=Xt(l.extension,p).map(E=>E.name);if(!a.includes(s)&&s!=="help"&&!O.includes(s))throw Pc(r,s,O)}const h=_O(r,l,p),g=hO(r,s,n),{args:b,warnings:_}=bE(g,h,{category:r,action:s});if(_.length>0&&e.debug)for(const O of _)process.stderr.write(`[warn] ${O}
530
+ `);const w={action:s,...b},P=[$,t,o,...n].join(" ").trim(),D=async O=>{const E=O===void 0?w:{...w,page:O};return yE({client:c,category:r,name:t,action:s,args:E,requestText:r==="extension"?[$,t,s].join(" "):P,slimResponses:l.debug.slimResponses&&!e.debug},()=>f.callTool(c,E,l[r],u,p))},A=await D(),T=Do(A,{json:e.json,debug:e.debug});return T!==0||e.json||await yO(A,D,{json:e.json,debug:e.debug}),T}catch(c){return Ye(c,{debug:e.debug}),1}finally{i===void 0?delete process.env.SIYUAN_MCP_TRANSPORT:process.env.SIYUAN_MCP_TRANSPORT=i}}function hO(e,t,o){const n=o.filter(r=>!r.startsWith("-"));if(n.length===0)return o;if(e==="fs"){if(["ls","tree","read","rm"].includes(t))return fo(o,"path",n[0]);if(t==="search")return fo(fo(o,"path",n[0]),"query",n[1]);if(t==="mv")return fo(fo(o,"from",n[0]),"to",n[1])}return o}function fo(e,t,o){return!o||mO(e,t)?e:[`--${t}`,o,...gO(e,o)]}function mO(e,t){const o=new Set([t,t.replace(/_/g,"-"),t.replace(/-/g,"_")]);return e.some(n=>{if(!n.startsWith("-"))return!1;const r=n.replace(/^-+/,"").split("=")[0];return o.has(r)})}function gO(e,t){let o=!1;return e.filter(n=>!o&&n===t&&!n.startsWith("-")?(o=!0,!1):!0)}async function yO(e,t,o){var i,c;if(!bO())return;let n=Xa(e);if(!n||n.pageCount<=1)return;const r=process.stdin,s=process.stdout,a=!!r.isRaw;try{for((i=r.setRawMode)==null||i.call(r,!0),r.resume();n.pageCount>1;){s.write(`
531
+ Paging: Enter/n next, p previous, q quit › `);const l=await kO();if(s.write(`
532
+ `),l===""||l==="\x1B"||l.toLowerCase()==="q")return;const u=wO(l,n.page,n.pageCount);if(u===null)continue;const p=await t(u);Do(p,o);const f=Xa(p);if(!f)return;n=f}}finally{(c=r.setRawMode)==null||c.call(r,a),r.pause()}}function bO(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function wO(e,t,o){const n=e.toLowerCase();return(e==="\r"||e===`
533
+ `||n==="n")&&t<o?t+1:n==="p"&&t>1?t-1:null}function kO(){return new Promise(e=>{process.stdin.once("data",t=>{e(String(t))})})}function _O(e,t,o){const r=eo[e].listTools(t[e],o)[0];if(!r)throw new Error(`Tool "${e}" has no aggregated descriptor — this is a bug.`);return r.inputSchema}function vO(e){const t=Qe.join(", ");return new Error(`Unknown tool "${e}". Available tools: ${t}. Try "${$} list".`)}function Pc(e,t,o=[]){const n=[...Un[e],...o].join(", ");return new Error(`Unknown action "${t}" for tool "${e}". Available actions: ${n}. Try "${$} help ${e}".`)}class IO{constructor(){ee(this,"rl");ee(this,"closed",!1);this.rl=am.createInterface({input:process.stdin,output:process.stdout}),this.rl.once("close",()=>{this.closed=!0})}ask(t){return this.closed?Promise.resolve(""):new Promise(o=>{let n=!1;const r=()=>{n||(n=!0,o(""))};this.rl.once("close",r),this.rl.question(t,s=>{n||(n=!0,this.rl.off("close",r),o(s.trim()))})})}close(){this.closed||this.rl.close()}}async function SO(e){const t=xc(e??_s()),o=ro(e),n=ht(o),r=new IO;try{Je("SiYuan CLI setup"),ve("Path",t),ve("Tip","Press Enter to accept the default shown in brackets."),process.stdout.write(`
534
+ `);const s=await r.ask("Profile name [default]: ")||"default";if(n.profiles[s]){const p=(await r.ask(`Profile "${s}" already exists. Overwrite it? [y/N] `)).toLowerCase();if(p!=="y"&&p!=="yes"){ge("warning","Aborted. Existing profile was kept.");return}}const a=await r.ask("SiYuan API URL [http://127.0.0.1:6806]: ")||"http://127.0.0.1:6806",i=await r.ask("SiYuan API token (find it in SiYuan > Settings > About): "),c=(await r.ask(`Make "${s}" the active profile? [Y/n] `)).toLowerCase(),u=Oc(o,s,{apiUrl:a,token:i},{makeCurrent:!c||c==="y"||c==="yes"});vs(u,e),process.stdout.write(`
529
535
  `),ge("success","Config written."),Me([{key:"path",value:t},{key:"profile",value:s},{key:"current",value:u.currentProfile},{key:"apiUrl",value:a},{key:"token",value:i?"configured":"empty"}]),process.stdout.write(`
530
- `),ve("Next","Run `siyuan-sisyphus notebook list` to verify the connection, or `siyuan-sisyphus config list` to inspect all profiles.")}finally{r.close()}}async function vO(e){const t=process.stdout,o=e.tool?va(e.tool):null,{toolConfig:n,officialMcpRuntime:r}=await Va(e,{loadPermissions:!1});if(await Ia("extension",n,r),!o){e.tool&&Ye(`Unknown tool "${e.tool}". Showing all tools instead.`);const a=Qe.filter(i=>Xt[i].listTools(n[i],r).length>0);return Je("SiYuan tools",t),Pe(a.map(i=>{const c=i==="extension"?["list",...Qt(n.extension,r).map(p=>p.name)]:To(n[i]),l=c.filter(p=>Do(i,p)==="basic").length,u=c.length-l;return`${i} — ${c.length} actions (${l} common, ${u} advanced)`}),t),oe("Next Step",t),ve("Tip",`Run \`${$} list <tool>\` to see a tool’s actions.`,t),0}if(Xt[o].listTools(n[o],r).length===0)return Ye(`Tool "${o}" is disabled.`),1;Je(`${o} actions`,t);const s=o==="extension"?["list",...Qt(n.extension,r).map(a=>a.name)]:To(n[o]);return Pe(s.map(a=>{const i=o==="extension"?r.bridge.getTools().find(p=>p.name===a):void 0,c=Do(o,a)==="basic"?"common":"advanced",l=i?i.readOnlyHint?" · declared read-only":" · confirmation required":Bt(o,a)?" · confirmation required":"",u=i?` · ${i.source}`:"";return`${a} — ${c}${u}${l}`}),t),oe("Next Step",t),ve("Tip",`Run \`${$} help ${o} <action>\` for fields and examples.`,t),0}async function IO(e){const t=e.tool;if(!t)return Ye(`Missing tool. Usage: ${$} help <tool> [action]`),2;const o=va(t);if(!o)return Ye(`Unknown tool "${t}". Available: ${Qe.join(", ")}.`),2;try{const{client:n,toolConfig:r,permMgr:s,officialMcpRuntime:a}=await Va(e,{loadPermissions:!1});if(!r[o].enabled)return Io({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const i=Xt[o];await Ia(o,r,a);const c={action:"help"};e.action&&(c.topic=ro(o,e.action));const l=await i.callTool(n,c,r[o],s,a);return Io(l,{json:e.json,debug:e.debug})}catch(n){return Ye(n,{debug:e.debug}),1}}const SO={cli:"siyuan-sisyphus",mcp:"siyuan-mcp"};function DO(e){switch(e.skillAction){case"list":return AO(e);case"read":return TO(e);case"install":return PO(e);case"uninstall":return EO(e);default:throw new Error("Unknown skill action.")}}function AO(e){const t=ar(e.bundle),o=oo(void 0,t);if(e.json)return process.stdout.write(JSON.stringify({bundle:t,skills:o})+`
536
+ `),ve("Next","Run `siyuan-sisyphus notebook list` to verify the connection, or `siyuan-sisyphus config list` to inspect all profiles.")}finally{r.close()}}async function DO(e){const t=process.stdout,o=e.tool?Sa(e.tool):null,{toolConfig:n,officialMcpRuntime:r}=await Ya(e,{loadPermissions:!1});if(await Da("extension",n,r),!o){e.tool&&Ye(`Unknown tool "${e.tool}". Showing all tools instead.`);const a=Qe.filter(i=>eo[i].listTools(n[i],r).length>0);return Je("SiYuan tools",t),Pe(a.map(i=>{const c=i==="extension"?["list",...Xt(n.extension,r).map(p=>p.name)]:Co(n[i]),l=c.filter(p=>Ao(i,p)==="basic").length,u=c.length-l;return`${i} — ${c.length} actions (${l} common, ${u} advanced)`}),t),ne("Next Step",t),ve("Tip",`Run \`${$} list <tool>\` to see a tool’s actions.`,t),0}if(eo[o].listTools(n[o],r).length===0)return Ye(`Tool "${o}" is disabled.`),1;Je(`${o} actions`,t);const s=o==="extension"?["list",...Xt(n.extension,r).map(a=>a.name)]:Co(n[o]);return Pe(s.map(a=>{const i=o==="extension"?r.bridge.getTools().find(p=>p.name===a):void 0,c=Ao(o,a)==="basic"?"common":"advanced",l=i?i.readOnlyHint?" · declared read-only":" · confirmation required":Bt(o,a)?" · confirmation required":"",u=i?` · ${i.source}`:"";return`${a} — ${c}${u}${l}`}),t),ne("Next Step",t),ve("Tip",`Run \`${$} help ${o} <action>\` for fields and examples.`,t),0}async function TO(e){const t=e.tool;if(!t)return Ye(`Missing tool. Usage: ${$} help <tool> [action]`),2;const o=Sa(t);if(!o)return Ye(`Unknown tool "${t}". Available: ${Qe.join(", ")}.`),2;try{const{client:n,toolConfig:r,permMgr:s,officialMcpRuntime:a}=await Ya(e,{loadPermissions:!1});if(!r[o].enabled)return Do({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const i=eo[o];await Da(o,r,a);const c={action:"help"};e.action&&(c.topic=so(o,e.action));const l=await i.callTool(n,c,r[o],s,a);return Do(l,{json:e.json,debug:e.debug})}catch(n){return Ye(n,{debug:e.debug}),1}}const AO={cli:"siyuan-sisyphus",mcp:"siyuan-mcp"};function PO(e){switch(e.skillAction){case"list":return CO(e);case"read":return EO(e);case"install":return RO(e);case"uninstall":return xO(e);default:throw new Error("Unknown skill action.")}}function CO(e){const t=dr(e.bundle),o=no(void 0,t);if(e.json)return process.stdout.write(JSON.stringify({bundle:t,skills:o})+`
531
537
  `),0;Je("Bundled SiYuan Sisyphus skills");for(const n of o)process.stdout.write(` ${n.name}
532
- `);return ve("Next","Run `siyuan-sisyphus skill install` to install them."),0}function TO(e){const t=RO(e.skillName,ar(e.bundle));return process.stdout.write(t),t.endsWith(`
538
+ `);return ve("Next","Run `siyuan-sisyphus skill install` to install them."),0}function EO(e){const t=NO(e.skillName,dr(e.bundle));return process.stdout.write(t),t.endsWith(`
533
539
  `)||process.stdout.write(`
534
- `),0}function PO(e){const t=OO({target:e.target,local:e.local,dryRun:e.dryRun,bundle:e.bundle});return e.json||e.dryRun?(process.stdout.write(JSON.stringify(t,null,2)+`
535
- `),0):(ge("success","Bundled skills installed."),Me([{key:"target",value:t.target},{key:"count",value:t.skills.length}]),0)}function EO(e){const t=NO({target:e.target,local:e.local,bundle:e.bundle});return e.json?(process.stdout.write(JSON.stringify(t,null,2)+`
536
- `),0):(ge("success","Bundled skills removed."),Me([{key:"target",value:t.target},{key:"count",value:t.removed.length}]),0)}function CO(e=U.dirname(rm.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:ir&&ir.tagName.toUpperCase()==="SCRIPT"&&ir.src||new URL("cli.cjs",document.baseURI).href)),t=H.existsSync,o="cli"){const n=SO[o],r=[U.resolve(e,"skills",n),U.resolve(e,"../skills",n),U.resolve(e,"../../skills",n),U.resolve(e,"../../../skills",n)];for(const s of r)if(t(U.join(s,Xh(o),"SKILL.md")))return s;for(const s of r)if(t(s))return s;return r[0]}function oo(e,t="cli"){if(t==="all")return[...oo(void 0,"cli"),...oo(void 0,"mcp")].sort((n,r)=>n.name.localeCompare(r.name));const o=CO(void 0,H.existsSync,t==="all"?"cli":t);return H.readdirSync(o).map(n=>({name:n,path:U.join(o,n)})).filter(n=>{try{return H.statSync(n.path).isDirectory()&&H.existsSync(U.join(n.path,"SKILL.md"))}catch{return!1}}).sort((n,r)=>n.name.localeCompare(r.name))}function RO(e,t="cli"){const o=(e==null?void 0:e.trim())||Xh(t==="all"?"cli":t);em(o);const n=oo(void 0,t).find(r=>r.name===o);if(!n)throw new Error(`Unknown bundled skill "${o}". Run \`siyuan-sisyphus skill list\` to see available skills.`);return H.readFileSync(U.join(n.path,"SKILL.md"),"utf8")}function xO(e){const t=(e??"agents").trim();return t?(em(t),t==="agents"||t==="claude"||t.startsWith(".")?t:`.${t}`):"agents"}function Qh(e={}){const t=xO(e.target);if(t==="agents"){if(e.local)throw new Error('Target "agents" uses the home directory shortcut. Use `--target .agents --local` for a project-local path.');return U.join(go.homedir(),".agents","skills")}if(t==="claude"){if(e.local)throw new Error('Target "claude" uses the home directory shortcut. Use `--target .claude --local` for a project-local path.');return U.join(go.homedir(),".claude","skills")}const o=e.local?e.cwd??process.cwd():go.homedir();return U.join(o,t,"skills")}function OO(e={}){const t=ar(e.bundle),o=oo(void 0,t),n=Qh(e),r=o.map(s=>({op:H.existsSync(U.join(n,s.name))?"update":"install",from:s.path,to:U.join(n,s.name)}));if(e.dryRun)return{target:n,bundle:t,dryRun:!0,skills:o.map(s=>s.name),operations:r};H.mkdirSync(n,{recursive:!0});for(const s of r)H.rmSync(s.to,{recursive:!0,force:!0}),H.cpSync(s.from,s.to,{recursive:!0,force:!0});return{target:n,bundle:t,dryRun:!1,skills:o.map(s=>s.name)}}function NO(e={}){const t=ar(e.bundle),o=oo(void 0,t),n=Qh(e),r=[];for(const s of o){const a=U.join(n,s.name);H.existsSync(a)&&(H.rmSync(a,{recursive:!0,force:!0}),r.push(U.basename(a)))}return{target:n,bundle:t,removed:r}}function ar(e){const t=(e??"cli").trim().toLowerCase();if(t==="cli"||t==="mcp"||t==="all")return t;throw new Error(`Invalid skill bundle "${e}". Use cli, mcp, or all.`)}function Xh(e){return e==="mcp"?"siyuan-mcp-sisyphus":"siyuan-sisyphus"}function em(e){if(!e||e==="."||e==="..")throw new Error(`Invalid skill target: "${e||"(empty)"}".`);if(/[\\/]/.test(e)||!/^[A-Za-z0-9._-]+$/.test(e))throw new Error(`Invalid skill target: "${e}". Use a simple name such as agents, claude, codex, or .codex.`)}async function $O(){let e;try{e=um(process.argv.slice(2))}catch(t){return Ye(t),2}switch(e.command){case"show-help":return process.stdout.write(pm()),0;case"version":return process.stdout.write(`0.2.0
537
- `),0;case"init":return await _O(e.configPath),0;case"config":return Vm(e);case"skill":return DO(e);case"list":return await vO(e);case"help":return await IO(e);case"dispatch":return await uO(e);default:throw new Error(`Unknown command: ${String(e.command)}`)}}$O().then(e=>process.exit(e)).catch(e=>{Ye(e,{debug:process.env.SIYUAN_MCP_DEBUG==="1"}),process.exit(1)});
540
+ `),0}function RO(e){const t=MO({target:e.target,local:e.local,dryRun:e.dryRun,bundle:e.bundle});return e.json||e.dryRun?(process.stdout.write(JSON.stringify(t,null,2)+`
541
+ `),0):(ge("success","Bundled skills installed."),Me([{key:"target",value:t.target},{key:"count",value:t.skills.length}]),0)}function xO(e){const t=zO({target:e.target,local:e.local,bundle:e.bundle});return e.json?(process.stdout.write(JSON.stringify(t,null,2)+`
542
+ `),0):(ge("success","Bundled skills removed."),Me([{key:"target",value:t.target},{key:"count",value:t.removed.length}]),0)}function OO(e=U.dirname(im.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:pr&&pr.tagName.toUpperCase()==="SCRIPT"&&pr.src||new URL("cli.cjs",document.baseURI).href)),t=H.existsSync,o="cli"){const n=AO[o],r=[U.resolve(e,"skills",n),U.resolve(e,"../skills",n),U.resolve(e,"../../skills",n),U.resolve(e,"../../../skills",n)];for(const s of r)if(t(U.join(s,om(o),"SKILL.md")))return s;for(const s of r)if(t(s))return s;return r[0]}function no(e,t="cli"){if(t==="all")return[...no(void 0,"cli"),...no(void 0,"mcp")].sort((n,r)=>n.name.localeCompare(r.name));const o=OO(void 0,H.existsSync,t==="all"?"cli":t);return H.readdirSync(o).map(n=>({name:n,path:U.join(o,n)})).filter(n=>{try{return H.statSync(n.path).isDirectory()&&H.existsSync(U.join(n.path,"SKILL.md"))}catch{return!1}}).sort((n,r)=>n.name.localeCompare(r.name))}function NO(e,t="cli"){const o=(e==null?void 0:e.trim())||om(t==="all"?"cli":t);nm(o);const n=no(void 0,t).find(r=>r.name===o);if(!n)throw new Error(`Unknown bundled skill "${o}". Run \`siyuan-sisyphus skill list\` to see available skills.`);return H.readFileSync(U.join(n.path,"SKILL.md"),"utf8")}function $O(e){const t=(e??"agents").trim();return t?(nm(t),t==="agents"||t==="claude"||t.startsWith(".")?t:`.${t}`):"agents"}function tm(e={}){const t=$O(e.target);if(t==="agents"){if(e.local)throw new Error('Target "agents" uses the home directory shortcut. Use `--target .agents --local` for a project-local path.');return U.join(yo.homedir(),".agents","skills")}if(t==="claude"){if(e.local)throw new Error('Target "claude" uses the home directory shortcut. Use `--target .claude --local` for a project-local path.');return U.join(yo.homedir(),".claude","skills")}const o=e.local?e.cwd??process.cwd():yo.homedir();return U.join(o,t,"skills")}function MO(e={}){const t=dr(e.bundle),o=no(void 0,t),n=tm(e),r=o.map(s=>({op:H.existsSync(U.join(n,s.name))?"update":"install",from:s.path,to:U.join(n,s.name)}));if(e.dryRun)return{target:n,bundle:t,dryRun:!0,skills:o.map(s=>s.name),operations:r};H.mkdirSync(n,{recursive:!0});for(const s of r)H.rmSync(s.to,{recursive:!0,force:!0}),H.cpSync(s.from,s.to,{recursive:!0,force:!0});return{target:n,bundle:t,dryRun:!1,skills:o.map(s=>s.name)}}function zO(e={}){const t=dr(e.bundle),o=no(void 0,t),n=tm(e),r=[];for(const s of o){const a=U.join(n,s.name);H.existsSync(a)&&(H.rmSync(a,{recursive:!0,force:!0}),r.push(U.basename(a)))}return{target:n,bundle:t,removed:r}}function dr(e){const t=(e??"cli").trim().toLowerCase();if(t==="cli"||t==="mcp"||t==="all")return t;throw new Error(`Invalid skill bundle "${e}". Use cli, mcp, or all.`)}function om(e){return e==="mcp"?"siyuan-mcp-sisyphus":"siyuan-sisyphus"}function nm(e){if(!e||e==="."||e==="..")throw new Error(`Invalid skill target: "${e||"(empty)"}".`);if(/[\\/]/.test(e)||!/^[A-Za-z0-9._-]+$/.test(e))throw new Error(`Invalid skill target: "${e}". Use a simple name such as agents, claude, codex, or .codex.`)}async function FO(){let e;try{e=fm(process.argv.slice(2))}catch(t){return Ye(t),2}switch(e.command){case"show-help":return process.stdout.write(mm()),0;case"version":return process.stdout.write(`0.2.1
543
+ `),0;case"init":return await SO(e.configPath),0;case"config":return Wm(e);case"skill":return PO(e);case"list":return await DO(e);case"help":return await TO(e);case"dispatch":return await fO(e);default:throw new Error(`Unknown command: ${String(e.command)}`)}}FO().then(e=>process.exit(e)).catch(e=>{Ye(e,{debug:process.env.SIYUAN_MCP_DEBUG==="1"}),process.exit(1)});