siyuan-sisyphus 0.1.13 → 0.1.14

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 +75 -75
  2. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ml=Object.defineProperty;var gl=(e,t,o)=>t in e?ml(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var me=(e,t,o)=>gl(e,typeof t!="symbol"?t+"":t,o);const j=require("node:fs"),Dt=require("node:os"),F=require("node:path"),yl=require("node:readline"),bl=require("node:url");var xo=typeof document<"u"?document.currentScript:null;function kl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function wl(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 ar(e){return typeof e=="number"||/^0x[0-9a-f]+$/i.test(e)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function ir(e,t){return t==="constructor"&&typeof e[t]=="function"||t==="__proto__"}var _l=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(I){o.bools[I]=!0});var n={};function r(I){return n[I].some(function(A){return o.bools[A]})}Object.keys(t.alias||{}).forEach(function(I){n[I]=[].concat(t.alias[I]),n[I].forEach(function(A){n[A]=[I].concat(n[I].filter(function(B){return A!==B}))})}),[].concat(t.string).filter(Boolean).forEach(function(I){o.strings[I]=!0,n[I]&&[].concat(n[I]).forEach(function(A){o.strings[A]=!0})});var s=t.default||{},a={_:[]};function i(I,A){return o.allBools&&/^--[^=]+$/.test(A)||o.strings[I]||o.bools[I]||n[I]}function c(I,A,B){for(var x=I,_e=0;_e<A.length-1;_e++){var ce=A[_e];if(ir(x,ce))return;x[ce]===void 0&&(x[ce]={}),(x[ce]===Object.prototype||x[ce]===Number.prototype||x[ce]===String.prototype)&&(x[ce]={}),x[ce]===Array.prototype&&(x[ce]=[]),x=x[ce]}var he=A[A.length-1];ir(x,he)||((x===Object.prototype||x===Number.prototype||x===String.prototype)&&(x={}),x===Array.prototype&&(x=[]),x[he]===void 0||o.bools[he]||typeof x[he]=="boolean"?x[he]=B:Array.isArray(x[he])?x[he].push(B):x[he]=[x[he],B])}function u(I,A,B){if(!(B&&o.unknownFn&&!i(I,B)&&o.unknownFn(B)===!1)){var x=!o.strings[I]&&ar(A)?Number(A):A;c(a,I.split("."),x),(n[I]||[]).forEach(function(_e){c(a,_e.split("."),x)})}}Object.keys(o.bools).forEach(function(I){u(I,s[I]===void 0?!1:s[I])});var l=[];e.indexOf("--")!==-1&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var d=0;d<e.length;d++){var f=e[d],h,m;if(/^--.+=/.test(f)){var k=f.match(/^--([^=]+)=([\s\S]*)$/);h=k[1];var v=k[2];o.bools[h]&&(v=v!=="false"),u(h,v,f)}else if(/^--no-.+/.test(f))h=f.match(/^--no-(.+)/)[1],u(h,!1,f);else if(/^--.+/.test(f))h=f.match(/^--(.+)/)[1],m=e[d+1],m!==void 0&&!/^(-|--)[^-]/.test(m)&&!o.bools[h]&&!o.allBools&&(!n[h]||!r(h))?(u(h,m,f),d+=1):/^(true|false)$/.test(m)?(u(h,m==="true",f),d+=1):u(h,o.strings[h]?"":!0,f);else if(/^-[^-]+/.test(f)){for(var E=f.slice(1,-1).split(""),C=!1,$=0;$<E.length;$++){if(m=f.slice($+2),m==="-"){u(E[$],m,f);continue}if(/[A-Za-z]/.test(E[$])&&m[0]==="="){u(E[$],m.slice(1),f),C=!0;break}if(/[A-Za-z]/.test(E[$])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(m)){u(E[$],m,f),C=!0;break}if(E[$+1]&&E[$+1].match(/\W/)){u(E[$],f.slice($+2),f),C=!0;break}else u(E[$],o.strings[E[$]]?"":!0,f)}h=f.slice(-1)[0],!C&&h!=="-"&&(e[d+1]&&!/^(-|--)[^-]/.test(e[d+1])&&!o.bools[h]&&(!n[h]||!r(h))?(u(h,e[d+1],f),d+=1):e[d+1]&&/^(true|false)$/.test(e[d+1])?(u(h,e[d+1]==="true",f),d+=1):u(h,o.strings[h]?"":!0,f))}else if((!o.unknownFn||o.unknownFn(f)!==!1)&&a._.push(o.strings._||!ar(f)?f:Number(f)),t.stopEarly){a._.push.apply(a._,e.slice(d+1));break}}return Object.keys(s).forEach(function(I){wl(a,I.split("."))||(c(a,I.split("."),s[I]),(n[I]||[]).forEach(function(A){c(a,A.split("."),s[I])}))}),t["--"]?a["--"]=l.slice():l.forEach(function(I){a._.push(I)}),a};const _s=kl(_l),P="siyuan-sisyphus",vl="siyuan",Il=`${P} — Direct command-line control for SiYuan Note
2
+ "use strict";var wl=Object.defineProperty;var _l=(e,t,o)=>t in e?wl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var ge=(e,t,o)=>_l(e,typeof t!="symbol"?t+"":t,o);const j=require("node:fs"),St=require("node:os"),B=require("node:path"),vl=require("node:readline"),Il=require("node:url");var Fo=typeof document<"u"?document.currentScript:null;function Dl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Sl(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 fr(e){return typeof e=="number"||/^0x[0-9a-f]+$/i.test(e)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function hr(e,t){return t==="constructor"&&typeof e[t]=="function"||t==="__proto__"}var Al=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(I){o.bools[I]=!0});var n={};function r(I){return n[I].some(function(D){return o.bools[D]})}Object.keys(t.alias||{}).forEach(function(I){n[I]=[].concat(t.alias[I]),n[I].forEach(function(D){n[D]=[I].concat(n[I].filter(function($){return D!==$}))})}),[].concat(t.string).filter(Boolean).forEach(function(I){o.strings[I]=!0,n[I]&&[].concat(n[I]).forEach(function(D){o.strings[D]=!0})});var s=t.default||{},a={_:[]};function i(I,D){return o.allBools&&/^--[^=]+$/.test(D)||o.strings[I]||o.bools[I]||n[I]}function c(I,D,$){for(var N=I,ve=0;ve<D.length-1;ve++){var ce=D[ve];if(hr(N,ce))return;N[ce]===void 0&&(N[ce]={}),(N[ce]===Object.prototype||N[ce]===Number.prototype||N[ce]===String.prototype)&&(N[ce]={}),N[ce]===Array.prototype&&(N[ce]=[]),N=N[ce]}var me=D[D.length-1];hr(N,me)||((N===Object.prototype||N===Number.prototype||N===String.prototype)&&(N={}),N===Array.prototype&&(N=[]),N[me]===void 0||o.bools[me]||typeof N[me]=="boolean"?N[me]=$:Array.isArray(N[me])?N[me].push($):N[me]=[N[me],$])}function u(I,D,$){if(!($&&o.unknownFn&&!i(I,$)&&o.unknownFn($)===!1)){var N=!o.strings[I]&&fr(D)?Number(D):D;c(a,I.split("."),N),(n[I]||[]).forEach(function(ve){c(a,ve.split("."),N)})}}Object.keys(o.bools).forEach(function(I){u(I,s[I]===void 0?!1:s[I])});var l=[];e.indexOf("--")!==-1&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var d=0;d<e.length;d++){var f=e[d],h,m;if(/^--.+=/.test(f)){var _=f.match(/^--([^=]+)=([\s\S]*)$/);h=_[1];var v=_[2];o.bools[h]&&(v=v!=="false"),u(h,v,f)}else if(/^--no-.+/.test(f))h=f.match(/^--no-(.+)/)[1],u(h,!1,f);else if(/^--.+/.test(f))h=f.match(/^--(.+)/)[1],m=e[d+1],m!==void 0&&!/^(-|--)[^-]/.test(m)&&!o.bools[h]&&!o.allBools&&(!n[h]||!r(h))?(u(h,m,f),d+=1):/^(true|false)$/.test(m)?(u(h,m==="true",f),d+=1):u(h,o.strings[h]?"":!0,f);else if(/^-[^-]+/.test(f)){for(var A=f.slice(1,-1).split(""),x=!1,C=0;C<A.length;C++){if(m=f.slice(C+2),m==="-"){u(A[C],m,f);continue}if(/[A-Za-z]/.test(A[C])&&m[0]==="="){u(A[C],m.slice(1),f),x=!0;break}if(/[A-Za-z]/.test(A[C])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(m)){u(A[C],m,f),x=!0;break}if(A[C+1]&&A[C+1].match(/\W/)){u(A[C],f.slice(C+2),f),x=!0;break}else u(A[C],o.strings[A[C]]?"":!0,f)}h=f.slice(-1)[0],!x&&h!=="-"&&(e[d+1]&&!/^(-|--)[^-]/.test(e[d+1])&&!o.bools[h]&&(!n[h]||!r(h))?(u(h,e[d+1],f),d+=1):e[d+1]&&/^(true|false)$/.test(e[d+1])?(u(h,e[d+1]==="true",f),d+=1):u(h,o.strings[h]?"":!0,f))}else if((!o.unknownFn||o.unknownFn(f)!==!1)&&a._.push(o.strings._||!fr(f)?f:Number(f)),t.stopEarly){a._.push.apply(a._,e.slice(d+1));break}}return Object.keys(s).forEach(function(I){Sl(a,I.split("."))||(c(a,I.split("."),s[I]),(n[I]||[]).forEach(function(D){c(a,D.split("."),s[I])}))}),t["--"]?a["--"]=l.slice():l.forEach(function(I){a._.push(I)}),a};const As=Dl(Al),E="siyuan-sisyphus",Tl="siyuan",Pl=`${E} — Direct command-line control for SiYuan Note
3
3
 
4
4
  Agent bootstrap:
5
- If you are an AI model or coding agent, run \`${P} skill install\`
5
+ If you are an AI model or coding agent, run \`${E} skill install\`
6
6
  before using this CLI for SiYuan work. The bundled skills contain the
7
7
  task-specific guidance for safe search, reading, editing, export, database,
8
8
  tag, flashcard, and system operations.
9
9
 
10
10
  Commands:
11
- ${P} <tool> <action> [--flag value ...] Execute a SiYuan operation
12
- ${P} list [tool] List tools or a tool's actions
13
- ${P} help <tool> [action] Show terminal-friendly help
14
- ${P} init Create ~/.siyuan-sisyphus/config.json
15
- ${P} config <action> ... Manage saved SiYuan profiles
16
- ${P} skill install [--target agents] Install bundled agent skills
17
- ${P} skill list List bundled agent skills
18
- ${P} --help | -h Show this help
19
- ${P} --version | -v Show version
11
+ ${E} <tool> <action> [--flag value ...] Execute a SiYuan operation
12
+ ${E} list [tool] List tools or a tool's actions
13
+ ${E} help <tool> [action] Show terminal-friendly help
14
+ ${E} init Create ~/.siyuan-sisyphus/config.json
15
+ ${E} config <action> ... Manage saved SiYuan profiles
16
+ ${E} skill install [--target agents] Install bundled agent skills
17
+ ${E} skill list List bundled agent skills
18
+ ${E} --help | -h Show this help
19
+ ${E} --version | -v Show version
20
20
 
21
21
  Tools:
22
22
  fs, notebook, document, block, av, file, search, tag, system, flashcard, mascot
23
23
 
24
24
  Alias:
25
- ${vl} Same CLI, shorter command name
25
+ ${Tl} 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
@@ -38,19 +38,19 @@ Paging:
38
38
  --page, --page-size, and --json explicitly.
39
39
 
40
40
  Examples:
41
- ${P} notebook list
42
- ${P} --profile work notebook list
43
- ${P} config set work --url http://127.0.0.1:6807 --token xxx
44
- ${P} config use work
45
- ${P} skill install
46
- ${P} skill install --target claude
47
- ${P} skill install --target .codex --local
48
- ${P} help document create
49
- ${P} fs read --path "/Inbox/Test"
50
- ${P} document create --notebook <id> --path "/Inbox/Test" --markdown "# Hello"
51
- ${P} block append --parent-id <id> --data-type markdown --data "- item"
52
- ${P} search fulltext --query "keyword" --page-size 10
53
- ${P} document list-tree --notebook <id> --json | jq '.data[].title'
41
+ ${E} notebook list
42
+ ${E} --profile work notebook list
43
+ ${E} config set work --url http://127.0.0.1:6807 --token xxx
44
+ ${E} config use work
45
+ ${E} skill install
46
+ ${E} skill install --target claude
47
+ ${E} skill install --target .codex --local
48
+ ${E} help document create
49
+ ${E} fs read --path "/Inbox/Test"
50
+ ${E} document create --notebook <id> --path "/Inbox/Test" --markdown "# Hello"
51
+ ${E} block append --parent-id <id> --data-type markdown --data "- item"
52
+ ${E} search fulltext --query "keyword" --page-size 10
53
+ ${E} document list-tree --notebook <id> --json | jq '.data[].title'
54
54
 
55
55
  Config precedence:
56
56
  --url/--token > --profile > environment variables > active config profile > defaults
@@ -67,71 +67,71 @@ Flag naming:
67
67
  fs mv /Notebook/Old /Notebook/New.
68
68
  Boolean flags: use --flag, --flag=false, or --no-flag.
69
69
  For complex object/array values, use --<key>-json '<json>'.
70
- `,vs=["json","debug","help","version"],Is=["config","profile","url","token"];function Dl(e){const t=_s(e,{boolean:vs,string:Is,alias:{h:"help",v:"version"},stopEarly:!1});if(t.help)return No("show-help");if(t.version)return No("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 "${P} config list", "${P} config get [name]", "${P} config set <name> --url <url>", or "${P} 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 "${P} skill list", "${P} skill read [name]", "${P} skill install", or "${P} skill uninstall".`);return{command:"skill",skillAction:a,skillName: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,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 No("show-help");const r=typeof o[1]=="string"?o[1]:void 0;if(!r)throw new Error(`Missing action for tool "${n}". Try "${P} help ${n}".`);const s=Sl(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 No(e){return{command:e,rest:[],json:!1,debug:!1}}function Sl(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(Is.includes(i)){s===-1&&n++;continue}vs.includes(i)||i==="h"||i==="v"||t.push(r)}return t}function Al(){return Il}const We="default",un="http://127.0.0.1:6806";function ln(){return F.join(Dt.homedir(),".siyuan-sisyphus","config.json")}function Tl(){return F.join(Dt.homedir(),".siyuan-mcp","config.json")}function Ds(e){return e??ln()}function ft(e){const t=Ol(e);if(!j.existsSync(t))return{};try{const o=j.readFileSync(t,"utf8"),n=JSON.parse(o);if(!n||typeof n!="object")return{};const r=n,s=xl(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 je(e){const t=Nl(e.profiles);if(Object.keys(t).length>0){const r=typeof e.currentProfile=="string"&&e.currentProfile?e.currentProfile:cr(t);return{currentProfile:t[r]?r:cr(t),profiles:t}}const o=typeof e.apiUrl=="string"&&e.apiUrl?e.apiUrl:un,n=typeof e.token=="string"?e.token:"";return{currentProfile:We,profiles:{[We]:{apiUrl:o,token:n}}}}function Pl(e,t={}){const o=je(e),n=t.profile||o.currentProfile||We,r=o.profiles[n];if(t.profile&&!r)throw new Error(`Unknown profile "${t.profile}". Available profiles: ${Object.keys(o.profiles).join(", ")||We}.`);const s=r??o.profiles[o.currentProfile]??o.profiles[We]??{},a=t.cliUrl||process.env.SIYUAN_API_URL||s.apiUrl||un,i=t.cliToken||process.env.SIYUAN_TOKEN||s.token||"";return{apiUrl:a,token:i,profileName:n}}function El(e){process.env.SIYUAN_API_URL=e.apiUrl,e.token?process.env.SIYUAN_TOKEN=e.token:delete process.env.SIYUAN_TOKEN}function dn(e,t){const o=Ds(t),n=F.dirname(o);return j.existsSync(n)||j.mkdirSync(n,{recursive:!0,mode:448}),j.writeFileSync(o,JSON.stringify(e,null,2)+`
71
- `,{mode:384}),o}function Ss(e,t,o,n={}){const r=je(e),s=r.profiles[t]??{},a={currentProfile:n.makeCurrent?t:r.currentProfile,profiles:{...r.profiles,[t]:{apiUrl:o.apiUrl??s.apiUrl??un,token:o.token??s.token??""}}};return a.profiles[a.currentProfile]||(a.currentProfile=t),a}function Cl(e,t){const o=je(e);if(!o.profiles[t])throw new Error(`Unknown profile "${t}".`);return{...o,currentProfile:t}}function Ol(e){if(e)return e;const t=ln();if(j.existsSync(t))return t;const o=Tl();return j.existsSync(o)?o:t}function xl(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 Nl(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 cr(e){return Object.keys(e)[0]??We}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ts(e){return As(e)?typeof e.tool=="string"&&(Array.isArray(e.commonActions)||Array.isArray(e.advancedActions))&&e.action===void 0:!1}function Ps(e){return As(e)?typeof e.tool=="string"&&typeof e.action=="string"&&(e.example!==void 0||Array.isArray(e.examples)||Array.isArray(e.shapes)):!1}const $l=new Set(["action","as","only","optional","required","requires","mode"]);function tt(e,t){return t==="cli"?`--${Et(e)}`:e}function Es(e,t,o={},n){{const r=Object.entries(o).filter(([,s])=>s!==void 0).map(([s,a])=>ql(s,a));return[P,e,Et(t),...r].join(" ").trim()}}function K(e,t){if(!e)return e;let o=e;return o=o.replace(/siyuan:\/\/help\/action\/([a-z_]+)\/([a-z_]+)/g,(n,r,s)=>`${P} ${r} ${Et(s)}`),o=o.replace(/siyuan:\/\/help\/tool-overview/g,`${P} list`),o=o.replace(/siyuan:\/\/help\/examples/g,`${P} help <tool> <action>`),o=o.replace(/siyuan:\/\/help\/ai-layout-guide/g,`${P} help document create`),o=o.replace(/\b([a-z]+)\(action=["”“]([a-z_]+)["”“](?:,\s*([^)]*))?\)/g,(n,r,s,a)=>{const i=jl(a);if(s==="help"){const c=typeof i.topic=="string"?Os(i.topic).trim():"";return c?`${P} help ${r} ${Et(c)}`:`${P} help ${r}`}return Es(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=>ur(n,"+")),o=o.replace(new RegExp("(?<![\\/\\-=])\\b([A-Za-z][A-Za-z0-9_]*)(\\s*\\/\\s*[A-Za-z][A-Za-z0-9_]*)+\\b","g"),n=>ur(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=>tt(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=>tt(n,"cli")).join(", "):o==="action only"?"command only":o}function Cs(e,t){if(!ve(e))return e;if(Ps(e)){const o={...e};return typeof o.hint=="string"&&(o.hint=K(o.hint)),Array.isArray(o.shapes)&&(o.shapes=o.shapes.map(n=>typeof n=="string"?K(n):n)),o.requiredFields=Fl(o.requiredFields,t),o.example=pn(o.tool,o.action,o.example),Array.isArray(o.examples)&&(o.examples=o.examples.map(n=>zl(o.tool,o.action,n))),Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?K(n):n)),typeof o.fullDocResource=="string"&&(o.fullDocResource=`${P} help ${o.tool} ${Et(String(o.action))}`),o}if(Ts(e)){const o={...e};return Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?K(n):n)),ve(o.actionSummaries)&&(o.actionSummaries=Object.fromEntries(Object.entries(o.actionSummaries).map(([n,r])=>[n,typeof r=="string"?K(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:K(r.hint)}]))),typeof o.detailsHint=="string"&&(o.detailsHint=K(o.detailsHint)),Array.isArray(o.helpResources)&&(o.helpResources=o.helpResources.map(n=>typeof n=="string"?K(n):n)),o}if(ve(e.error)){const o=e.error;return{...e,error:{...o,...typeof o.hint=="string"?{hint:K(o.hint)}:{},...typeof o.details=="string"?{details:K(o.details)}:{}}}}return Rl(e)}function Rl(e,t){const o={...e};for(const n of["hint","detailsHint"])typeof o[n]=="string"&&(o[n]=K(o[n]));for(const n of["guidance","hints"])Array.isArray(o[n])&&(o[n]=o[n].map(r=>typeof r=="string"?K(r):r));return o}function pn(e,t,o,n){if(typeof e!="string"||typeof t!="string")return o;if(Array.isArray(o))return o.map(s=>pn(e,t,s));if(!ve(o))return typeof o=="string"?K(o):o;const r={...o};return delete r.action,Es(e,t,r)}function zl(e,t,o,n){if(!ve(o))return o;const r={...o};return typeof r.description=="string"&&(r.description=K(r.description)),r.mcp=pn(e,t,r.mcp),r}function Fl(e,t){return Array.isArray(e)&&e.every(o=>typeof o=="string")?e.map(o=>tt(o,t)):Array.isArray(e)?e.map(o=>Array.isArray(o)?o.map(n=>typeof n=="string"?tt(n,t):n):o):e}function ur(e,t){const o=t==="+"?/\s*\+\s*/:/\s*\/\s*/,n=e.split(o);return n.some(r=>!Bl(r))?e:n.map(r=>tt(r,"cli")).join(` ${t} `)}function Bl(e){const t=e.trim();return!t||$l.has(t.toLowerCase())?!1:/^[A-Za-z][A-Za-z0-9_]*$/.test(t)}function jl(e){if(!e)return{};const t={};for(const o of Ul(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]=Os(a))}return t}function Ul(e,t){const o=[];let n="",r=!1,s=!1,a=!1,i=0,c=0,u=0;for(const l of e){if(l==="'"&&!s&&!a){r=!r,n+=l;continue}if(l==='"'&&!r&&!a){s=!s,n+=l;continue}if((l==="“"||l==="”")&&!r&&!s){a=!a,n+=l;continue}if(!r&&!s&&!a&&(l==="["&&i++,l==="]"&&(i=Math.max(0,i-1)),l==="{"&&c++,l==="}"&&(c=Math.max(0,c-1)),l==="("&&u++,l===")"&&(u=Math.max(0,u-1)),l===t&&i===0&&c===0&&u===0)){o.push(n),n="";continue}n+=l}return n&&o.push(n),o}function ql(e,t){const o=tt(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} ${Ml(String(t))}`}function Ml(e){return e==="..."||/^<[^>]+>$/.test(e)||/^(true|false|null|-?\d+(\.\d+)?)$/i.test(e)||/^[A-Za-z0-9_./:-]+$/.test(e)?e:JSON.stringify(e)}function Os(e){return e.replace(/^["“”']/,"").replace(/["“”']$/,"")}function Et(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 W={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m",bold:"\x1B[1m"},xs=["id","name","title","path","hpath","notebook","box","rootID","blockID","docID","avID","deckID","cardID","status","version","count","total","page","pageCount"],Ll=new Map(xs.map((e,t)=>[e,t]));function Zl(e){return!!e.isTTY}function we(e,t,o){return Zl(e)?`${t}${o}${W.reset}`:o}function Ns(e){switch(e){case"success":return W.green+W.bold;case"warning":return W.yellow+W.bold;case"error":return W.red+W.bold;case"muted":return W.dim;case"info":default:return W.cyan+W.bold}}function J(e,t=""){e.write(t.endsWith(`
70
+ `,Ts=["json","debug","help","version"],Ps=["config","profile","url","token"];function El(e){const t=As(e,{boolean:Ts,string:Ps,alias:{h:"help",v:"version"},stopEarly:!1});if(t.help)return Bo("show-help");if(t.version)return Bo("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 "${E} config list", "${E} config get [name]", "${E} config set <name> --url <url>", or "${E} 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 "${E} skill list", "${E} skill read [name]", "${E} skill install", or "${E} skill uninstall".`);return{command:"skill",skillAction:a,skillName: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,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 Bo("show-help");const r=typeof o[1]=="string"?o[1]:void 0;if(!r)throw new Error(`Missing action for tool "${n}". Try "${E} help ${n}".`);const s=Cl(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 Bo(e){return{command:e,rest:[],json:!1,debug:!1}}function Cl(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(Ps.includes(i)){s===-1&&n++;continue}Ts.includes(i)||i==="h"||i==="v"||t.push(r)}return t}function Ol(){return Pl}const Qe="default",mn="http://127.0.0.1:6806";function gn(){return B.join(St.homedir(),".siyuan-sisyphus","config.json")}function xl(){return B.join(St.homedir(),".siyuan-mcp","config.json")}function Es(e){return e??gn()}function ht(e){const t=zl(e);if(!j.existsSync(t))return{};try{const o=j.readFileSync(t,"utf8"),n=JSON.parse(o);if(!n||typeof n!="object")return{};const r=n,s=Fl(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 qe(e){const t=Bl(e.profiles);if(Object.keys(t).length>0){const r=typeof e.currentProfile=="string"&&e.currentProfile?e.currentProfile:mr(t);return{currentProfile:t[r]?r:mr(t),profiles:t}}const o=typeof e.apiUrl=="string"&&e.apiUrl?e.apiUrl:mn,n=typeof e.token=="string"?e.token:"";return{currentProfile:Qe,profiles:{[Qe]:{apiUrl:o,token:n}}}}function Nl(e,t={}){const o=qe(e),n=t.profile||o.currentProfile||Qe,r=o.profiles[n];if(t.profile&&!r)throw new Error(`Unknown profile "${t.profile}". Available profiles: ${Object.keys(o.profiles).join(", ")||Qe}.`);const s=r??o.profiles[o.currentProfile]??o.profiles[Qe]??{},a=t.cliUrl||process.env.SIYUAN_API_URL||s.apiUrl||mn,i=t.cliToken||process.env.SIYUAN_TOKEN||s.token||"";return{apiUrl:a,token:i,profileName:n}}function Rl(e){process.env.SIYUAN_API_URL=e.apiUrl,e.token?process.env.SIYUAN_TOKEN=e.token:delete process.env.SIYUAN_TOKEN}function yn(e,t){const o=Es(t),n=B.dirname(o);return j.existsSync(n)||j.mkdirSync(n,{recursive:!0,mode:448}),j.writeFileSync(o,JSON.stringify(e,null,2)+`
71
+ `,{mode:384}),o}function Cs(e,t,o,n={}){const r=qe(e),s=r.profiles[t]??{},a={currentProfile:n.makeCurrent?t:r.currentProfile,profiles:{...r.profiles,[t]:{apiUrl:o.apiUrl??s.apiUrl??mn,token:o.token??s.token??""}}};return a.profiles[a.currentProfile]||(a.currentProfile=t),a}function $l(e,t){const o=qe(e);if(!o.profiles[t])throw new Error(`Unknown profile "${t}".`);return{...o,currentProfile:t}}function zl(e){if(e)return e;const t=gn();if(j.existsSync(t))return t;const o=xl();return j.existsSync(o)?o:t}function Fl(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 Bl(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 mr(e){return Object.keys(e)[0]??Qe}function Os(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xs(e){return Os(e)?typeof e.tool=="string"&&(Array.isArray(e.commonActions)||Array.isArray(e.advancedActions))&&e.action===void 0:!1}function Ns(e){return Os(e)?typeof e.tool=="string"&&typeof e.action=="string"&&(e.example!==void 0||Array.isArray(e.examples)||Array.isArray(e.shapes)):!1}const jl=new Set(["action","as","only","optional","required","requires","mode"]);function nt(e,t){return t==="cli"?`--${Ct(e)}`:e}function Rs(e,t,o={},n){{const r=Object.entries(o).filter(([,s])=>s!==void 0).map(([s,a])=>Vl(s,a));return[E,e,Ct(t),...r].join(" ").trim()}}function Q(e,t){if(!e)return e;let o=e;return o=o.replace(/siyuan:\/\/help\/action\/([a-z_]+)\/([a-z_]+)/g,(n,r,s)=>`${E} ${r} ${Ct(s)}`),o=o.replace(/siyuan:\/\/help\/tool-overview/g,`${E} list`),o=o.replace(/siyuan:\/\/help\/examples/g,`${E} help <tool> <action>`),o=o.replace(/siyuan:\/\/help\/ai-layout-guide/g,`${E} help document create`),o=o.replace(/\b([a-z]+)\(action=["”“]([a-z_]+)["”“](?:,\s*([^)]*))?\)/g,(n,r,s,a)=>{const i=Zl(a);if(s==="help"){const c=typeof i.topic=="string"?zs(i.topic).trim():"";return c?`${E} help ${r} ${Ct(c)}`:`${E} help ${r}`}return Rs(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=>gr(n,"+")),o=o.replace(new RegExp("(?<![\\/\\-=])\\b([A-Za-z][A-Za-z0-9_]*)(\\s*\\/\\s*[A-Za-z][A-Za-z0-9_]*)+\\b","g"),n=>gr(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=>nt(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=>nt(n,"cli")).join(", "):o==="action only"?"command only":o}function $s(e,t){if(!Ie(e))return e;if(Ns(e)){const o={...e};return typeof o.hint=="string"&&(o.hint=Q(o.hint)),Array.isArray(o.shapes)&&(o.shapes=o.shapes.map(n=>typeof n=="string"?Q(n):n)),o.requiredFields=Ml(o.requiredFields,t),o.example=bn(o.tool,o.action,o.example),Array.isArray(o.examples)&&(o.examples=o.examples.map(n=>ql(o.tool,o.action,n))),Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?Q(n):n)),typeof o.fullDocResource=="string"&&(o.fullDocResource=`${E} help ${o.tool} ${Ct(String(o.action))}`),o}if(xs(e)){const o={...e};return Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?Q(n):n)),Ie(o.actionSummaries)&&(o.actionSummaries=Object.fromEntries(Object.entries(o.actionSummaries).map(([n,r])=>[n,typeof r=="string"?Q(r):r]))),Ie(o.actions)&&(o.actions=Object.fromEntries(Object.entries(o.actions).map(([n,r])=>!Ie(r)||typeof r.hint!="string"?[n,r]:[n,{...r,hint:Q(r.hint)}]))),typeof o.detailsHint=="string"&&(o.detailsHint=Q(o.detailsHint)),Array.isArray(o.helpResources)&&(o.helpResources=o.helpResources.map(n=>typeof n=="string"?Q(n):n)),o}if(Ie(e.error)){const o=e.error;return{...e,error:{...o,...typeof o.hint=="string"?{hint:Q(o.hint)}:{},...typeof o.details=="string"?{details:Q(o.details)}:{}}}}return Ul(e)}function Ul(e,t){const o={...e};for(const n of["hint","detailsHint"])typeof o[n]=="string"&&(o[n]=Q(o[n]));for(const n of["guidance","hints"])Array.isArray(o[n])&&(o[n]=o[n].map(r=>typeof r=="string"?Q(r):r));return o}function bn(e,t,o,n){if(typeof e!="string"||typeof t!="string")return o;if(Array.isArray(o))return o.map(s=>bn(e,t,s));if(!Ie(o))return typeof o=="string"?Q(o):o;const r={...o};return delete r.action,Rs(e,t,r)}function ql(e,t,o,n){if(!Ie(o))return o;const r={...o};return typeof r.description=="string"&&(r.description=Q(r.description)),r.mcp=bn(e,t,r.mcp),r}function Ml(e,t){return Array.isArray(e)&&e.every(o=>typeof o=="string")?e.map(o=>nt(o,t)):Array.isArray(e)?e.map(o=>Array.isArray(o)?o.map(n=>typeof n=="string"?nt(n,t):n):o):e}function gr(e,t){const o=t==="+"?/\s*\+\s*/:/\s*\/\s*/,n=e.split(o);return n.some(r=>!Ll(r))?e:n.map(r=>nt(r,"cli")).join(` ${t} `)}function Ll(e){const t=e.trim();return!t||jl.has(t.toLowerCase())?!1:/^[A-Za-z][A-Za-z0-9_]*$/.test(t)}function Zl(e){if(!e)return{};const t={};for(const o of Hl(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]=zs(a))}return t}function Hl(e,t){const o=[];let n="",r=!1,s=!1,a=!1,i=0,c=0,u=0;for(const l of e){if(l==="'"&&!s&&!a){r=!r,n+=l;continue}if(l==='"'&&!r&&!a){s=!s,n+=l;continue}if((l==="“"||l==="”")&&!r&&!s){a=!a,n+=l;continue}if(!r&&!s&&!a&&(l==="["&&i++,l==="]"&&(i=Math.max(0,i-1)),l==="{"&&c++,l==="}"&&(c=Math.max(0,c-1)),l==="("&&u++,l===")"&&(u=Math.max(0,u-1)),l===t&&i===0&&c===0&&u===0)){o.push(n),n="";continue}n+=l}return n&&o.push(n),o}function Vl(e,t){const o=nt(e,"cli");return Array.isArray(t)||Ie(t)?`${o}-json '${JSON.stringify(t)}'`:typeof t=="boolean"?`${o} ${t?"true":"false"}`:typeof t=="number"?`${o} ${t}`:`${o} ${Yl(String(t))}`}function Yl(e){return e==="..."||/^<[^>]+>$/.test(e)||/^(true|false|null|-?\d+(\.\d+)?)$/i.test(e)||/^[A-Za-z0-9_./:-]+$/.test(e)?e:JSON.stringify(e)}function zs(e){return e.replace(/^["“”']/,"").replace(/["“”']$/,"")}function Ct(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const W={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m",bold:"\x1B[1m"},Fs=["id","name","title","path","hpath","notebook","box","rootID","blockID","docID","avID","deckID","cardID","status","version","count","total","page","pageCount"],Gl=new Map(Fs.map((e,t)=>[e,t]));function Jl(e){return!!e.isTTY}function _e(e,t,o){return Jl(e)?`${t}${o}${W.reset}`:o}function Bs(e){switch(e){case"success":return W.green+W.bold;case"warning":return W.yellow+W.bold;case"error":return W.red+W.bold;case"muted":return W.dim;case"info":default:return W.cyan+W.bold}}function J(e,t=""){e.write(t.endsWith(`
72
72
  `)?t:`${t}
73
- `)}function Te(e,t=process.stdout){J(t,we(t,W.bold,e))}function ee(e,t,o=process.stdout){const n=e==="success"?"✓":e==="warning"?"!":e==="error"?"✗":"•";J(o,we(o,Ns(e),`${n} ${t}`))}function lr(e,t=process.stdout){J(t,we(t,W.dim,e))}function G(e,t=process.stdout){J(t),J(t,we(t,W.cyan+W.bold,e))}function ie(e,t=process.stdout,o="info"){for(const n of e)J(t,`${we(t,Ns(o)," •")} ${n}`)}function fe(e,t=process.stdout){if(e.length===0)return;const o=e.map(r=>so(r.key)),n=Math.max(...o.map(r=>r.length));for(let r=0;r<e.length;r++){const s=o[r].padEnd(n);J(t,` ${we(t,W.bold,`${s}:`)} ${ao(e[r].value)}`)}}function ne(e,t,o=process.stdout){J(o,`${we(o,W.dim+W.bold,`${e}:`)} ${t}`)}function Se(e,t={}){const o=process.stderr,n=K(e instanceof Error?e.message:String(e));ee("error",n,o),t.exitHint&&ne("Hint",K(t.exitHint),o),t.debug&&e instanceof Error&&e.stack&&J(o,e.stack)}function Ct(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(`
73
+ `)}function Pe(e,t=process.stdout){J(t,_e(t,W.bold,e))}function ee(e,t,o=process.stdout){const n=e==="success"?"✓":e==="warning"?"!":e==="error"?"✗":"•";J(o,_e(o,Bs(e),`${n} ${t}`))}function yr(e,t=process.stdout){J(t,_e(t,W.dim,e))}function G(e,t=process.stdout){J(t),J(t,_e(t,W.cyan+W.bold,e))}function ie(e,t=process.stdout,o="info"){for(const n of e)J(t,`${_e(t,Bs(o)," •")} ${n}`)}function he(e,t=process.stdout){if(e.length===0)return;const o=e.map(r=>uo(r.key)),n=Math.max(...o.map(r=>r.length));for(let r=0;r<e.length;r++){const s=o[r].padEnd(n);J(t,` ${_e(t,W.bold,`${s}:`)} ${lo(e[r].value)}`)}}function ne(e,t,o=process.stdout){J(o,`${_e(o,W.dim+W.bold,`${e}:`)} ${t}`)}function Ae(e,t={}){const o=process.stderr,n=Q(e instanceof Error?e.message:String(e));ee("error",n,o),t.exitHint&&ne("Hint",Q(t.exitHint),o),t.debug&&e instanceof Error&&e.stack&&J(o,e.stack)}function Ot(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(`
74
74
  `)||process.stdout.write(`
75
- `),e.isError?1:0}return n=Cs(n,"cli"),t.json?Hl(n,e.isError):e.isError?(Vl(n),1):(Yl(n),0)}function dr(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=Cs(o,"cli"),!be(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 Hl(e,t){return process.stdout.write(JSON.stringify(e)+`
76
- `),t?1:0}function Vl(e){const t=process.stderr;if(be(e)&&be(e.error)){const o=e.error,n=typeof o.type=="string"?o.type:"error",r=typeof o.message=="string"?o.message:"Unknown error";if(ee("error",`[${n}] ${r}`,t),Array.isArray(o.fields)){const s=o.fields.filter(be).map(a=>{const i=typeof a.path=="string"&&a.path?a.path:"(field)",c=typeof a.message=="string"?a.message:"Invalid value";return`${we(t,W.yellow+W.bold,i)} — ${c}`});s.length>0&&(G("Fields",t),ie(s,t,"warning"))}typeof o.hint=="string"&&o.hint&&(G("Hint",t),J(t,` ${o.hint}`)),typeof o.details=="string"&&o.details&&(G("Details",t),J(t,_o(o.details,2)));return}ee("error",`Error: ${Ue(e)}`,t)}function Yl(e){const t=process.stdout;if(typeof e=="string"){t.write(e),e.endsWith(`
75
+ `),e.isError?1:0}return n=$s(n,"cli"),t.json?Wl(n,e.isError):e.isError?(Kl(n),1):(Ql(n),0)}function br(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=$s(o,"cli"),!we(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 Wl(e,t){return process.stdout.write(JSON.stringify(e)+`
76
+ `),t?1:0}function Kl(e){const t=process.stderr;if(we(e)&&we(e.error)){const o=e.error,n=typeof o.type=="string"?o.type:"error",r=typeof o.message=="string"?o.message:"Unknown error";if(ee("error",`[${n}] ${r}`,t),Array.isArray(o.fields)){const s=o.fields.filter(we).map(a=>{const i=typeof a.path=="string"&&a.path?a.path:"(field)",c=typeof a.message=="string"?a.message:"Invalid value";return`${_e(t,W.yellow+W.bold,i)} — ${c}`});s.length>0&&(G("Fields",t),ie(s,t,"warning"))}typeof o.hint=="string"&&o.hint&&(G("Hint",t),J(t,` ${o.hint}`)),typeof o.details=="string"&&o.details&&(G("Details",t),J(t,So(o.details,2)));return}ee("error",`Error: ${Me(e)}`,t)}function Ql(e){const t=process.stdout;if(typeof e=="string"){t.write(e),e.endsWith(`
77
77
  `)||t.write(`
78
- `);return}if(e==null){ee("success","Done",t);return}if(Array.isArray(e)){ee("info",`${e.length} item${e.length===1?"":"s"}`,t),fn(e,"Items",t);return}if(!be(e)){J(t,Ue(e));return}const o=e;if(Ts(o)){Kl(o,t);return}if(Ps(o)){Ql(o,t);return}const n=o;if(Array.isArray(n.data)&&typeof n.total=="number"&&typeof n.page=="number"){Gl(o,t);return}Jl(o,t)}function Gl(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;ee("success",`${o.length} of ${n} items · page ${r}/${s}`,t),fe([...a!==void 0?[{key:"pageSize",value:a}]:[],...typeof e.hasNextPage=="boolean"?[{key:"hasNextPage",value:e.hasNextPage}]:[]],t),fn(o,"Items",t,{maxItems:o.length}),e.hasNextPage&&(G("Next Step",t),ne("Tip","More pages are available. In a TTY, press Enter/n for next page, or re-run with `--page <n>`.",t))}function Jl(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?ee("success",n??"Success",t):n&&ee("info",n,t);const s=$s(r,new Set(n?["message"]:[]));s.length>0&&fe(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&&J(t,Ue(e));return}for(const[c,u]of i)Wl(c,u,t)}function Wl(e,t,o){if(t!==void 0){if(Array.isArray(t)){fn(t,so(e),o);return}if(G(so(e),o),be(t)){const n=ed(t);if(n.length>0&&n.length===Object.keys(t).length){fe(n,o);return}J(o,_o(Ue(t),2));return}J(o,` ${ao(t)}`)}}function fn(e,t,o,n={}){if(e.length===0){G(t,o),lr(" No items.",o);return}G(t,o);const r=n.maxItems??10,s=e.slice(0,r);for(const a of s){const i=td(a);if(i){J(o,` • ${i}`);continue}J(o,_o(Ue(a),2))}e.length>s.length&&lr(` … ${e.length-s.length} more item(s) not shown. Use --json for full output.`,o)}function Kl(e,t){const o=typeof e.tool=="string"?e.tool:"tool";Te(`${o} tool`,t);const n=Ve(e.guidance);n.length>0&&(G("Guidance",t),ie(n,t)),pr("Common Actions",Ve(e.commonActions),e.actionSummaries,t),pr("Advanced Actions",Ve(e.advancedActions),e.actionSummaries,t);const r=Ve(e.requiresConfirmation);r.length>0&&(G("Confirmation",t),ie(r.map(s=>`${s} requires explicit confirmation.`),t,"warning")),typeof e.detailsHint=="string"&&e.detailsHint&&(G("Next Step",t),ne("Tip",e.detailsHint,t))}function Ql(e,t){const o=typeof e.tool=="string"?e.tool:"tool",n=typeof e.action=="string"?e.action:"help";Te(`${o} ${n}`,t),typeof e.hint=="string"&&e.hint&&ee("info",e.hint,t);const r=Ve(e.shapes);r.length>0&&(G("Accepted Shapes",t),ie(r,t));const s=od(e.requiredFields);s.length>0&&(G("Required Fields",t),ie(s,t));const a=Array.isArray(e.examples)?e.examples:[];a.length>0?(G("Examples",t),Xl(a,t)):e.example!==void 0&&(G("Example",t),Zo(e.example,t));const i=Ve(e.guidance);i.length>0&&(G("Guidance",t),ie(i,t)),e.requiresConfirmation===!0&&(G("Safety",t),ie(["This action requires explicit confirmation."],t,"warning")),typeof e.fullDocResource=="string"&&e.fullDocResource&&(G("Reference",t),ne("Resource",e.fullDocResource,t))}function pr(e,t,o,n){if(t.length===0)return;const r=be(o)?o:{};G(e,n),ie(t.map(s=>{const a=typeof r[s]=="string"?String(r[s]):"";return a?`${s} — ${a}`:s}),n)}function Zo(e,t){if(typeof e=="string"){J(t,` ${e}`);return}if(Array.isArray(e)&&e.every(o=>typeof o=="string")){ie(e,t);return}J(t,_o(Ue(e),2))}function Xl(e,t){for(const o of e){if(!be(o)){Zo(o,t);continue}const n=typeof o.title=="string"?o.title:"Example";J(t,` ${we(t,W.bold,n)}`),typeof o.description=="string"&&o.description&&J(t,` ${o.description}`);const r=o.mcp??o.command??o.example;r!==void 0&&Zo(r,t)}}function $s(e,t=new Set){return e.filter(([n,r])=>!t.has(n)&&hn(r)).map(([n,r])=>({key:n,value:r})).sort((n,r)=>fr(n.key)-fr(r.key)||n.key.localeCompare(r.key)).slice(0,8)}function fr(e){return Ll.get(e)??xs.length+100}function ed(e){return Object.entries(e).filter(([,t])=>hn(t)).map(([t,o])=>({key:t,value:o}))}function td(e){if(hn(e))return ao(e);if(!be(e))return null;const t=$s(Object.entries(e));return t.length===0?null:t.slice(0,4).map(o=>`${so(o.key)}: ${ao(o.value)}`).join(" · ")}function od(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 Ve(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ue(e){return JSON.stringify(e,null,2)}function so(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 ao(e){return typeof e=="string"?nd(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":Ue(e)}function nd(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}…`}function _o(e,t){const o=" ".repeat(t);return e.split(`
78
+ `);return}if(e==null){ee("success","Done",t);return}if(Array.isArray(e)){ee("info",`${e.length} item${e.length===1?"":"s"}`,t),kn(e,"Items",t);return}if(!we(e)){J(t,Me(e));return}const o=e;if(xs(o)){od(o,t);return}if(Ns(o)){nd(o,t);return}const n=o;if(Array.isArray(n.data)&&typeof n.total=="number"&&typeof n.page=="number"){Xl(o,t);return}ed(o,t)}function Xl(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;ee("success",`${o.length} of ${n} items · page ${r}/${s}`,t),he([...a!==void 0?[{key:"pageSize",value:a}]:[],...typeof e.hasNextPage=="boolean"?[{key:"hasNextPage",value:e.hasNextPage}]:[]],t),kn(o,"Items",t,{maxItems:o.length}),e.hasNextPage&&(G("Next Step",t),ne("Tip","More pages are available. In a TTY, press Enter/n for next page, or re-run with `--page <n>`.",t))}function ed(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?ee("success",n??"Success",t):n&&ee("info",n,t);const s=js(r,new Set(n?["message"]:[]));s.length>0&&he(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&&J(t,Me(e));return}for(const[c,u]of i)td(c,u,t)}function td(e,t,o){if(t!==void 0){if(Array.isArray(t)){kn(t,uo(e),o);return}if(G(uo(e),o),we(t)){const n=sd(t);if(n.length>0&&n.length===Object.keys(t).length){he(n,o);return}J(o,So(Me(t),2));return}J(o,` ${lo(t)}`)}}function kn(e,t,o,n={}){if(e.length===0){G(t,o),yr(" No items.",o);return}G(t,o);const r=n.maxItems??10,s=e.slice(0,r);for(const a of s){const i=ad(a);if(i){J(o,` • ${i}`);continue}J(o,So(Me(a),2))}e.length>s.length&&yr(` … ${e.length-s.length} more item(s) not shown. Use --json for full output.`,o)}function od(e,t){const o=typeof e.tool=="string"?e.tool:"tool";Pe(`${o} tool`,t);const n=Ge(e.guidance);n.length>0&&(G("Guidance",t),ie(n,t)),kr("Common Actions",Ge(e.commonActions),e.actionSummaries,t),kr("Advanced Actions",Ge(e.advancedActions),e.actionSummaries,t);const r=Ge(e.requiresConfirmation);r.length>0&&(G("Confirmation",t),ie(r.map(s=>`${s} requires explicit confirmation.`),t,"warning")),typeof e.detailsHint=="string"&&e.detailsHint&&(G("Next Step",t),ne("Tip",e.detailsHint,t))}function nd(e,t){const o=typeof e.tool=="string"?e.tool:"tool",n=typeof e.action=="string"?e.action:"help";Pe(`${o} ${n}`,t),typeof e.hint=="string"&&e.hint&&ee("info",e.hint,t);const r=Ge(e.shapes);r.length>0&&(G("Accepted Shapes",t),ie(r,t));const s=id(e.requiredFields);s.length>0&&(G("Required Fields",t),ie(s,t));const a=Array.isArray(e.examples)?e.examples:[];a.length>0?(G("Examples",t),rd(a,t)):e.example!==void 0&&(G("Example",t),Wo(e.example,t));const i=Ge(e.guidance);i.length>0&&(G("Guidance",t),ie(i,t)),e.requiresConfirmation===!0&&(G("Safety",t),ie(["This action requires explicit confirmation."],t,"warning")),typeof e.fullDocResource=="string"&&e.fullDocResource&&(G("Reference",t),ne("Resource",e.fullDocResource,t))}function kr(e,t,o,n){if(t.length===0)return;const r=we(o)?o:{};G(e,n),ie(t.map(s=>{const a=typeof r[s]=="string"?String(r[s]):"";return a?`${s} — ${a}`:s}),n)}function Wo(e,t){if(typeof e=="string"){J(t,` ${e}`);return}if(Array.isArray(e)&&e.every(o=>typeof o=="string")){ie(e,t);return}J(t,So(Me(e),2))}function rd(e,t){for(const o of e){if(!we(o)){Wo(o,t);continue}const n=typeof o.title=="string"?o.title:"Example";J(t,` ${_e(t,W.bold,n)}`),typeof o.description=="string"&&o.description&&J(t,` ${o.description}`);const r=o.mcp??o.command??o.example;r!==void 0&&Wo(r,t)}}function js(e,t=new Set){return e.filter(([n,r])=>!t.has(n)&&wn(r)).map(([n,r])=>({key:n,value:r})).sort((n,r)=>wr(n.key)-wr(r.key)||n.key.localeCompare(r.key)).slice(0,8)}function wr(e){return Gl.get(e)??Fs.length+100}function sd(e){return Object.entries(e).filter(([,t])=>wn(t)).map(([t,o])=>({key:t,value:o}))}function ad(e){if(wn(e))return lo(e);if(!we(e))return null;const t=js(Object.entries(e));return t.length===0?null:t.slice(0,4).map(o=>`${uo(o.key)}: ${lo(o.value)}`).join(" · ")}function id(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 Ge(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Me(e){return JSON.stringify(e,null,2)}function uo(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 lo(e){return typeof e=="string"?cd(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":Me(e)}function cd(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}…`}function So(e,t){const o=" ".repeat(t);return e.split(`
79
79
  `).map(n=>`${o}${n}`).join(`
80
- `)}function hn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rd(e){switch(e.configAction){case"list":return sd(e);case"get":return ad(e);case"set":return id(e);case"use":return cd(e);default:throw new Error("Unknown config action.")}}function sd(e){const t=je(ft(e.configPath)),o=process.stdout;Te("SiYuan profiles",o);for(const[n,r]of Object.entries(t.profiles)){const s=n===t.currentProfile?" (current)":"";process.stdout.write(` ${n}${s}
81
- `),fe([{key:"apiUrl",value:r.apiUrl||""},{key:"token",value:r.token?"configured":"empty"}],o)}return G("Next Step",o),ne("Tip","Use `siyuan-sisyphus config use <name>` to switch the active profile.",o),0}function ad(e){const t=je(ft(e.configPath)),o=e.configName||t.currentProfile,n=t.profiles[o];if(!n)throw new Error(`Unknown profile "${o}".`);return Te(`Profile ${o}`),fe([{key:"current",value:o===t.currentProfile?"yes":"no"},{key:"apiUrl",value:n.apiUrl||""},{key:"token",value:n.token?"configured":"empty"}]),0}function id(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=ft(e.configPath),n=!!(o.apiUrl||o.token||o.currentProfile||o.profiles&&Object.keys(o.profiles).length>0),r=je(o).currentProfile,s=Ss(o,t,{apiUrl:e.url,token:e.token},{makeCurrent:!n||r===t}),a=dn(s,e.configPath);return ee("success","Profile saved."),fe([{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(`
82
- `),ne("Next",`Run \`siyuan-sisyphus config use ${t}\` to make it the default profile.`),0}function cd(e){const t=e.configName;if(!t)throw new Error("Missing profile name. Usage: siyuan-sisyphus config use <name>");const o=Cl(ft(e.configPath),t),n=dn(o,e.configPath);return ee("success","Active profile updated."),fe([{key:"path",value:n},{key:"profile",value:t}]),0}const Pe=["fs","notebook","document","block","av","file","search","tag","system","flashcard","mascot","feedback"],mn=["ls","tree","read","write","replace","rm","mv","search"],gn=["list","create","set_open_state","remove","rename","get_conf","set_conf","set_icon","get_permissions","set_permission","get_child_docs"],yn=["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"],bn=["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"],kn=["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"],wn=["upload_asset","render","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","extract_doc"],_n=["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"],vn=["list","rename","remove"],In=["workspace_info","network","conf","notify","get_version","get_current_time"],Dn=["list_cards","get_decks","get_cards","review_card","create_card","remove_card"],Sn=["get_balance","shop","buy"],An=["submit"],io="/data/storage/petal/siyuan-plugins-mcp-sisyphus/mcpToolsConfig",Q="/AGENTS.md",hr=new Set,vo={fs:mn,notebook:gn,document:yn,block:bn,av:kn,file:wn,search:_n,tag:vn,system:In,flashcard:Dn,mascot:Sn,feedback:An},ud={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",get_doc_assets:"basic",extract_doc:"basic",render:"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",workspace_info:"advanced",network:"advanced",notify:"advanced"},flashcard:{list_cards:"basic",get_decks:"basic",get_cards:"basic",review_card:"advanced",create_card:"advanced",remove_card:"advanced"},mascot:{get_balance:"basic",shop:"basic",buy:"basic"},feedback:{submit:"basic"}};function Ot(e,t){var o;return((o=ud[e])==null?void 0:o[t])??"advanced"}const ld={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","remove_unused_assets","delete_asset"]),search:new Set(["find_replace"]),tag:new Set(["remove"]),system:new Set(["workspace_info"]),flashcard:new Set(["remove_card"]),mascot:new Set,feedback:new Set},oe=(e,t)=>{const o=new Set(t);return e.reduce((n,r)=>(n[r]=o.has(r),n),{})};function xt(){return{fs:{enabled:!0,actions:oe(mn,["ls","tree","read","write","replace","rm","mv","search"])},notebook:{enabled:!0,actions:oe(gn,["list","create","set_open_state","rename","get_conf","set_conf","set_icon","get_permissions","get_child_docs"])},document:{enabled:!0,actions:oe(yn,["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:oe(bn,["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:oe(kn,["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:oe(wn,["upload_asset","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:oe(_n,["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"])},tag:{enabled:!0,actions:oe(vn,["list","rename","remove"])},system:{enabled:!0,actions:oe(In,["network","conf","notify","get_version","get_current_time"])},flashcard:{enabled:!0,actions:oe(Dn,["list_cards","get_decks","get_cards","review_card","create_card","remove_card"])},mascot:{enabled:!0,actions:oe(Sn,["get_balance","shop","buy"])},feedback:{enabled:!0,actions:oe(An,["submit"])},userRulesText:"创建文档/日记后主动设图标",agentSiyuanMemoryText:"",agentSiyuanMemoryUpdatedAt:"",debug:{includeUiRefreshMetadata:!1,slimResponses:!0}}}function St(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dd(e){const t=[];for(const n of Pe){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)&&!Pe.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 pd(e,t="mcpToolsConfig"){if(!St(e))return null;const o=dd(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 fd(e,t=o=>console.warn(o)){return e?(hr.has(e)||(hr.add(e),t(e)),e):null}function hd(e,t={}){const o=pd(e,t.source);return fd(o,t.warn)}function md(e){if(typeof e!="number"||!Number.isFinite(e))return 10;const t=Math.floor(e);return t<1?1:t>1024?1024:t}function gd(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),St(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 Pe){const n=t[o];if(St(n)&&(typeof n.enabled=="boolean"&&(e[o].enabled=n.enabled),o==="file"&&"uploadLargeFileThresholdMB"in n&&(e.file.uploadLargeFileThresholdMB=md(n.uploadLargeFileThresholdMB)),!!St(n.actions)))for(const r of vo[o]){const s=n.actions[r];typeof s=="boolean"&&(e[o].actions[r]=s)}}}function Tn(e){const t=xt();if(!St(e))return t;gd(t,e);for(const o of Pe)t[o].enabled&&Nt(t[o]).length===0&&(t[o].enabled=!1);return t}function Nt(e){return Object.entries(e.actions).filter(([,t])=>t).map(([t])=>t)}async function Rs(e){try{const t=await e.readFile(io);return t?Tn(JSON.parse(t)):xt()}catch{return xt()}}async function yd(e,t){const o=Tn(t);return await e.writeFile(io,JSON.stringify(o,null,2)),o}async function Pn(e,t){const o=await Rs(e);return yd(e,{...o,agentSiyuanMemoryText:t,agentSiyuanMemoryUpdatedAt:t.trim()?new Date().toISOString():""})}function ot(e,t){return ld[e].has(t)}const bd={list:["ls"],ls:["list"],move:["mv"],mv:["move"],remove:["rm","delete"],rm:["remove","delete"],delete:["rm","remove"],del:["delete","rm","remove"]};function zs(e,t){const o=t.replace(/-/g,"_"),n=vo[e];return n.includes(o)?o:(bd[o]??[]).find(s=>n.includes(s))??o}const Fs=["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.","Use document, block, search, or av only for advanced SiYuan-specific operations such as block-level layout, metadata, database rows, SQL, backlinks, or assets.",'fs(action="write") creates missing documents. If the document already exists, pass overwrite=true to replace its body while preserving the document node and title.','fs(action="replace") performs exact string replacement inside one document using old/new text snippets, including multi-line snippets, without requiring line numbers.','fs(action="rm") and fs(action="mv") require explicit user confirmation before execution.'],Bs=["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.'],js=['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.','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.'],Us=['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") performs exact old/new string replacement inside one block kramdown, without traversing child blocks.',`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.",'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.'],qs=["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.'],Ms=['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.','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.'],Ls=["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."],Zs=["All system actions in this tool are read-only.",'system(action="workspace_info") exposes the workspace path and is high-risk; it is disabled by default.','system(action="conf") returns masked configuration, not raw secrets.','Use system(action="conf", mode="summary") first, then mode="get" + keyPath such as conf.appearance.mode or conf.langs[0].'],Hs=["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_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.','flashcard(action="remove_card") requires explicit user confirmation before execution.'],Vs=["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.'],Ys=["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."],Gs={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 Markdown content only, with pagination for long documents.",write:"Creates a missing document. Existing documents are protected unless overwrite=true; overwrite replaces the body while preserving the document node and title.",replace:"Edits one existing document by exact old/new string matching. edit accepts one object or an array for sequential replacements. replace_all=true replaces every exact match of that old snippet.",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."},Js={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."},Ws={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; parentPath may be a notebook-local parent hpath or a .sy storage path returned by lookup. markdown is optional and defaults to empty.",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 content and supports page/pageSize for long documents; mode="html" uses the current focus view. For structured reading, prefer get_child_blocks.',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."},Ks={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. edit accepts one object or an array for sequential replacements. replace_all=true replaces every exact match of that old snippet.",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 plus previousID, parentID, or both to describe the destination. On success, MCP returns a structured success object instead of SiYuan's raw null. 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.'},Qs={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; this action does not accept avID) 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."},Xs={upload_asset:"Use assetsDirPath + localFilePath to read a local file and upload it into SiYuan 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.",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. 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. 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."},ea=["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."],ta={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."},oa={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."},na={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.",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."},ra={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 deckID + cardID + rating, or pass skip=true to skip. reviewedCards is optional; each entry must include cardID because SiYuan only reads reviewedCards[].cardID.",create_card:"Use deckID + blockIDs to turn existing blocks into flashcards. Non-built-in deck IDs must already exist. This calls SiYuan's addRiffCards flow, which writes custom-riff-decks and creates deck records together.",remove_card:"Use deckID + blockIDs to remove existing blocks from a deck. This action requires explicit user confirmation."},sa={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."},aa={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."},ia={fs:Fs,notebook:Bs,document:js,block:Us,av:qs,file:Ms,search:ea,tag:Ls,system:Zs,flashcard:Hs,mascot:Vs,feedback:Ys},$t={fs:Gs,notebook:Js,document:Ws,block:Ks,av:Qs,file:Xs,search:ta,tag:oa,system:na,flashcard:ra,mascot:sa,feedback:aa},kd={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:{},notebook:{},block:{},av:{},file:{},search:{},tag:{},system:{},flashcard:{},mascot:{},feedback:{}};function wd(e,t){var o;if(!(!e||!t)&&e in $t)return(o=$t[e])==null?void 0:o[t]}function y(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 u=a.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){const f=l[d];f in i||(i[f]=u[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 u=o!=null&&o.Parent?new s:this;n(u,i),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var c,u;return o!=null&&o.Parent&&i instanceof o.Parent?!0:(u=(c=i==null?void 0:i._zod)==null?void 0:c.traits)==null?void 0:u.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Ke extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ca extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const ua={};function Ee(e){return ua}function la(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 Ho(e,t){return typeof t=="bigint"?t.toString():t}function En(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Cn(e){return e==null}function On(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function _d(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 mr=Symbol("evaluating");function U(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==mr)return n===void 0&&(n=mr,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function qe(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function Oe(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function gr(e){return JSON.stringify(e)}function vd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const da="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Id=En(()=>{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 nt(e){if(co(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(co(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function pa(e){return nt(e)?{...e}:Array.isArray(e)?[...e]:e}const Dd=new Set(["string","number","symbol"]);function rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xe(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 D(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 Sd(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Ad={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 Td(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=Oe(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 qe(this,"shape",a),a},checks:[]});return xe(e,s)}function Pd(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=Oe(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 qe(this,"shape",a),a},checks:[]});return xe(e,s)}function Ed(e,t){if(!nt(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=Oe(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return qe(this,"shape",s),s}});return xe(e,r)}function Cd(e,t){if(!nt(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=Oe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return qe(this,"shape",n),n}});return xe(e,o)}function Od(e,t){const o=Oe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return qe(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return xe(e,o)}function xd(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=Oe(t._zod.def,{get shape(){const i=t._zod.def.shape,c={...i};if(o)for(const u in o){if(!(u in i))throw new Error(`Unrecognized key: "${u}"`);o[u]&&(c[u]=e?new e({type:"optional",innerType:i[u]}):i[u])}else for(const u in i)c[u]=e?new e({type:"optional",innerType:i[u]}):i[u];return qe(this,"shape",c),c},checks:[]});return xe(t,a)}function Nd(e,t,o){const n=Oe(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 qe(this,"shape",s),s}});return xe(t,n)}function Ye(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 Ge(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function Yt(e){return typeof e=="string"?e:e==null?void 0:e.message}function Ce(e,t,o){var r,s,a,i,c,u;const n={...e,path:e.path??[]};if(!e.message){const l=Yt((a=(s=(r=e.inst)==null?void 0:r._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??Yt((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??Yt((c=o.customError)==null?void 0:c.call(o,e))??Yt((u=o.localeError)==null?void 0:u.call(o,e))??"Invalid input";n.message=l}return delete n.inst,delete n.continue,t!=null&&t.reportInput||delete n.input,n}function xn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Rt(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const fa=(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,Ho,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ha=y("$ZodError",fa),ma=y("$ZodError",fa,{Parent:Error});function $d(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 Rd(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 Nn=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 Ke;if(a.issues.length){const i=new((r==null?void 0:r.Err)??e)(a.issues.map(c=>Ce(c,s,Ee())));throw da(i,r==null?void 0:r.callee),i}return a.value},$n=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=>Ce(c,s,Ee())));throw da(i,r==null?void 0:r.callee),i}return a.value},Io=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 Ke;return s.issues.length?{success:!1,error:new(e??ha)(s.issues.map(a=>Ce(a,r,Ee())))}:{success:!0,data:s.value}},zd=Io(ma),Do=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=>Ce(a,r,Ee())))}:{success:!0,data:s.value}},Fd=Do(ma),Bd=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Nn(e)(t,o,r)},jd=e=>(t,o,n)=>Nn(e)(t,o,n),Ud=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return $n(e)(t,o,r)},qd=e=>async(t,o,n)=>$n(e)(t,o,n),Md=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Io(e)(t,o,r)},Ld=e=>(t,o,n)=>Io(e)(t,o,n),Zd=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Do(e)(t,o,r)},Hd=e=>async(t,o,n)=>Do(e)(t,o,n),Vd=/^[cC][^\s-]{8,}$/,Yd=/^[0-9a-z]+$/,Gd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Jd=/^[0-9a-vA-V]{20}$/,Wd=/^[A-Za-z0-9]{27}$/,Kd=/^[a-zA-Z0-9_-]{21}$/,Qd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xd=/^([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})$/,yr=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)$/,ep=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,tp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function op(){return new RegExp(tp,"u")}const np=/^(?:(?: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])$/,rp=/^(([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}|:))$/,sp=/^((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])$/,ap=/^(([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])$/,ip=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ga=/^[A-Za-z0-9_-]*$/,cp=/^\+[1-9]\d{6,14}$/,ya="(?:(?:\\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])))",up=new RegExp(`^${ya}$`);function ba(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 lp(e){return new RegExp(`^${ba(e)}$`)}function dp(e){const t=ba({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(`^${ya}T(?:${n})$`)}const pp=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}$`)},fp=/^-?\d+$/,ka=/^-?\d+(?:\.\d+)?$/,hp=/^(?:true|false)$/i,mp=/^null$/i,gp=/^[^A-Z]*$/,yp=/^[^a-z]*$/,te=y("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),wa={number:"number",bigint:"bigint",object:"date"},_a=y("$ZodCheckLessThan",(e,t)=>{te.init(e,t);const o=wa[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})}}),va=y("$ZodCheckGreaterThan",(e,t)=>{te.init(e,t);const o=wa[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})}}),bp=y("$ZodCheckMultipleOf",(e,t)=>{te.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):_d(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})}}),kp=y("$ZodCheckNumberFormat",(e,t)=>{var a;te.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]=Ad[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=fp)}),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})}}),wp=y("$ZodCheckMaxLength",(e,t)=>{var o;te.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Cn(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=xn(r);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),_p=y("$ZodCheckMinLength",(e,t)=>{var o;te.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Cn(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=xn(r);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),vp=y("$ZodCheckLengthEquals",(e,t)=>{var o;te.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Cn(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=xn(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})}}),So=y("$ZodCheckStringFormat",(e,t)=>{var o,n;te.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=()=>{})}),Ip=y("$ZodCheckRegex",(e,t)=>{So.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})}}),Dp=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=gp),So.init(e,t)}),Sp=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yp),So.init(e,t)}),Ap=y("$ZodCheckIncludes",(e,t)=>{te.init(e,t);const o=rt(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})}}),Tp=y("$ZodCheckStartsWith",(e,t)=>{te.init(e,t);const o=new RegExp(`^${rt(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})}}),Pp=y("$ZodCheckEndsWith",(e,t)=>{te.init(e,t);const o=new RegExp(`.*${rt(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})}}),Ep=y("$ZodCheckOverwrite",(e,t)=>{te.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class Cp{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(`
80
+ `)}function wn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function we(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ud(e){switch(e.configAction){case"list":return ld(e);case"get":return dd(e);case"set":return pd(e);case"use":return fd(e);default:throw new Error("Unknown config action.")}}function ld(e){const t=qe(ht(e.configPath)),o=process.stdout;Pe("SiYuan profiles",o);for(const[n,r]of Object.entries(t.profiles)){const s=n===t.currentProfile?" (current)":"";process.stdout.write(` ${n}${s}
81
+ `),he([{key:"apiUrl",value:r.apiUrl||""},{key:"token",value:r.token?"configured":"empty"}],o)}return G("Next Step",o),ne("Tip","Use `siyuan-sisyphus config use <name>` to switch the active profile.",o),0}function dd(e){const t=qe(ht(e.configPath)),o=e.configName||t.currentProfile,n=t.profiles[o];if(!n)throw new Error(`Unknown profile "${o}".`);return Pe(`Profile ${o}`),he([{key:"current",value:o===t.currentProfile?"yes":"no"},{key:"apiUrl",value:n.apiUrl||""},{key:"token",value:n.token?"configured":"empty"}]),0}function pd(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=ht(e.configPath),n=!!(o.apiUrl||o.token||o.currentProfile||o.profiles&&Object.keys(o.profiles).length>0),r=qe(o).currentProfile,s=Cs(o,t,{apiUrl:e.url,token:e.token},{makeCurrent:!n||r===t}),a=yn(s,e.configPath);return ee("success","Profile saved."),he([{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(`
82
+ `),ne("Next",`Run \`siyuan-sisyphus config use ${t}\` to make it the default profile.`),0}function fd(e){const t=e.configName;if(!t)throw new Error("Missing profile name. Usage: siyuan-sisyphus config use <name>");const o=$l(ht(e.configPath),t),n=yn(o,e.configPath);return ee("success","Active profile updated."),he([{key:"path",value:n},{key:"profile",value:t}]),0}const Ee=["fs","notebook","document","block","av","file","search","tag","system","flashcard","mascot","feedback"],_n=["ls","tree","read","write","replace","rm","mv","search"],vn=["list","create","set_open_state","remove","rename","get_conf","set_conf","set_icon","get_permissions","set_permission","get_child_docs"],In=["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"],Dn=["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"],Sn=["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"],An=["upload_asset","render","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","extract_doc"],Tn=["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"],Pn=["list","rename","remove"],En=["workspace_info","network","conf","notify","get_version","get_current_time"],Cn=["list_cards","get_decks","get_cards","review_card","create_card","remove_card"],On=["get_balance","shop","buy"],xn=["submit"],xt="/data/storage/petal/siyuan-plugins-mcp-sisyphus/mcpToolsConfig",K="/AGENTS.md",ye="/USER_RULES.md",_r=new Set,Ao={fs:_n,notebook:vn,document:In,block:Dn,av:Sn,file:An,search:Tn,tag:Pn,system:En,flashcard:Cn,mascot:On,feedback:xn},hd={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",get_doc_assets:"basic",extract_doc:"basic",render:"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",workspace_info:"advanced",network:"advanced",notify:"advanced"},flashcard:{list_cards:"basic",get_decks:"basic",get_cards:"basic",review_card:"advanced",create_card:"advanced",remove_card:"advanced"},mascot:{get_balance:"basic",shop:"basic",buy:"basic"},feedback:{submit:"basic"}};function Nt(e,t){var o;return((o=hd[e])==null?void 0:o[t])??"advanced"}const md={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","remove_unused_assets","delete_asset"]),search:new Set(["find_replace"]),tag:new Set(["remove"]),system:new Set(["workspace_info"]),flashcard:new Set(["remove_card"]),mascot:new Set,feedback:new Set},oe=(e,t)=>{const o=new Set(t);return e.reduce((n,r)=>(n[r]=o.has(r),n),{})};function Rt(){return{fs:{enabled:!0,actions:oe(_n,["ls","tree","read","write","replace","rm","mv","search"])},notebook:{enabled:!0,actions:oe(vn,["list","create","set_open_state","rename","get_conf","set_conf","set_icon","get_permissions","get_child_docs"])},document:{enabled:!0,actions:oe(In,["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:oe(Dn,["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:oe(Sn,["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:oe(An,["upload_asset","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:oe(Tn,["fulltext","query_sql","get_backlinks","search_refs","find_replace","search_assets","fulltext_asset_content","list_invalid_refs"])},tag:{enabled:!0,actions:oe(Pn,["list","rename","remove"])},system:{enabled:!0,actions:oe(En,["network","conf","notify","get_version","get_current_time"])},flashcard:{enabled:!0,actions:oe(Cn,["list_cards","get_decks","get_cards","review_card","create_card","remove_card"])},mascot:{enabled:!0,actions:oe(On,["get_balance","shop","buy"])},feedback:{enabled:!0,actions:oe(xn,["submit"])},userRulesText:"创建文档/日记后主动设图标",agentSiyuanMemoryText:"",agentSiyuanMemoryUpdatedAt:"",debug:{includeUiRefreshMetadata:!1,slimResponses:!0}}}function At(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gd(e){const t=[];for(const n of Ee){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)&&!Ee.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 yd(e,t="mcpToolsConfig"){if(!At(e))return null;const o=gd(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 bd(e,t=o=>console.warn(o)){return e?(_r.has(e)||(_r.add(e),t(e)),e):null}function Us(e,t={}){const o=yd(e,t.source);return bd(o,t.warn)}function kd(e){if(typeof e!="number"||!Number.isFinite(e))return 10;const t=Math.floor(e);return t<1?1:t>1024?1024:t}function wd(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),At(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 Ee){const n=t[o];if(At(n)&&(typeof n.enabled=="boolean"&&(e[o].enabled=n.enabled),o==="file"&&"uploadLargeFileThresholdMB"in n&&(e.file.uploadLargeFileThresholdMB=kd(n.uploadLargeFileThresholdMB)),!!At(n.actions)))for(const r of Ao[o]){const s=n.actions[r];typeof s=="boolean"&&(e[o].actions[r]=s)}}}function Nn(e){const t=Rt();if(!At(e))return t;wd(t,e);for(const o of Ee)t[o].enabled&&$t(t[o]).length===0&&(t[o].enabled=!1);return t}function $t(e){return Object.entries(e.actions).filter(([,t])=>t).map(([t])=>t)}function _d(e){return e instanceof Error?e.message:String(e)}async function vd(e){try{const t=await e.readFile(xt);if(!t)return{config:Rt(),ok:!0,source:"api_file",rawLength:0};const o=JSON.parse(t);return Us(o,{source:`SiYuan API file "${xt}"`}),{config:Nn(o),ok:!0,source:"api_file",rawLength:t.length}}catch(t){return{config:Rt(),ok:!1,source:"default_fallback",errorMessage:_d(t)}}}async function Rn(e){return(await vd(e)).config}async function Id(e,t){const o=Nn(t);return await e.writeFile(xt,JSON.stringify(o,null,2)),o}async function $n(e,t){const o=await Rn(e);return Id(e,{...o,agentSiyuanMemoryText:t,agentSiyuanMemoryUpdatedAt:t.trim()?new Date().toISOString():""})}function rt(e,t){return md[e].has(t)}const Dd={list:["ls"],ls:["list"],move:["mv"],mv:["move"],remove:["rm","delete"],rm:["remove","delete"],delete:["rm","remove"],del:["delete","rm","remove"]};function qs(e,t){const o=t.replace(/-/g,"_"),n=Ao[e];return n.includes(o)?o:(Dd[o]??[]).find(s=>n.includes(s))??o}const Ms=["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.","Use document, block, search, or av only for advanced SiYuan-specific operations such as block-level layout, metadata, database rows, SQL, backlinks, or assets.",'fs(action="write") creates missing documents. If the document already exists, pass overwrite=true to replace its body while preserving the document node and title.','fs(action="replace") performs exact string replacement inside one document using old/new text snippets, including multi-line snippets, without requiring line numbers.','fs(action="rm") and fs(action="mv") require explicit user confirmation before execution.'],Ls=["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.'],Zs=['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.','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.'],Hs=['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") performs exact old/new string replacement inside one block kramdown, without traversing child blocks.',`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.",'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.'],Vs=["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.'],Ys=['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.','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.'],Gs=["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."],Js=["All system actions in this tool are read-only.",'system(action="workspace_info") exposes the workspace path and is high-risk; it is disabled by default.','system(action="conf") returns masked configuration, not raw secrets.','Use system(action="conf", mode="summary") first, then mode="get" + keyPath such as conf.appearance.mode or conf.langs[0].'],Ws=["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_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.','flashcard(action="remove_card") requires explicit user confirmation before execution.'],Ks=["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.'],Qs=["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."],Xs={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 Markdown content only, with pagination for long documents.",write:"Creates a missing document. Existing documents are protected unless overwrite=true; overwrite replaces the body while preserving the document node and title.",replace:"Edits one existing document by exact old/new string matching. edit accepts one object or an array for sequential replacements. replace_all=true replaces every exact match of that old snippet.",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."},ea={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."},ta={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; parentPath may be a notebook-local parent hpath or a .sy storage path returned by lookup. markdown is optional and defaults to empty.",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 content and supports page/pageSize for long documents; mode="html" uses the current focus view. For structured reading, prefer get_child_blocks.',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."},oa={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. edit accepts one object or an array for sequential replacements. replace_all=true replaces every exact match of that old snippet.",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 plus previousID, parentID, or both to describe the destination. On success, MCP returns a structured success object instead of SiYuan's raw null. 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.'},na={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; this action does not accept avID) 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."},ra={upload_asset:"Use assetsDirPath + localFilePath to read a local file and upload it into SiYuan 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.",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. 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. 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."},sa=["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."],aa={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."},ia={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."},ca={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.",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."},ua={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 deckID + cardID + rating, or pass skip=true to skip. reviewedCards is optional; each entry must include cardID because SiYuan only reads reviewedCards[].cardID.",create_card:"Use deckID + blockIDs to turn existing blocks into flashcards. Non-built-in deck IDs must already exist. This calls SiYuan's addRiffCards flow, which writes custom-riff-decks and creates deck records together.",remove_card:"Use deckID + blockIDs to remove existing blocks from a deck. This action requires explicit user confirmation."},la={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."},da={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."},pa={fs:Ms,notebook:Ls,document:Zs,block:Hs,av:Vs,file:Ys,search:sa,tag:Gs,system:Js,flashcard:Ws,mascot:Ks,feedback:Qs},zt={fs:Xs,notebook:ea,document:ta,block:oa,av:na,file:ra,search:aa,tag:ia,system:ca,flashcard:ua,mascot:la,feedback:da},Sd={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:{},notebook:{},block:{},av:{},file:{},search:{},tag:{},system:{},flashcard:{},mascot:{},feedback:{}};function Ad(e,t){var o;if(!(!e||!t)&&e in zt)return(o=zt[e])==null?void 0:o[t]}function y(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 u=a.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){const f=l[d];f in i||(i[f]=u[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 u=o!=null&&o.Parent?new s:this;n(u,i),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var c,u;return o!=null&&o.Parent&&i instanceof o.Parent?!0:(u=(c=i==null?void 0:i._zod)==null?void 0:c.traits)==null?void 0:u.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Xe extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class fa extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const ha={};function Ce(e){return ha}function ma(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 Ko(e,t){return typeof t=="bigint"?t.toString():t}function zn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Fn(e){return e==null}function Bn(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function Td(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 vr=Symbol("evaluating");function U(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==vr)return n===void 0&&(n=vr,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Le(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function xe(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function Ir(e){return JSON.stringify(e)}function Pd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ga="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ed=zn(()=>{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 st(e){if(po(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(po(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function ya(e){return st(e)?{...e}:Array.isArray(e)?[...e]:e}const Cd=new Set(["string","number","symbol"]);function at(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(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 S(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 Od(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const xd={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 Nd(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=xe(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 Le(this,"shape",a),a},checks:[]});return Ne(e,s)}function Rd(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=xe(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 Le(this,"shape",a),a},checks:[]});return Ne(e,s)}function $d(e,t){if(!st(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=xe(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return Le(this,"shape",s),s}});return Ne(e,r)}function zd(e,t){if(!st(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Le(this,"shape",n),n}});return Ne(e,o)}function Fd(e,t){const o=xe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Le(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Ne(e,o)}function Bd(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=xe(t._zod.def,{get shape(){const i=t._zod.def.shape,c={...i};if(o)for(const u in o){if(!(u in i))throw new Error(`Unrecognized key: "${u}"`);o[u]&&(c[u]=e?new e({type:"optional",innerType:i[u]}):i[u])}else for(const u in i)c[u]=e?new e({type:"optional",innerType:i[u]}):i[u];return Le(this,"shape",c),c},checks:[]});return Ne(t,a)}function jd(e,t,o){const n=xe(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 Le(this,"shape",s),s}});return Ne(t,n)}function Je(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 We(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function Wt(e){return typeof e=="string"?e:e==null?void 0:e.message}function Oe(e,t,o){var r,s,a,i,c,u;const n={...e,path:e.path??[]};if(!e.message){const l=Wt((a=(s=(r=e.inst)==null?void 0:r._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??Wt((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??Wt((c=o.customError)==null?void 0:c.call(o,e))??Wt((u=o.localeError)==null?void 0:u.call(o,e))??"Invalid input";n.message=l}return delete n.inst,delete n.continue,t!=null&&t.reportInput||delete n.input,n}function jn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ft(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const ba=(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,Ko,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ka=y("$ZodError",ba),wa=y("$ZodError",ba,{Parent:Error});function Ud(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 qd(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 Un=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 Xe;if(a.issues.length){const i=new((r==null?void 0:r.Err)??e)(a.issues.map(c=>Oe(c,s,Ce())));throw ga(i,r==null?void 0:r.callee),i}return a.value},qn=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=>Oe(c,s,Ce())));throw ga(i,r==null?void 0:r.callee),i}return a.value},To=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 Xe;return s.issues.length?{success:!1,error:new(e??ka)(s.issues.map(a=>Oe(a,r,Ce())))}:{success:!0,data:s.value}},Md=To(wa),Po=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=>Oe(a,r,Ce())))}:{success:!0,data:s.value}},Ld=Po(wa),Zd=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Un(e)(t,o,r)},Hd=e=>(t,o,n)=>Un(e)(t,o,n),Vd=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return qn(e)(t,o,r)},Yd=e=>async(t,o,n)=>qn(e)(t,o,n),Gd=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return To(e)(t,o,r)},Jd=e=>(t,o,n)=>To(e)(t,o,n),Wd=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Po(e)(t,o,r)},Kd=e=>async(t,o,n)=>Po(e)(t,o,n),Qd=/^[cC][^\s-]{8,}$/,Xd=/^[0-9a-z]+$/,ep=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tp=/^[0-9a-vA-V]{20}$/,op=/^[A-Za-z0-9]{27}$/,np=/^[a-zA-Z0-9_-]{21}$/,rp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sp=/^([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})$/,Dr=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)$/,ap=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ip="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function cp(){return new RegExp(ip,"u")}const up=/^(?:(?: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])$/,lp=/^(([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}|:))$/,dp=/^((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])$/,pp=/^(([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])$/,fp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_a=/^[A-Za-z0-9_-]*$/,hp=/^\+[1-9]\d{6,14}$/,va="(?:(?:\\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])))",mp=new RegExp(`^${va}$`);function Ia(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 gp(e){return new RegExp(`^${Ia(e)}$`)}function yp(e){const t=Ia({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(`^${va}T(?:${n})$`)}const bp=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}$`)},kp=/^-?\d+$/,Da=/^-?\d+(?:\.\d+)?$/,wp=/^(?:true|false)$/i,_p=/^null$/i,vp=/^[^A-Z]*$/,Ip=/^[^a-z]*$/,te=y("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),Sa={number:"number",bigint:"bigint",object:"date"},Aa=y("$ZodCheckLessThan",(e,t)=>{te.init(e,t);const o=Sa[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})}}),Ta=y("$ZodCheckGreaterThan",(e,t)=>{te.init(e,t);const o=Sa[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})}}),Dp=y("$ZodCheckMultipleOf",(e,t)=>{te.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):Td(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})}}),Sp=y("$ZodCheckNumberFormat",(e,t)=>{var a;te.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]=xd[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=kp)}),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})}}),Ap=y("$ZodCheckMaxLength",(e,t)=>{var o;te.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Fn(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=jn(r);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Tp=y("$ZodCheckMinLength",(e,t)=>{var o;te.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Fn(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=jn(r);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Pp=y("$ZodCheckLengthEquals",(e,t)=>{var o;te.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Fn(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=jn(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})}}),Eo=y("$ZodCheckStringFormat",(e,t)=>{var o,n;te.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=()=>{})}),Ep=y("$ZodCheckRegex",(e,t)=>{Eo.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})}}),Cp=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vp),Eo.init(e,t)}),Op=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ip),Eo.init(e,t)}),xp=y("$ZodCheckIncludes",(e,t)=>{te.init(e,t);const o=at(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})}}),Np=y("$ZodCheckStartsWith",(e,t)=>{te.init(e,t);const o=new RegExp(`^${at(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})}}),Rp=y("$ZodCheckEndsWith",(e,t)=>{te.init(e,t);const o=new RegExp(`.*${at(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})}}),$p=y("$ZodCheckOverwrite",(e,t)=>{te.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class zp{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(`
83
83
  `).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(`
84
- `))}}const Op={major:4,minor:3,patch:6},Z=y("$ZodType",(e,t)=>{var r;var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Op;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,u)=>{let l=Ye(i),d;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(i))continue}else if(l)continue;const h=i.issues.length,m=f._zod.check(i);if(m instanceof Promise&&(u==null?void 0:u.async)===!1)throw new Ke;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,i.issues.length!==h&&(l||(l=Ye(i,h)))});else{if(i.issues.length===h)continue;l||(l=Ye(i,h))}}return d?d.then(()=>i):i},a=(i,c,u)=>{if(Ye(i))return i.aborted=!0,i;const l=s(c,n,u);if(l instanceof Promise){if(u.async===!1)throw new Ke;return l.then(d=>e._zod.parse(d,u))}return e._zod.parse(l,u)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const l=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(d=>a(d,i,c)):a(l,i,c)}const u=e._zod.parse(i,c);if(u instanceof Promise){if(c.async===!1)throw new Ke;return u.then(l=>s(l,n,c))}return s(u,n,c)}}U(e,"~standard",()=>({validate:s=>{var a;try{const i=zd(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return Fd(e,s).then(c=>{var u;return c.success?{value:c.data}:{issues:(u=c.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}))}),Rn=y("$ZodString",(e,t)=>{var o;Z.init(e,t),e._zod.pattern=[...((o=e==null?void 0:e._zod.bag)==null?void 0:o.patterns)??[]].pop()??pp(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}}),H=y("$ZodStringFormat",(e,t)=>{So.init(e,t),Rn.init(e,t)}),xp=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xd),H.init(e,t)}),Np=y("$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=yr(n))}else t.pattern??(t.pattern=yr());H.init(e,t)}),$p=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ep),H.init(e,t)}),Rp=y("$ZodURL",(e,t)=>{H.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})}}}),zp=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=op()),H.init(e,t)}),Fp=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Kd),H.init(e,t)}),Bp=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Vd),H.init(e,t)}),jp=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yd),H.init(e,t)}),Up=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Gd),H.init(e,t)}),qp=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Jd),H.init(e,t)}),Mp=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Wd),H.init(e,t)}),Lp=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=dp(t)),H.init(e,t)}),Zp=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=up),H.init(e,t)}),Hp=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=lp(t)),H.init(e,t)}),Vp=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qd),H.init(e,t)}),Yp=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=np),H.init(e,t),e._zod.bag.format="ipv4"}),Gp=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=rp),H.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})}}}),Jp=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=sp),H.init(e,t)}),Wp=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ap),H.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 Ia(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Kp=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ip),H.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{Ia(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function Qp(e){if(!ga.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ia(o)}const Xp=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ga),H.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{Qp(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),ef=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=cp),H.init(e,t)});function tf(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 of=y("$ZodJWT",(e,t)=>{H.init(e,t),e._zod.check=o=>{tf(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),Da=y("$ZodNumber",(e,t)=>{Z.init(e,t),e._zod.pattern=e._zod.bag.pattern??ka,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}}),nf=y("$ZodNumberFormat",(e,t)=>{kp.init(e,t),Da.init(e,t)}),rf=y("$ZodBoolean",(e,t)=>{Z.init(e,t),e._zod.pattern=hp,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}}),sf=y("$ZodNull",(e,t)=>{Z.init(e,t),e._zod.pattern=mp,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}}),af=y("$ZodUnknown",(e,t)=>{Z.init(e,t),e._zod.parse=o=>o}),cf=y("$ZodNever",(e,t)=>{Z.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function br(e,t,o){e.issues.length&&t.issues.push(...Ge(o,e.issues)),t.value[o]=e.value}const uf=y("$ZodArray",(e,t)=>{Z.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(u=>br(u,o,a))):br(c,o,a)}return s.length?Promise.all(s).then(()=>o):o}});function uo(e,t,o,n,r){if(e.issues.length){if(r&&!(o in n))return;t.issues.push(...Ge(o,e.issues))}e.value===void 0?o in n&&(t.value[o]=void 0):t.value[o]=e.value}function Sa(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=Sd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Aa(e,t,o,n,r,s){const a=[],i=r.keySet,c=r.catchall._zod,u=c.def.type,l=c.optout==="optional";for(const d in t){if(i.has(d))continue;if(u==="never"){a.push(d);continue}const f=c.run({value:t[d],issues:[]},n);f instanceof Promise?e.push(f.then(h=>uo(h,o,d,t,l))):uo(f,o,d,t,l)}return a.length&&o.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>o):o}const lf=y("$ZodObject",(e,t)=>{Z.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=En(()=>Sa(t));U(e._zod,"propValues",()=>{const i=t.shape,c={};for(const u in i){const l=i[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(const d of l.values)c[u].add(d)}}return c});const r=co,s=t.catchall;let a;e._zod.parse=(i,c)=>{a??(a=n.value);const u=i.value;if(!r(u))return i.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),i;i.value={};const l=[],d=a.shape;for(const f of a.keys){const h=d[f],m=h._zod.optout==="optional",k=h._zod.run({value:u[f],issues:[]},c);k instanceof Promise?l.push(k.then(v=>uo(v,i,f,u,m))):uo(k,i,f,u,m)}return s?Aa(l,u,i,c,n.value,e):l.length?Promise.all(l).then(()=>i):i}}),df=y("$ZodObjectJIT",(e,t)=>{lf.init(e,t);const o=e._zod.parse,n=En(()=>Sa(t)),r=f=>{var $;const h=new Cp(["shape","payload","ctx"]),m=n.value,k=I=>{const A=gr(I);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};h.write("const input = payload.value;");const v=Object.create(null);let E=0;for(const I of m.keys)v[I]=`key_${E++}`;h.write("const newResult = {};");for(const I of m.keys){const A=v[I],B=gr(I),x=f[I],_e=(($=x==null?void 0:x._zod)==null?void 0:$.optout)==="optional";h.write(`const ${A} = ${k(I)};`),_e?h.write(`
85
- if (${A}.issues.length) {
86
- if (${B} in input) {
87
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
84
+ `))}}const Fp={major:4,minor:3,patch:6},Z=y("$ZodType",(e,t)=>{var r;var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fp;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,u)=>{let l=Je(i),d;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(i))continue}else if(l)continue;const h=i.issues.length,m=f._zod.check(i);if(m instanceof Promise&&(u==null?void 0:u.async)===!1)throw new Xe;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,i.issues.length!==h&&(l||(l=Je(i,h)))});else{if(i.issues.length===h)continue;l||(l=Je(i,h))}}return d?d.then(()=>i):i},a=(i,c,u)=>{if(Je(i))return i.aborted=!0,i;const l=s(c,n,u);if(l instanceof Promise){if(u.async===!1)throw new Xe;return l.then(d=>e._zod.parse(d,u))}return e._zod.parse(l,u)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const l=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(d=>a(d,i,c)):a(l,i,c)}const u=e._zod.parse(i,c);if(u instanceof Promise){if(c.async===!1)throw new Xe;return u.then(l=>s(l,n,c))}return s(u,n,c)}}U(e,"~standard",()=>({validate:s=>{var a;try{const i=Md(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return Ld(e,s).then(c=>{var u;return c.success?{value:c.data}:{issues:(u=c.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}))}),Mn=y("$ZodString",(e,t)=>{var o;Z.init(e,t),e._zod.pattern=[...((o=e==null?void 0:e._zod.bag)==null?void 0:o.patterns)??[]].pop()??bp(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}}),H=y("$ZodStringFormat",(e,t)=>{Eo.init(e,t),Mn.init(e,t)}),Bp=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=sp),H.init(e,t)}),jp=y("$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=Dr(n))}else t.pattern??(t.pattern=Dr());H.init(e,t)}),Up=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ap),H.init(e,t)}),qp=y("$ZodURL",(e,t)=>{H.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})}}}),Mp=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=cp()),H.init(e,t)}),Lp=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=np),H.init(e,t)}),Zp=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Qd),H.init(e,t)}),Hp=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Xd),H.init(e,t)}),Vp=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ep),H.init(e,t)}),Yp=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=tp),H.init(e,t)}),Gp=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=op),H.init(e,t)}),Jp=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=yp(t)),H.init(e,t)}),Wp=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=mp),H.init(e,t)}),Kp=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gp(t)),H.init(e,t)}),Qp=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=rp),H.init(e,t)}),Xp=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=up),H.init(e,t),e._zod.bag.format="ipv4"}),ef=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=lp),H.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})}}}),tf=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=dp),H.init(e,t)}),of=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pp),H.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 Pa(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const nf=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=fp),H.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{Pa(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function rf(e){if(!_a.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return Pa(o)}const sf=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_a),H.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{rf(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),af=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=hp),H.init(e,t)});function cf(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 uf=y("$ZodJWT",(e,t)=>{H.init(e,t),e._zod.check=o=>{cf(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),Ea=y("$ZodNumber",(e,t)=>{Z.init(e,t),e._zod.pattern=e._zod.bag.pattern??Da,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}}),lf=y("$ZodNumberFormat",(e,t)=>{Sp.init(e,t),Ea.init(e,t)}),df=y("$ZodBoolean",(e,t)=>{Z.init(e,t),e._zod.pattern=wp,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}}),pf=y("$ZodNull",(e,t)=>{Z.init(e,t),e._zod.pattern=_p,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}}),ff=y("$ZodUnknown",(e,t)=>{Z.init(e,t),e._zod.parse=o=>o}),hf=y("$ZodNever",(e,t)=>{Z.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function Sr(e,t,o){e.issues.length&&t.issues.push(...We(o,e.issues)),t.value[o]=e.value}const mf=y("$ZodArray",(e,t)=>{Z.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(u=>Sr(u,o,a))):Sr(c,o,a)}return s.length?Promise.all(s).then(()=>o):o}});function fo(e,t,o,n,r){if(e.issues.length){if(r&&!(o in n))return;t.issues.push(...We(o,e.issues))}e.value===void 0?o in n&&(t.value[o]=void 0):t.value[o]=e.value}function Ca(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=Od(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Oa(e,t,o,n,r,s){const a=[],i=r.keySet,c=r.catchall._zod,u=c.def.type,l=c.optout==="optional";for(const d in t){if(i.has(d))continue;if(u==="never"){a.push(d);continue}const f=c.run({value:t[d],issues:[]},n);f instanceof Promise?e.push(f.then(h=>fo(h,o,d,t,l))):fo(f,o,d,t,l)}return a.length&&o.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>o):o}const gf=y("$ZodObject",(e,t)=>{Z.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=zn(()=>Ca(t));U(e._zod,"propValues",()=>{const i=t.shape,c={};for(const u in i){const l=i[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(const d of l.values)c[u].add(d)}}return c});const r=po,s=t.catchall;let a;e._zod.parse=(i,c)=>{a??(a=n.value);const u=i.value;if(!r(u))return i.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),i;i.value={};const l=[],d=a.shape;for(const f of a.keys){const h=d[f],m=h._zod.optout==="optional",_=h._zod.run({value:u[f],issues:[]},c);_ instanceof Promise?l.push(_.then(v=>fo(v,i,f,u,m))):fo(_,i,f,u,m)}return s?Oa(l,u,i,c,n.value,e):l.length?Promise.all(l).then(()=>i):i}}),yf=y("$ZodObjectJIT",(e,t)=>{gf.init(e,t);const o=e._zod.parse,n=zn(()=>Ca(t)),r=f=>{var C;const h=new zp(["shape","payload","ctx"]),m=n.value,_=I=>{const D=Ir(I);return`shape[${D}]._zod.run({ value: input[${D}], issues: [] }, ctx)`};h.write("const input = payload.value;");const v=Object.create(null);let A=0;for(const I of m.keys)v[I]=`key_${A++}`;h.write("const newResult = {};");for(const I of m.keys){const D=v[I],$=Ir(I),N=f[I],ve=((C=N==null?void 0:N._zod)==null?void 0:C.optout)==="optional";h.write(`const ${D} = ${_(I)};`),ve?h.write(`
85
+ if (${D}.issues.length) {
86
+ if (${$} in input) {
87
+ payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
88
88
  ...iss,
89
- path: iss.path ? [${B}, ...iss.path] : [${B}]
89
+ path: iss.path ? [${$}, ...iss.path] : [${$}]
90
90
  })));
91
91
  }
92
92
  }
93
93
 
94
- if (${A}.value === undefined) {
95
- if (${B} in input) {
96
- newResult[${B}] = undefined;
94
+ if (${D}.value === undefined) {
95
+ if (${$} in input) {
96
+ newResult[${$}] = undefined;
97
97
  }
98
98
  } else {
99
- newResult[${B}] = ${A}.value;
99
+ newResult[${$}] = ${D}.value;
100
100
  }
101
101
 
102
102
  `):h.write(`
103
- if (${A}.issues.length) {
104
- payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
103
+ if (${D}.issues.length) {
104
+ payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
105
105
  ...iss,
106
- path: iss.path ? [${B}, ...iss.path] : [${B}]
106
+ path: iss.path ? [${$}, ...iss.path] : [${$}]
107
107
  })));
108
108
  }
109
109
 
110
- if (${A}.value === undefined) {
111
- if (${B} in input) {
112
- newResult[${B}] = undefined;
110
+ if (${D}.value === undefined) {
111
+ if (${$} in input) {
112
+ newResult[${$}] = undefined;
113
113
  }
114
114
  } else {
115
- newResult[${B}] = ${A}.value;
115
+ newResult[${$}] = ${D}.value;
116
116
  }
117
117
 
118
- `)}h.write("payload.value = newResult;"),h.write("return payload;");const C=h.compile();return(I,A)=>C(f,I,A)};let s;const a=co,i=!ua.jitless,u=i&&Id.value,l=t.catchall;let d;e._zod.parse=(f,h)=>{d??(d=n.value);const m=f.value;return a(m)?i&&u&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(s||(s=r(t.shape)),f=s(f,h),l?Aa([],m,f,h,d,e):f):o(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f)}});function kr(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=>!Ye(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=>Ce(a,n,Ee())))}),t)}const pf=y("$ZodUnion",(e,t)=>{Z.init(e,t),U(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),U(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),U(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),U(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=>On(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 u=c._zod.run({value:r.value,issues:[]},s);if(u instanceof Promise)i.push(u),a=!0;else{if(u.issues.length===0)return u;i.push(u)}}return a?Promise.all(i).then(c=>kr(c,r,e,s)):kr(i,r,e,s)}}),ff=y("$ZodIntersection",(e,t)=>{Z.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,u])=>wr(o,c,u)):wr(o,s,a)}});function Vo(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(nt(e)&&nt(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=Vo(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=Vo(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 wr(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}),Ye(e))return e;const a=Vo(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 hf=y("$ZodRecord",(e,t)=>{Z.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!nt(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 u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){i.add(typeof u=="number"?u.toString():u);const l=t.valueType._zod.run({value:r[u],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&o.issues.push(...Ge(u,d.issues)),o.value[u]=d.value})):(l.issues.length&&o.issues.push(...Ge(u,l.issues)),o.value[u]=l.value)}let c;for(const u in r)i.has(u)||(c=c??[],c.push(u));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"&&ka.test(i)&&c.issues.length){const d=t.keyType._zod.run({value:Number(i),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){t.mode==="loose"?o.value[i]=r[i]:o.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Ce(d,n,Ee())),input:i,path:[i],inst:e});continue}const l=t.valueType._zod.run({value:r[i],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&o.issues.push(...Ge(i,d.issues)),o.value[c.value]=d.value})):(l.issues.length&&o.issues.push(...Ge(i,l.issues)),o.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>o):o}}),mf=y("$ZodEnum",(e,t)=>{Z.init(e,t);const o=la(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>Dd.has(typeof r)).map(r=>typeof r=="string"?rt(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}}),gf=y("$ZodLiteral",(e,t)=>{if(Z.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"?rt(n):n?rt(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}}),yf=y("$ZodTransform",(e,t)=>{Z.init(e,t),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new ca(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 Ke;return o.value=r,o}});function _r(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Ta=y("$ZodOptional",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",U(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),U(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${On(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=>_r(s,o.value)):_r(r,o.value)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),bf=y("$ZodExactOptional",(e,t)=>{Ta.init(e,t),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),kf=y("$ZodNullable",(e,t)=>{Z.init(e,t),U(e._zod,"optin",()=>t.innerType._zod.optin),U(e._zod,"optout",()=>t.innerType._zod.optout),U(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${On(o.source)}|null)$`):void 0}),U(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)}),wf=y("$ZodDefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",U(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=>vr(s,t)):vr(r,t)}});function vr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const _f=y("$ZodPrefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",U(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))}),vf=y("$ZodNonOptional",(e,t)=>{Z.init(e,t),U(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=>Ir(s,e)):Ir(r,e)}});function Ir(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 If=y("$ZodCatch",(e,t)=>{Z.init(e,t),U(e._zod,"optin",()=>t.innerType._zod.optin),U(e._zod,"optout",()=>t.innerType._zod.optout),U(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=>Ce(a,n,Ee()))},input:o.value}),o.issues=[]),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(s=>Ce(s,n,Ee()))},input:o.value}),o.issues=[]),o)}}),Df=y("$ZodPipe",(e,t)=>{Z.init(e,t),U(e._zod,"values",()=>t.in._zod.values),U(e._zod,"optin",()=>t.in._zod.optin),U(e._zod,"optout",()=>t.out._zod.optout),U(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=>Gt(a,t.in,n)):Gt(s,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(s=>Gt(s,t.out,n)):Gt(r,t.out,n)}});function Gt(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},o)}const Sf=y("$ZodReadonly",(e,t)=>{Z.init(e,t),U(e._zod,"propValues",()=>t.innerType._zod.propValues),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"optin",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optin}),U(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(Dr):Dr(r)}});function Dr(e){return e.value=Object.freeze(e.value),e}const Af=y("$ZodCustom",(e,t)=>{te.init(e,t),Z.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=>Sr(s,o,n,e));Sr(r,o,n,e)}});function Sr(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(Rt(r))}}var Ar;class Tf{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 Pf(){return new Tf}(Ar=globalThis).__zod_globalRegistry??(Ar.__zod_globalRegistry=Pf());const _t=globalThis.__zod_globalRegistry;function Ef(e,t){return new e({type:"string",...D(t)})}function Cf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...D(t)})}function Tr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...D(t)})}function Of(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...D(t)})}function xf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(t)})}function Nf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(t)})}function $f(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(t)})}function Rf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...D(t)})}function zf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...D(t)})}function Ff(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(t)})}function Bf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...D(t)})}function jf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(t)})}function Uf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...D(t)})}function qf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...D(t)})}function Mf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(t)})}function Lf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(t)})}function Zf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(t)})}function Hf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(t)})}function Vf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(t)})}function Yf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...D(t)})}function Gf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...D(t)})}function Jf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...D(t)})}function Wf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...D(t)})}function Kf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(t)})}function Qf(e,t){return new e({type:"string",format:"date",check:"string_format",...D(t)})}function Xf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...D(t)})}function eh(e,t){return new e({type:"string",format:"duration",check:"string_format",...D(t)})}function th(e,t){return new e({type:"number",checks:[],...D(t)})}function oh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...D(t)})}function nh(e,t){return new e({type:"boolean",...D(t)})}function rh(e,t){return new e({type:"null",...D(t)})}function sh(e){return new e({type:"unknown"})}function ah(e,t){return new e({type:"never",...D(t)})}function Pr(e,t){return new _a({check:"less_than",...D(t),value:e,inclusive:!1})}function $o(e,t){return new _a({check:"less_than",...D(t),value:e,inclusive:!0})}function Er(e,t){return new va({check:"greater_than",...D(t),value:e,inclusive:!1})}function Ro(e,t){return new va({check:"greater_than",...D(t),value:e,inclusive:!0})}function Cr(e,t){return new bp({check:"multiple_of",...D(t),value:e})}function Pa(e,t){return new wp({check:"max_length",...D(t),maximum:e})}function lo(e,t){return new _p({check:"min_length",...D(t),minimum:e})}function Ea(e,t){return new vp({check:"length_equals",...D(t),length:e})}function ih(e,t){return new Ip({check:"string_format",format:"regex",...D(t),pattern:e})}function ch(e){return new Dp({check:"string_format",format:"lowercase",...D(e)})}function uh(e){return new Sp({check:"string_format",format:"uppercase",...D(e)})}function lh(e,t){return new Ap({check:"string_format",format:"includes",...D(t),includes:e})}function dh(e,t){return new Tp({check:"string_format",format:"starts_with",...D(t),prefix:e})}function ph(e,t){return new Pp({check:"string_format",format:"ends_with",...D(t),suffix:e})}function ht(e){return new Ep({check:"overwrite",tx:e})}function fh(e){return ht(t=>t.normalize(e))}function hh(){return ht(e=>e.trim())}function mh(){return ht(e=>e.toLowerCase())}function gh(){return ht(e=>e.toUpperCase())}function yh(){return ht(e=>vd(e))}function bh(e,t,o){return new e({type:"array",element:t,...D(o)})}function kh(e,t,o){return new e({type:"custom",check:"custom",fn:t,...D(o)})}function wh(e){const t=_h(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Rt(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(Rt(r))}},e(o.value,o)));return t}function _h(e,t){const o=new te({check:"custom",...D(t)});return o._zod.check=e,o}function po(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)??_t,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 M(e,t,o={path:[],schemaPath:[]}){var l,d;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=(d=(l=e._zod).toJSONSchema)==null?void 0:d.call(l);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 m=a.schema,k=t.processors[r.type];if(!k)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);k(e,t,m,f)}const h=e._zod.parent;h&&(a.ref||(a.ref=h),M(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"&&X(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 fo(e,t){var a,i,c,u;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 l of e.seen.entries()){const d=(a=e.metadataRegistry.get(l[0]))==null?void 0:a.id;if(d){const f=n.get(d);if(f&&f!==l[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(d,l[0])}}const r=l=>{var k;const d=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const v=(k=e.external.registry.get(l[0]))==null?void 0:k.id,E=e.external.uri??($=>$);if(v)return{ref:E(v)};const C=l[1].defId??l[1].schema.id??`schema${e.counter++}`;return l[1].defId=C,{defId:C,ref:`${E("__shared")}#/${d}/${C}`}}if(l[1]===o)return{ref:"#"};const h=`#/${d}/`,m=l[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:h+m}},s=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:f,defId:h}=r(l);d.def={...d.schema},h&&(d.defId=h);const m=d.schema;for(const k in m)delete m[k];m.$ref=f};if(e.cycles==="throw")for(const l of e.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${(i=d.cycle)==null?void 0:i.join("/")}/<root>
118
+ `)}h.write("payload.value = newResult;"),h.write("return payload;");const x=h.compile();return(I,D)=>x(f,I,D)};let s;const a=po,i=!ha.jitless,u=i&&Ed.value,l=t.catchall;let d;e._zod.parse=(f,h)=>{d??(d=n.value);const m=f.value;return a(m)?i&&u&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(s||(s=r(t.shape)),f=s(f,h),l?Oa([],m,f,h,d,e):f):o(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f)}});function Ar(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=>!Je(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=>Oe(a,n,Ce())))}),t)}const bf=y("$ZodUnion",(e,t)=>{Z.init(e,t),U(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),U(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),U(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),U(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=>Bn(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 u=c._zod.run({value:r.value,issues:[]},s);if(u instanceof Promise)i.push(u),a=!0;else{if(u.issues.length===0)return u;i.push(u)}}return a?Promise.all(i).then(c=>Ar(c,r,e,s)):Ar(i,r,e,s)}}),kf=y("$ZodIntersection",(e,t)=>{Z.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,u])=>Tr(o,c,u)):Tr(o,s,a)}});function Qo(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(st(e)&&st(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=Qo(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=Qo(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 Tr(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}),Je(e))return e;const a=Qo(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 wf=y("$ZodRecord",(e,t)=>{Z.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!st(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 u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){i.add(typeof u=="number"?u.toString():u);const l=t.valueType._zod.run({value:r[u],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&o.issues.push(...We(u,d.issues)),o.value[u]=d.value})):(l.issues.length&&o.issues.push(...We(u,l.issues)),o.value[u]=l.value)}let c;for(const u in r)i.has(u)||(c=c??[],c.push(u));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"&&Da.test(i)&&c.issues.length){const d=t.keyType._zod.run({value:Number(i),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){t.mode==="loose"?o.value[i]=r[i]:o.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Oe(d,n,Ce())),input:i,path:[i],inst:e});continue}const l=t.valueType._zod.run({value:r[i],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&o.issues.push(...We(i,d.issues)),o.value[c.value]=d.value})):(l.issues.length&&o.issues.push(...We(i,l.issues)),o.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>o):o}}),_f=y("$ZodEnum",(e,t)=>{Z.init(e,t);const o=ma(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>Cd.has(typeof r)).map(r=>typeof r=="string"?at(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}}),vf=y("$ZodLiteral",(e,t)=>{if(Z.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"?at(n):n?at(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}}),If=y("$ZodTransform",(e,t)=>{Z.init(e,t),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new fa(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 Xe;return o.value=r,o}});function Pr(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const xa=y("$ZodOptional",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",U(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),U(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Bn(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=>Pr(s,o.value)):Pr(r,o.value)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),Df=y("$ZodExactOptional",(e,t)=>{xa.init(e,t),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),Sf=y("$ZodNullable",(e,t)=>{Z.init(e,t),U(e._zod,"optin",()=>t.innerType._zod.optin),U(e._zod,"optout",()=>t.innerType._zod.optout),U(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Bn(o.source)}|null)$`):void 0}),U(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)}),Af=y("$ZodDefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",U(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=>Er(s,t)):Er(r,t)}});function Er(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Tf=y("$ZodPrefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",U(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))}),Pf=y("$ZodNonOptional",(e,t)=>{Z.init(e,t),U(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=>Cr(s,e)):Cr(r,e)}});function Cr(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 Ef=y("$ZodCatch",(e,t)=>{Z.init(e,t),U(e._zod,"optin",()=>t.innerType._zod.optin),U(e._zod,"optout",()=>t.innerType._zod.optout),U(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=>Oe(a,n,Ce()))},input:o.value}),o.issues=[]),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(s=>Oe(s,n,Ce()))},input:o.value}),o.issues=[]),o)}}),Cf=y("$ZodPipe",(e,t)=>{Z.init(e,t),U(e._zod,"values",()=>t.in._zod.values),U(e._zod,"optin",()=>t.in._zod.optin),U(e._zod,"optout",()=>t.out._zod.optout),U(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=>Kt(a,t.in,n)):Kt(s,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(s=>Kt(s,t.out,n)):Kt(r,t.out,n)}});function Kt(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},o)}const Of=y("$ZodReadonly",(e,t)=>{Z.init(e,t),U(e._zod,"propValues",()=>t.innerType._zod.propValues),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"optin",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optin}),U(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(Or):Or(r)}});function Or(e){return e.value=Object.freeze(e.value),e}const xf=y("$ZodCustom",(e,t)=>{te.init(e,t),Z.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=>xr(s,o,n,e));xr(r,o,n,e)}});function xr(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(Ft(r))}}var Nr;class Nf{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 Rf(){return new Nf}(Nr=globalThis).__zod_globalRegistry??(Nr.__zod_globalRegistry=Rf());const vt=globalThis.__zod_globalRegistry;function $f(e,t){return new e({type:"string",...S(t)})}function zf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...S(t)})}function Rr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...S(t)})}function Ff(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...S(t)})}function Bf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(t)})}function jf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(t)})}function Uf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(t)})}function qf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...S(t)})}function Mf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...S(t)})}function Lf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(t)})}function Zf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...S(t)})}function Hf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(t)})}function Vf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...S(t)})}function Yf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...S(t)})}function Gf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(t)})}function Jf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(t)})}function Wf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(t)})}function Kf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(t)})}function Qf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(t)})}function Xf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...S(t)})}function eh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...S(t)})}function th(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...S(t)})}function oh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...S(t)})}function nh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(t)})}function rh(e,t){return new e({type:"string",format:"date",check:"string_format",...S(t)})}function sh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...S(t)})}function ah(e,t){return new e({type:"string",format:"duration",check:"string_format",...S(t)})}function ih(e,t){return new e({type:"number",checks:[],...S(t)})}function ch(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...S(t)})}function uh(e,t){return new e({type:"boolean",...S(t)})}function lh(e,t){return new e({type:"null",...S(t)})}function dh(e){return new e({type:"unknown"})}function ph(e,t){return new e({type:"never",...S(t)})}function $r(e,t){return new Aa({check:"less_than",...S(t),value:e,inclusive:!1})}function jo(e,t){return new Aa({check:"less_than",...S(t),value:e,inclusive:!0})}function zr(e,t){return new Ta({check:"greater_than",...S(t),value:e,inclusive:!1})}function Uo(e,t){return new Ta({check:"greater_than",...S(t),value:e,inclusive:!0})}function Fr(e,t){return new Dp({check:"multiple_of",...S(t),value:e})}function Na(e,t){return new Ap({check:"max_length",...S(t),maximum:e})}function ho(e,t){return new Tp({check:"min_length",...S(t),minimum:e})}function Ra(e,t){return new Pp({check:"length_equals",...S(t),length:e})}function fh(e,t){return new Ep({check:"string_format",format:"regex",...S(t),pattern:e})}function hh(e){return new Cp({check:"string_format",format:"lowercase",...S(e)})}function mh(e){return new Op({check:"string_format",format:"uppercase",...S(e)})}function gh(e,t){return new xp({check:"string_format",format:"includes",...S(t),includes:e})}function yh(e,t){return new Np({check:"string_format",format:"starts_with",...S(t),prefix:e})}function bh(e,t){return new Rp({check:"string_format",format:"ends_with",...S(t),suffix:e})}function mt(e){return new $p({check:"overwrite",tx:e})}function kh(e){return mt(t=>t.normalize(e))}function wh(){return mt(e=>e.trim())}function _h(){return mt(e=>e.toLowerCase())}function vh(){return mt(e=>e.toUpperCase())}function Ih(){return mt(e=>Pd(e))}function Dh(e,t,o){return new e({type:"array",element:t,...S(o)})}function Sh(e,t,o){return new e({type:"custom",check:"custom",fn:t,...S(o)})}function Ah(e){const t=Th(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Ft(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(Ft(r))}},e(o.value,o)));return t}function Th(e,t){const o=new te({check:"custom",...S(t)});return o._zod.check=e,o}function mo(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)??vt,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 M(e,t,o={path:[],schemaPath:[]}){var l,d;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=(d=(l=e._zod).toJSONSchema)==null?void 0:d.call(l);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 m=a.schema,_=t.processors[r.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);_(e,t,m,f)}const h=e._zod.parent;h&&(a.ref||(a.ref=h),M(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"&&X(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 go(e,t){var a,i,c,u;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 l of e.seen.entries()){const d=(a=e.metadataRegistry.get(l[0]))==null?void 0:a.id;if(d){const f=n.get(d);if(f&&f!==l[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(d,l[0])}}const r=l=>{var _;const d=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const v=(_=e.external.registry.get(l[0]))==null?void 0:_.id,A=e.external.uri??(C=>C);if(v)return{ref:A(v)};const x=l[1].defId??l[1].schema.id??`schema${e.counter++}`;return l[1].defId=x,{defId:x,ref:`${A("__shared")}#/${d}/${x}`}}if(l[1]===o)return{ref:"#"};const h=`#/${d}/`,m=l[1].schema.id??`__schema${e.counter++}`;return{defId:m,ref:h+m}},s=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:f,defId:h}=r(l);d.def={...d.schema},h&&(d.defId=h);const m=d.schema;for(const _ in m)delete m[_];m.$ref=f};if(e.cycles==="throw")for(const l of e.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${(i=d.cycle)==null?void 0:i.join("/")}/<root>
119
119
 
120
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of e.seen.entries()){const d=l[1];if(t===l[0]){s(l);continue}if(e.external){const h=(c=e.external.registry.get(l[0]))==null?void 0:c.id;if(t!==l[0]&&h){s(l);continue}}if((u=e.metadataRegistry.get(l[0]))==null?void 0:u.id){s(l);continue}if(d.cycle){s(l);continue}if(d.count>1&&e.reused==="ref"){s(l);continue}}}function ho(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=u=>{const l=e.seen.get(u);if(l.ref===null)return;const d=l.def??l.schema,f={...d},h=l.ref;if(l.ref=null,h){n(h);const k=e.seen.get(h),v=k.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(v)):Object.assign(d,v),Object.assign(d,f),u._zod.parent===h)for(const C in d)C==="$ref"||C==="allOf"||C in f||delete d[C];if(v.$ref&&k.def)for(const C in d)C==="$ref"||C==="allOf"||C in k.def&&JSON.stringify(d[C])===JSON.stringify(k.def[C])&&delete d[C]}const m=u._zod.parent;if(m&&m!==h){n(m);const k=e.seen.get(m);if(k!=null&&k.schema.$ref&&(d.$ref=k.schema.$ref,k.def))for(const v in d)v==="$ref"||v==="allOf"||v in k.def&&JSON.stringify(d[v])===JSON.stringify(k.def[v])&&delete d[v]}e.override({zodSchema:u,jsonSchema:d,path:l.path??[]})};for(const u of[...e.seen.entries()].reverse())n(u[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 u=(i=e.external.registry.get(t))==null?void 0:i.id;if(!u)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(u)}Object.assign(r,o.def??o.schema);const s=((c=e.external)==null?void 0:c.defs)??{};for(const u of e.seen.entries()){const l=u[1];l.def&&l.defId&&(s[l.defId]=l.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const u=JSON.parse(JSON.stringify(r));return Object.defineProperty(u,"~standard",{value:{...t["~standard"],jsonSchema:{input:mo(t,"input",e.processors),output:mo(t,"output",e.processors)}},enumerable:!1,writable:!1}),u}catch{throw new Error("Error converting schema to JSON.")}}function X(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 X(n.element,o);if(n.type==="set")return X(n.valueType,o);if(n.type==="lazy")return X(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 X(n.innerType,o);if(n.type==="intersection")return X(n.left,o)||X(n.right,o);if(n.type==="record"||n.type==="map")return X(n.keyType,o)||X(n.valueType,o);if(n.type==="pipe")return X(n.in,o)||X(n.out,o);if(n.type==="object"){for(const r in n.shape)if(X(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(X(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(X(r,o))return!0;return!!(n.rest&&X(n.rest,o))}return!1}const vh=(e,t={})=>o=>{const n=po({...o,processors:t});return M(e,n),fo(n,e),ho(n,e)},mo=(e,t,o={})=>n=>{const{libraryOptions:r,target:s}=n??{},a=po({...r??{},target:s,io:t,processors:o});return M(e,a),fo(a,e),ho(a,e)},Ih={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ca=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:s,maximum:a,format:i,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof a=="number"&&(r.maxLength=a),i&&(r.format=Ih[i]??i,r.format===""&&delete r.format,i==="time"&&delete r.format),u&&(r.contentEncoding=u),c&&c.size>0){const l=[...c];l.length===1?r.pattern=l[0].source:l.length>1&&(r.allOf=[...l.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Oa=(e,t,o,n)=>{const r=o,{minimum:s,maximum:a,format:i,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof i=="string"&&i.includes("int")?r.type="integer":r.type="number",typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l),typeof s=="number"&&(r.minimum=s,typeof l=="number"&&t.target!=="draft-04"&&(l>=s?delete r.minimum:delete r.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u),typeof a=="number"&&(r.maximum=a,typeof u=="number"&&t.target!=="draft-04"&&(u<=a?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},xa=(e,t,o,n)=>{o.type="boolean"},Dh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Sh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Na=(e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},Ah=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Th=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},$a=(e,t,o,n)=>{o.not={}},Ph=(e,t,o,n)=>{},Ra=(e,t,o,n)=>{},Eh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},za=(e,t,o,n)=>{const r=e._zod.def,s=la(r.entries);s.every(a=>typeof a=="number")&&(o.type="number"),s.every(a=>typeof a=="string")&&(o.type="string"),o.enum=s},Fa=(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},Ch=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Oh=(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},xh=(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(u=>({contentMediaType:u}))):Object.assign(r,s)},Nh=(e,t,o,n)=>{o.type="boolean"},Ba=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},$h=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},ja=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Rh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},zh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Ua=(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=M(s.element,t,{...n,path:[...n.path,"items"]})},qa=(e,t,o,n)=>{var u;const r=o,s=e._zod.def;r.type="object",r.properties={};const a=s.shape;for(const l in a)r.properties[l]=M(a[l],t,{...n,path:[...n.path,"properties",l]});const i=new Set(Object.keys(a)),c=new Set([...i].filter(l=>{const d=s.shape[l]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(r.required=Array.from(c)),((u=s.catchall)==null?void 0:u._zod.def.type)==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=M(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Ma=(e,t,o,n)=>{const r=e._zod.def,s=r.inclusive===!1,a=r.options.map((i,c)=>M(i,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?o.oneOf=a:o.anyOf=a},La=(e,t,o,n)=>{const r=e._zod.def,s=M(r.left,t,{...n,path:[...n.path,"allOf",0]}),a=M(r.right,t,{...n,path:[...n.path,"allOf",1]}),i=u=>"allOf"in u&&Object.keys(u).length===1,c=[...i(s)?s.allOf:[s],...i(a)?a.allOf:[a]];o.allOf=c},Fh=(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)=>M(f,t,{...n,path:[...n.path,a,h]})),u=s.rest?M(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,u&&(r.items=u)):t.target==="openapi-3.0"?(r.items={anyOf:c},u&&r.items.anyOf.push(u),r.minItems=c.length,u||(r.maxItems=c.length)):(r.items=c,u&&(r.additionalItems=u));const{minimum:l,maximum:d}=e._zod.bag;typeof l=="number"&&(r.minItems=l),typeof d=="number"&&(r.maxItems=d)},Za=(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 l=M(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const d of c)r.patternProperties[d.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=M(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=M(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const u=a._zod.values;if(u){const l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(r.required=l)}},Ha=(e,t,o,n)=>{const r=e._zod.def,s=M(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"}]},Va=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Ya=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},Ga=(e,t,o,n)=>{const r=e._zod.def;M(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)))},Ja=(e,t,o,n)=>{const r=e._zod.def;M(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},Wa=(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;M(s,t,n);const a=t.seen.get(e);a.ref=s},Ka=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.readOnly=!0},Bh=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},zn=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},jh=(e,t,o,n)=>{const r=e._zod.innerType;M(r,t,n);const s=t.seen.get(e);s.ref=r},Or={string:Ca,number:Oa,boolean:xa,bigint:Dh,symbol:Sh,null:Na,undefined:Ah,void:Th,never:$a,any:Ph,unknown:Ra,date:Eh,enum:za,literal:Fa,nan:Ch,template_literal:Oh,file:xh,success:Nh,custom:Ba,function:$h,transform:ja,map:Rh,set:zh,array:Ua,object:qa,union:Ma,intersection:La,tuple:Fh,record:Za,nullable:Ha,nonoptional:Va,default:Ya,prefault:Ga,catch:Ja,pipe:Wa,readonly:Ka,promise:Bh,optional:zn,lazy:jh};function Uh(e,t){if("_idmap"in e){const n=e,r=po({...t,processors:Or}),s={};for(const c of n._idmap.entries()){const[u,l]=c;M(l,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[u,l]=c;fo(r,l),a[u]=ho(r,l)}if(Object.keys(s).length>0){const c=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:s}}return{schemas:a}}const o=po({...t,processors:Or});return M(e,o),fo(o,e),ho(o,e)}const qh=y("ZodISODateTime",(e,t)=>{Lp.init(e,t),Y.init(e,t)});function Mh(e){return Kf(qh,e)}const Lh=y("ZodISODate",(e,t)=>{Zp.init(e,t),Y.init(e,t)});function Zh(e){return Qf(Lh,e)}const Hh=y("ZodISOTime",(e,t)=>{Hp.init(e,t),Y.init(e,t)});function Vh(e){return Xf(Hh,e)}const Yh=y("ZodISODuration",(e,t)=>{Vp.init(e,t),Y.init(e,t)});function Gh(e){return eh(Yh,e)}const Qa=(e,t)=>{ha.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>Rd(e,o)},flatten:{value:o=>$d(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,Ho,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,Ho,2)}},isEmpty:{get(){return e.issues.length===0}}})},Jh=y("ZodError",Qa),se=y("ZodError",Qa,{Parent:Error}),Wh=Nn(se),Kh=$n(se),Qh=Io(se),Xh=Do(se),em=Bd(se),tm=jd(se),om=Ud(se),nm=qd(se),rm=Md(se),sm=Ld(se),am=Zd(se),im=Hd(se),V=y("ZodType",(e,t)=>(Z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:mo(e,"input"),output:mo(e,"output")}}),e.toJSONSchema=vh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...o)=>e.clone(Oe(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)=>xe(e,o,n),e.brand=()=>e,e.register=(o,n)=>(o.add(e,n),e),e.parse=(o,n)=>Wh(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>Qh(e,o,n),e.parseAsync=async(o,n)=>Kh(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>Xh(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>em(e,o,n),e.decode=(o,n)=>tm(e,o,n),e.encodeAsync=async(o,n)=>om(e,o,n),e.decodeAsync=async(o,n)=>nm(e,o,n),e.safeEncode=(o,n)=>rm(e,o,n),e.safeDecode=(o,n)=>sm(e,o,n),e.safeEncodeAsync=async(o,n)=>am(e,o,n),e.safeDecodeAsync=async(o,n)=>im(e,o,n),e.refine=(o,n)=>e.check(og(o,n)),e.superRefine=o=>e.check(ng(o)),e.overwrite=o=>e.check(ht(o)),e.optional=()=>$r(e),e.exactOptional=()=>Lm(e),e.nullable=()=>Rr(e),e.nullish=()=>$r(Rr(e)),e.nonoptional=o=>Jm(e,o),e.array=()=>z(e),e.or=o=>st([e,o]),e.and=o=>Fm(e,o),e.transform=o=>zr(e,qm(o)),e.default=o=>Vm(e,o),e.prefault=o=>Gm(e,o),e.catch=o=>Km(e,o),e.pipe=o=>zr(e,o),e.readonly=()=>eg(e),e.describe=o=>{const n=e.clone();return _t.add(n,{description:o}),n},Object.defineProperty(e,"description",{get(){var o;return(o=_t.get(e))==null?void 0:o.description},configurable:!0}),e.meta=(...o)=>{if(o.length===0)return _t.get(e);const n=e.clone();return _t.add(n,o[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=o=>o(e),e)),Xa=y("_ZodString",(e,t)=>{Rn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Ca(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(ih(...n)),e.includes=(...n)=>e.check(lh(...n)),e.startsWith=(...n)=>e.check(dh(...n)),e.endsWith=(...n)=>e.check(ph(...n)),e.min=(...n)=>e.check(lo(...n)),e.max=(...n)=>e.check(Pa(...n)),e.length=(...n)=>e.check(Ea(...n)),e.nonempty=(...n)=>e.check(lo(1,...n)),e.lowercase=n=>e.check(ch(n)),e.uppercase=n=>e.check(uh(n)),e.trim=()=>e.check(hh()),e.normalize=(...n)=>e.check(fh(...n)),e.toLowerCase=()=>e.check(mh()),e.toUpperCase=()=>e.check(gh()),e.slugify=()=>e.check(yh())}),cm=y("ZodString",(e,t)=>{Rn.init(e,t),Xa.init(e,t),e.email=o=>e.check(Cf(um,o)),e.url=o=>e.check(Rf(lm,o)),e.jwt=o=>e.check(Wf(Sm,o)),e.emoji=o=>e.check(zf(dm,o)),e.guid=o=>e.check(Tr(xr,o)),e.uuid=o=>e.check(Of(Jt,o)),e.uuidv4=o=>e.check(xf(Jt,o)),e.uuidv6=o=>e.check(Nf(Jt,o)),e.uuidv7=o=>e.check($f(Jt,o)),e.nanoid=o=>e.check(Ff(pm,o)),e.guid=o=>e.check(Tr(xr,o)),e.cuid=o=>e.check(Bf(fm,o)),e.cuid2=o=>e.check(jf(hm,o)),e.ulid=o=>e.check(Uf(mm,o)),e.base64=o=>e.check(Yf(vm,o)),e.base64url=o=>e.check(Gf(Im,o)),e.xid=o=>e.check(qf(gm,o)),e.ksuid=o=>e.check(Mf(ym,o)),e.ipv4=o=>e.check(Lf(bm,o)),e.ipv6=o=>e.check(Zf(km,o)),e.cidrv4=o=>e.check(Hf(wm,o)),e.cidrv6=o=>e.check(Vf(_m,o)),e.e164=o=>e.check(Jf(Dm,o)),e.datetime=o=>e.check(Mh(o)),e.date=o=>e.check(Zh(o)),e.time=o=>e.check(Vh(o)),e.duration=o=>e.check(Gh(o))});function p(e){return Ef(cm,e)}const Y=y("ZodStringFormat",(e,t)=>{H.init(e,t),Xa.init(e,t)}),um=y("ZodEmail",(e,t)=>{$p.init(e,t),Y.init(e,t)}),xr=y("ZodGUID",(e,t)=>{xp.init(e,t),Y.init(e,t)}),Jt=y("ZodUUID",(e,t)=>{Np.init(e,t),Y.init(e,t)}),lm=y("ZodURL",(e,t)=>{Rp.init(e,t),Y.init(e,t)}),dm=y("ZodEmoji",(e,t)=>{zp.init(e,t),Y.init(e,t)}),pm=y("ZodNanoID",(e,t)=>{Fp.init(e,t),Y.init(e,t)}),fm=y("ZodCUID",(e,t)=>{Bp.init(e,t),Y.init(e,t)}),hm=y("ZodCUID2",(e,t)=>{jp.init(e,t),Y.init(e,t)}),mm=y("ZodULID",(e,t)=>{Up.init(e,t),Y.init(e,t)}),gm=y("ZodXID",(e,t)=>{qp.init(e,t),Y.init(e,t)}),ym=y("ZodKSUID",(e,t)=>{Mp.init(e,t),Y.init(e,t)}),bm=y("ZodIPv4",(e,t)=>{Yp.init(e,t),Y.init(e,t)}),km=y("ZodIPv6",(e,t)=>{Gp.init(e,t),Y.init(e,t)}),wm=y("ZodCIDRv4",(e,t)=>{Jp.init(e,t),Y.init(e,t)}),_m=y("ZodCIDRv6",(e,t)=>{Wp.init(e,t),Y.init(e,t)}),vm=y("ZodBase64",(e,t)=>{Kp.init(e,t),Y.init(e,t)}),Im=y("ZodBase64URL",(e,t)=>{Xp.init(e,t),Y.init(e,t)}),Dm=y("ZodE164",(e,t)=>{ef.init(e,t),Y.init(e,t)}),Sm=y("ZodJWT",(e,t)=>{of.init(e,t),Y.init(e,t)}),ei=y("ZodNumber",(e,t)=>{Da.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Oa(e,n,r),e.gt=(n,r)=>e.check(Er(n,r)),e.gte=(n,r)=>e.check(Ro(n,r)),e.min=(n,r)=>e.check(Ro(n,r)),e.lt=(n,r)=>e.check(Pr(n,r)),e.lte=(n,r)=>e.check($o(n,r)),e.max=(n,r)=>e.check($o(n,r)),e.int=n=>e.check(Nr(n)),e.safe=n=>e.check(Nr(n)),e.positive=n=>e.check(Er(0,n)),e.nonnegative=n=>e.check(Ro(0,n)),e.negative=n=>e.check(Pr(0,n)),e.nonpositive=n=>e.check($o(0,n)),e.multipleOf=(n,r)=>e.check(Cr(n,r)),e.step=(n,r)=>e.check(Cr(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 O(e){return th(ei,e)}const Am=y("ZodNumberFormat",(e,t)=>{nf.init(e,t),ei.init(e,t)});function Nr(e){return oh(Am,e)}const Tm=y("ZodBoolean",(e,t)=>{rf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>xa(e,o,n)});function L(e){return nh(Tm,e)}const Pm=y("ZodNull",(e,t)=>{sf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Na(e,o,n)});function Em(e){return rh(Pm,e)}const Cm=y("ZodUnknown",(e,t)=>{af.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ra()});function Yo(){return sh(Cm)}const Om=y("ZodNever",(e,t)=>{cf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>$a(e,o,n)});function xm(e){return ah(Om,e)}const Nm=y("ZodArray",(e,t)=>{uf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ua(e,o,n,r),e.element=t.element,e.min=(o,n)=>e.check(lo(o,n)),e.nonempty=o=>e.check(lo(1,o)),e.max=(o,n)=>e.check(Pa(o,n)),e.length=(o,n)=>e.check(Ea(o,n)),e.unwrap=()=>e.element});function z(e,t){return bh(Nm,e,t)}const $m=y("ZodObject",(e,t)=>{df.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>qa(e,o,n,r),U(e,"shape",()=>t.shape),e.keyof=()=>R(Object.keys(e._zod.def.shape)),e.catchall=o=>e.clone({...e._zod.def,catchall:o}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Yo()}),e.loose=()=>e.clone({...e._zod.def,catchall:Yo()}),e.strict=()=>e.clone({...e._zod.def,catchall:xm()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=o=>Ed(e,o),e.safeExtend=o=>Cd(e,o),e.merge=o=>Od(e,o),e.pick=o=>Td(e,o),e.omit=o=>Pd(e,o),e.partial=(...o)=>xd(ti,e,o[0]),e.required=(...o)=>Nd(oi,e,o[0])});function b(e,t){const o={type:"object",shape:e??{},...D(t)};return new $m(o)}const Rm=y("ZodUnion",(e,t)=>{pf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ma(e,o,n,r),e.options=t.options});function st(e,t){return new Rm({type:"union",options:e,...D(t)})}const zm=y("ZodIntersection",(e,t)=>{ff.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>La(e,o,n,r)});function Fm(e,t){return new zm({type:"intersection",left:e,right:t})}const Bm=y("ZodRecord",(e,t)=>{hf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Za(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function at(e,t,o){return new Bm({type:"record",keyType:e,valueType:t,...D(o)})}const Go=y("ZodEnum",(e,t)=>{mf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,r,s)=>za(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 Go({...t,checks:[],...D(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 Go({...t,checks:[],...D(r),entries:s})}});function R(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Go({type:"enum",entries:o,...D(t)})}const jm=y("ZodLiteral",(e,t)=>{gf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Fa(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 _(e,t){return new jm({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}const Um=y("ZodTransform",(e,t)=>{yf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ja(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new ca(e.constructor.name);o.addIssue=s=>{if(typeof s=="string")o.issues.push(Rt(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(Rt(a))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(s=>(o.value=s,o)):(o.value=r,o)}});function qm(e){return new Um({type:"transform",transform:e})}const ti=y("ZodOptional",(e,t)=>{Ta.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>zn(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function $r(e){return new ti({type:"optional",innerType:e})}const Mm=y("ZodExactOptional",(e,t)=>{bf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>zn(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Lm(e){return new Mm({type:"optional",innerType:e})}const Zm=y("ZodNullable",(e,t)=>{kf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ha(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Rr(e){return new Zm({type:"nullable",innerType:e})}const Hm=y("ZodDefault",(e,t)=>{wf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ya(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Vm(e,t){return new Hm({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():pa(t)}})}const Ym=y("ZodPrefault",(e,t)=>{_f.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ga(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Gm(e,t){return new Ym({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():pa(t)}})}const oi=y("ZodNonOptional",(e,t)=>{vf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Va(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Jm(e,t){return new oi({type:"nonoptional",innerType:e,...D(t)})}const Wm=y("ZodCatch",(e,t)=>{If.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ja(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Km(e,t){return new Wm({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Qm=y("ZodPipe",(e,t)=>{Df.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Wa(e,o,n,r),e.in=t.in,e.out=t.out});function zr(e,t){return new Qm({type:"pipe",in:e,out:t})}const Xm=y("ZodReadonly",(e,t)=>{Sf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ka(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function eg(e){return new Xm({type:"readonly",innerType:e})}const tg=y("ZodCustom",(e,t)=>{Af.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ba(e,o)});function og(e,t={}){return kh(tg,e,t)}function ng(e){return wh(e)}const N={custom:"custom"},rg=b({name:p().optional(),closed:L().optional(),refCreateSavePath:p().optional(),createDocNameTemplate:p().optional(),dailyNoteSavePath:p().optional(),dailyNoteTemplatePath:p().optional()}),ni=b({id:p().optional(),notebook:p().optional(),path:p().optional()}),sg=ni.superRefine((e,t)=>{const o=typeof e.id=="string",n=typeof e.notebook=="string"||typeof e.path=="string";if(o===n){t.addIssue({code:N.custom,message:"Provide either id or notebook + path."});return}n&&(!e.notebook||!e.path)&&t.addIssue({code:N.custom,message:"Both notebook and path are required when id is not provided."})}),ag=b({fromPaths:z(p()).optional(),toNotebook:p().optional(),toPath:p().optional(),fromIDs:z(p()).optional(),toID:p().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:N.custom,message:"Provide either fromPaths + toNotebook + toPath or fromIDs + toID."});return}o&&(!e.fromPaths||!e.toNotebook||!e.toPath)&&t.addIssue({code:N.custom,message:"fromPaths, toNotebook, and toPath are required for path-based moves."}),n&&(!e.fromIDs||!e.toID)&&t.addIssue({code:N.custom,message:"fromIDs and toID are required for ID-based moves."})}),ig=R(mn),cg=R(gn),ug=R(yn),lg=R(bn),dg=R(kn),pg=R(wn),fg=R(Dn),hg=R(Sn),mg=R(An),ri=b({action:_("ls"),path:p().describe("Human-readable workspace path, such as /Notebook/Folder or / for notebook roots")}),si=b({action:_("tree"),path:p().describe("Human-readable workspace path, such as /Notebook/Folder or / for all readable notebooks"),maxDepth:O().int().min(0).max(20).optional().describe("Max tree depth to return (default 3)")}),ai=b({action:_("read"),path:p().describe("Human-readable document path"),page:O().int().min(1).optional().describe("Page number for markdown pagination (1-based)"),pageSize:O().int().min(1).max(2e4).optional().describe("Characters per page for markdown pagination (default 8000)")}),ii=b({action:_("write"),path:p().describe("Human-readable document path"),markdown:p().describe("Markdown content to create or write"),overwrite:L().optional().describe("When true, replace an existing document body while keeping the document node and title")}),go=b({old:p().min(1).describe("Original text to match exactly. Supports multi-line strings."),new:p().describe("Replacement text. Supports multi-line strings."),replace_all:L().optional().describe("When true, replace every exact match. Defaults to false.")}),ci=b({action:_("replace"),path:p().describe("Human-readable document path to modify"),edit:st([go,z(go).min(1)]).describe("One replacement edit or an array of edits to apply sequentially within the same document")}),ui=b({action:_("rm"),path:p().describe("Human-readable document path to delete")}),li=b({action:_("mv"),from:p().describe("Human-readable source document path"),to:p().describe("Human-readable destination document path")}),di=b({action:_("search"),path:p().describe("Human-readable document or folder path to search within"),query:p().describe("Text or regular expression to search for"),regex:L().optional().describe("Treat query as a JavaScript regular expression"),caseSensitive:L().optional().describe("Use case-sensitive matching"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).max(200).optional().describe("Matches per page, default 50")}),pi=b({action:_("list")}),fi=b({action:_("create"),name:p().describe("Notebook name"),icon:p().optional().describe("Optional notebook icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}),hi=b({action:_("set_open_state"),notebook:p().describe("Notebook ID"),opened:L().describe("true to open, false to close")}),mi=b({action:_("remove"),notebook:p().describe("Notebook ID")}),gi=b({action:_("rename"),notebook:p().describe("Notebook ID"),name:p().describe("New notebook name")}),yi=b({action:_("get_conf"),notebook:p().describe("Notebook ID")}),bi=b({action:_("set_conf"),notebook:p().describe("Notebook ID"),conf:rg.describe("Notebook configuration")}),ki=b({action:_("set_icon"),notebook:p().describe("Notebook ID"),icon:p().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.")}),wi=b({action:_("get_permissions"),notebook:p().optional().describe('Notebook ID, or "all" to return every notebook permission entry. Omit to return all notebooks.')}),_i=b({action:_("set_permission"),notebook:p().describe("Notebook ID"),permission:R(["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')}),vi=b({action:_("get_child_docs"),notebook:p().describe("Notebook ID"),page:O().int().positive().optional().describe("Page number (1-based), default 1"),pageSize:O().int().positive().optional().describe("Rows per page, default 50")}),Ii=b({action:_("create"),notebook:p().describe("Notebook ID"),path:p().optional().describe("Human-readable target path, must start with / (e.g., /foo/bar). Parent paths must already exist."),parentPath:p().optional().describe("Parent human-readable path or storage path ending in .sy for title-based creation, must start with /"),title:p().optional().describe("Document title when creating under parentPath"),markdown:p().optional().describe("Markdown content, defaults to empty"),sorts:z(p()).optional().describe("Compatibility option retained for older callers; title-based creation now uses the reliable path flow"),icon:p().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:N.custom,message:"Provide either path, or parentPath + title, not both.",path:["path"]});return}!o&&(!e.parentPath||!e.title)&&t.addIssue({code:N.custom,message:"Provide path, or provide both parentPath and title.",path:["path"]})}),gg=R(["id","ids","path","hpath","docInfo"]),Di=b({action:_("lookup"),id:p().optional().describe("Document ID to look up"),notebook:p().optional().describe("Notebook ID, required with path or hpath"),path:p().optional().describe("Storage path to look up when notebook is provided, e.g. /20240318112233-abc123.sy. Human-readable paths should use hpath instead."),hpath:p().optional().describe("Human-readable path to look up when notebook is provided"),hPath:p().optional().describe("Alias for hpath"),include:z(gg).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:N.custom,message:"Provide exactly one source: id, notebook + path, or notebook + hpath.",path:["id"]}),!e.id&&!e.notebook&&t.addIssue({code:N.custom,message:"notebook is required when resolving path or hpath.",path:["notebook"]})}),Si=b({action:_("rename"),title:p().describe("New document title")}).and(sg),Ai=b({action:_("remove"),ids:z(p()).min(1).optional().describe("One or more document IDs to remove"),paths:z(p()).min(1).optional().describe("One or more storage paths to remove in batch")}).and(ni).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:N.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:N.custom,message:"Both notebook and path are required for path-based remove."})}),Ti=b({action:_("move")}).and(ag),Pi=b({action:_("get_child_blocks"),id:p().describe("Document ID")}),Ei=b({action:_("get_child_docs"),id:p().describe("Document ID")}),Ci=b({action:_("set_attr"),id:p().describe("Document ID"),attrs:b({icon:p().optional().describe("Icon value. Prefer a Unicode hex code string such as '1f4d4'."),cover:st([p(),Em()]).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:N.custom,message:"Provide at least one of attrs.icon or attrs.cover.",path:["attrs"]})}),Oi=b({action:_("list_tree"),notebook:p().describe("Notebook ID"),path:p().describe("Storage path or / for the notebook root"),maxDepth:O().optional().describe("Max tree depth to return (default 3). Deeper nodes are collapsed to childCount.")}),xi=b({action:_("search_docs"),notebook:p().describe("Notebook ID"),query:p().describe("Keyword to search in document titles"),path:p().optional().describe("Optional storage path to narrow the search scope after permission filtering")}),Ni=b({action:_("get_doc"),id:p().describe("Document ID"),mode:R(["markdown","html"]).optional().describe('Return mode: "markdown" (default) or "html"'),size:O().optional().describe("Optional maximum content size hint"),page:O().int().min(1).optional().describe("Page number for markdown pagination (1-based)"),pageSize:O().int().min(1).max(2e4).optional().describe("Characters per page for markdown pagination (default 8000)")}),$i=b({action:_("create_daily_note"),notebook:p().describe("Notebook ID"),app:p().optional().describe("Optional app identifier passed through to SiYuan")}),Ri=b({action:_("duplicate"),id:p().describe("Source document ID")}),zi=b({action:_("heading_to_doc"),headingID:p().describe("Heading block ID to convert into a document"),targetNotebook:p().describe("Target notebook ID"),targetPath:p().optional().describe("Optional target storage path"),previousPath:p().optional().describe("Optional previous sibling storage path")}),Fi=b({action:_("doc_to_heading"),srcID:p().describe("Source document ID"),targetID:p().describe("Target document or heading block ID"),after:L().optional().describe("When true, insert after the target heading instead of before it")}),Bi=b({action:_("get_balance")}),ji=b({action:_("shop")}),Ui=b({action:_("buy"),item_id:p().describe('Stable shop item ID returned by mascot(action="shop")')}),qi=b({action:_("submit"),description:p().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:p().trim().max(1e3).optional().describe("Optional one- or two-sentence impact summary, such as affected workflow, error risk, confusion, or inconvenience."),suggestion:p().trim().max(1e3).optional().describe("Optional direct improvement suggestion; keep it focused and avoid repeating the full description."),agent:p().trim().max(200).optional().describe("Optional Agent product and model name, such as Claude Desktop / Claude Sonnet 4.5. Defaults to 无."),source:p().trim().max(100).optional().describe("Internal source label. Defaults to the current runtime transport.")}),yg=R(["all","deck","notebook","tree"]),bg=R(["due","new","old"]),Mi=b({action:_("list_cards"),scope:yg.describe('Query scope: "all", "deck", "notebook", or "tree"'),filter:bg.describe('Filter returned cards: "due", "new", or "old"'),deckID:p().optional().describe('Deck ID, required when scope=deck. For scope="all", omit deckID; an empty string is treated as omitted.'),notebook:p().optional().describe("Notebook ID, required when scope=notebook"),rootID:p().optional().describe("Root document/block ID, required when scope=tree"),reviewedCards:z(b({cardID:p().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:N.custom,message:'scope="all" does not accept deckID, notebook, or rootID.'}),e.scope==="deck"&&!o&&t.addIssue({code:N.custom,path:["deckID"],message:'deckID is required when scope="deck".'}),e.scope==="notebook"&&!n&&t.addIssue({code:N.custom,path:["notebook"],message:'notebook is required when scope="notebook".'}),e.scope==="tree"&&!r&&t.addIssue({code:N.custom,path:["rootID"],message:'rootID is required when scope="tree".'})}),Li=b({action:_("get_decks")}),Zi=b({action:_("review_card"),deckID:p().describe("Deck ID"),cardID:p().describe("Card ID"),rating:O().optional().describe("Review rating passed through to the kernel"),skip:L().optional().describe("When true, skip the current card instead of submitting a rating"),reviewedCards:z(b({cardID:p().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:N.custom,message:"rating is required unless skip=true.",path:["rating"]})}),Hi=b({action:_("create_card"),deckID:p().describe("Deck ID"),blockIDs:z(p()).min(1).describe("Existing block IDs to turn into flashcards"),mode:R(["full","attach"]).optional().describe("Compatibility option. SiYuan addRiffCards writes deck attrs and registers cards in both modes.")}),Vi=b({action:_("remove_card"),deckID:p().describe("Deck ID"),blockIDs:z(p()).min(1).describe("Existing block IDs to remove from flashcards")}),Yi=b({action:_("get_cards"),deckID:p().describe("Deck ID (use empty string to query across all decks)"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).max(512).optional().describe("Cards per page, default 32")}),Gi=b({action:_("insert"),dataType:R(["markdown","dom"]).optional().describe("Data format"),data:p().optional().describe("Block content"),nextID:p().optional().describe("Next block ID"),previousID:p().optional().describe("Previous block ID"),parentID:p().optional().describe("Parent block or document ID"),blocks:z(b({dataType:R(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),nextID:p().optional().describe("Next block ID"),previousID:p().optional().describe("Previous block ID"),parentID:p().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:N.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:N.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:N.custom,message:"dataType is required for single insert.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:N.custom,message:"data is required for single insert.",path:["data"]})}),Ji=b({action:_("prepend"),dataType:R(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),parentID:p().describe("Parent block or document ID")}),Wi=b({action:_("append"),dataType:R(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),parentID:p().describe("Parent block or document ID")}),Ki=b({action:_("update"),dataType:R(["markdown","dom"]).optional().describe("Data format"),data:p().optional().describe("New block content"),id:p().optional().describe("Block ID"),items:z(b({id:p().describe("Block ID"),dataType:R(["markdown","dom"]).describe("Data format"),data:p().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:N.custom,message:"Provide either items or single update fields, not both.",path:["items"]});return}e.id||t.addIssue({code:N.custom,message:"id is required for single update.",path:["id"]}),e.dataType||t.addIssue({code:N.custom,message:"dataType is required for single update.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:N.custom,message:"data is required for single update.",path:["data"]})}),Qi=b({action:_("replace"),id:p().describe("Block ID"),edit:st([go,z(go).min(1)]).describe("One replacement edit or an array of edits to apply sequentially within the same block kramdown")}),Xi=b({action:_("delete"),id:p().describe("Block ID")}),ec=b({action:_("move"),id:p().describe("Block ID"),previousID:p().optional().describe("Previous block ID"),parentID:p().optional().describe("New parent block ID")}).superRefine((e,t)=>{!e.previousID&&!e.parentID&&t.addIssue({code:N.custom,message:"Provide previousID, parentID, or both to describe the destination.",path:["previousID"]})}),tc=b({action:_("set_fold_state"),id:p().describe("Foldable block ID"),folded:L().describe("true to fold, false to unfold")}),oc=b({action:_("get_kramdown"),id:p().describe("Block ID or document ID")}),nc=b({action:_("get_children"),id:p().describe("Block ID or document ID"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).max(200).optional().describe("Items per page, default 50")}),rc=b({action:_("transfer_references"),fromID:p().describe("Source block ID"),toID:p().describe("Target block ID"),refIDs:z(p()).optional().describe("Reference block IDs")}),sc=b({action:_("set_attrs"),id:p().describe("Block ID"),attrs:at(p(),p()).describe("Block attributes")}),ac=b({action:_("get_attrs"),id:p().describe("Block ID")}),ic=b({action:_("info"),id:p().describe("Block ID")}),cc=b({action:_("breadcrumb"),id:p().describe("Block ID"),excludeTypes:z(p()).optional().describe("Optional block types to exclude from the breadcrumb")}),uc=b({action:_("dom"),id:p().describe("Block ID")}),lc=b({action:_("recent_updated"),count:O().optional().describe("Maximum number of recent readable blocks to return after permission filtering")}),dc=b({action:_("word_count"),ids:z(p()).describe("One or more block IDs")}),pc=b({action:_("add_to_daily_note"),notebook:p().describe("Notebook ID"),dataType:R(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),position:R(["append","prepend"]).describe("Where to add content in today's daily note")}),fc=b({action:_("docs_info"),id:p().optional().describe("Single document/block ID"),ids:z(p()).min(1).optional().describe("Document IDs"),refCount:L().optional().describe("When true, include reference counts"),av:L().optional().describe("When true, include AV metadata")}).superRefine((e,t)=>{(e.id&&e.ids||!e.id&&!e.ids)&&t.addIssue({code:N.custom,message:"Provide exactly one of id or ids.",path:["ids"]})}),kg=R(["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"]),wg=b({type:R(["image","file"]).describe("Asset entry type"),content:p().describe("Asset path stored by SiYuan, e.g. assets/foo.png"),name:p().optional().describe("Optional display name")}),hc=b({valueType:kg.describe("Cell value type"),text:p().optional().describe("Text value for valueType=text"),number:O().optional().describe("Number value for valueType=number"),numberFormat:p().optional().describe("Optional number format such as commas, percent, USD, or CNY"),date:st([p(),O()]).optional().describe("Date/time value as ISO text or epoch milliseconds for valueType=date"),endDate:st([p(),O()]).optional().describe("Optional end date as ISO text or epoch milliseconds for ranged dates"),includeTime:L().optional().describe("When false, store the date without a time component"),checked:L().optional().describe("Checkbox state for valueType=checkbox"),option:p().optional().describe("Selected option label for valueType=select"),options:z(p()).optional().describe("Selected option labels for valueType=multi_select"),relationBlockIDs:z(p()).optional().describe("Related block IDs for valueType=relation"),url:p().optional().describe("URL value for valueType=url"),email:p().optional().describe("Email value for valueType=email"),phone:p().optional().describe("Phone value for valueType=phone"),assets:z(wg).optional().describe("Asset entries for valueType=mAsset")}),mc=hc.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:N.custom,message:`${String(n)} is required when valueType="${e.valueType}".`,path:[n]})}),Fr=b({rowID:p().describe("Row item ID"),columnID:p().describe("Column key ID")}).and(mc),gc=b({action:_("get"),id:p().describe("Attribute view ID"),blockID:p().optional().describe("Optional database block ID for exact context or fallback permission resolution")}),yc=b({action:_("render"),id:p().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:p().optional().describe("Optional database block ID; required when creating a new AV"),viewID:p().optional().describe("Optional target view ID"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().optional().describe("Rows per page; use -1 or omit for kernel default"),query:p().optional().describe("Optional row query filter"),groupPaging:at(p(),Yo()).optional().describe("Optional group paging map passed through to SiYuan"),createIfNotExist:L().optional().describe("Create the default view only when explicitly true; provide blockID when creating a new AV")}),bc=b({action:_("get_attribute_view_keys"),id:p().describe("Attribute view ID")}),kc=b({action:_("get_attribute_view_filter_sort"),id:p().describe("Attribute view ID"),blockID:p().optional().describe("Database block ID (optional)")}),wc=b({action:_("search"),keyword:p().describe("Keyword to search in attribute view names"),excludes:z(p()).optional().describe("Optional AV IDs to exclude")}),_c=b({action:_("add_rows"),avID:p().describe("Attribute view ID"),blockIDs:z(p()).optional().describe("Existing block IDs to add as bound rows"),primaryKeyTexts:z(p()).optional().describe("Plain-text primary key values to add as detached rows"),blockID:p().optional().describe("Optional database block ID used to pin a specific database-block view context"),viewID:p().optional().describe("Optional target view ID"),groupID:p().optional().describe("Optional target group ID"),previousID:p().optional().describe("Optional previous row item ID"),ignoreDefaultFill:L().optional().describe("When true, skip view/group default value filling")}),vc=b({action:_("remove_rows"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),srcIDs:z(p()).min(1).describe("Bound row block/item IDs to remove")}),Ic=b({action:_("add_column"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),keyID:p().optional().describe("Optional new column key ID; MCP generates one when omitted"),keyName:p().describe("New column name"),keyType:R(["text","number","date","select","mSelect","url","email","phone","mAsset","template","created","updated","checkbox","relation","rollup","lineNumber"]).describe("Column type"),keyIcon:p().optional().describe("Optional column icon"),previousKeyID:p().optional().describe("Insert after this existing column key ID")}),Dc=b({action:_("remove_column"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),keyID:p().optional().describe("Column key ID"),columnID:p().optional().describe("Alias of keyID"),removeRelationDest:L().optional().describe("Also remove reverse relation metadata when deleting a relation column")}).superRefine((e,t)=>{!e.keyID&&!e.columnID&&t.addIssue({code:N.custom,message:"Provide keyID or columnID.",path:["keyID"]})}),Sc=b({action:_("set_cells"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),cells:z(Fr).min(1).optional().describe("Cell updates"),items:z(Fr).min(1).optional().describe("Alias for cells"),rowID:p().optional().describe("Single-cell row item ID"),columnID:p().optional().describe("Single-cell column key ID")}).and(hc.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:N.custom,message:"Provide either cells/items or single-cell fields, not both.",path:["cells"]});return}if(!n){if(e.rowID||t.addIssue({code:N.custom,message:"rowID is required for single-cell set_cells calls.",path:["rowID"]}),e.columnID||t.addIssue({code:N.custom,message:"columnID is required for single-cell set_cells calls.",path:["columnID"]}),!e.valueType){t.addIssue({code:N.custom,message:"valueType is required for single-cell set_cells calls.",path:["valueType"]});return}const s=mc.safeParse(e);if(!s.success)for(const a of s.error.issues)t.addIssue({code:N.custom,message:a.message,path:a.path})}}),Ac=b({action:_("duplicate"),avID:p().describe("Source attribute view ID"),blockID:p().optional().describe("Optional source database block ID used as exact context and default insertion target"),previousID:p().optional().describe("Optional block ID to insert the duplicated mirror database block after")}),Tc=b({action:_("get_primary_key_values"),avID:p().describe("Attribute view ID"),keyword:p().optional().describe("Optional keyword filter for primary key values"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).optional().describe("Rows per page, default all")}),Pc=b({action:_("upload_asset"),assetsDirPath:p().describe("Asset directory path (e.g., /assets/)"),localFilePath:p().describe("Local file path to read and upload into the assets directory"),confirmLargeFile:L().optional().describe("Set to true only after the user explicitly confirms uploading a file larger than the configured safety threshold.")}),Ec=b({action:_("render"),engine:R(["template","sprig"]).describe("Template engine to use"),id:p().optional().describe("Document ID for template context"),path:p().optional().describe("Template file path inside the SiYuan workspace"),template:p().optional().describe("Sprig template content")}).superRefine((e,t)=>{e.engine==="template"&&(e.id||t.addIssue({code:N.custom,message:'id is required when engine="template".',path:["id"]}),e.path||t.addIssue({code:N.custom,message:'path is required when engine="template".',path:["path"]})),e.engine==="sprig"&&!e.template&&t.addIssue({code:N.custom,message:'template is required when engine="sprig".',path:["template"]})}),Cc=b({action:_("export_md"),id:p().describe("Document ID to export")}),Oc=b({action:_("export_resources"),paths:z(p()).describe("Paths to export"),name:p().optional().describe("Export file name"),outputPath:p().optional().describe("Optional local absolute or relative filesystem path to save the exported ZIP")}),xc=b({action:_("list_unused_assets")}),Nc=b({action:_("get_doc_assets"),id:p().describe("Document ID"),assetType:R(["all","image"]).optional().describe("Filter asset type: 'all' (default) returns all assets, 'image' returns only image assets.")}),$c=b({action:_("get_image_ocr_text"),path:p().optional().describe("Asset path; omit to receive an empty OCR text payload")}),Rc=b({action:_("remove_unused_assets")}),zc=b({action:_("rename_asset"),oldPath:p().describe("Existing asset path"),newName:p().describe("New asset file name")}),Fc=b({action:_("delete_asset"),path:p().describe("Asset path to delete")}),Bc=b({action:_("extract_doc"),id:p().describe("Document ID to extract"),outputDir:p().optional().describe("Output root directory. Defaults to ~/siyuan-extracted/ (resolved to absolute path).")}),_g=R(_n),Fn=R(["keyword","query","query_syntax","sql","regex"]),jc=R(["relevance","date","updated_desc","updated_asc","created_desc","created_asc","type"]),vg=R(["relevance","relevance_desc","relevance_asc","updated_asc","updated_desc"]),Uc=b({action:_("fulltext"),query:p().describe("Search query string"),method:O().optional().describe("Search method: 0=keyword (default), 1=query syntax, 2=SQL, 3=regex"),methodName:Fn.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:at(p(),L()).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:z(p()).optional().describe('Alternative shorthand type filter as array: ["h","p"]. Merged with types if both provided.'),paths:z(p()).optional().describe("Restrict search to specific notebook paths"),groupBy:O().optional().describe("0=no grouping (default), 1=group by document"),orderBy:O().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:jc.optional().describe('Semantic sort alias: "relevance", "date", "updated_desc", "updated_asc", "created_desc", "created_asc", or "type". Overrides orderBy if both provided.'),page:O().optional().describe("Page number (1-based), default 1"),pageSize:O().optional().describe("Results per page, default 32, max 128"),parentId:p().optional().describe("Post-filter results to blocks whose root_id or parent_id matches this ID, scoping search within a document subtree."),hasTags:L().optional().describe("When true, only return blocks that have tags. When false, only return blocks without tags."),stripHtml:L().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.")}),qc=b({action:_("query_sql"),stmt:p().optional().describe("SQL SELECT statement to execute against the blocks/spans/assets tables; returned rows are permission-filtered"),sql:p().optional().describe("Semantic alias for stmt. Overrides stmt when both are provided.")}).superRefine((e,t)=>{!e.stmt&&!e.sql&&t.addIssue({code:N.custom,message:"Provide stmt or sql.",path:["stmt"]})}),Mc=b({action:_("get_backlinks"),id:p().describe("Block or document ID to find backlinks for"),keyword:p().optional().describe("Filter backlinks by keyword"),refTreeID:p().optional().describe("Optional document tree ID to narrow backlink scope"),scopeRootId:p().optional().describe("Semantic alias for refTreeID. Overrides refTreeID when both are provided."),mode:R(["links","mentions","both"]).optional().describe('Result mode: "links", "mentions", or "both" (default).')}),Lc=b({action:_("search_refs"),id:p().describe("Referenced block or document ID"),rootID:p().optional().describe("Optional current root document ID"),k:p().optional().describe("Keyword filter"),beforeLen:O().int().min(0).optional().describe("Context length before the reference, default 512"),isSquareBrackets:L().optional().describe("Search in square-bracket reference mode"),isDatabase:L().optional().describe("Whether the reference target is a database"),reqId:p().optional().describe("Optional passthrough request ID")}),Zc=b({action:_("find_replace"),k:p().describe("Find keyword"),r:p().describe("Replacement text; use empty string to delete matches"),ids:z(p()).min(1).describe("Document or block IDs to mutate"),paths:z(p()).optional().describe("Optional path scope list"),types:at(p(),L()).optional().describe("Optional block type filter"),method:O().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Fn.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:O().optional().describe("Legacy numeric sort order"),sortBy:jc.optional().describe("Semantic sort alias that overrides orderBy when both are provided."),groupBy:O().optional().describe("Grouping mode"),replaceTypes:at(p(),L()).optional().describe("Replace target kinds such as text, code, docTitle, blockRef")}),Hc=b({action:_("search_assets"),k:p().optional().describe("Legacy asset filename keyword field"),query:p().optional().describe("Semantic alias for k. Overrides k when both are provided."),exts:z(p()).optional().describe("Optional extension filters")}).superRefine((e,t)=>{!e.k&&!e.query&&t.addIssue({code:N.custom,message:"Provide k or query.",path:["k"]})}),Vc=b({action:_("fulltext_asset_content"),query:p().optional().describe("Search query string"),assetId:p().optional().describe("Asset content ID for an exact content lookup"),queryMethod:O().optional().describe("Query method for assetId lookup: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),types:at(p(),L()).optional().describe("Asset type filter"),method:O().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Fn.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:O().optional().describe("Legacy numeric sort order: 0=relevance DESC, 1=relevance ASC, 2=updated ASC, 3=updated DESC"),sortBy:vg.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:O().int().min(1).optional().describe("Page number (1-based)"),pageSize:O().int().min(1).max(128).optional().describe("Results per page")}).superRefine((e,t)=>{!e.query&&!e.assetId&&t.addIssue({code:N.custom,message:"Provide query or assetId.",path:["query"]})}),Yc=b({action:_("list_invalid_refs"),page:O().int().min(1).optional().describe("Page number (1-based)"),pageSize:O().int().min(1).max(128).optional().describe("Results per page")}),Ig=R(vn),Gc=b({action:_("list"),keyword:p().optional().describe("Optional keyword used to search/filter tags"),query:p().optional().describe("Alias for keyword"),sort:O().optional().describe("Optional tag sort mode"),ignoreMaxListHint:L().optional().describe("Ignore the maximum list hint from SiYuan"),app:p().optional().describe("Optional app identifier passed through to SiYuan")}),Jc=b({action:_("rename"),oldLabel:p().describe("Existing tag label"),newLabel:p().describe("New tag label")}),Wc=b({action:_("remove"),label:p().describe("Tag label to remove")}),Dg=R(In),Kc=b({action:_("workspace_info")}),Qc=b({action:_("network")}),Xc=b({action:_("conf"),mode:R(["summary","get"]).optional().describe('Read mode: "summary" returns a navigable overview, "get" reads a specific key path'),keyPath:p().optional().describe('Dot/bracket path to a specific config field, e.g. "conf.appearance.mode" or "conf.langs[0]"'),maxDepth:O().int().min(0).max(5).optional().describe("Maximum object traversal depth for summary/get responses"),maxItems:O().int().min(1).max(100).optional().describe("Maximum keys/items to include per level")}),eu=b({action:_("notify"),msg:p().describe("Message content"),level:R(["info","error"]).describe("Notification level"),timeout:O().optional().describe("Display timeout in milliseconds")}),tu=b({action:_("get_version")}),ou=b({action:_("get_current_time")}),Sg=[{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 Bn(e){const t=e.message??"";for(const o of Sg)if(o.patterns.some(n=>n.test(t)))return{code:o.code,hint:o.hint};return null}function jn(e){var t;return e instanceof Error?((t=Bn(e))==null?void 0:t.code)==="block_not_found":!1}function Ag(e){return typeof e.description=="string"?e.description:null}function mt(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ao(e){return Array.isArray(e.required)?e.required.filter(t=>typeof t=="string"):[]}function Tg(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(Ao(i.schema));for(const[u,l]of Object.entries(mt(i.schema))){if(u==="action"||!l||typeof l!="object")continue;o[u]={...o[u],...l};const d=Ag(l);if(d){const k=n.get(u)??new Set;k.add(d),n.set(u,k)}const f=l.enum;if(Array.isArray(f)){const k=r.get(u)??new Set;for(const v of f)k.add(v);r.set(u,k)}const h=c.has(u)?s:a,m=h.get(u)??new Set;m.add(i.action),h.set(u,m)}}for(const[i,c]of Object.entries(o)){const u=n.get(i),l=t[i]??(u&&u.size>0?[...u].join(" / "):void 0),d=[...s.get(i)??[]].sort(),f=[...a.get(i)??[]].sort(),h=[...d.length>0?[`Required by: ${d.join(", ")}`]:[],...f.length>0?[`Optional in: ${f.join(", ")}`]:[]],m=h.length>0?`[${h.join("; ")}]`:"";c.description=l?m?`${l} ${m}`:l:m||void 0;const k=r.get(i);k&&k.size>0&&(c.enum=[...k])}return o}function $e(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return t.type==="array"&&(t.items=$e(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,$e(n)]))),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=$e(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(o=>$e(o))),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(o=>$e(o))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(o=>$e(o))),t}function Un(e){return $e(e)}function nu(e){return Ao(e).filter(t=>t!=="action")}function zt(e,t){const o=new Set(nu(e));return Object.entries(mt(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 Jo(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`# Weekly Notes
120
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of e.seen.entries()){const d=l[1];if(t===l[0]){s(l);continue}if(e.external){const h=(c=e.external.registry.get(l[0]))==null?void 0:c.id;if(t!==l[0]&&h){s(l);continue}}if((u=e.metadataRegistry.get(l[0]))==null?void 0:u.id){s(l);continue}if(d.cycle){s(l);continue}if(d.count>1&&e.reused==="ref"){s(l);continue}}}function yo(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=u=>{const l=e.seen.get(u);if(l.ref===null)return;const d=l.def??l.schema,f={...d},h=l.ref;if(l.ref=null,h){n(h);const _=e.seen.get(h),v=_.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(v)):Object.assign(d,v),Object.assign(d,f),u._zod.parent===h)for(const x in d)x==="$ref"||x==="allOf"||x in f||delete d[x];if(v.$ref&&_.def)for(const x in d)x==="$ref"||x==="allOf"||x in _.def&&JSON.stringify(d[x])===JSON.stringify(_.def[x])&&delete d[x]}const m=u._zod.parent;if(m&&m!==h){n(m);const _=e.seen.get(m);if(_!=null&&_.schema.$ref&&(d.$ref=_.schema.$ref,_.def))for(const v in d)v==="$ref"||v==="allOf"||v in _.def&&JSON.stringify(d[v])===JSON.stringify(_.def[v])&&delete d[v]}e.override({zodSchema:u,jsonSchema:d,path:l.path??[]})};for(const u of[...e.seen.entries()].reverse())n(u[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 u=(i=e.external.registry.get(t))==null?void 0:i.id;if(!u)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(u)}Object.assign(r,o.def??o.schema);const s=((c=e.external)==null?void 0:c.defs)??{};for(const u of e.seen.entries()){const l=u[1];l.def&&l.defId&&(s[l.defId]=l.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const u=JSON.parse(JSON.stringify(r));return Object.defineProperty(u,"~standard",{value:{...t["~standard"],jsonSchema:{input:bo(t,"input",e.processors),output:bo(t,"output",e.processors)}},enumerable:!1,writable:!1}),u}catch{throw new Error("Error converting schema to JSON.")}}function X(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 X(n.element,o);if(n.type==="set")return X(n.valueType,o);if(n.type==="lazy")return X(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 X(n.innerType,o);if(n.type==="intersection")return X(n.left,o)||X(n.right,o);if(n.type==="record"||n.type==="map")return X(n.keyType,o)||X(n.valueType,o);if(n.type==="pipe")return X(n.in,o)||X(n.out,o);if(n.type==="object"){for(const r in n.shape)if(X(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(X(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(X(r,o))return!0;return!!(n.rest&&X(n.rest,o))}return!1}const Ph=(e,t={})=>o=>{const n=mo({...o,processors:t});return M(e,n),go(n,e),yo(n,e)},bo=(e,t,o={})=>n=>{const{libraryOptions:r,target:s}=n??{},a=mo({...r??{},target:s,io:t,processors:o});return M(e,a),go(a,e),yo(a,e)},Eh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$a=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:s,maximum:a,format:i,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof a=="number"&&(r.maxLength=a),i&&(r.format=Eh[i]??i,r.format===""&&delete r.format,i==="time"&&delete r.format),u&&(r.contentEncoding=u),c&&c.size>0){const l=[...c];l.length===1?r.pattern=l[0].source:l.length>1&&(r.allOf=[...l.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},za=(e,t,o,n)=>{const r=o,{minimum:s,maximum:a,format:i,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof i=="string"&&i.includes("int")?r.type="integer":r.type="number",typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l),typeof s=="number"&&(r.minimum=s,typeof l=="number"&&t.target!=="draft-04"&&(l>=s?delete r.minimum:delete r.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u),typeof a=="number"&&(r.maximum=a,typeof u=="number"&&t.target!=="draft-04"&&(u<=a?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},Fa=(e,t,o,n)=>{o.type="boolean"},Ch=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Oh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Ba=(e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},xh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Nh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},ja=(e,t,o,n)=>{o.not={}},Rh=(e,t,o,n)=>{},Ua=(e,t,o,n)=>{},$h=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},qa=(e,t,o,n)=>{const r=e._zod.def,s=ma(r.entries);s.every(a=>typeof a=="number")&&(o.type="number"),s.every(a=>typeof a=="string")&&(o.type="string"),o.enum=s},Ma=(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},zh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Fh=(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},Bh=(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(u=>({contentMediaType:u}))):Object.assign(r,s)},jh=(e,t,o,n)=>{o.type="boolean"},La=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Uh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Za=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},qh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Mh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Ha=(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=M(s.element,t,{...n,path:[...n.path,"items"]})},Va=(e,t,o,n)=>{var u;const r=o,s=e._zod.def;r.type="object",r.properties={};const a=s.shape;for(const l in a)r.properties[l]=M(a[l],t,{...n,path:[...n.path,"properties",l]});const i=new Set(Object.keys(a)),c=new Set([...i].filter(l=>{const d=s.shape[l]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(r.required=Array.from(c)),((u=s.catchall)==null?void 0:u._zod.def.type)==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=M(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Ya=(e,t,o,n)=>{const r=e._zod.def,s=r.inclusive===!1,a=r.options.map((i,c)=>M(i,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?o.oneOf=a:o.anyOf=a},Ga=(e,t,o,n)=>{const r=e._zod.def,s=M(r.left,t,{...n,path:[...n.path,"allOf",0]}),a=M(r.right,t,{...n,path:[...n.path,"allOf",1]}),i=u=>"allOf"in u&&Object.keys(u).length===1,c=[...i(s)?s.allOf:[s],...i(a)?a.allOf:[a]];o.allOf=c},Lh=(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)=>M(f,t,{...n,path:[...n.path,a,h]})),u=s.rest?M(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,u&&(r.items=u)):t.target==="openapi-3.0"?(r.items={anyOf:c},u&&r.items.anyOf.push(u),r.minItems=c.length,u||(r.maxItems=c.length)):(r.items=c,u&&(r.additionalItems=u));const{minimum:l,maximum:d}=e._zod.bag;typeof l=="number"&&(r.minItems=l),typeof d=="number"&&(r.maxItems=d)},Ja=(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 l=M(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const d of c)r.patternProperties[d.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=M(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=M(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const u=a._zod.values;if(u){const l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(r.required=l)}},Wa=(e,t,o,n)=>{const r=e._zod.def,s=M(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"}]},Ka=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Qa=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},Xa=(e,t,o,n)=>{const r=e._zod.def;M(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)))},ei=(e,t,o,n)=>{const r=e._zod.def;M(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},ti=(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;M(s,t,n);const a=t.seen.get(e);a.ref=s},oi=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.readOnly=!0},Zh=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Ln=(e,t,o,n)=>{const r=e._zod.def;M(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Hh=(e,t,o,n)=>{const r=e._zod.innerType;M(r,t,n);const s=t.seen.get(e);s.ref=r},Br={string:$a,number:za,boolean:Fa,bigint:Ch,symbol:Oh,null:Ba,undefined:xh,void:Nh,never:ja,any:Rh,unknown:Ua,date:$h,enum:qa,literal:Ma,nan:zh,template_literal:Fh,file:Bh,success:jh,custom:La,function:Uh,transform:Za,map:qh,set:Mh,array:Ha,object:Va,union:Ya,intersection:Ga,tuple:Lh,record:Ja,nullable:Wa,nonoptional:Ka,default:Qa,prefault:Xa,catch:ei,pipe:ti,readonly:oi,promise:Zh,optional:Ln,lazy:Hh};function Vh(e,t){if("_idmap"in e){const n=e,r=mo({...t,processors:Br}),s={};for(const c of n._idmap.entries()){const[u,l]=c;M(l,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[u,l]=c;go(r,l),a[u]=yo(r,l)}if(Object.keys(s).length>0){const c=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:s}}return{schemas:a}}const o=mo({...t,processors:Br});return M(e,o),go(o,e),yo(o,e)}const Yh=y("ZodISODateTime",(e,t)=>{Jp.init(e,t),Y.init(e,t)});function Gh(e){return nh(Yh,e)}const Jh=y("ZodISODate",(e,t)=>{Wp.init(e,t),Y.init(e,t)});function Wh(e){return rh(Jh,e)}const Kh=y("ZodISOTime",(e,t)=>{Kp.init(e,t),Y.init(e,t)});function Qh(e){return sh(Kh,e)}const Xh=y("ZodISODuration",(e,t)=>{Qp.init(e,t),Y.init(e,t)});function em(e){return ah(Xh,e)}const ni=(e,t)=>{ka.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>qd(e,o)},flatten:{value:o=>Ud(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,Ko,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,Ko,2)}},isEmpty:{get(){return e.issues.length===0}}})},tm=y("ZodError",ni),se=y("ZodError",ni,{Parent:Error}),om=Un(se),nm=qn(se),rm=To(se),sm=Po(se),am=Zd(se),im=Hd(se),cm=Vd(se),um=Yd(se),lm=Gd(se),dm=Jd(se),pm=Wd(se),fm=Kd(se),V=y("ZodType",(e,t)=>(Z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:bo(e,"input"),output:bo(e,"output")}}),e.toJSONSchema=Ph(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...o)=>e.clone(xe(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)=>Ne(e,o,n),e.brand=()=>e,e.register=(o,n)=>(o.add(e,n),e),e.parse=(o,n)=>om(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>rm(e,o,n),e.parseAsync=async(o,n)=>nm(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>sm(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>am(e,o,n),e.decode=(o,n)=>im(e,o,n),e.encodeAsync=async(o,n)=>cm(e,o,n),e.decodeAsync=async(o,n)=>um(e,o,n),e.safeEncode=(o,n)=>lm(e,o,n),e.safeDecode=(o,n)=>dm(e,o,n),e.safeEncodeAsync=async(o,n)=>pm(e,o,n),e.safeDecodeAsync=async(o,n)=>fm(e,o,n),e.refine=(o,n)=>e.check(cg(o,n)),e.superRefine=o=>e.check(ug(o)),e.overwrite=o=>e.check(mt(o)),e.optional=()=>qr(e),e.exactOptional=()=>Jm(e),e.nullable=()=>Mr(e),e.nullish=()=>qr(Mr(e)),e.nonoptional=o=>tg(e,o),e.array=()=>F(e),e.or=o=>it([e,o]),e.and=o=>Lm(e,o),e.transform=o=>Lr(e,Ym(o)),e.default=o=>Qm(e,o),e.prefault=o=>eg(e,o),e.catch=o=>ng(e,o),e.pipe=o=>Lr(e,o),e.readonly=()=>ag(e),e.describe=o=>{const n=e.clone();return vt.add(n,{description:o}),n},Object.defineProperty(e,"description",{get(){var o;return(o=vt.get(e))==null?void 0:o.description},configurable:!0}),e.meta=(...o)=>{if(o.length===0)return vt.get(e);const n=e.clone();return vt.add(n,o[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=o=>o(e),e)),ri=y("_ZodString",(e,t)=>{Mn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,r,s)=>$a(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(fh(...n)),e.includes=(...n)=>e.check(gh(...n)),e.startsWith=(...n)=>e.check(yh(...n)),e.endsWith=(...n)=>e.check(bh(...n)),e.min=(...n)=>e.check(ho(...n)),e.max=(...n)=>e.check(Na(...n)),e.length=(...n)=>e.check(Ra(...n)),e.nonempty=(...n)=>e.check(ho(1,...n)),e.lowercase=n=>e.check(hh(n)),e.uppercase=n=>e.check(mh(n)),e.trim=()=>e.check(wh()),e.normalize=(...n)=>e.check(kh(...n)),e.toLowerCase=()=>e.check(_h()),e.toUpperCase=()=>e.check(vh()),e.slugify=()=>e.check(Ih())}),hm=y("ZodString",(e,t)=>{Mn.init(e,t),ri.init(e,t),e.email=o=>e.check(zf(mm,o)),e.url=o=>e.check(qf(gm,o)),e.jwt=o=>e.check(oh(Om,o)),e.emoji=o=>e.check(Mf(ym,o)),e.guid=o=>e.check(Rr(jr,o)),e.uuid=o=>e.check(Ff(Qt,o)),e.uuidv4=o=>e.check(Bf(Qt,o)),e.uuidv6=o=>e.check(jf(Qt,o)),e.uuidv7=o=>e.check(Uf(Qt,o)),e.nanoid=o=>e.check(Lf(bm,o)),e.guid=o=>e.check(Rr(jr,o)),e.cuid=o=>e.check(Zf(km,o)),e.cuid2=o=>e.check(Hf(wm,o)),e.ulid=o=>e.check(Vf(_m,o)),e.base64=o=>e.check(Xf(Pm,o)),e.base64url=o=>e.check(eh(Em,o)),e.xid=o=>e.check(Yf(vm,o)),e.ksuid=o=>e.check(Gf(Im,o)),e.ipv4=o=>e.check(Jf(Dm,o)),e.ipv6=o=>e.check(Wf(Sm,o)),e.cidrv4=o=>e.check(Kf(Am,o)),e.cidrv6=o=>e.check(Qf(Tm,o)),e.e164=o=>e.check(th(Cm,o)),e.datetime=o=>e.check(Gh(o)),e.date=o=>e.check(Wh(o)),e.time=o=>e.check(Qh(o)),e.duration=o=>e.check(em(o))});function p(e){return $f(hm,e)}const Y=y("ZodStringFormat",(e,t)=>{H.init(e,t),ri.init(e,t)}),mm=y("ZodEmail",(e,t)=>{Up.init(e,t),Y.init(e,t)}),jr=y("ZodGUID",(e,t)=>{Bp.init(e,t),Y.init(e,t)}),Qt=y("ZodUUID",(e,t)=>{jp.init(e,t),Y.init(e,t)}),gm=y("ZodURL",(e,t)=>{qp.init(e,t),Y.init(e,t)}),ym=y("ZodEmoji",(e,t)=>{Mp.init(e,t),Y.init(e,t)}),bm=y("ZodNanoID",(e,t)=>{Lp.init(e,t),Y.init(e,t)}),km=y("ZodCUID",(e,t)=>{Zp.init(e,t),Y.init(e,t)}),wm=y("ZodCUID2",(e,t)=>{Hp.init(e,t),Y.init(e,t)}),_m=y("ZodULID",(e,t)=>{Vp.init(e,t),Y.init(e,t)}),vm=y("ZodXID",(e,t)=>{Yp.init(e,t),Y.init(e,t)}),Im=y("ZodKSUID",(e,t)=>{Gp.init(e,t),Y.init(e,t)}),Dm=y("ZodIPv4",(e,t)=>{Xp.init(e,t),Y.init(e,t)}),Sm=y("ZodIPv6",(e,t)=>{ef.init(e,t),Y.init(e,t)}),Am=y("ZodCIDRv4",(e,t)=>{tf.init(e,t),Y.init(e,t)}),Tm=y("ZodCIDRv6",(e,t)=>{of.init(e,t),Y.init(e,t)}),Pm=y("ZodBase64",(e,t)=>{nf.init(e,t),Y.init(e,t)}),Em=y("ZodBase64URL",(e,t)=>{sf.init(e,t),Y.init(e,t)}),Cm=y("ZodE164",(e,t)=>{af.init(e,t),Y.init(e,t)}),Om=y("ZodJWT",(e,t)=>{uf.init(e,t),Y.init(e,t)}),si=y("ZodNumber",(e,t)=>{Ea.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,r,s)=>za(e,n,r),e.gt=(n,r)=>e.check(zr(n,r)),e.gte=(n,r)=>e.check(Uo(n,r)),e.min=(n,r)=>e.check(Uo(n,r)),e.lt=(n,r)=>e.check($r(n,r)),e.lte=(n,r)=>e.check(jo(n,r)),e.max=(n,r)=>e.check(jo(n,r)),e.int=n=>e.check(Ur(n)),e.safe=n=>e.check(Ur(n)),e.positive=n=>e.check(zr(0,n)),e.nonnegative=n=>e.check(Uo(0,n)),e.negative=n=>e.check($r(0,n)),e.nonpositive=n=>e.check(jo(0,n)),e.multipleOf=(n,r)=>e.check(Fr(n,r)),e.step=(n,r)=>e.check(Fr(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 O(e){return ih(si,e)}const xm=y("ZodNumberFormat",(e,t)=>{lf.init(e,t),si.init(e,t)});function Ur(e){return ch(xm,e)}const Nm=y("ZodBoolean",(e,t)=>{df.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Fa(e,o,n)});function L(e){return uh(Nm,e)}const Rm=y("ZodNull",(e,t)=>{pf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ba(e,o,n)});function $m(e){return lh(Rm,e)}const zm=y("ZodUnknown",(e,t)=>{ff.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ua()});function Xo(){return dh(zm)}const Fm=y("ZodNever",(e,t)=>{hf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ja(e,o,n)});function Bm(e){return ph(Fm,e)}const jm=y("ZodArray",(e,t)=>{mf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ha(e,o,n,r),e.element=t.element,e.min=(o,n)=>e.check(ho(o,n)),e.nonempty=o=>e.check(ho(1,o)),e.max=(o,n)=>e.check(Na(o,n)),e.length=(o,n)=>e.check(Ra(o,n)),e.unwrap=()=>e.element});function F(e,t){return Dh(jm,e,t)}const Um=y("ZodObject",(e,t)=>{yf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Va(e,o,n,r),U(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:Xo()}),e.loose=()=>e.clone({...e._zod.def,catchall:Xo()}),e.strict=()=>e.clone({...e._zod.def,catchall:Bm()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=o=>$d(e,o),e.safeExtend=o=>zd(e,o),e.merge=o=>Fd(e,o),e.pick=o=>Nd(e,o),e.omit=o=>Rd(e,o),e.partial=(...o)=>Bd(ai,e,o[0]),e.required=(...o)=>jd(ii,e,o[0])});function b(e,t){const o={type:"object",shape:e??{},...S(t)};return new Um(o)}const qm=y("ZodUnion",(e,t)=>{bf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ya(e,o,n,r),e.options=t.options});function it(e,t){return new qm({type:"union",options:e,...S(t)})}const Mm=y("ZodIntersection",(e,t)=>{kf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ga(e,o,n,r)});function Lm(e,t){return new Mm({type:"intersection",left:e,right:t})}const Zm=y("ZodRecord",(e,t)=>{wf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ja(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function ct(e,t,o){return new Zm({type:"record",keyType:e,valueType:t,...S(o)})}const en=y("ZodEnum",(e,t)=>{_f.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,r,s)=>qa(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 en({...t,checks:[],...S(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 en({...t,checks:[],...S(r),entries:s})}});function z(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new en({type:"enum",entries:o,...S(t)})}const Hm=y("ZodLiteral",(e,t)=>{vf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ma(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 w(e,t){return new Hm({type:"literal",values:Array.isArray(e)?e:[e],...S(t)})}const Vm=y("ZodTransform",(e,t)=>{If.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Za(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new fa(e.constructor.name);o.addIssue=s=>{if(typeof s=="string")o.issues.push(Ft(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(Ft(a))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(s=>(o.value=s,o)):(o.value=r,o)}});function Ym(e){return new Vm({type:"transform",transform:e})}const ai=y("ZodOptional",(e,t)=>{xa.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ln(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function qr(e){return new ai({type:"optional",innerType:e})}const Gm=y("ZodExactOptional",(e,t)=>{Df.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ln(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Jm(e){return new Gm({type:"optional",innerType:e})}const Wm=y("ZodNullable",(e,t)=>{Sf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Wa(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Mr(e){return new Wm({type:"nullable",innerType:e})}const Km=y("ZodDefault",(e,t)=>{Af.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Qa(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Qm(e,t){return new Km({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ya(t)}})}const Xm=y("ZodPrefault",(e,t)=>{Tf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Xa(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function eg(e,t){return new Xm({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ya(t)}})}const ii=y("ZodNonOptional",(e,t)=>{Pf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ka(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function tg(e,t){return new ii({type:"nonoptional",innerType:e,...S(t)})}const og=y("ZodCatch",(e,t)=>{Ef.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ei(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ng(e,t){return new og({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const rg=y("ZodPipe",(e,t)=>{Cf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ti(e,o,n,r),e.in=t.in,e.out=t.out});function Lr(e,t){return new rg({type:"pipe",in:e,out:t})}const sg=y("ZodReadonly",(e,t)=>{Of.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>oi(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function ag(e){return new sg({type:"readonly",innerType:e})}const ig=y("ZodCustom",(e,t)=>{xf.init(e,t),V.init(e,t),e._zod.processJSONSchema=(o,n,r)=>La(e,o)});function cg(e,t={}){return Sh(ig,e,t)}function ug(e){return Ah(e)}const R={custom:"custom"},lg=b({name:p().optional(),closed:L().optional(),refCreateSavePath:p().optional(),createDocNameTemplate:p().optional(),dailyNoteSavePath:p().optional(),dailyNoteTemplatePath:p().optional()}),ci=b({id:p().optional(),notebook:p().optional(),path:p().optional()}),dg=ci.superRefine((e,t)=>{const o=typeof e.id=="string",n=typeof e.notebook=="string"||typeof e.path=="string";if(o===n){t.addIssue({code:R.custom,message:"Provide either id or notebook + path."});return}n&&(!e.notebook||!e.path)&&t.addIssue({code:R.custom,message:"Both notebook and path are required when id is not provided."})}),pg=b({fromPaths:F(p()).optional(),toNotebook:p().optional(),toPath:p().optional(),fromIDs:F(p()).optional(),toID:p().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:R.custom,message:"Provide either fromPaths + toNotebook + toPath or fromIDs + toID."});return}o&&(!e.fromPaths||!e.toNotebook||!e.toPath)&&t.addIssue({code:R.custom,message:"fromPaths, toNotebook, and toPath are required for path-based moves."}),n&&(!e.fromIDs||!e.toID)&&t.addIssue({code:R.custom,message:"fromIDs and toID are required for ID-based moves."})}),fg=z(_n),hg=z(vn),mg=z(In),gg=z(Dn),yg=z(Sn),bg=z(An),kg=z(Cn),wg=z(On),_g=z(xn),ui=b({action:w("ls"),path:p().describe("Human-readable workspace path, such as /Notebook/Folder or / for notebook roots")}),li=b({action:w("tree"),path:p().describe("Human-readable workspace path, such as /Notebook/Folder or / for all readable notebooks"),maxDepth:O().int().min(0).max(20).optional().describe("Max tree depth to return (default 3)")}),di=b({action:w("read"),path:p().describe("Human-readable document path"),page:O().int().min(1).optional().describe("Page number for markdown pagination (1-based)"),pageSize:O().int().min(1).max(2e4).optional().describe("Characters per page for markdown pagination (default 8000)")}),pi=b({action:w("write"),path:p().describe("Human-readable document path"),markdown:p().describe("Markdown content to create or write"),overwrite:L().optional().describe("When true, replace an existing document body while keeping the document node and title")}),ko=b({old:p().min(1).describe("Original text to match exactly. Supports multi-line strings."),new:p().describe("Replacement text. Supports multi-line strings."),replace_all:L().optional().describe("When true, replace every exact match. Defaults to false.")}),fi=b({action:w("replace"),path:p().describe("Human-readable document path to modify"),edit:it([ko,F(ko).min(1)]).describe("One replacement edit or an array of edits to apply sequentially within the same document")}),hi=b({action:w("rm"),path:p().describe("Human-readable document path to delete")}),mi=b({action:w("mv"),from:p().describe("Human-readable source document path"),to:p().describe("Human-readable destination document path")}),gi=b({action:w("search"),path:p().describe("Human-readable document or folder path to search within"),query:p().describe("Text or regular expression to search for"),regex:L().optional().describe("Treat query as a JavaScript regular expression"),caseSensitive:L().optional().describe("Use case-sensitive matching"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).max(200).optional().describe("Matches per page, default 50")}),yi=b({action:w("list")}),bi=b({action:w("create"),name:p().describe("Notebook name"),icon:p().optional().describe("Optional notebook icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}),ki=b({action:w("set_open_state"),notebook:p().describe("Notebook ID"),opened:L().describe("true to open, false to close")}),wi=b({action:w("remove"),notebook:p().describe("Notebook ID")}),_i=b({action:w("rename"),notebook:p().describe("Notebook ID"),name:p().describe("New notebook name")}),vi=b({action:w("get_conf"),notebook:p().describe("Notebook ID")}),Ii=b({action:w("set_conf"),notebook:p().describe("Notebook ID"),conf:lg.describe("Notebook configuration")}),Di=b({action:w("set_icon"),notebook:p().describe("Notebook ID"),icon:p().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.")}),Si=b({action:w("get_permissions"),notebook:p().optional().describe('Notebook ID, or "all" to return every notebook permission entry. Omit to return all notebooks.')}),Ai=b({action:w("set_permission"),notebook:p().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')}),Ti=b({action:w("get_child_docs"),notebook:p().describe("Notebook ID"),page:O().int().positive().optional().describe("Page number (1-based), default 1"),pageSize:O().int().positive().optional().describe("Rows per page, default 50")}),Pi=b({action:w("create"),notebook:p().describe("Notebook ID"),path:p().optional().describe("Human-readable target path, must start with / (e.g., /foo/bar). Parent paths must already exist."),parentPath:p().optional().describe("Parent human-readable path or storage path ending in .sy for title-based creation, must start with /"),title:p().optional().describe("Document title when creating under parentPath"),markdown:p().optional().describe("Markdown content, defaults to empty"),sorts:F(p()).optional().describe("Compatibility option retained for older callers; title-based creation now uses the reliable path flow"),icon:p().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:R.custom,message:"Provide either path, or parentPath + title, not both.",path:["path"]});return}!o&&(!e.parentPath||!e.title)&&t.addIssue({code:R.custom,message:"Provide path, or provide both parentPath and title.",path:["path"]})}),vg=z(["id","ids","path","hpath","docInfo"]),Ei=b({action:w("lookup"),id:p().optional().describe("Document ID to look up"),notebook:p().optional().describe("Notebook ID, required with path or hpath"),path:p().optional().describe("Storage path to look up when notebook is provided, e.g. /20240318112233-abc123.sy. Human-readable paths should use hpath instead."),hpath:p().optional().describe("Human-readable path to look up when notebook is provided"),hPath:p().optional().describe("Alias for hpath"),include:F(vg).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:R.custom,message:"Provide exactly one source: id, notebook + path, or notebook + hpath.",path:["id"]}),!e.id&&!e.notebook&&t.addIssue({code:R.custom,message:"notebook is required when resolving path or hpath.",path:["notebook"]})}),Ci=b({action:w("rename"),title:p().describe("New document title")}).and(dg),Oi=b({action:w("remove"),ids:F(p()).min(1).optional().describe("One or more document IDs to remove"),paths:F(p()).min(1).optional().describe("One or more storage paths to remove in batch")}).and(ci).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:R.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:R.custom,message:"Both notebook and path are required for path-based remove."})}),xi=b({action:w("move")}).and(pg),Ni=b({action:w("get_child_blocks"),id:p().describe("Document ID")}),Ri=b({action:w("get_child_docs"),id:p().describe("Document ID")}),$i=b({action:w("set_attr"),id:p().describe("Document ID"),attrs:b({icon:p().optional().describe("Icon value. Prefer a Unicode hex code string such as '1f4d4'."),cover:it([p(),$m()]).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:R.custom,message:"Provide at least one of attrs.icon or attrs.cover.",path:["attrs"]})}),zi=b({action:w("list_tree"),notebook:p().describe("Notebook ID"),path:p().describe("Storage path or / for the notebook root"),maxDepth:O().optional().describe("Max tree depth to return (default 3). Deeper nodes are collapsed to childCount.")}),Fi=b({action:w("search_docs"),notebook:p().describe("Notebook ID"),query:p().describe("Keyword to search in document titles"),path:p().optional().describe("Optional storage path to narrow the search scope after permission filtering")}),Bi=b({action:w("get_doc"),id:p().describe("Document ID"),mode:z(["markdown","html"]).optional().describe('Return mode: "markdown" (default) or "html"'),size:O().optional().describe("Optional maximum content size hint"),page:O().int().min(1).optional().describe("Page number for markdown pagination (1-based)"),pageSize:O().int().min(1).max(2e4).optional().describe("Characters per page for markdown pagination (default 8000)")}),ji=b({action:w("create_daily_note"),notebook:p().describe("Notebook ID"),app:p().optional().describe("Optional app identifier passed through to SiYuan")}),Ui=b({action:w("duplicate"),id:p().describe("Source document ID")}),qi=b({action:w("heading_to_doc"),headingID:p().describe("Heading block ID to convert into a document"),targetNotebook:p().describe("Target notebook ID"),targetPath:p().optional().describe("Optional target storage path"),previousPath:p().optional().describe("Optional previous sibling storage path")}),Mi=b({action:w("doc_to_heading"),srcID:p().describe("Source document ID"),targetID:p().describe("Target document or heading block ID"),after:L().optional().describe("When true, insert after the target heading instead of before it")}),Li=b({action:w("get_balance")}),Zi=b({action:w("shop")}),Hi=b({action:w("buy"),item_id:p().describe('Stable shop item ID returned by mascot(action="shop")')}),Vi=b({action:w("submit"),description:p().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:p().trim().max(1e3).optional().describe("Optional one- or two-sentence impact summary, such as affected workflow, error risk, confusion, or inconvenience."),suggestion:p().trim().max(1e3).optional().describe("Optional direct improvement suggestion; keep it focused and avoid repeating the full description."),agent:p().trim().max(200).optional().describe("Optional Agent product and model name, such as Claude Desktop / Claude Sonnet 4.5. Defaults to 无."),source:p().trim().max(100).optional().describe("Internal source label. Defaults to the current runtime transport.")}),Ig=z(["all","deck","notebook","tree"]),Dg=z(["due","new","old"]),Yi=b({action:w("list_cards"),scope:Ig.describe('Query scope: "all", "deck", "notebook", or "tree"'),filter:Dg.describe('Filter returned cards: "due", "new", or "old"'),deckID:p().optional().describe('Deck ID, required when scope=deck. For scope="all", omit deckID; an empty string is treated as omitted.'),notebook:p().optional().describe("Notebook ID, required when scope=notebook"),rootID:p().optional().describe("Root document/block ID, required when scope=tree"),reviewedCards:F(b({cardID:p().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:R.custom,message:'scope="all" does not accept deckID, notebook, or rootID.'}),e.scope==="deck"&&!o&&t.addIssue({code:R.custom,path:["deckID"],message:'deckID is required when scope="deck".'}),e.scope==="notebook"&&!n&&t.addIssue({code:R.custom,path:["notebook"],message:'notebook is required when scope="notebook".'}),e.scope==="tree"&&!r&&t.addIssue({code:R.custom,path:["rootID"],message:'rootID is required when scope="tree".'})}),Gi=b({action:w("get_decks")}),Ji=b({action:w("review_card"),deckID:p().describe("Deck ID"),cardID:p().describe("Card ID"),rating:O().optional().describe("Review rating passed through to the kernel"),skip:L().optional().describe("When true, skip the current card instead of submitting a rating"),reviewedCards:F(b({cardID:p().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:R.custom,message:"rating is required unless skip=true.",path:["rating"]})}),Wi=b({action:w("create_card"),deckID:p().describe("Deck ID"),blockIDs:F(p()).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.")}),Ki=b({action:w("remove_card"),deckID:p().describe("Deck ID"),blockIDs:F(p()).min(1).describe("Existing block IDs to remove from flashcards")}),Qi=b({action:w("get_cards"),deckID:p().describe("Deck ID (use empty string to query across all decks)"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).max(512).optional().describe("Cards per page, default 32")}),Xi=b({action:w("insert"),dataType:z(["markdown","dom"]).optional().describe("Data format"),data:p().optional().describe("Block content"),nextID:p().optional().describe("Next block ID"),previousID:p().optional().describe("Previous block ID"),parentID:p().optional().describe("Parent block or document ID"),blocks:F(b({dataType:z(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),nextID:p().optional().describe("Next block ID"),previousID:p().optional().describe("Previous block ID"),parentID:p().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:R.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:R.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:R.custom,message:"dataType is required for single insert.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:R.custom,message:"data is required for single insert.",path:["data"]})}),ec=b({action:w("prepend"),dataType:z(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),parentID:p().describe("Parent block or document ID")}),tc=b({action:w("append"),dataType:z(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),parentID:p().describe("Parent block or document ID")}),oc=b({action:w("update"),dataType:z(["markdown","dom"]).optional().describe("Data format"),data:p().optional().describe("New block content"),id:p().optional().describe("Block ID"),items:F(b({id:p().describe("Block ID"),dataType:z(["markdown","dom"]).describe("Data format"),data:p().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:R.custom,message:"Provide either items or single update fields, not both.",path:["items"]});return}e.id||t.addIssue({code:R.custom,message:"id is required for single update.",path:["id"]}),e.dataType||t.addIssue({code:R.custom,message:"dataType is required for single update.",path:["dataType"]}),e.data===void 0&&t.addIssue({code:R.custom,message:"data is required for single update.",path:["data"]})}),nc=b({action:w("replace"),id:p().describe("Block ID"),edit:it([ko,F(ko).min(1)]).describe("One replacement edit or an array of edits to apply sequentially within the same block kramdown")}),rc=b({action:w("delete"),id:p().describe("Block ID")}),sc=b({action:w("move"),id:p().describe("Block ID"),previousID:p().optional().describe("Previous block ID"),parentID:p().optional().describe("New parent block ID")}).superRefine((e,t)=>{!e.previousID&&!e.parentID&&t.addIssue({code:R.custom,message:"Provide previousID, parentID, or both to describe the destination.",path:["previousID"]})}),ac=b({action:w("set_fold_state"),id:p().describe("Foldable block ID"),folded:L().describe("true to fold, false to unfold")}),ic=b({action:w("get_kramdown"),id:p().describe("Block ID or document ID")}),cc=b({action:w("get_children"),id:p().describe("Block ID or document ID"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).max(200).optional().describe("Items per page, default 50")}),uc=b({action:w("transfer_references"),fromID:p().describe("Source block ID"),toID:p().describe("Target block ID"),refIDs:F(p()).optional().describe("Reference block IDs")}),lc=b({action:w("set_attrs"),id:p().describe("Block ID"),attrs:ct(p(),p()).describe("Block attributes")}),dc=b({action:w("get_attrs"),id:p().describe("Block ID")}),pc=b({action:w("info"),id:p().describe("Block ID")}),fc=b({action:w("breadcrumb"),id:p().describe("Block ID"),excludeTypes:F(p()).optional().describe("Optional block types to exclude from the breadcrumb")}),hc=b({action:w("dom"),id:p().describe("Block ID")}),mc=b({action:w("recent_updated"),count:O().optional().describe("Maximum number of recent readable blocks to return after permission filtering")}),gc=b({action:w("word_count"),ids:F(p()).describe("One or more block IDs")}),yc=b({action:w("add_to_daily_note"),notebook:p().describe("Notebook ID"),dataType:z(["markdown","dom"]).describe("Data format"),data:p().describe("Block content"),position:z(["append","prepend"]).describe("Where to add content in today's daily note")}),bc=b({action:w("docs_info"),id:p().optional().describe("Single document/block ID"),ids:F(p()).min(1).optional().describe("Document IDs"),refCount:L().optional().describe("When true, include reference counts"),av:L().optional().describe("When true, include AV metadata")}).superRefine((e,t)=>{(e.id&&e.ids||!e.id&&!e.ids)&&t.addIssue({code:R.custom,message:"Provide exactly one of id or ids.",path:["ids"]})}),Sg=z(["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"]),Ag=b({type:z(["image","file"]).describe("Asset entry type"),content:p().describe("Asset path stored by SiYuan, e.g. assets/foo.png"),name:p().optional().describe("Optional display name")}),kc=b({valueType:Sg.describe("Cell value type"),text:p().optional().describe("Text value for valueType=text"),number:O().optional().describe("Number value for valueType=number"),numberFormat:p().optional().describe("Optional number format such as commas, percent, USD, or CNY"),date:it([p(),O()]).optional().describe("Date/time value as ISO text or epoch milliseconds for valueType=date"),endDate:it([p(),O()]).optional().describe("Optional end date as ISO text or epoch milliseconds for ranged dates"),includeTime:L().optional().describe("When false, store the date without a time component"),checked:L().optional().describe("Checkbox state for valueType=checkbox"),option:p().optional().describe("Selected option label for valueType=select"),options:F(p()).optional().describe("Selected option labels for valueType=multi_select"),relationBlockIDs:F(p()).optional().describe("Related block IDs for valueType=relation"),url:p().optional().describe("URL value for valueType=url"),email:p().optional().describe("Email value for valueType=email"),phone:p().optional().describe("Phone value for valueType=phone"),assets:F(Ag).optional().describe("Asset entries for valueType=mAsset")}),wc=kc.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:R.custom,message:`${String(n)} is required when valueType="${e.valueType}".`,path:[n]})}),Zr=b({rowID:p().describe("Row item ID"),columnID:p().describe("Column key ID")}).and(wc),_c=b({action:w("get"),id:p().describe("Attribute view ID"),blockID:p().optional().describe("Optional database block ID for exact context or fallback permission resolution")}),vc=b({action:w("render"),id:p().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:p().optional().describe("Optional database block ID; required when creating a new AV"),viewID:p().optional().describe("Optional target view ID"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().optional().describe("Rows per page; use -1 or omit for kernel default"),query:p().optional().describe("Optional row query filter"),groupPaging:ct(p(),Xo()).optional().describe("Optional group paging map passed through to SiYuan"),createIfNotExist:L().optional().describe("Create the default view only when explicitly true; provide blockID when creating a new AV")}),Ic=b({action:w("get_attribute_view_keys"),id:p().describe("Attribute view ID")}),Dc=b({action:w("get_attribute_view_filter_sort"),id:p().describe("Attribute view ID"),blockID:p().optional().describe("Database block ID (optional)")}),Sc=b({action:w("search"),keyword:p().describe("Keyword to search in attribute view names"),excludes:F(p()).optional().describe("Optional AV IDs to exclude")}),Ac=b({action:w("add_rows"),avID:p().describe("Attribute view ID"),blockIDs:F(p()).optional().describe("Existing block IDs to add as bound rows"),primaryKeyTexts:F(p()).optional().describe("Plain-text primary key values to add as detached rows"),blockID:p().optional().describe("Optional database block ID used to pin a specific database-block view context"),viewID:p().optional().describe("Optional target view ID"),groupID:p().optional().describe("Optional target group ID"),previousID:p().optional().describe("Optional previous row item ID"),ignoreDefaultFill:L().optional().describe("When true, skip view/group default value filling")}),Tc=b({action:w("remove_rows"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),srcIDs:F(p()).min(1).describe("Bound row block/item IDs to remove")}),Pc=b({action:w("add_column"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),keyID:p().optional().describe("Optional new column key ID; MCP generates one when omitted"),keyName:p().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:p().optional().describe("Optional column icon"),previousKeyID:p().optional().describe("Insert after this existing column key ID")}),Ec=b({action:w("remove_column"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),keyID:p().optional().describe("Column key ID"),columnID:p().optional().describe("Alias of keyID"),removeRelationDest:L().optional().describe("Also remove reverse relation metadata when deleting a relation column")}).superRefine((e,t)=>{!e.keyID&&!e.columnID&&t.addIssue({code:R.custom,message:"Provide keyID or columnID.",path:["keyID"]})}),Cc=b({action:w("set_cells"),avID:p().describe("Attribute view ID"),blockID:p().optional().describe("Registered database block ID for explicit database-block context"),cells:F(Zr).min(1).optional().describe("Cell updates"),items:F(Zr).min(1).optional().describe("Alias for cells"),rowID:p().optional().describe("Single-cell row item ID"),columnID:p().optional().describe("Single-cell column key ID")}).and(kc.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:R.custom,message:"Provide either cells/items or single-cell fields, not both.",path:["cells"]});return}if(!n){if(e.rowID||t.addIssue({code:R.custom,message:"rowID is required for single-cell set_cells calls.",path:["rowID"]}),e.columnID||t.addIssue({code:R.custom,message:"columnID is required for single-cell set_cells calls.",path:["columnID"]}),!e.valueType){t.addIssue({code:R.custom,message:"valueType is required for single-cell set_cells calls.",path:["valueType"]});return}const s=wc.safeParse(e);if(!s.success)for(const a of s.error.issues)t.addIssue({code:R.custom,message:a.message,path:a.path})}}),Oc=b({action:w("duplicate"),avID:p().describe("Source attribute view ID"),blockID:p().optional().describe("Optional source database block ID used as exact context and default insertion target"),previousID:p().optional().describe("Optional block ID to insert the duplicated mirror database block after")}),xc=b({action:w("get_primary_key_values"),avID:p().describe("Attribute view ID"),keyword:p().optional().describe("Optional keyword filter for primary key values"),page:O().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:O().int().min(1).optional().describe("Rows per page, default all")}),Nc=b({action:w("upload_asset"),assetsDirPath:p().describe("Asset directory path (e.g., /assets/)"),localFilePath:p().describe("Local file path to read and upload into the assets directory"),confirmLargeFile:L().optional().describe("Set to true only after the user explicitly confirms uploading a file larger than the configured safety threshold.")}),Rc=b({action:w("render"),engine:z(["template","sprig"]).describe("Template engine to use"),id:p().optional().describe("Document ID for template context"),path:p().optional().describe("Template file path inside the SiYuan workspace"),template:p().optional().describe("Sprig template content")}).superRefine((e,t)=>{e.engine==="template"&&(e.id||t.addIssue({code:R.custom,message:'id is required when engine="template".',path:["id"]}),e.path||t.addIssue({code:R.custom,message:'path is required when engine="template".',path:["path"]})),e.engine==="sprig"&&!e.template&&t.addIssue({code:R.custom,message:'template is required when engine="sprig".',path:["template"]})}),$c=b({action:w("export_md"),id:p().describe("Document ID to export")}),zc=b({action:w("export_resources"),paths:F(p()).describe("Paths to export"),name:p().optional().describe("Export file name"),outputPath:p().optional().describe("Optional local absolute or relative filesystem path to save the exported ZIP")}),Fc=b({action:w("list_unused_assets")}),Bc=b({action:w("get_doc_assets"),id:p().describe("Document ID"),assetType:z(["all","image"]).optional().describe("Filter asset type: 'all' (default) returns all assets, 'image' returns only image assets.")}),jc=b({action:w("get_image_ocr_text"),path:p().optional().describe("Asset path; omit to receive an empty OCR text payload")}),Uc=b({action:w("remove_unused_assets")}),qc=b({action:w("rename_asset"),oldPath:p().describe("Existing asset path"),newName:p().describe("New asset file name")}),Mc=b({action:w("delete_asset"),path:p().describe("Asset path to delete")}),Lc=b({action:w("extract_doc"),id:p().describe("Document ID to extract"),outputDir:p().optional().describe("Output root directory. Defaults to ~/siyuan-extracted/ (resolved to absolute path).")}),Tg=z(Tn),Zn=z(["keyword","query","query_syntax","sql","regex"]),Zc=z(["relevance","date","updated_desc","updated_asc","created_desc","created_asc","type"]),Pg=z(["relevance","relevance_desc","relevance_asc","updated_asc","updated_desc"]),Hc=b({action:w("fulltext"),query:p().describe("Search query string"),method:O().optional().describe("Search method: 0=keyword (default), 1=query syntax, 2=SQL, 3=regex"),methodName:Zn.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:ct(p(),L()).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:F(p()).optional().describe('Alternative shorthand type filter as array: ["h","p"]. Merged with types if both provided.'),paths:F(p()).optional().describe("Restrict search to specific notebook paths"),groupBy:O().optional().describe("0=no grouping (default), 1=group by document"),orderBy:O().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:Zc.optional().describe('Semantic sort alias: "relevance", "date", "updated_desc", "updated_asc", "created_desc", "created_asc", or "type". Overrides orderBy if both provided.'),page:O().optional().describe("Page number (1-based), default 1"),pageSize:O().optional().describe("Results per page, default 32, max 128"),parentId:p().optional().describe("Post-filter results to blocks whose root_id or parent_id matches this ID, scoping search within a document subtree."),hasTags:L().optional().describe("When true, only return blocks that have tags. When false, only return blocks without tags."),stripHtml:L().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.")}),Vc=b({action:w("query_sql"),stmt:p().optional().describe("SQL SELECT statement to execute against the blocks/spans/assets tables; returned rows are permission-filtered"),sql:p().optional().describe("Semantic alias for stmt. Overrides stmt when both are provided.")}).superRefine((e,t)=>{!e.stmt&&!e.sql&&t.addIssue({code:R.custom,message:"Provide stmt or sql.",path:["stmt"]})}),Yc=b({action:w("get_backlinks"),id:p().describe("Block or document ID to find backlinks for"),keyword:p().optional().describe("Filter backlinks by keyword"),refTreeID:p().optional().describe("Optional document tree ID to narrow backlink scope"),scopeRootId:p().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).')}),Gc=b({action:w("search_refs"),id:p().describe("Referenced block or document ID"),rootID:p().optional().describe("Optional current root document ID"),k:p().optional().describe("Keyword filter"),beforeLen:O().int().min(0).optional().describe("Context length before the reference, default 512"),isSquareBrackets:L().optional().describe("Search in square-bracket reference mode"),isDatabase:L().optional().describe("Whether the reference target is a database"),reqId:p().optional().describe("Optional passthrough request ID")}),Jc=b({action:w("find_replace"),k:p().describe("Find keyword"),r:p().describe("Replacement text; use empty string to delete matches"),ids:F(p()).min(1).describe("Document or block IDs to mutate"),paths:F(p()).optional().describe("Optional path scope list"),types:ct(p(),L()).optional().describe("Optional block type filter"),method:O().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Zn.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:O().optional().describe("Legacy numeric sort order"),sortBy:Zc.optional().describe("Semantic sort alias that overrides orderBy when both are provided."),groupBy:O().optional().describe("Grouping mode"),replaceTypes:ct(p(),L()).optional().describe("Replace target kinds such as text, code, docTitle, blockRef")}),Wc=b({action:w("search_assets"),k:p().optional().describe("Legacy asset filename keyword field"),query:p().optional().describe("Semantic alias for k. Overrides k when both are provided."),exts:F(p()).optional().describe("Optional extension filters")}).superRefine((e,t)=>{!e.k&&!e.query&&t.addIssue({code:R.custom,message:"Provide k or query.",path:["k"]})}),Kc=b({action:w("fulltext_asset_content"),query:p().optional().describe("Search query string"),assetId:p().optional().describe("Asset content ID for an exact content lookup"),queryMethod:O().optional().describe("Query method for assetId lookup: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),types:ct(p(),L()).optional().describe("Asset type filter"),method:O().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),methodName:Zn.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:O().optional().describe("Legacy numeric sort order: 0=relevance DESC, 1=relevance ASC, 2=updated ASC, 3=updated DESC"),sortBy:Pg.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:O().int().min(1).optional().describe("Page number (1-based)"),pageSize:O().int().min(1).max(128).optional().describe("Results per page")}).superRefine((e,t)=>{!e.query&&!e.assetId&&t.addIssue({code:R.custom,message:"Provide query or assetId.",path:["query"]})}),Qc=b({action:w("list_invalid_refs"),page:O().int().min(1).optional().describe("Page number (1-based)"),pageSize:O().int().min(1).max(128).optional().describe("Results per page")}),Eg=z(Pn),Xc=b({action:w("list"),keyword:p().optional().describe("Optional keyword used to search/filter tags"),query:p().optional().describe("Alias for keyword"),sort:O().optional().describe("Optional tag sort mode"),ignoreMaxListHint:L().optional().describe("Ignore the maximum list hint from SiYuan"),app:p().optional().describe("Optional app identifier passed through to SiYuan")}),eu=b({action:w("rename"),oldLabel:p().describe("Existing tag label"),newLabel:p().describe("New tag label")}),tu=b({action:w("remove"),label:p().describe("Tag label to remove")}),Cg=z(En),ou=b({action:w("workspace_info")}),nu=b({action:w("network")}),ru=b({action:w("conf"),mode:z(["summary","get"]).optional().describe('Read mode: "summary" returns a navigable overview, "get" reads a specific key path'),keyPath:p().optional().describe('Dot/bracket path to a specific config field, e.g. "conf.appearance.mode" or "conf.langs[0]"'),maxDepth:O().int().min(0).max(5).optional().describe("Maximum object traversal depth for summary/get responses"),maxItems:O().int().min(1).max(100).optional().describe("Maximum keys/items to include per level")}),su=b({action:w("notify"),msg:p().describe("Message content"),level:z(["info","error"]).describe("Notification level"),timeout:O().optional().describe("Display timeout in milliseconds")}),au=b({action:w("get_version")}),iu=b({action:w("get_current_time")}),Og=[{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 Hn(e){const t=e.message??"";for(const o of Og)if(o.patterns.some(n=>n.test(t)))return{code:o.code,hint:o.hint};return null}function Vn(e){var t;return e instanceof Error?((t=Hn(e))==null?void 0:t.code)==="block_not_found":!1}function xg(e){return typeof e.description=="string"?e.description:null}function gt(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Co(e){return Array.isArray(e.required)?e.required.filter(t=>typeof t=="string"):[]}function Ng(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(Co(i.schema));for(const[u,l]of Object.entries(gt(i.schema))){if(u==="action"||!l||typeof l!="object")continue;o[u]={...o[u],...l};const d=xg(l);if(d){const _=n.get(u)??new Set;_.add(d),n.set(u,_)}const f=l.enum;if(Array.isArray(f)){const _=r.get(u)??new Set;for(const v of f)_.add(v);r.set(u,_)}const h=c.has(u)?s:a,m=h.get(u)??new Set;m.add(i.action),h.set(u,m)}}for(const[i,c]of Object.entries(o)){const u=n.get(i),l=t[i]??(u&&u.size>0?[...u].join(" / "):void 0),d=[...s.get(i)??[]].sort(),f=[...a.get(i)??[]].sort(),h=[...d.length>0?[`Required by: ${d.join(", ")}`]:[],...f.length>0?[`Optional in: ${f.join(", ")}`]:[]],m=h.length>0?`[${h.join("; ")}]`:"";c.description=l?m?`${l} ${m}`:l:m||void 0;const _=r.get(i);_&&_.size>0&&(c.enum=[..._])}return o}function $e(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return t.type==="array"&&(t.items=$e(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,$e(n)]))),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=$e(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(o=>$e(o))),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(o=>$e(o))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(o=>$e(o))),t}function Yn(e){return $e(e)}function cu(e){return Co(e).filter(t=>t!=="action")}function Bt(e,t){const o=new Set(cu(e));return Object.entries(gt(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 tn(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`# Weekly Notes
121
121
 
122
- - 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[Jo(`${e}Item`,r)]}if(t.type==="object"){const r=mt(t),s=Object.keys(r)[0];return s?{[s]:Jo(s,r[s])}:{}}return t.type==="number"?1:t.type==="boolean"?!1:`<${e}>`}function Pg(e,t){return e.filter(n=>n.action===t).map(n=>{const r=mt(n.schema),s={action:t};for(const a of nu(n.schema))s[a]=Jo(a,r[a]??{});return s})}function Eg(e,t){var o;return((o=kd[e])==null?void 0:o[t])??[]}function Cg(e){return e.length>0?e.join(", "):"no additional fields"}function Og(e){const t=new Map;for(const o of e){const n=Cg(zt(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 xg(e,t){const o=new Set;return t.flatMap(n=>{if(o.has(n.action))return[];o.add(n.action);const r=zt(n.schema,!0),s=zt(n.schema,!1);return[`${e}.${n.action}: required ${r.length>0?`[${r.join(", ")}]`:"[]"} | optional ${s.length>0?`[${s.join(", ")}]`:"[]"}`]}).join(`
123
- `)}function Ng(e,t,o){var c;const n={basic:[],advanced:[]};for(const u of t)n[Ot(e,u)].push(u);const r={},s={},a=new Set;for(const u of o){if(a.has(u.action))continue;a.add(u.action);const l=(c=$t[e])==null?void 0:c[u.action],d=zt(u.schema,!0);r[u.action]=l??(d.length>0?`requires: ${d.join(", ")}`:"no extra fields"),s[u.action]={...l?{hint:l}:{},requiresConfirmation:ot(e,u.action)}}const i=t.filter(u=>ot(e,u));return{tool:e,commonActions:n.basic,advancedActions:n.advanced,guidance:ia[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(u=>u.action===t),r=n.map(u=>zt(u.schema,!0)),s=Pg(n,t),a=Eg(e,t),i=s.length===1?s[0]:s;return{tool:e,action:t,...(c=$t[e])!=null&&c[t]?{hint:$t[e][t]}:{},shapes:r.map(u=>u.length>0?u.join(" + "):"action only"),requiredFields:r.length===1?r[0]:r,example:i,...a.length>0?{examples:a}:{},guidance:ia[e]??[],requiresConfirmation:ot(e,t),fullDocResource:`siyuan://help/action/${e}/${t}`}}const Rg="x-sisyphus-actionSchemas";function w(e,t,o){const n=Re(Uh(t));return delete n.$schema,o&&!n.description&&(n.description=o),{action:e,schema:Un(n)}}function Re(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)?Re(c):c]))),t.items&&typeof t.items=="object"&&!Array.isArray(t.items)&&(t.items=Re(t.items)),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=Re(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?Re(i):i)),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?Re(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=Re(i);if(c.type!=="object")return e;Object.assign(o,mt(c));for(const u of Ao(c))n.add(u);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 zg(e){const t={action:{type:"string",const:e.action,description:"Action to perform"},...mt(e.schema)};return Un({...e.schema,type:"object",additionalProperties:!1,properties:t,required:Array.from(new Set(["action",...Ao(e.schema)]))})}function Fg(e){const t={...e};return delete t.const,delete t.required,t}function Bg(e){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,o&&typeof o=="object"&&!Array.isArray(o)?Fg(o):{}]))}function jg(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 Ug(e,t,o){const n=[],r=o.guidanceInlineLimit??2,s=o.guidance??[];n.push(...s.slice(0,r));const a=t.filter(i=>ot(e,i));return a.length>0&&n.push(`Requires user confirmation before: ${a.join(", ")}.`),n}function ru(e){return e.map(t=>typeof t=="number"?`[${t}]`:String(t)).join(".").replace(/\.\[/g,"[")}function qg(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 Mg(e,t){const o=ru(e.path),n=o?qg(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 Lg(e,t){return e.issues.map(o=>({path:ru(o.path),message:Mg(o,t)}))}function Zg(e,t){return e&&t?`Invalid arguments for ${e}(action="${t}").`:e?`Invalid arguments for tool "${e}".`:"Invalid arguments."}function zo(e){return(e==null?void 0:e.hint)??wd(e==null?void 0:e.tool,e==null?void 0:e.action)}function it(e,t=!0){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:t}}function Hg(e){return e.name==="SiYuanError"||e.message.startsWith("SiYuan API error:")||e.message.startsWith("HTTP error:")||e.message.startsWith("Request timeout")}function Vg(){return process.env.SIYUAN_MCP_DEBUG_ERRORS==="1"}function Yg(e,t,o,n,r){const s=o.filter(f=>Ot(e,f)==="basic"),a=o.filter(f=>Ot(e,f)==="advanced"),i=n.filter(f=>s.includes(f.action)),c=Og(i),u=[`${t} Use the "action" field to select the operation.`];s.length>0&&u.push(`Common actions: ${s.join(", ")}. Required fields: ${c}.`),a.length>0&&u.push(`Additional actions: ${a.join(", ")}. Read siyuan://help/action/${e}/{action} for details, or call action="help" if resources are unavailable.`);const l=xg(e,n);l.length>0&&u.push(`Parameter contract per action (fields outside the action's optional list should not be sent):
124
- ${l}`);const d=Ug(e,o,r);return d.length>0&&u.push(d.join(" ")),u.join(`
122
+ - 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[tn(`${e}Item`,r)]}if(t.type==="object"){const r=gt(t),s=Object.keys(r)[0];return s?{[s]:tn(s,r[s])}:{}}return t.type==="number"?1:t.type==="boolean"?!1:`<${e}>`}function Rg(e,t){return e.filter(n=>n.action===t).map(n=>{const r=gt(n.schema),s={action:t};for(const a of cu(n.schema))s[a]=tn(a,r[a]??{});return s})}function $g(e,t){var o;return((o=Sd[e])==null?void 0:o[t])??[]}function zg(e){return e.length>0?e.join(", "):"no additional fields"}function Fg(e){const t=new Map;for(const o of e){const n=zg(Bt(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 Bg(e,t){const o=new Set;return t.flatMap(n=>{if(o.has(n.action))return[];o.add(n.action);const r=Bt(n.schema,!0),s=Bt(n.schema,!1);return[`${e}.${n.action}: required ${r.length>0?`[${r.join(", ")}]`:"[]"} | optional ${s.length>0?`[${s.join(", ")}]`:"[]"}`]}).join(`
123
+ `)}function jg(e,t,o){var c;const n={basic:[],advanced:[]};for(const u of t)n[Nt(e,u)].push(u);const r={},s={},a=new Set;for(const u of o){if(a.has(u.action))continue;a.add(u.action);const l=(c=zt[e])==null?void 0:c[u.action],d=Bt(u.schema,!0);r[u.action]=l??(d.length>0?`requires: ${d.join(", ")}`:"no extra fields"),s[u.action]={...l?{hint:l}:{},requiresConfirmation:rt(e,u.action)}}const i=t.filter(u=>rt(e,u));return{tool:e,commonActions:n.basic,advancedActions:n.advanced,guidance:pa[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 Ug(e,t,o){var c;const n=o.filter(u=>u.action===t),r=n.map(u=>Bt(u.schema,!0)),s=Rg(n,t),a=$g(e,t),i=s.length===1?s[0]:s;return{tool:e,action:t,...(c=zt[e])!=null&&c[t]?{hint:zt[e][t]}:{},shapes:r.map(u=>u.length>0?u.join(" + "):"action only"),requiredFields:r.length===1?r[0]:r,example:i,...a.length>0?{examples:a}:{},guidance:pa[e]??[],requiresConfirmation:rt(e,t),fullDocResource:`siyuan://help/action/${e}/${t}`}}const qg="x-sisyphus-actionSchemas";function k(e,t,o){const n=ze(Vh(t));return delete n.$schema,o&&!n.description&&(n.description=o),{action:e,schema:Yn(n)}}function ze(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)?ze(c):c]))),t.items&&typeof t.items=="object"&&!Array.isArray(t.items)&&(t.items=ze(t.items)),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=ze(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?ze(i):i)),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(i=>i&&typeof i=="object"&&!Array.isArray(i)?ze(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=ze(i);if(c.type!=="object")return e;Object.assign(o,gt(c));for(const u of Co(c))n.add(u);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 Mg(e){const t={action:{type:"string",const:e.action,description:"Action to perform"},...gt(e.schema)};return Yn({...e.schema,type:"object",additionalProperties:!1,properties:t,required:Array.from(new Set(["action",...Co(e.schema)]))})}function Lg(e){const t={...e};return delete t.const,delete t.required,t}function Zg(e){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,o&&typeof o=="object"&&!Array.isArray(o)?Lg(o):{}]))}function Hg(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 Vg(e,t,o){const n=[],r=o.guidanceInlineLimit??2,s=o.guidance??[];n.push(...s.slice(0,r));const a=t.filter(i=>rt(e,i));return a.length>0&&n.push(`Requires user confirmation before: ${a.join(", ")}.`),n}function uu(e){return e.map(t=>typeof t=="number"?`[${t}]`:String(t)).join(".").replace(/\.\[/g,"[")}function Yg(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 Gg(e,t){const o=uu(e.path),n=o?Yg(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 Jg(e,t){return e.issues.map(o=>({path:uu(o.path),message:Gg(o,t)}))}function Wg(e,t){return e&&t?`Invalid arguments for ${e}(action="${t}").`:e?`Invalid arguments for tool "${e}".`:"Invalid arguments."}function qo(e){return(e==null?void 0:e.hint)??Ad(e==null?void 0:e.tool,e==null?void 0:e.action)}function ut(e,t=!0){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:t}}function Kg(e){return e.name==="SiYuanError"||e.message.startsWith("SiYuan API error:")||e.message.startsWith("HTTP error:")||e.message.startsWith("Request timeout")}function Qg(){return process.env.SIYUAN_MCP_DEBUG_ERRORS==="1"}function Xg(e,t,o,n,r){const s=o.filter(f=>Nt(e,f)==="basic"),a=o.filter(f=>Nt(e,f)==="advanced"),i=n.filter(f=>s.includes(f.action)),c=Fg(i),u=[`${t} Use the "action" field to select the operation.`];s.length>0&&u.push(`Common actions: ${s.join(", ")}. Required fields: ${c}.`),a.length>0&&u.push(`Additional actions: ${a.join(", ")}. Read siyuan://help/action/${e}/{action} for details, or call action="help" if resources are unavailable.`);const l=Bg(e,n);l.length>0&&u.push(`Parameter contract per action (fields outside the action's optional list should not be sent):
124
+ ${l}`);const d=Vg(e,o,r);return d.length>0&&u.push(d.join(" ")),u.join(`
125
125
 
126
- `)}function Gg(e,t,o,n,r={}){if(!o.enabled)return[];const s=Nt(o),a=new Set(s),i=n.filter(h=>a.has(h.action));if(i.length===0)return[];const c=Yg(e,t,s,i,r),u=s.filter(h=>ot(e,h)),l=Tg(i,r.propertyDescriptionOverrides);"topic"in l||(l.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 d=[...i.map(h=>zg(h)),jg(s)],f=Un({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.${u.length>0?` User confirmation is required before calling: ${u.join(", ")}.`:""}`},...Bg(l)},additionalProperties:!0});return Object.defineProperty(f,Rg,{value:d,enumerable:!1}),[{name:e,description:c,inputSchema:f}]}function Jg(e,t,o,n){if(t.action!=="help")return null;const r=Nt(o),s=new Set(r),a=n.filter(u=>s.has(u.action)),i=typeof t.topic=="string"?t.topic.trim():"",c=i&&i!=="overview"?i:null;return c?s.has(c)?g($g(e,c,a)):it({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.`}}):g(Ng(e,r,a))}function qn(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 su(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 ct(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 g(n)}function g(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function Mn(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 le(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?g({success:!0,...t,...e}):g({success:!0,...e})}function yo(e,t){if(e instanceof Jh){const i=Lg(e,t==null?void 0:t.rawArgs),c={error:{type:"validation_error",message:Zg(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}:{},...zo(t)?{hint:zo(t)}:{}}};return it(c)}const o=e instanceof Error?e:new Error(String(e)),n=Bn(o),r=zo(t),s=n&&r?`${n.hint} ${r}`:(n==null?void 0:n.hint)??r,a={error:{type:Hg(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}:{},...Vg()&&o.stack?{details:o.stack}:{}}};return it(a)}function Ln(e,t,o){return it({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 Wg(e,t){return it({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 Kg(e,t,o){return it({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 ae(e){const{name:t,description:o,variants:n,handlers:r,actionSchema:s,aggregateOptions:a}=e;return{listTools(i){return Gg(t,o,i,n,a)},async callTool(i,c,u,l){const d=c??{},f=typeof d.action=="string"?d.action:void 0,h=f?zs(t,f):void 0,m=h&&h!==f?{...d,action:h}:d,k=Jg(t,m,u,n);if(k)return k;try{const v=n.map($=>$.action).filter($=>u.actions[$]);if(f&&!n.some($=>$.action===h))return Kg(t,f,v);const E=s.parse(m.action);if(!u.enabled||!u.actions[E])return Wg(t,E);const C=r[E];return C?await C({client:i,rawArgs:m,permMgr:l}):yo(new Error(`No handler registered for action "${E}" on tool "${t}".`),{tool:t,action:E,rawArgs:m})}catch(v){return yo(v,{tool:t,action:h??f,rawArgs:m})}}}}async function Zn(e,t){return e.request("/api/av/getAttributeView",{id:t})}async function Qg(e,t){return e.request("/api/av/renderAttributeView",t)}async function Xg(e,t){return e.request("/api/av/getAttributeViewKeys",{id:t})}async function ey(e,t){return e.request("/api/av/getAttributeViewFilterSort",{...t,blockID:t.blockID??""})}async function ty(e,t,o){return e.request("/api/av/searchAttributeView",{keyword:t,excludes:o})}async function oy(e,t){return e.request("/api/av/duplicateAttributeViewBlock",{avID:t})}async function au(e,t){return e.request("/api/lute/spinBlockDOM",{dom:t})}async function ny(e,t){return e.request("/api/av/getMirrorDatabaseBlocks",{avID:t})}async function iu(e,t){return e.request("/api/av/getAttributeViewPrimaryKeyValues",t)}async function ry(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 sy(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/prependBlock",r)}async function cu(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/appendBlock",r)}async function uu(e,t,o,n){const r={dataType:t,data:o,id:n};return e.request("/api/block/updateBlock",r)}async function lu(e,t){const o={id:t};return e.request("/api/block/deleteBlock",o)}async function ay(e,t,o,n){const r={id:t,previousID:o,parentID:n};return e.request("/api/block/moveBlock",r)}async function iy(e,t){const o={id:t};return e.request("/api/block/foldBlock",o)}async function cy(e,t){const o={id:t};return e.request("/api/block/unfoldBlock",o)}async function du(e,t){const o={id:t};return e.request("/api/block/getBlockKramdown",o)}async function Hn(e,t){const o={id:t};return e.request("/api/block/getChildBlocks",o)}async function Je(e,t){const o={id:t};return e.request("/api/block/getDocInfo",o)}async function uy(e,t,o,n){const r={fromID:t,toID:o,refIDs:n};return e.request("/api/block/transferBlockRef",r)}async function ly(e,t){return e.request("/api/block/getBlockInfo",{id:t})}async function dy(e,t,o){return e.request("/api/block/getBlockBreadcrumb",{id:t,excludeTypes:o})}async function pu(e,t){return e.request("/api/block/getBlockDOM",{id:t})}async function py(e){return e.request("/api/block/getRecentUpdatedBlocks",{})}async function fy(e,t){return e.request("/api/block/getBlocksWordCount",{ids:t})}async function hy(e,t){return e.request("/api/block/batchInsertBlock",{blocks:t})}async function my(e,t){return e.request("/api/block/batchUpdateBlock",{blocks:t})}async function gy(e,t,o,n){return e.request("/api/block/appendDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function yy(e,t,o,n){return e.request("/api/block/prependDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function by(e,t,o=!1,n=!1){return e.request("/api/block/getDocsInfo",{ids:t,refCount:o,av:n})}async function fu(e,t){const o={id:t};return e.request("/api/attr/getBlockAttrs",o)}async function ky(e,t){return e.request("/api/search/fullTextSearchBlock",t)}async function gt(e,t){const o={stmt:t},n=await e.request("/api/query/sql",o);return Array.isArray(n)?n:[]}async function wy(e,t){const o={k:t};return e.request("/api/search/searchTag",o)}async function _y(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBacklinkDoc",r)}async function vy(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBackmentionDoc",r)}async function Iy(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 Dy(e,t){return e.request("/api/search/findReplace",t)}async function Sy(e,t,o){return e.request("/api/search/searchAsset",{k:t,exts:o})}async function Ay(e,t,o,n=0){return e.request("/api/search/getAssetContent",{id:t,query:o,queryMethod:n})}async function Ty(e,t){return e.request("/api/search/fullTextSearchAssetContent",t)}async function Py(e,t,o){return e.request("/api/search/listInvalidBlockRefs",{page:t,pageSize:o})}async function de(e,t,o={}){return e.request("/api/transactions",{transactions:t,reqId:o.reqId??Date.now(),app:o.app??"",session:o.session??""})}async function hu(e,t,o,n){return e.request("/api/filetree/createDocWithMd",{notebook:t,path:o,markdown:n})}async function Ey(e,t,o,n){return e.request("/api/filetree/renameDoc",{notebook:t,path:o,title:n})}async function mu(e,t,o){return e.request("/api/filetree/renameDocByID",{id:t,title:o})}async function Cy(e,t,o){return e.request("/api/filetree/removeDoc",{notebook:t,path:o})}async function Wo(e,t){return e.request("/api/filetree/removeDocByID",{id:t})}async function Oy(e,t,o,n){return e.request("/api/filetree/moveDocs",{fromPaths:t,toNotebook:o,toPath:n})}async function gu(e,t,o){return e.request("/api/filetree/moveDocsByID",{fromIDs:t,toID:o})}async function Vn(e,t,o){return e.request("/api/filetree/getHPathByPath",{notebook:t,path:o})}async function To(e,t){return e.request("/api/filetree/getHPathByID",{id:t})}async function At(e,t){return e.request("/api/filetree/getPathByID",{id:t})}async function Xt(e,t,o){return e.request("/api/filetree/getIDsByHPath",{path:t,notebook:o})}async function xy(e,t,o){return e.request("/api/filetree/listDocsByPath",{notebook:t,path:o})}async function Qe(e,t,o){return e.request("/api/filetree/listDocTree",{notebook:t,path:o})}async function Ny(e,t,o,n){return e.request("/api/filetree/searchDocs",{k:t,flashcard:o,excludeIDs:n})}async function $y(e,t,o,n){return e.request("/api/filetree/getDoc",{id:t,mode:o,size:n})}async function Ry(e,t,o){return e.request("/api/filetree/createDailyNote",{notebook:t,app:o})}async function zy(e,t){return e.request("/api/filetree/duplicateDoc",{id:t})}async function Fy(e,t){return e.request("/api/filetree/removeDocs",{paths:t})}async function By(e,t,o,n,r){return e.request("/api/filetree/heading2Doc",{srcHeadingID:t,targetNoteBook:o,targetPath:n,previousPath:r})}async function jy(e,t,o,n=!1){return e.request("/api/filetree/doc2Heading",{srcID:t,targetID:o,after:n})}async function Ne(e){return e.request("/api/notebook/lsNotebooks")}async function Uy(e,t){return e.request("/api/notebook/openNotebook",{notebook:t})}async function qy(e,t){return e.request("/api/notebook/closeNotebook",{notebook:t})}async function My(e,t){return e.request("/api/notebook/createNotebook",{name:t})}async function Ly(e,t){return e.request("/api/notebook/removeNotebook",{notebook:t})}async function Zy(e,t,o){return e.request("/api/notebook/renameNotebook",{notebook:t,name:o})}async function Hy(e,t){return e.request("/api/notebook/getNotebookConf",{notebook:t})}async function Vy(e,t,o){return e.request("/api/notebook/setNotebookConf",{notebook:t,conf:o})}async function yu(e,t,o){return e.request("/api/notebook/setNotebookIcon",{notebook:t,icon:o})}function Yy(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Ae(e){return e.startsWith("/")?e:`/${e}`}function Gy(e){const t=Ae(e).split("/").filter(Boolean).at(-1)??"";return t.endsWith(".sy")?t.slice(0,-3):t}function ge(e){return e.replace(/\0/g,"").replace(/'/g,"''")}async function Jy(e,t){const o=await gt(e,`SELECT id, root_id, box, path, hpath, content, type FROM blocks WHERE id = '${ge(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:Ae(s),hPath:i,name:c}}async function Be(e,t){try{const s=await Jy(e,t);if(s)return s}catch{}const o=await Je(e,t),n=o.rootID||o.id,r=await At(e,n);return{documentId:n,notebook:r.notebook,path:Ae(r.path),name:o.name}}const Wy=500;function bu(e,t,o){if(e.size>=Wy){const n=e.keys().next().value;n!==void 0&&e.delete(n)}e.set(t,o)}function Mt(){return{documentContextById:new Map,notebookByPath:new Map}}async function Ky(e,t,o){if(!o)return Be(e,t);let n=o.documentContextById.get(t);return n||(n=Be(e,t),bu(o.documentContextById,t,n)),n}async function Qy(e,t,o){const n=Ae(t);if(!o)return Ft(e,n);let r=o.notebookByPath.get(n);return r||(r=Ft(e,n),bu(o.notebookByPath,n,r)),r}async function Lt(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:Ae(s),documentId:a};if(a)try{const i=await Ky(e,a,o);return{notebook:i.notebook,path:i.path,documentId:i.documentId}}catch{}if(s){const i=await Qy(e,s,o);if(i)return{notebook:r??i,path:Ae(s),documentId:a}}return r?{notebook:r,path:s?Ae(s):void 0,documentId:a}:null}async function Xy(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t.notebook):o==="write"?e.canWrite(t.notebook):e.canRead(t.notebook))?null:Ln(t.notebook,e.get(t.notebook),o)}async function S(e,t,o,n){const r=await Be(e,o),s=await Xy(t,r,n);return{context:r,denied:s}}async function q(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t))?null:Ln(t,e.get(t),o)}async function eb(e,t){const n=(await Ne(e)).notebooks.find(s=>s.id===t);return n?n.id:(await Be(e,t)).notebook}async function Ft(e,t){const o=await Ne(e);for(const n of o.notebooks)try{return await Vn(e,n.id,t),n.id}catch{continue}return null}async function Po(e,t,o){const n=await xy(e,t,o);return n.files.map(r=>({id:typeof r.id=="string"&&r.id.length>0?r.id:Gy(r.path),notebook:r.box||n.box||t,path:Ae(r.path),hPath:r.hPath,name:Yy(r.name),icon:r.icon,subFileCount:r.subFileCount??r.count}))}async function tb(e){return e.request("/api/system/getWorkspaceInfo",{})}async function ob(e){return e.request("/api/system/getNetwork",{})}async function nb(e){return e.request("/api/system/getConf",{})}async function rb(e){return e.request("/api/system/version")}async function sb(e){return e.request("/api/system/currentTime")}async function ab(e){return e.request("/api/ui/reloadIcon",{})}async function ib(e){return e.request("/api/ui/reloadFiletree",{})}async function cb(e,t){return e.request("/api/ui/reloadProtyle",{id:t})}async function ub(e,t){return e.request("/api/ui/reloadAttributeView",{id:t})}async function lb(e){return e.request("/api/ui/reloadTag",{})}function db(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 pb(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 fb(e,t){switch(t.type){case"reloadProtyle":await cb(e,t.id);return;case"reloadAttributeView":await ub(e,t.id);return;case"reloadIcon":await ab(e);return;case"reloadFiletree":await ib(e);return;case"reloadTag":await lb(e);return;default:{const o=t;throw new Error(`Unknown UI refresh operation: ${String(o)}`)}}}async function T(e,t,o){if(t.isError||o.length===0||!e||typeof e.request!="function")return t;const n=db(t);if(!n)return t;const r=pb(o),s=[];for(const a of r)try{await fb(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 Zt(e){return new Promise(t=>{setTimeout(t,e)})}const Xe="av";function et(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 Br=6,hb=500,jr=6,mb=300,gb="/data/storage/av",yb=/^\d{14}-[a-z0-9]{7}$/;function bb(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 kb(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 Yn(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 ku(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 wb(e){return Yn(e,["blockID","itemId","itemID","rowID"])??ku(e,["block","blockID"])}function _b(e){return ku(e,["block","id"])??Yn(e,["srcID","srcId"])}function vb(e){return Yn(e,["id"])}function Gn(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 u=c,l=u.values;Array.isArray(l)&&l.forEach(d=>{var v;const f=wb(d);if(!f)return;let h=t.get(f);h||(h={rowID:f,valueIDs:[]},t.set(f,h),o.push(h));const m=vb(d),k=((v=u.key)==null?void 0:v.type)==="block"?_b(d):void 0;k&&(h.sourceBlockID=k),m&&!h.valueIDs.includes(m)&&h.valueIDs.push(m)})}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 u=a.get(c.sourceBlockID)??[];u.includes(c.rowID)||(u.push(c.rowID),a.set(c.sourceBlockID,u))}if(c.rowID)for(const u of c.valueIDs){const l=i.get(u)??[];l.includes(c.rowID)||(l.push(c.rowID),i.set(u,l))}}return{rows:r,rowIDs:s,sourceBlockToRowIDs:a,valueIdToRowIDs:i}}function bt(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:Xe,action:e,...t}},null,2)}],isError:!0}}function Ib(e,t,o,n=[]){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:Xe,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 Db(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 Sb(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 Ab(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<Br;s+=1){const a=await Zn(e,t),i=Gn(a.av),c=Db(i,o),u=Sb(i,n);if(r={rows:[...c.rows,...u.rows],unresolvedBlockIDs:c.unresolvedBlockIDs,unresolvedRowIDs:u.unresolvedRowIDs},r.unresolvedBlockIDs.length===0&&(!r.unresolvedRowIDs||r.unresolvedRowIDs.length===0))return r;s<Br-1&&await Zt(hb)}return r}function Tb(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:bt(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:bt(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:bt(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:bt(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:bt(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 Pb(e,t){const o=bb(t);return{avData:t,blockID:o}}function Eb(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 wu(e,t){try{return Eb(await ny(e,t))}catch(o){if(jn(o))return[];throw o}}async function Cb(e,t){const o=ge(t),n=await gt(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 Jn(e,t,o){const n=[],r=await Pb(e,o);r.blockID&&n.push(r.blockID);const s=await wu(e,t);for(const i of s)n.includes(i)||n.push(i);const a=await Cb(e,t);for(const i of a)n.includes(i)||n.push(i);return n}async function Ob(e,t,o,n){if((await Jn(e,t,o)).includes(n))return!0;try{const s=await pu(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(jn(s))return!1;throw s}}function xb(e,t,o){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:Xe,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 re(e,t,o,n,r){const a=(await Zn(e,o)).av;if(r!=null&&r.blockID){const{denied:c}=await S(e,t,r.blockID,n);return c?{denied:c,avData:a}:await Ob(e,o,a,r.blockID)?{denied:null,avData:a}:{denied:xb(r.action??"get",o,r.blockID),avData:a}}const i=await Jn(e,o,a);for(const c of i)try{const{denied:u}=await S(e,t,c,n);return{denied:u,avData:a}}catch(u){if(jn(u))continue;throw u}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 Nb(e){return e instanceof Error&&e.message.includes("The database may have no rows yet; AV writes require a resolvable owning block context.")}function $b(e){var t;return e instanceof Error&&((t=Bn(e))==null?void 0:t.code)==="av_not_found"}async function Rb(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 S(e,t,o.blockID,"write");return{denied:s,shouldMaterialize:!0,targetDocumentId:a.documentId}}try{const{denied:s}=await re(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){if(!(Nb(s)||$b(s)))throw s;const{denied:i,context:c}=await S(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 re(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){throw s}}async function Wn(e,t,o){const n=o??(await Zn(e,t)).av;return(await Jn(e,t,n))[0]}async function ut(e,t,o,n){const r=[];n&&r.push(n);try{const s=await Wn(e,t,o);s&&!r.includes(s)&&r.push(s)}catch{}for(const s of r)try{const a=await Be(e,s);if(a.documentId)return[{type:"reloadProtyle",id:a.documentId}]}catch{}return[{type:"reloadAttributeView",id:t}]}async function zb(e,t,o){const n=Mt();await t.reload();const r=[],s=[];let a=0,i=0,c=0;for(const u of o){const l=await Lt(e,u,n);if(!(l!=null&&l.notebook)){a+=1,i+=1,s.push(u);continue}if(!t.canRead(l.notebook)){a+=1,c+=1;continue}r.push(u)}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 Fb(e){const t=await e.request("/api/file/readDir",{path:gb});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=>yb.test(o))}function Bb(e){if(!e||typeof e!="object")return[];const t=e.values;return Array.isArray(t)?t.filter(o=>!!(o&&typeof o=="object")):[]}async function jb(e,t,o){if(!t.trim())return[];if(typeof e.request!="function")return[];const n=new Set(o??[]),r=await Fb(e),s=[];for(const a of r)if(!n.has(a))try{const i=await iu(e,{id:a,keyword:t,page:1,pageSize:3}),c=Bb(i.rows);if(c.length===0)continue;const u=Array.isArray(i.blockIDs)?i.blockIDs.filter(l=>typeof l=="string"&&l.length>0):[];if(u.length===0)continue;s.push({avID:a,avName:i.name,blockID:u[0],blockIDs:u,rows:i.rows,matchedRowCount:c.length,matchSource:"primary_key"})}catch{}return s}function Ur(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 _u(e,t){return`<div class="av" data-node-id="${e}" data-av-id="${t}" data-type="NodeAttributeView" data-av-type="table"></div>`}function Ub(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 lt(e,t,o,n){return n??await Wn(e,t,o)}function dt(e,t,o){if(!t)return{doOperations:e,undoOperations:[]};const n=Ub();return{doOperations:[...e,{action:"doUpdateUpdated",id:t,data:n}],undoOperations:[{action:"doUpdateUpdated",id:t,data:""}]}}function qr(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=Ur(o.date,"date"),s=o.endDate===void 0?0:Ur(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(`
127
- `);return{...n,type:"mAsset",text:{content:s},mAsset:r}}default:throw new Error(`Unsupported AV valueType: ${o.valueType}`)}}async function qb({client:e,permMgr:t,rawArgs:o}){const n=gc.parse(o),{denied:r,avData:s}=await re(e,t,n.id,"read",{blockID:n.blockID,action:"get"});if(r)return r;const a=Gn(s);return g({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 Mb({client:e,permMgr:t,rawArgs:o}){const n=wc.parse(o),r=await ty(e,n.keyword,n.excludes),s=Array.isArray(r.results)?r.results:[],a=await jb(e,n.keyword,n.excludes),i=[...s],c=new Set(i.map(l=>l&&typeof l=="object"?l.avID:void 0).filter(l=>typeof l=="string"&&l.length>0));for(const l of a){const d=l.avID;typeof d=="string"&&c.has(d)||(typeof d=="string"&&c.add(d),i.push(l))}const u=await zb(e,t,i);return g({keyword:n.keyword,searchScope:{kernel:"attribute_view_name_or_kernel_candidates",fallback:"primary_key_values"},...u,...u.filteredOutCount>0?{emptyReason:u.results.length===0?u.unresolvedCount>0&&u.permissionFilteredOutCount===0?"no_verified_results_unresolved_candidates_available":u.permissionFilteredOutCount>0&&u.unresolvedCount===0?"all_results_permission_filtered":"all_results_filtered":void 0,unresolvedHint:u.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&&u.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 Lb({client:e,permMgr:t,rawArgs:o}){const n=yc.parse(o),r=new Date,s=!n.id,a=n.id??et(r),i=await Rb(e,t,n,a,s);if(i.denied)return i.denied;const c=await Qg(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 u,l;if(i.shouldMaterialize){u=et(r);let B=_u(u,a);try{const x=await au(e,B);typeof x.dom=="string"&&x.dom.length>0&&(B=x.dom)}catch{}await de(e,[{doOperations:[{action:"insert",id:u,data:B,parentID:n.blockID}],undoOperations:[{action:"delete",id:u}]}]),l=!1;for(let x=0;x<jr;x+=1){if((await wu(e,a)).includes(u)){l=!0;break}if(x===jr-1)break;await Zt(mb)}}const d=c&&typeof c=="object"&&!Array.isArray(c)?c:{},f=Array.isArray(d.rows)?d.rows:[],h=n.page??1,m=n.pageSize??(f.length||1),k=typeof d.pageCount=="number"?d.pageCount:1,v=typeof d.rowCount=="number"?d.rowCount:f.length,{rows:E,pageCount:C,rowCount:$,...I}=d,A=ct(f,{total:v,page:h,pageSize:m,pageCount:k,hasNextPage:h<k},{...I,avID:a,id:a,...n.createIfNotExist===!0?{generatedAvID:s}:{},...i.shouldMaterialize?{materialized:!0,blockID:u,parentID:n.blockID,databaseBlockRegistrationVerified:l===!0,...l===!1?{warning:`Created attribute view "${a}" and materialized database block "${u}", 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?T(e,A,[{type:"reloadAttributeView",id:a},...i.targetDocumentId?[{type:"reloadProtyle",id:i.targetDocumentId}]:[]]):A}async function Zb({client:e,permMgr:t,rawArgs:o}){const n=bc.parse(o),{denied:r,avData:s}=await re(e,t,n.id,"read");if(r)return r;const a=await Xg(e,n.id),i=a&&typeof a=="object"&&!Array.isArray(a)&&Array.isArray(a.keys)?a.keys:Array.isArray(a)&&a.length>0?a:kb(s);return g({avID:n.id,keys:i})}async function Hb({client:e,permMgr:t,rawArgs:o}){const n=kc.parse(o),{denied:r}=await re(e,t,n.id,"read");if(r)return r;const s=await ey(e,{id:n.id,blockID:n.blockID??""});return g({avID:n.id,...n.blockID?{blockID:n.blockID}:{},...s})}async function Vb({client:e,permMgr:t,rawArgs:o}){const n=_c.parse(o),{denied:r,avData:s}=await re(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 le({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(m=>({primaryKeyText:m,rowID:et(),srcID:et()})),u=await lt(e,n.avID,s,n.blockID),l=[...a.map(m=>({itemID:et(),id:m,isDetached:!1})),...c.map(m=>({itemID:m.rowID,id:m.srcID,isDetached:!0,content:m.primaryKeyText}))],d=dt([{action:"insertAttrViewBlock",avID:n.avID,blockID:u,viewID:n.viewID,groupID:n.groupID,previousID:n.previousID,ignoreDefaultFill:n.ignoreDefaultFill,srcs:l}],u);await de(e,[{doOperations:d.doOperations,undoOperations:[{action:"removeAttrViewBlock",srcIDs:[...a,...c.map(m=>m.rowID)],avID:n.avID},...d.undoOperations]}]);const f=await Ab(e,n.avID,a,c.map(m=>({primaryKeyText:m.primaryKeyText,rowID:m.rowID})));if(f.unresolvedBlockIDs.length>0||f.unresolvedRowIDs&&f.unresolvedRowIDs.length>0)return Ib(n.avID,a,f,i);const h=await ut(e,n.avID,s,n.blockID);return T(e,le({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 Yb({client:e,permMgr:t,rawArgs:o}){const n=vc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_rows"});if(r)return r;const a=await lt(e,n.avID,s,n.blockID),i=dt([{action:"removeAttrViewBlock",srcIDs:n.srcIDs,avID:n.avID}],a);await de(e,[{doOperations:i.doOperations,undoOperations:i.undoOperations}]);const c=await ut(e,n.avID,s,n.blockID);return T(e,le({action:"remove_rows",avID:n.avID,srcIDs:n.srcIDs,removed:n.srcIDs.length}),c)}async function Gb({client:e,permMgr:t,rawArgs:o}){const n=Ic.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"add_column"});if(r)return r;const a=n.keyID??et(),i=await lt(e,n.avID,s,n.blockID),c=dt([{action:"addAttrViewCol",name:n.keyName,avID:n.avID,type:n.keyType,id:a,data:n.keyIcon??"",previousID:n.previousKeyID??""}],i);await de(e,[{doOperations:c.doOperations,undoOperations:[{action:"removeAttrViewCol",id:a,avID:n.avID},...c.undoOperations]}]);const u=await ut(e,n.avID,s,n.blockID);return T(e,le({action:"add_column",avID:n.avID,keyID:a,keyName:n.keyName,keyType:n.keyType}),u)}async function Jb({client:e,permMgr:t,rawArgs:o}){const n=Dc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_column"});if(r)return r;const a=n.keyID??n.columnID,i=await lt(e,n.avID,s,n.blockID),c=dt([{action:"removeAttrViewCol",id:a,avID:n.avID,removeDest:n.removeRelationDest??!1}],i);await de(e,[{doOperations:c.doOperations,undoOperations:c.undoOperations}]);const u=await ut(e,n.avID,s,n.blockID);return T(e,le({action:"remove_column",avID:n.avID,keyID:a,removeRelationDest:n.removeRelationDest??!1}),u)}async function Wb({client:e,permMgr:t,rawArgs:o}){const n=Sc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"set_cells"});if(r)return r;const a=Gn(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}],u=[];for(let h=0;h<c.length;h+=1){const m=c[h],k=Tb(n.avID,"set_cells",a,m.rowID,i?void 0:h);if(k.ok===!1)return k.result;if(i){const v=await lt(e,n.avID,s,n.blockID),E=dt([{action:"updateAttrViewCell",avID:n.avID,keyID:m.columnID,rowID:k.rowID,data:qr(m.columnID,k.rowID,m)}],v);await de(e,[{doOperations:E.doOperations,undoOperations:E.undoOperations}]);const C=await ut(e,n.avID,s,n.blockID);return T(e,le({action:"set_cells",avID:n.avID,rowID:m.rowID,columnID:m.columnID,valueType:m.valueType}),C)}u.push({action:"updateAttrViewCell",avID:n.avID,keyID:m.columnID,rowID:k.rowID,data:qr(m.columnID,k.rowID,m)})}const l=await lt(e,n.avID,s,n.blockID),d=dt(u,l);await de(e,[{doOperations:d.doOperations,undoOperations:d.undoOperations}]);const f=await ut(e,n.avID,s,n.blockID);return T(e,le({action:"set_cells",avID:n.avID,updated:c.length}),f)}async function Kb({client:e,permMgr:t,rawArgs:o}){const n=Ac.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"duplicate"});if(r)return r;const a=await oy(e,n.avID);if(!a.avID||!a.blockID)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Xe,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 Wn(e,n.avID,s);if(!i)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Xe,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 S(e,t,i,"write");if(c.denied)return c.denied;let u=_u(a.blockID,a.avID);try{const l=await au(e,u);typeof l.dom=="string"&&l.dom.length>0&&(u=l.dom)}catch{}try{await de(e,[{doOperations:[{action:"insert",id:a.blockID,data:u,previousID:i}],undoOperations:[{action:"delete",id:a.blockID}]}])}catch(l){const d=l instanceof Error?l:new Error(String(l));return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Xe,action:"duplicate",reason:"duplicate_insert_failed",message:d.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 le({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 Qb({client:e,permMgr:t,rawArgs:o}){const n=Tc.parse(o),{denied:r}=await re(e,t,n.avID,"read");if(r)return r;const s=await iu(e,{id:n.avID,keyword:n.keyword,page:n.page,pageSize:n.pageSize}),a=s.blockIDs??[];if(a.length>0){const i=Mt();await t.reload();const c=[],u=[];let l=0;for(let d=0;d<a.length;d+=1){const f=a[d],h=await Lt(e,{id:f},i)??await Be(e,f).catch(()=>null),m=h&&"notebook"in h?h.notebook:void 0;if(!m||!t.canRead(m)){l+=1;continue}c.push(f),u.push(s.rows[d])}return g({avID:n.avID,name:s.name,blockIDs:c,rows:u,...l>0?{filteredOutCount:l,partial:!0,reason:"permission_filtered"}:{}})}return g({avID:n.avID,...s})}const Xb={get:qb,render:Lb,get_attribute_view_keys:Zb,get_attribute_view_filter_sort:Hb,search:Mb,add_rows:Vb,remove_rows:Yb,add_column:Gb,remove_column:Jb,set_cells:Wb,duplicate:Kb,get_primary_key_values:Qb},ek=[w("get",gc,"Get the full attribute view payload by AV ID; blockID is an optional exact database-block context."),w("render",yc,"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."),w("get_attribute_view_keys",bc,"Get the column (key) definitions of an attribute view."),w("get_attribute_view_filter_sort",kc,"Get filter and sort settings for an attribute view."),w("search",wc,"Search attribute views by name or primary-key values."),w("add_rows",_c,"Add bound block rows or detached plain-text primary-key rows to a database."),w("remove_rows",vc,"Remove rows from a database."),w("add_column",Ic,"Add a column to a database."),w("remove_column",Dc,"Remove a column from a database."),w("set_cells",Sc,"Set one or more cell values in a database. Provide cells/items, or pass rowID + columnID + valueType for a single-cell write."),w("duplicate",Ac,"Duplicate an attribute view using SiYuan copy-as-mirror semantics; previousID overrides the insertion target."),w("get_primary_key_values",Tc,"Get primary key values for an attribute view.")],vu=ae({name:"av",description:"🗃️ Grouped attribute-view (database) operations.",variants:ek,actionSchema:dg,aggregateOptions:{guidance:qs,actionHints:Qs},handlers:Xb});function tk(e){return vu.listTools(e)}async function ok(e,t,o,n){return vu.callTool(e,t,o,n)}const nk=/[\u200B\u200C\u200D\u2060\uFEFF]/g,rk=/<[^>]+>/g;function Kn(e){return e.replace(nk,"")}function Ht(e){return{...e,content:Kn(e.content)}}function Iu(e){return{...e,kramdown:Kn(e.kramdown)}}function Du(e){return e.replace(rk,"")}function Su(e){const t=e==null?void 0:e.trim().toLowerCase();return t||void 0}const Au={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"},Mr={keyword:0,query:1,query_syntax:1,sql:2,regex:3},sk={0:"keyword",1:"query_syntax",2:"sql",3:"regex"};function ak(e){const t={};for(const o of e){const n=Au[o];n&&(t[n]=!0)}return t}function ik(e){const t={};for(const[o,n]of Object.entries(e)){const r=Au[o];r?t[r]=n:t[o]=n}return t}function ck(e,t){const o=Su(e);return o&&o in Mr?Mr[o]:t}function uk(e){if(e!==void 0)return sk[e]}const lk={relevance:7,date:4,updated_desc:4,updated_asc:3,created_desc:2,created_asc:1,type:0},dk={7:"relevance",4:"updated_desc",3:"updated_asc",2:"created_desc",1:"created_asc",0:"type"},pk={relevance:0,relevance_desc:0,relevance_asc:1,updated_asc:2,updated_desc:3},fk={0:"relevance_desc",1:"relevance_asc",2:"updated_asc",3:"updated_desc"};function Ko(e,t,o=lk){const n=Su(e);return n&&n in o?o[n]:t}function Lr(e){if(e!==void 0)return dk[e]}function hk(e,t){return Ko(e,t,pk)}function mk(e){if(e!==void 0)return fk[e]}function gk(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=Du(s)),r})}:e}const yk=["id","type","box"],bk=["hPath","hpath"],kk=["content","plainContent","markdown","name","alias","memo","tag","subType","subtype","path","parentID","parent_id","rootID","root_id"];function Zr(e){return!(e==null||e===""||Array.isArray(e)&&e.length===0)}function wk(e){const t={};for(const o of yk)o in e&&(t[o]=e[o]);for(const o of bk)if(Zr(e[o])){t.hPath=e[o];break}for(const o of kk)Zr(e[o])&&(t[o]=e[o]);return t}const _k=/<mark>[^<]*<\/mark>/g,Fo=400,vk=150;function Ik(e,t=vk){if(e.length<=Fo)return e;const o=[...e.matchAll(_k)];if(o.length===0)return e.length>Fo?e.slice(0,Fo)+"...":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 Hr=400,Vr=200;function Dk(e){return e.map(t=>{if(!t||typeof t!="object")return t;const n=wk(t);if(n.type==="NodeDocument")return n;if(typeof n.content=="string"){const r=Du(n.content).trim();r.length>0&&(n.excerpt=r.length>Vr?r.slice(0,Vr)+"...":r),n.content=Ik(n.content)}return typeof n.markdown=="string"&&n.markdown.length>Hr&&(n.markdown=n.markdown.slice(0,Hr)+"..."),n})}function Sk(e){const t=gk({blocks:e});return Dk(Array.isArray(t.blocks)?t.blocks:[])}function Ak(e,t){let o=0,n=0;for(;;){if(n=e.indexOf(t,n),n===-1)return o;o+=1,n+=t.length}}function Tk(e,t,o,n){const r=Ak(e,t.old);if(r===0)throw new Error(`${n} edit #${o+1} did not match any text.`);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 Qo(e,t,o){let n=e;const r=t.map((s,a)=>{const i=Tk(n,s,a,o);return n=i.content,{index:a+1,replaced:i.replaced,replace_all:i.replaceAll}});return{content:n,summary:r}}function Pk(e){const t=e.notebook??e.box??e.boxID??e.notebookId;return typeof t=="string"&&t.length>0?t:void 0}async function Tu(e){const t=await Ne(e),o=new Map;for(const n of t.notebooks??[])n.id&&n.name&&o.set(n.id,n.name);return o}async function Xo(e,t){if(t)try{return(await Tu(e)).get(t)}catch{return}}async function Ek(e,t){if(t.filter(n=>n!==null&&typeof n=="object").length===0)return t;try{const n=await Tu(e);return t.map(r=>{if(r===null||typeof r!="object")return r;const s=r,a=Pk(s),i=a?n.get(a):void 0;return i?{...s,notebookName:i}:r})}catch{return t}}function Ck(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 en(e,t){const o=e.filter(n=>{const r=Ck(n);return!r||t.canRead(r)});return{items:o,removedCount:e.length-o.length}}function ze(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 Ok(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 eo(e,t,o){const n=Mt(),r=[];let s=0;for(const a of t){const i=await Lt(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 Bo(e,t,o,n){const r=Mt(),s=[];let a=0,i=0;const c=typeof n=="string"&&n.length>0?n.startsWith("/")?n:`/${n}`:void 0;for(const u of t){const l=await Lt(e,u,r);if(!(l!=null&&l.notebook)||!o.canRead(l.notebook)){a+=1;continue}if(c&&(!l.path||!(l.path===c||l.path.startsWith(`${c}/`)))){i+=1;continue}s.push(u)}return{items:s,permissionFilteredOutCount:a,pathFilteredOutCount:i}}function Yr(e,t){if(!Array.isArray(e.blocks))return e;const{items:o,removedCount:n}=en(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 to(e,t){const o=Array.isArray(e.backlinks)?en(e.backlinks,t):void 0,n=Array.isArray(e.backmentions)?en(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}:{},...ze(r)}}function xk(e){return e.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_").replace(/'/g,"''")}function Nk(e){return!!e&&typeof e=="object"}const ye="Only SELECT statements and WITH CTEs whose main statement is SELECT are allowed. Mutation queries (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE) are forbidden.";function $k(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]!==`
126
+ `)}function ey(e,t,o,n,r={}){if(!o.enabled)return[];const s=$t(o),a=new Set(s),i=n.filter(h=>a.has(h.action));if(i.length===0)return[];const c=Xg(e,t,s,i,r),u=s.filter(h=>rt(e,h)),l=Ng(i,r.propertyDescriptionOverrides);"topic"in l||(l.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 d=[...i.map(h=>Mg(h)),Hg(s)],f=Yn({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.${u.length>0?` User confirmation is required before calling: ${u.join(", ")}.`:""}`},...Zg(l)},additionalProperties:!0});return Object.defineProperty(f,qg,{value:d,enumerable:!1}),[{name:e,description:c,inputSchema:f}]}function ty(e,t,o,n){if(t.action!=="help")return null;const r=$t(o),s=new Set(r),a=n.filter(u=>s.has(u.action)),i=typeof t.topic=="string"?t.topic.trim():"",c=i&&i!=="overview"?i:null;return c?s.has(c)?g(Ug(e,c,a)):ut({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.`}}):g(jg(e,r,a))}function Gn(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 lu(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 Fe(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 g(n)}function g(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function Jn(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 le(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?g({success:!0,...t,...e}):g({success:!0,...e})}function wo(e,t){if(e instanceof tm){const i=Jg(e,t==null?void 0:t.rawArgs),c={error:{type:"validation_error",message:Wg(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}:{},...qo(t)?{hint:qo(t)}:{}}};return ut(c)}const o=e instanceof Error?e:new Error(String(e)),n=Hn(o),r=qo(t),s=n&&r?`${n.hint} ${r}`:(n==null?void 0:n.hint)??r,a={error:{type:Kg(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}:{},...Qg()&&o.stack?{details:o.stack}:{}}};return ut(a)}function Wn(e,t,o){return ut({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 oy(e,t){return ut({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 ny(e,t,o){return ut({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 ae(e){const{name:t,description:o,variants:n,handlers:r,actionSchema:s,aggregateOptions:a}=e;return{listTools(i){return ey(t,o,i,n,a)},async callTool(i,c,u,l){const d=c??{},f=typeof d.action=="string"?d.action:void 0,h=f?qs(t,f):void 0,m=h&&h!==f?{...d,action:h}:d,_=ty(t,m,u,n);if(_)return _;try{const v=n.map(C=>C.action).filter(C=>u.actions[C]);if(f&&!n.some(C=>C.action===h))return ny(t,f,v);const A=s.parse(m.action);if(!u.enabled||!u.actions[A])return oy(t,A);const x=r[A];return x?await x({client:i,rawArgs:m,permMgr:l}):wo(new Error(`No handler registered for action "${A}" on tool "${t}".`),{tool:t,action:A,rawArgs:m})}catch(v){return wo(v,{tool:t,action:h??f,rawArgs:m})}}}}async function Kn(e,t){return e.request("/api/av/getAttributeView",{id:t})}async function ry(e,t){return e.request("/api/av/renderAttributeView",t)}async function sy(e,t){return e.request("/api/av/getAttributeViewKeys",{id:t})}async function ay(e,t){return e.request("/api/av/getAttributeViewFilterSort",{...t,blockID:t.blockID??""})}async function iy(e,t,o){return e.request("/api/av/searchAttributeView",{keyword:t,excludes:o})}async function cy(e,t){return e.request("/api/av/duplicateAttributeViewBlock",{avID:t})}async function du(e,t){return e.request("/api/lute/spinBlockDOM",{dom:t})}async function uy(e,t){return e.request("/api/av/getMirrorDatabaseBlocks",{avID:t})}async function pu(e,t){return e.request("/api/av/getAttributeViewPrimaryKeyValues",t)}async function ly(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 dy(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/prependBlock",r)}async function fu(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/appendBlock",r)}async function hu(e,t,o,n){const r={dataType:t,data:o,id:n};return e.request("/api/block/updateBlock",r)}async function mu(e,t){const o={id:t};return e.request("/api/block/deleteBlock",o)}async function py(e,t,o,n){const r={id:t,previousID:o,parentID:n};return e.request("/api/block/moveBlock",r)}async function fy(e,t){const o={id:t};return e.request("/api/block/foldBlock",o)}async function hy(e,t){const o={id:t};return e.request("/api/block/unfoldBlock",o)}async function gu(e,t){const o={id:t};return e.request("/api/block/getBlockKramdown",o)}async function Qn(e,t){const o={id:t};return e.request("/api/block/getChildBlocks",o)}async function Ke(e,t){const o={id:t};return e.request("/api/block/getDocInfo",o)}async function my(e,t,o,n){const r={fromID:t,toID:o,refIDs:n};return e.request("/api/block/transferBlockRef",r)}async function gy(e,t){return e.request("/api/block/getBlockInfo",{id:t})}async function yy(e,t,o){return e.request("/api/block/getBlockBreadcrumb",{id:t,excludeTypes:o})}async function yu(e,t){return e.request("/api/block/getBlockDOM",{id:t})}async function by(e){return e.request("/api/block/getRecentUpdatedBlocks",{})}async function ky(e,t){return e.request("/api/block/getBlocksWordCount",{ids:t})}async function wy(e,t){return e.request("/api/block/batchInsertBlock",{blocks:t})}async function _y(e,t){return e.request("/api/block/batchUpdateBlock",{blocks:t})}async function vy(e,t,o,n){return e.request("/api/block/appendDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function Iy(e,t,o,n){return e.request("/api/block/prependDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function Dy(e,t,o=!1,n=!1){return e.request("/api/block/getDocsInfo",{ids:t,refCount:o,av:n})}async function bu(e,t){const o={id:t};return e.request("/api/attr/getBlockAttrs",o)}async function Sy(e,t){return e.request("/api/search/fullTextSearchBlock",t)}async function yt(e,t){const o={stmt:t},n=await e.request("/api/query/sql",o);return Array.isArray(n)?n:[]}async function Ay(e,t){const o={k:t};return e.request("/api/search/searchTag",o)}async function Ty(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBacklinkDoc",r)}async function Py(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBackmentionDoc",r)}async function Ey(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 Cy(e,t){return e.request("/api/search/findReplace",t)}async function Oy(e,t,o){return e.request("/api/search/searchAsset",{k:t,exts:o})}async function xy(e,t,o,n=0){return e.request("/api/search/getAssetContent",{id:t,query:o,queryMethod:n})}async function Ny(e,t){return e.request("/api/search/fullTextSearchAssetContent",t)}async function Ry(e,t,o){return e.request("/api/search/listInvalidBlockRefs",{page:t,pageSize:o})}async function de(e,t,o={}){return e.request("/api/transactions",{transactions:t,reqId:o.reqId??Date.now(),app:o.app??"",session:o.session??""})}async function ku(e,t,o,n){return e.request("/api/filetree/createDocWithMd",{notebook:t,path:o,markdown:n})}async function $y(e,t,o,n){return e.request("/api/filetree/renameDoc",{notebook:t,path:o,title:n})}async function wu(e,t,o){return e.request("/api/filetree/renameDocByID",{id:t,title:o})}async function zy(e,t,o){return e.request("/api/filetree/removeDoc",{notebook:t,path:o})}async function on(e,t){return e.request("/api/filetree/removeDocByID",{id:t})}async function Fy(e,t,o,n){return e.request("/api/filetree/moveDocs",{fromPaths:t,toNotebook:o,toPath:n})}async function _u(e,t,o){return e.request("/api/filetree/moveDocsByID",{fromIDs:t,toID:o})}async function Xn(e,t,o){return e.request("/api/filetree/getHPathByPath",{notebook:t,path:o})}async function Oo(e,t){return e.request("/api/filetree/getHPathByID",{id:t})}async function Tt(e,t){return e.request("/api/filetree/getPathByID",{id:t})}async function no(e,t,o){return e.request("/api/filetree/getIDsByHPath",{path:t,notebook:o})}async function By(e,t,o){return e.request("/api/filetree/listDocsByPath",{notebook:t,path:o})}async function et(e,t,o){return e.request("/api/filetree/listDocTree",{notebook:t,path:o})}async function jy(e,t,o,n){return e.request("/api/filetree/searchDocs",{k:t,flashcard:o,excludeIDs:n})}async function Uy(e,t,o,n){return e.request("/api/filetree/getDoc",{id:t,mode:o,size:n})}async function qy(e,t,o){return e.request("/api/filetree/createDailyNote",{notebook:t,app:o})}async function My(e,t){return e.request("/api/filetree/duplicateDoc",{id:t})}async function Ly(e,t){return e.request("/api/filetree/removeDocs",{paths:t})}async function Zy(e,t,o,n,r){return e.request("/api/filetree/heading2Doc",{srcHeadingID:t,targetNoteBook:o,targetPath:n,previousPath:r})}async function Hy(e,t,o,n=!1){return e.request("/api/filetree/doc2Heading",{srcID:t,targetID:o,after:n})}async function Re(e){return e.request("/api/notebook/lsNotebooks")}async function Vy(e,t){return e.request("/api/notebook/openNotebook",{notebook:t})}async function Yy(e,t){return e.request("/api/notebook/closeNotebook",{notebook:t})}async function Gy(e,t){return e.request("/api/notebook/createNotebook",{name:t})}async function Jy(e,t){return e.request("/api/notebook/removeNotebook",{notebook:t})}async function Wy(e,t,o){return e.request("/api/notebook/renameNotebook",{notebook:t,name:o})}async function Ky(e,t){return e.request("/api/notebook/getNotebookConf",{notebook:t})}async function Qy(e,t,o){return e.request("/api/notebook/setNotebookConf",{notebook:t,conf:o})}async function vu(e,t,o){return e.request("/api/notebook/setNotebookIcon",{notebook:t,icon:o})}function Xy(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Te(e){return e.startsWith("/")?e:`/${e}`}function eb(e){const t=Te(e).split("/").filter(Boolean).at(-1)??"";return t.endsWith(".sy")?t.slice(0,-3):t}function be(e){return e.replace(/\0/g,"").replace(/'/g,"''")}async function tb(e,t){const o=await yt(e,`SELECT id, root_id, box, path, hpath, content, type FROM blocks WHERE id = '${be(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:Te(s),hPath:i,name:c}}async function Ue(e,t){try{const s=await tb(e,t);if(s)return s}catch{}const o=await Ke(e,t),n=o.rootID||o.id,r=await Tt(e,n);return{documentId:n,notebook:r.notebook,path:Te(r.path),name:o.name}}const ob=500;function Iu(e,t,o){if(e.size>=ob){const n=e.keys().next().value;n!==void 0&&e.delete(n)}e.set(t,o)}function Ht(){return{documentContextById:new Map,notebookByPath:new Map}}async function nb(e,t,o){if(!o)return Ue(e,t);let n=o.documentContextById.get(t);return n||(n=Ue(e,t),Iu(o.documentContextById,t,n)),n}async function rb(e,t,o){const n=Te(t);if(!o)return jt(e,n);let r=o.notebookByPath.get(n);return r||(r=jt(e,n),Iu(o.notebookByPath,n,r)),r}async function Vt(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:Te(s),documentId:a};if(a)try{const i=await nb(e,a,o);return{notebook:i.notebook,path:i.path,documentId:i.documentId}}catch{}if(s){const i=await rb(e,s,o);if(i)return{notebook:r??i,path:Te(s),documentId:a}}return r?{notebook:r,path:s?Te(s):void 0,documentId:a}:null}async function sb(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t.notebook):o==="write"?e.canWrite(t.notebook):e.canRead(t.notebook))?null:Wn(t.notebook,e.get(t.notebook),o)}async function T(e,t,o,n){const r=await Ue(e,o),s=await sb(t,r,n);return{context:r,denied:s}}async function q(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t))?null:Wn(t,e.get(t),o)}async function ab(e,t){const n=(await Re(e)).notebooks.find(s=>s.id===t);return n?n.id:(await Ue(e,t)).notebook}async function jt(e,t){const o=await Re(e);for(const n of o.notebooks)try{return await Xn(e,n.id,t),n.id}catch{continue}return null}async function xo(e,t,o){const n=await By(e,t,o);return n.files.map(r=>({id:typeof r.id=="string"&&r.id.length>0?r.id:eb(r.path),notebook:r.box||n.box||t,path:Te(r.path),hPath:r.hPath,name:Xy(r.name),icon:r.icon,subFileCount:r.subFileCount??r.count}))}async function ib(e){return e.request("/api/system/getWorkspaceInfo",{})}async function cb(e){return e.request("/api/system/getNetwork",{})}async function ub(e){return e.request("/api/system/getConf",{})}async function lb(e){return e.request("/api/system/version")}async function db(e){return e.request("/api/system/currentTime")}async function pb(e){return e.request("/api/ui/reloadIcon",{})}async function fb(e){return e.request("/api/ui/reloadFiletree",{})}async function hb(e,t){return e.request("/api/ui/reloadProtyle",{id:t})}async function mb(e,t){return e.request("/api/ui/reloadAttributeView",{id:t})}async function gb(e){return e.request("/api/ui/reloadTag",{})}function yb(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 bb(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 kb(e,t){switch(t.type){case"reloadProtyle":await hb(e,t.id);return;case"reloadAttributeView":await mb(e,t.id);return;case"reloadIcon":await pb(e);return;case"reloadFiletree":await fb(e);return;case"reloadTag":await gb(e);return;default:{const o=t;throw new Error(`Unknown UI refresh operation: ${String(o)}`)}}}async function P(e,t,o){if(t.isError||o.length===0||!e||typeof e.request!="function")return t;const n=yb(t);if(!n)return t;const r=bb(o),s=[];for(const a of r)try{await kb(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 Yt(e){return new Promise(t=>{setTimeout(t,e)})}const tt="av";function ot(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 Hr=6,wb=500,Vr=6,_b=300,vb="/data/storage/av",Ib=/^\d{14}-[a-z0-9]{7}$/;function Db(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 Sb(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 er(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 Du(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 Ab(e){return er(e,["blockID","itemId","itemID","rowID"])??Du(e,["block","blockID"])}function Tb(e){return Du(e,["block","id"])??er(e,["srcID","srcId"])}function Pb(e){return er(e,["id"])}function tr(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 u=c,l=u.values;Array.isArray(l)&&l.forEach(d=>{var v;const f=Ab(d);if(!f)return;let h=t.get(f);h||(h={rowID:f,valueIDs:[]},t.set(f,h),o.push(h));const m=Pb(d),_=((v=u.key)==null?void 0:v.type)==="block"?Tb(d):void 0;_&&(h.sourceBlockID=_),m&&!h.valueIDs.includes(m)&&h.valueIDs.push(m)})}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 u=a.get(c.sourceBlockID)??[];u.includes(c.rowID)||(u.push(c.rowID),a.set(c.sourceBlockID,u))}if(c.rowID)for(const u of c.valueIDs){const l=i.get(u)??[];l.includes(c.rowID)||(l.push(c.rowID),i.set(u,l))}}return{rows:r,rowIDs:s,sourceBlockToRowIDs:a,valueIdToRowIDs:i}}function kt(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:tt,action:e,...t}},null,2)}],isError:!0}}function Eb(e,t,o,n=[]){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:tt,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 Cb(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 Ob(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 xb(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<Hr;s+=1){const a=await Kn(e,t),i=tr(a.av),c=Cb(i,o),u=Ob(i,n);if(r={rows:[...c.rows,...u.rows],unresolvedBlockIDs:c.unresolvedBlockIDs,unresolvedRowIDs:u.unresolvedRowIDs},r.unresolvedBlockIDs.length===0&&(!r.unresolvedRowIDs||r.unresolvedRowIDs.length===0))return r;s<Hr-1&&await Yt(wb)}return r}function Nb(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:kt(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:kt(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:kt(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:kt(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:kt(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 Rb(e,t){const o=Db(t);return{avData:t,blockID:o}}function $b(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 Su(e,t){try{return $b(await uy(e,t))}catch(o){if(Vn(o))return[];throw o}}async function zb(e,t){const o=be(t),n=await yt(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 or(e,t,o){const n=[],r=await Rb(e,o);r.blockID&&n.push(r.blockID);const s=await Su(e,t);for(const i of s)n.includes(i)||n.push(i);const a=await zb(e,t);for(const i of a)n.includes(i)||n.push(i);return n}async function Fb(e,t,o,n){if((await or(e,t,o)).includes(n))return!0;try{const s=await yu(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(Vn(s))return!1;throw s}}function Bb(e,t,o){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:tt,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 re(e,t,o,n,r){const a=(await Kn(e,o)).av;if(r!=null&&r.blockID){const{denied:c}=await T(e,t,r.blockID,n);return c?{denied:c,avData:a}:await Fb(e,o,a,r.blockID)?{denied:null,avData:a}:{denied:Bb(r.action??"get",o,r.blockID),avData:a}}const i=await or(e,o,a);for(const c of i)try{const{denied:u}=await T(e,t,c,n);return{denied:u,avData:a}}catch(u){if(Vn(u))continue;throw u}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 jb(e){return e instanceof Error&&e.message.includes("The database may have no rows yet; AV writes require a resolvable owning block context.")}function Ub(e){var t;return e instanceof Error&&((t=Hn(e))==null?void 0:t.code)==="av_not_found"}async function qb(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 T(e,t,o.blockID,"write");return{denied:s,shouldMaterialize:!0,targetDocumentId:a.documentId}}try{const{denied:s}=await re(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){if(!(jb(s)||Ub(s)))throw s;const{denied:i,context:c}=await T(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 re(e,t,n,"read");return{denied:s,shouldMaterialize:!1}}catch(s){throw s}}async function nr(e,t,o){const n=o??(await Kn(e,t)).av;return(await or(e,t,n))[0]}async function lt(e,t,o,n){const r=[];n&&r.push(n);try{const s=await nr(e,t,o);s&&!r.includes(s)&&r.push(s)}catch{}for(const s of r)try{const a=await Ue(e,s);if(a.documentId)return[{type:"reloadProtyle",id:a.documentId}]}catch{}return[{type:"reloadAttributeView",id:t}]}async function Mb(e,t,o){const n=Ht();await t.reload();const r=[],s=[];let a=0,i=0,c=0;for(const u of o){const l=await Vt(e,u,n);if(!(l!=null&&l.notebook)){a+=1,i+=1,s.push(u);continue}if(!t.canRead(l.notebook)){a+=1,c+=1;continue}r.push(u)}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 Lb(e){const t=await e.request("/api/file/readDir",{path:vb});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=>Ib.test(o))}function Zb(e){if(!e||typeof e!="object")return[];const t=e.values;return Array.isArray(t)?t.filter(o=>!!(o&&typeof o=="object")):[]}async function Hb(e,t,o){if(!t.trim())return[];if(typeof e.request!="function")return[];const n=new Set(o??[]),r=await Lb(e),s=[];for(const a of r)if(!n.has(a))try{const i=await pu(e,{id:a,keyword:t,page:1,pageSize:3}),c=Zb(i.rows);if(c.length===0)continue;const u=Array.isArray(i.blockIDs)?i.blockIDs.filter(l=>typeof l=="string"&&l.length>0):[];if(u.length===0)continue;s.push({avID:a,avName:i.name,blockID:u[0],blockIDs:u,rows:i.rows,matchedRowCount:c.length,matchSource:"primary_key"})}catch{}return s}function Yr(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 Au(e,t){return`<div class="av" data-node-id="${e}" data-av-id="${t}" data-type="NodeAttributeView" data-av-type="table"></div>`}function Vb(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 dt(e,t,o,n){return n??await nr(e,t,o)}function pt(e,t,o){if(!t)return{doOperations:e,undoOperations:[]};const n=Vb();return{doOperations:[...e,{action:"doUpdateUpdated",id:t,data:n}],undoOperations:[{action:"doUpdateUpdated",id:t,data:""}]}}function Gr(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=Yr(o.date,"date"),s=o.endDate===void 0?0:Yr(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(`
127
+ `);return{...n,type:"mAsset",text:{content:s},mAsset:r}}default:throw new Error(`Unsupported AV valueType: ${o.valueType}`)}}async function Yb({client:e,permMgr:t,rawArgs:o}){const n=_c.parse(o),{denied:r,avData:s}=await re(e,t,n.id,"read",{blockID:n.blockID,action:"get"});if(r)return r;const a=tr(s);return g({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 Gb({client:e,permMgr:t,rawArgs:o}){const n=Sc.parse(o),r=await iy(e,n.keyword,n.excludes),s=Array.isArray(r.results)?r.results:[],a=await Hb(e,n.keyword,n.excludes),i=[...s],c=new Set(i.map(l=>l&&typeof l=="object"?l.avID:void 0).filter(l=>typeof l=="string"&&l.length>0));for(const l of a){const d=l.avID;typeof d=="string"&&c.has(d)||(typeof d=="string"&&c.add(d),i.push(l))}const u=await Mb(e,t,i);return g({keyword:n.keyword,searchScope:{kernel:"attribute_view_name_or_kernel_candidates",fallback:"primary_key_values"},...u,...u.filteredOutCount>0?{emptyReason:u.results.length===0?u.unresolvedCount>0&&u.permissionFilteredOutCount===0?"no_verified_results_unresolved_candidates_available":u.permissionFilteredOutCount>0&&u.unresolvedCount===0?"all_results_permission_filtered":"all_results_filtered":void 0,unresolvedHint:u.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&&u.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 Jb({client:e,permMgr:t,rawArgs:o}){const n=vc.parse(o),r=new Date,s=!n.id,a=n.id??ot(r),i=await qb(e,t,n,a,s);if(i.denied)return i.denied;const c=await ry(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 u,l;if(i.shouldMaterialize){u=ot(r);let $=Au(u,a);try{const N=await du(e,$);typeof N.dom=="string"&&N.dom.length>0&&($=N.dom)}catch{}await de(e,[{doOperations:[{action:"insert",id:u,data:$,parentID:n.blockID}],undoOperations:[{action:"delete",id:u}]}]),l=!1;for(let N=0;N<Vr;N+=1){if((await Su(e,a)).includes(u)){l=!0;break}if(N===Vr-1)break;await Yt(_b)}}const d=c&&typeof c=="object"&&!Array.isArray(c)?c:{},f=Array.isArray(d.rows)?d.rows:[],h=n.page??1,m=n.pageSize??(f.length||1),_=typeof d.pageCount=="number"?d.pageCount:1,v=typeof d.rowCount=="number"?d.rowCount:f.length,{rows:A,pageCount:x,rowCount:C,...I}=d,D=Fe(f,{total:v,page:h,pageSize:m,pageCount:_,hasNextPage:h<_},{...I,avID:a,id:a,...n.createIfNotExist===!0?{generatedAvID:s}:{},...i.shouldMaterialize?{materialized:!0,blockID:u,parentID:n.blockID,databaseBlockRegistrationVerified:l===!0,...l===!1?{warning:`Created attribute view "${a}" and materialized database block "${u}", 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?P(e,D,[{type:"reloadAttributeView",id:a},...i.targetDocumentId?[{type:"reloadProtyle",id:i.targetDocumentId}]:[]]):D}async function Wb({client:e,permMgr:t,rawArgs:o}){const n=Ic.parse(o),{denied:r,avData:s}=await re(e,t,n.id,"read");if(r)return r;const a=await sy(e,n.id),i=a&&typeof a=="object"&&!Array.isArray(a)&&Array.isArray(a.keys)?a.keys:Array.isArray(a)&&a.length>0?a:Sb(s);return g({avID:n.id,keys:i})}async function Kb({client:e,permMgr:t,rawArgs:o}){const n=Dc.parse(o),{denied:r}=await re(e,t,n.id,"read");if(r)return r;const s=await ay(e,{id:n.id,blockID:n.blockID??""});return g({avID:n.id,...n.blockID?{blockID:n.blockID}:{},...s})}async function Qb({client:e,permMgr:t,rawArgs:o}){const n=Ac.parse(o),{denied:r,avData:s}=await re(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 le({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(m=>({primaryKeyText:m,rowID:ot(),srcID:ot()})),u=await dt(e,n.avID,s,n.blockID),l=[...a.map(m=>({itemID:ot(),id:m,isDetached:!1})),...c.map(m=>({itemID:m.rowID,id:m.srcID,isDetached:!0,content:m.primaryKeyText}))],d=pt([{action:"insertAttrViewBlock",avID:n.avID,blockID:u,viewID:n.viewID,groupID:n.groupID,previousID:n.previousID,ignoreDefaultFill:n.ignoreDefaultFill,srcs:l}],u);await de(e,[{doOperations:d.doOperations,undoOperations:[{action:"removeAttrViewBlock",srcIDs:[...a,...c.map(m=>m.rowID)],avID:n.avID},...d.undoOperations]}]);const f=await xb(e,n.avID,a,c.map(m=>({primaryKeyText:m.primaryKeyText,rowID:m.rowID})));if(f.unresolvedBlockIDs.length>0||f.unresolvedRowIDs&&f.unresolvedRowIDs.length>0)return Eb(n.avID,a,f,i);const h=await lt(e,n.avID,s,n.blockID);return P(e,le({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 Xb({client:e,permMgr:t,rawArgs:o}){const n=Tc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_rows"});if(r)return r;const a=await dt(e,n.avID,s,n.blockID),i=pt([{action:"removeAttrViewBlock",srcIDs:n.srcIDs,avID:n.avID}],a);await de(e,[{doOperations:i.doOperations,undoOperations:i.undoOperations}]);const c=await lt(e,n.avID,s,n.blockID);return P(e,le({action:"remove_rows",avID:n.avID,srcIDs:n.srcIDs,removed:n.srcIDs.length}),c)}async function ek({client:e,permMgr:t,rawArgs:o}){const n=Pc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"add_column"});if(r)return r;const a=n.keyID??ot(),i=await dt(e,n.avID,s,n.blockID),c=pt([{action:"addAttrViewCol",name:n.keyName,avID:n.avID,type:n.keyType,id:a,data:n.keyIcon??"",previousID:n.previousKeyID??""}],i);await de(e,[{doOperations:c.doOperations,undoOperations:[{action:"removeAttrViewCol",id:a,avID:n.avID},...c.undoOperations]}]);const u=await lt(e,n.avID,s,n.blockID);return P(e,le({action:"add_column",avID:n.avID,keyID:a,keyName:n.keyName,keyType:n.keyType}),u)}async function tk({client:e,permMgr:t,rawArgs:o}){const n=Ec.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"remove_column"});if(r)return r;const a=n.keyID??n.columnID,i=await dt(e,n.avID,s,n.blockID),c=pt([{action:"removeAttrViewCol",id:a,avID:n.avID,removeDest:n.removeRelationDest??!1}],i);await de(e,[{doOperations:c.doOperations,undoOperations:c.undoOperations}]);const u=await lt(e,n.avID,s,n.blockID);return P(e,le({action:"remove_column",avID:n.avID,keyID:a,removeRelationDest:n.removeRelationDest??!1}),u)}async function ok({client:e,permMgr:t,rawArgs:o}){const n=Cc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"set_cells"});if(r)return r;const a=tr(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}],u=[];for(let h=0;h<c.length;h+=1){const m=c[h],_=Nb(n.avID,"set_cells",a,m.rowID,i?void 0:h);if(_.ok===!1)return _.result;if(i){const v=await dt(e,n.avID,s,n.blockID),A=pt([{action:"updateAttrViewCell",avID:n.avID,keyID:m.columnID,rowID:_.rowID,data:Gr(m.columnID,_.rowID,m)}],v);await de(e,[{doOperations:A.doOperations,undoOperations:A.undoOperations}]);const x=await lt(e,n.avID,s,n.blockID);return P(e,le({action:"set_cells",avID:n.avID,rowID:m.rowID,columnID:m.columnID,valueType:m.valueType}),x)}u.push({action:"updateAttrViewCell",avID:n.avID,keyID:m.columnID,rowID:_.rowID,data:Gr(m.columnID,_.rowID,m)})}const l=await dt(e,n.avID,s,n.blockID),d=pt(u,l);await de(e,[{doOperations:d.doOperations,undoOperations:d.undoOperations}]);const f=await lt(e,n.avID,s,n.blockID);return P(e,le({action:"set_cells",avID:n.avID,updated:c.length}),f)}async function nk({client:e,permMgr:t,rawArgs:o}){const n=Oc.parse(o),{denied:r,avData:s}=await re(e,t,n.avID,"write",{blockID:n.blockID,action:"duplicate"});if(r)return r;const a=await cy(e,n.avID);if(!a.avID||!a.blockID)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:tt,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 nr(e,n.avID,s);if(!i)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:tt,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 T(e,t,i,"write");if(c.denied)return c.denied;let u=Au(a.blockID,a.avID);try{const l=await du(e,u);typeof l.dom=="string"&&l.dom.length>0&&(u=l.dom)}catch{}try{await de(e,[{doOperations:[{action:"insert",id:a.blockID,data:u,previousID:i}],undoOperations:[{action:"delete",id:a.blockID}]}])}catch(l){const d=l instanceof Error?l:new Error(String(l));return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:tt,action:"duplicate",reason:"duplicate_insert_failed",message:d.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 le({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 rk({client:e,permMgr:t,rawArgs:o}){const n=xc.parse(o),{denied:r}=await re(e,t,n.avID,"read");if(r)return r;const s=await pu(e,{id:n.avID,keyword:n.keyword,page:n.page,pageSize:n.pageSize}),a=s.blockIDs??[];if(a.length>0){const i=Ht();await t.reload();const c=[],u=[];let l=0;for(let d=0;d<a.length;d+=1){const f=a[d],h=await Vt(e,{id:f},i)??await Ue(e,f).catch(()=>null),m=h&&"notebook"in h?h.notebook:void 0;if(!m||!t.canRead(m)){l+=1;continue}c.push(f),u.push(s.rows[d])}return g({avID:n.avID,name:s.name,blockIDs:c,rows:u,...l>0?{filteredOutCount:l,partial:!0,reason:"permission_filtered"}:{}})}return g({avID:n.avID,...s})}const sk={get:Yb,render:Jb,get_attribute_view_keys:Wb,get_attribute_view_filter_sort:Kb,search:Gb,add_rows:Qb,remove_rows:Xb,add_column:ek,remove_column:tk,set_cells:ok,duplicate:nk,get_primary_key_values:rk},ak=[k("get",_c,"Get the full attribute view payload by AV ID; blockID is an optional exact database-block context."),k("render",vc,"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."),k("get_attribute_view_keys",Ic,"Get the column (key) definitions of an attribute view."),k("get_attribute_view_filter_sort",Dc,"Get filter and sort settings for an attribute view."),k("search",Sc,"Search attribute views by name or primary-key values."),k("add_rows",Ac,"Add bound block rows or detached plain-text primary-key rows to a database."),k("remove_rows",Tc,"Remove rows from a database."),k("add_column",Pc,"Add a column to a database."),k("remove_column",Ec,"Remove a column from a database."),k("set_cells",Cc,"Set one or more cell values in a database. Provide cells/items, or pass rowID + columnID + valueType for a single-cell write."),k("duplicate",Oc,"Duplicate an attribute view using SiYuan copy-as-mirror semantics; previousID overrides the insertion target."),k("get_primary_key_values",xc,"Get primary key values for an attribute view.")],Tu=ae({name:"av",description:"🗃️ Grouped attribute-view (database) operations.",variants:ak,actionSchema:yg,aggregateOptions:{guidance:Vs,actionHints:na},handlers:sk});function ik(e){return Tu.listTools(e)}async function ck(e,t,o,n){return Tu.callTool(e,t,o,n)}const uk=/[\u200B\u200C\u200D\u2060\uFEFF]/g,lk=/<[^>]+>/g;function rr(e){return e.replace(uk,"")}function Gt(e){return{...e,content:rr(e.content)}}function Pu(e){return{...e,kramdown:rr(e.kramdown)}}function Eu(e){return e.replace(lk,"")}function Cu(e){const t=e==null?void 0:e.trim().toLowerCase();return t||void 0}const Ou={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"},Jr={keyword:0,query:1,query_syntax:1,sql:2,regex:3},dk={0:"keyword",1:"query_syntax",2:"sql",3:"regex"};function pk(e){const t={};for(const o of e){const n=Ou[o];n&&(t[n]=!0)}return t}function fk(e){const t={};for(const[o,n]of Object.entries(e)){const r=Ou[o];r?t[r]=n:t[o]=n}return t}function hk(e,t){const o=Cu(e);return o&&o in Jr?Jr[o]:t}function mk(e){if(e!==void 0)return dk[e]}const gk={relevance:7,date:4,updated_desc:4,updated_asc:3,created_desc:2,created_asc:1,type:0},yk={7:"relevance",4:"updated_desc",3:"updated_asc",2:"created_desc",1:"created_asc",0:"type"},bk={relevance:0,relevance_desc:0,relevance_asc:1,updated_asc:2,updated_desc:3},kk={0:"relevance_desc",1:"relevance_asc",2:"updated_asc",3:"updated_desc"};function nn(e,t,o=gk){const n=Cu(e);return n&&n in o?o[n]:t}function Wr(e){if(e!==void 0)return yk[e]}function wk(e,t){return nn(e,t,bk)}function _k(e){if(e!==void 0)return kk[e]}function vk(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=Eu(s)),r})}:e}const Ik=["id","type","box"],Dk=["hPath","hpath"],Sk=["content","plainContent","markdown","name","alias","memo","tag","subType","subtype","path","parentID","parent_id","rootID","root_id"];function Kr(e){return!(e==null||e===""||Array.isArray(e)&&e.length===0)}function Ak(e){const t={};for(const o of Ik)o in e&&(t[o]=e[o]);for(const o of Dk)if(Kr(e[o])){t.hPath=e[o];break}for(const o of Sk)Kr(e[o])&&(t[o]=e[o]);return t}const Tk=/<mark>[^<]*<\/mark>/g,Mo=400,Pk=150;function Ek(e,t=Pk){if(e.length<=Mo)return e;const o=[...e.matchAll(Tk)];if(o.length===0)return e.length>Mo?e.slice(0,Mo)+"...":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 Qr=400,Xr=200;function Ck(e){return e.map(t=>{if(!t||typeof t!="object")return t;const n=Ak(t);if(n.type==="NodeDocument")return n;if(typeof n.content=="string"){const r=Eu(n.content).trim();r.length>0&&(n.excerpt=r.length>Xr?r.slice(0,Xr)+"...":r),n.content=Ek(n.content)}return typeof n.markdown=="string"&&n.markdown.length>Qr&&(n.markdown=n.markdown.slice(0,Qr)+"..."),n})}function Ok(e){const t=vk({blocks:e});return Ck(Array.isArray(t.blocks)?t.blocks:[])}function xk(e,t){let o=0,n=0;for(;;){if(n=e.indexOf(t,n),n===-1)return o;o+=1,n+=t.length}}function Nk(e,t,o,n){const r=xk(e,t.old);if(r===0)throw new Error(`${n} edit #${o+1} did not match any text.`);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 rn(e,t,o){let n=e;const r=t.map((s,a)=>{const i=Nk(n,s,a,o);return n=i.content,{index:a+1,replaced:i.replaced,replace_all:i.replaceAll}});return{content:n,summary:r}}function Rk(e){const t=e.notebook??e.box??e.boxID??e.notebookId;return typeof t=="string"&&t.length>0?t:void 0}async function xu(e){const t=await Re(e),o=new Map;for(const n of t.notebooks??[])n.id&&n.name&&o.set(n.id,n.name);return o}async function sn(e,t){if(t)try{return(await xu(e)).get(t)}catch{return}}async function $k(e,t){if(t.filter(n=>n!==null&&typeof n=="object").length===0)return t;try{const n=await xu(e);return t.map(r=>{if(r===null||typeof r!="object")return r;const s=r,a=Rk(s),i=a?n.get(a):void 0;return i?{...s,notebookName:i}:r})}catch{return t}}function zk(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 an(e,t){const o=e.filter(n=>{const r=zk(n);return!r||t.canRead(r)});return{items:o,removedCount:e.length-o.length}}function Be(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 Fk(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 ro(e,t,o){const n=Ht(),r=[];let s=0;for(const a of t){const i=await Vt(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 Lo(e,t,o,n){const r=Ht(),s=[];let a=0,i=0;const c=typeof n=="string"&&n.length>0?n.startsWith("/")?n:`/${n}`:void 0;for(const u of t){const l=await Vt(e,u,r);if(!(l!=null&&l.notebook)||!o.canRead(l.notebook)){a+=1;continue}if(c&&(!l.path||!(l.path===c||l.path.startsWith(`${c}/`)))){i+=1;continue}s.push(u)}return{items:s,permissionFilteredOutCount:a,pathFilteredOutCount:i}}function es(e,t){if(!Array.isArray(e.blocks))return e;const{items:o,removedCount:n}=an(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 so(e,t){const o=Array.isArray(e.backlinks)?an(e.backlinks,t):void 0,n=Array.isArray(e.backmentions)?an(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}:{},...Be(r)}}function Bk(e){return e.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_").replace(/'/g,"''")}function jk(e){return!!e&&typeof e=="object"}const ke="Only SELECT statements and WITH CTEs whose main statement is SELECT are allowed. Mutation queries (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE) are forbidden.";function Uk(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]!==`
128
128
  `;)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]===`
129
129
  `?`
130
130
  `:" ",o+=1}continue}if(n==="'"||n==='"'||n==="`"){const s=n;for(t+=" ",o+=1;o<e.length;){const a=e[o];if(t+=a===`
131
131
  `?`
132
132
  `:" ",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===`
133
133
  `?`
134
- `:" ",o+=1,s==="]")break}continue}t+=n,o+=1}return t}function ue(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Ze(e,t){const o=ue(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 Rk(e,t){const o=ue(e,t),n=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(e.slice(o));if(!n)throw new Error(ye);return o+n[0].length}function Gr(e,t){const o=ue(e,t);if(e[o]!=="(")throw new Error(ye);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(ye)}function zk(e){const t=e.indexOf(";");if(!(t<0)&&e.slice(t+1).trim().length>0)throw new Error(ye)}function Fk(e,t){let o=ue(e,t);const n=Ze(e,o);for((n==null?void 0:n.keyword)==="RECURSIVE"&&(o=n.end);o<e.length;){o=Rk(e,o),o=ue(e,o),e[o]==="("&&(o=Gr(e,o),o=ue(e,o));const r=Ze(e,o);if((r==null?void 0:r.keyword)!=="AS")throw new Error(ye);o=ue(e,r.end);const s=Ze(e,o);if((s==null?void 0:s.keyword)==="MATERIALIZED")o=ue(e,s.end);else if((s==null?void 0:s.keyword)==="NOT"){const i=Ze(e,s.end);if((i==null?void 0:i.keyword)!=="MATERIALIZED")throw new Error(ye);o=ue(e,i.end)}if(o=Gr(e,o),o=ue(e,o),e[o]===","){o+=1;continue}const a=Ze(e,o);if((a==null?void 0:a.keyword)!=="SELECT")throw new Error(ye);return}throw new Error(ye)}function Bk(e){const t=$k(e).trim();zk(t);const o=Ze(t,0);if((o==null?void 0:o.keyword)!=="SELECT"){if((o==null?void 0:o.keyword)==="WITH"){Fk(t,o.end);return}throw new Error(ye)}}async function jk(e,t){const o=await gt(e,`SELECT content, name FROM blocks WHERE id = '${ge(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 Uk(e,t,o,n){const s=["s.type = 'textmark block-ref'",`instr(s.markdown, '${ge(t)}') > 0`];return n&&s.push(`s.root_id = '${ge(n)}'`),o&&o.trim()&&s.push(`b.content LIKE '%${xk(o.trim())}%' ESCAPE '\\'`),gt(e,`
134
+ `:" ",o+=1,s==="]")break}continue}t+=n,o+=1}return t}function ue(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Ve(e,t){const o=ue(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 qk(e,t){const o=ue(e,t),n=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(e.slice(o));if(!n)throw new Error(ke);return o+n[0].length}function ts(e,t){const o=ue(e,t);if(e[o]!=="(")throw new Error(ke);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(ke)}function Mk(e){const t=e.indexOf(";");if(!(t<0)&&e.slice(t+1).trim().length>0)throw new Error(ke)}function Lk(e,t){let o=ue(e,t);const n=Ve(e,o);for((n==null?void 0:n.keyword)==="RECURSIVE"&&(o=n.end);o<e.length;){o=qk(e,o),o=ue(e,o),e[o]==="("&&(o=ts(e,o),o=ue(e,o));const r=Ve(e,o);if((r==null?void 0:r.keyword)!=="AS")throw new Error(ke);o=ue(e,r.end);const s=Ve(e,o);if((s==null?void 0:s.keyword)==="MATERIALIZED")o=ue(e,s.end);else if((s==null?void 0:s.keyword)==="NOT"){const i=Ve(e,s.end);if((i==null?void 0:i.keyword)!=="MATERIALIZED")throw new Error(ke);o=ue(e,i.end)}if(o=ts(e,o),o=ue(e,o),e[o]===","){o+=1;continue}const a=Ve(e,o);if((a==null?void 0:a.keyword)!=="SELECT")throw new Error(ke);return}throw new Error(ke)}function Zk(e){const t=Uk(e).trim();Mk(t);const o=Ve(t,0);if((o==null?void 0:o.keyword)!=="SELECT"){if((o==null?void 0:o.keyword)==="WITH"){Lk(t,o.end);return}throw new Error(ke)}}async function Hk(e,t){const o=await yt(e,`SELECT content, name FROM blocks WHERE id = '${be(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 Vk(e,t,o,n){const s=["s.type = 'textmark block-ref'",`instr(s.markdown, '${be(t)}') > 0`];return n&&s.push(`s.root_id = '${be(n)}'`),o&&o.trim()&&s.push(`b.content LIKE '%${Bk(o.trim())}%' ESCAPE '\\'`),yt(e,`
135
135
  SELECT
136
136
  s.block_id AS id,
137
137
  s.root_id,
@@ -146,7 +146,7 @@ ${l}`);const d=Ug(e,o,r);return d.length>0&&u.push(d.join(" ")),u.join(`
146
146
  WHERE ${s.join(" AND ")}
147
147
  ORDER BY b.updated DESC
148
148
  LIMIT 200
149
- `.trim())}async function Pu(e,t,o,n){const r=await jk(e,t);if(!r)return[];const s=[`id != '${ge(t)}'`,`instr(content, '${ge(r)}') > 0`];return n&&s.push(`root_id = '${ge(n)}'`),o&&o.trim()&&s.push(`instr(content, '${ge(o.trim())}') > 0`),gt(e,`
149
+ `.trim())}async function Nu(e,t,o,n){const r=await Hk(e,t);if(!r)return[];const s=[`id != '${be(t)}'`,`instr(content, '${be(r)}') > 0`];return n&&s.push(`root_id = '${be(n)}'`),o&&o.trim()&&s.push(`instr(content, '${be(o.trim())}') > 0`),yt(e,`
150
150
  SELECT
151
151
  id,
152
152
  root_id,
@@ -160,20 +160,20 @@ ${l}`);const d=Ug(e,o,r);return d.length>0&&u.push(d.join(" ")),u.join(`
160
160
  WHERE ${s.join(" AND ")}
161
161
  ORDER BY updated DESC
162
162
  LIMIT 200
163
- `.trim())}async function qk(e,t,o,n){const r=await _y(e,t,o,n);if(Nk(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([Uk(e,t,o,n),Pu(e,t,o,n)]);return{backlinks:s,backmentions:a,fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}async function Mk(e,t,o,n){const r=await vy(e,t,o,n);return r&&typeof r=="object"&&Array.isArray(r.backmentions)?{backmentions:r.backmentions}:{backmentions:await Pu(e,t,o,n),fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}const Lk="search";function Zk(e){return typeof e=="string"&&e.trim().length>0}function jo(e,t){return Zk(t)?t:e}function Wt(e){const t=Object.entries(e).filter(([,o])=>o!==void 0);return t.length===0?{}:{resolvedArgs:Object.fromEntries(t)}}function Qn(e,t){return t?{showing:t.showing,truncated:t.truncated,hint:t.hint}:{showing:e,truncated:!1}}function kt(e){return Array.isArray(e)?Sk(e):[]}function Hk(e){let t=e.types?ik(e.types):e.types;return e.typeShortcodes&&e.typeShortcodes.length>0&&(t={...ak(e.typeShortcodes),...t}),t}function Vk(e){return e.parentId?Math.min((e.pageSize??32)*3,128):e.pageSize}function Yk(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 Gk(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 Uo(e){const t=ck(e.methodName,e.method);return{...t!==void 0?{method:t}:{},...t!==void 0?{methodName:uk(t)}:{}}}function Jk(e,t,o,n){const r=Array.isArray(e.blocks)?e.blocks:[],s=t.page??1,a=t.pageSize??32,i=qn(r,20,`Use page/pageSize parameters to paginate. Current page: ${s}.`),c=r.length,u=typeof o.pageCount=="number"?o.pageCount:1,l=typeof e.filteredOutBlockCount=="number"?e.filteredOutBlockCount:0,d=l>0||!!t.parentId||t.hasTags!==void 0,h={total:d?c:typeof o.matchedBlockCount=="number"?o.matchedBlockCount:c,page:s,pageSize:a,pageCount:d?1:u,hasNextPage:d?!1:s<u},{blocks:m,pageCount:k,...v}=e;return ct(i.items,h,{...v,...ze(l),...Qn(c,i.meta),returnedTotal:c,returnedPageCount:1,returnedHasNextPage:!1,...o.matchedBlockCount!==void 0?{kernelMatchedBlockCount:o.matchedBlockCount}:{},...o.matchedRootCount!==void 0?{kernelMatchedRootCount:o.matchedRootCount}:{},kernelPageCount:u,kernelHasNextPage:s<u,...d?{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 Wk(e,t,o){const n=qn(e,50,"Add LIMIT and OFFSET to your SQL for pagination."),r=e.length;return g({data:n.items,total:r,totalRows:r,...Qn(r,n.meta),...ze(t),...o?{resolvedArgs:o}:{}})}function Kk(e,t,o,n){const r=qn(t,20,"Use page/pageSize parameters to paginate asset content results."),s=t.length;return g({...e,assetContents:r.items,data:r.items,total:s,...Qn(s,r.meta),...ze(o),...n?{resolvedArgs:n}:{}})}const Qk={fulltext:async({client:e,permMgr:t,rawArgs:o})=>{const n=Uc.parse(o);if(n.parentId){const{denied:f}=await S(e,t,n.parentId,"read");if(f)return f}const r=Uo(n),s=Ko(n.sortBy,n.orderBy),a=await ky(e,{query:n.query,method:r.method,types:Hk(n),paths:n.paths,groupBy:n.groupBy,orderBy:s,page:n.page,pageSize:Vk(n)}),c=Yr(a,t),u={...c,blocks:kt(Array.isArray(c.blocks)?c.blocks:[])};n.parentId&&Yk(u,n.parentId),n.hasTags!==void 0&&Gk(u,n.hasTags),Array.isArray(u.blocks)&&(u.blocks=await Ek(e,u.blocks));const d=n.methodName!==void 0||n.sortBy!==void 0?Wt({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:Lr(s)}:{}}).resolvedArgs:void 0;return Jk(u,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},d)},query_sql:async({client:e,permMgr:t,rawArgs:o})=>{const n=qc.parse(o),r=jo(n.stmt,n.sql);try{Bk(r??"")}catch(u){return yo(u,{tool:Lk,action:"query_sql",rawArgs:o})}const s=await gt(e,r??""),a=Array.isArray(s)?s:[],i=await eo(e,a,t),c=n.sql!==void 0?Wt({stmt:r}).resolvedArgs:void 0;return Wk(i.items,i.removedCount,c)},get_backlinks:async({client:e,permMgr:t,rawArgs:o})=>{const n=Mc.parse(o),r=jo(n.refTreeID,n.scopeRootId),s=n.mode??"both",{denied:a}=await S(e,t,n.id,"read");if(a)return a;try{const i=s!=="mentions"?await qk(e,n.id,n.keyword,r):{},c=s!=="links"?await Mk(e,n.id,n.keyword,r):{},u={...i,...c},l=to(u,t);return g({...l,mode:s,backlinks:s!=="mentions"?kt(Array.isArray(l.backlinks)?l.backlinks:[]):[],backmentions:s!=="links"?kt(Array.isArray(l.backmentions)?l.backmentions:[]):[],...u.sourcePayloadMissing?{sourcePayloadMissing:!0}:{},...u.fallbackQuery?{fallbackQuery:u.fallbackQuery}:{},...u.resultConfidence?{resultConfidence:u.resultConfidence}:{},...n.scopeRootId!==void 0?{resolvedArgs:{refTreeID:r}}:{},...u.fallbackUsed?{warning:"SiYuan returned no backlink/backmention payload; SQL fallback results are shown."}:{}})}catch(i){if(Ok(i))return g({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:ze(1).permissionSummary});throw i}},search_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=Lc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=await Iy(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.blocks)?a.blocks:[],c=await eo(e,i,t),u=kt(c.items);return g({...a,blocks:u,data:u,total:u.length,showing:u.length,truncated:!1,...ze(c.removedCount)})},find_replace:async({client:e,permMgr:t,rawArgs:o})=>{const n=Zc.parse(o);for(const i of n.ids){const{denied:c}=await S(e,t,i,"write");if(c)return c}if(Array.isArray(n.paths))for(const i of n.paths){const c=await Ft(e,i);if(!c)continue;const u=await q(t,c,"write");if(u)return u}const r=Uo(n),s=Ko(n.sortBy,n.orderBy);await Dy(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 g({success:!0,replaced:!0,ids:n.ids,k:n.k,r:n.r,...n.paths?{paths:n.paths}:{},...a?{resolvedArgs:Wt({...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:Lr(s)}:{}}).resolvedArgs}:{}})},search_assets:async({client:e,rawArgs:t})=>{const o=Hc.parse(t),n=jo(o.k,o.query)??"",r=await Sy(e,n,o.exts);return o.query===void 0?g(r):g({...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=Vc.parse(o);if(n.assetId){const d=await Ay(e,n.assetId,n.query??"",n.queryMethod??0);return g(d)}const r=Uo(n),s=hk(n.sortBy,n.orderBy),a=await Ty(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:[],u=await eo(e,c,t),l=n.methodName!==void 0||n.sortBy!==void 0;return Kk(i,u.items,u.removedCount,l?Wt({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:mk(s)}:{}}).resolvedArgs:void 0)},list_invalid_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=Yc.parse(o),r=await Py(e,n.page,n.pageSize),a=Yr(r??{},t),i=Array.isArray(a.blocks)?a.blocks:[],c=kt(i);return g({...a,blocks:c,data:c,total:c.length,showing:c.length,truncated:!1,...ze(typeof a.filteredOutBlockCount=="number"?a.filteredOutBlockCount:0)})}},Xk="search",ew=[w("fulltext",Uc,"Full-text search across all blocks."),w("query_sql",qc,"Execute a read-only SQL query against the database."),w("get_backlinks",Mc,"Find documents/blocks that link to or mention the given block."),w("search_refs",Lc,"Search blocks that reference a given block or document."),w("find_replace",Zc,"Find and replace text in documents or blocks."),w("search_assets",Hc,"Search asset files by filename."),w("fulltext_asset_content",Vc,"Full-text search indexed asset contents."),w("list_invalid_refs",Yc,"List invalid block references.")],Eu=ae({name:Xk,description:"🔍 Grouped search and query operations.",variants:ew,actionSchema:_g,aggregateOptions:{guidance:ea,actionHints:ta,guidanceInlineLimit:5},handlers:Qk});function tw(e){return Eu.listTools(e)}async function ow(e,t,o,n){return Eu.callTool(e,t,o,n)}function nw(e){return typeof e!="string"?!1:e!=="d"}function rw(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 sw(e,t){const o=Mt(),n=new Map;let r=!1;for(const s of t){s&&typeof s=="object"&&nw(s.type)&&(r=!0);const a=await Lt(e,s,o);if(!(a!=null&&a.documentId)||!a.notebook||!a.path)continue;let i=n.get(a.documentId);if(!i){let c,u;try{const l=await Be(e,a.documentId);c=l.name,u=l.hPath}catch{c=void 0,u=void 0}i={documentId:a.documentId,notebook:a.notebook,path:a.path,...u?{hPath:u}:{},...c?{name:c}:{},updatedBlockCount:0,sampleBlocks:[]},n.set(a.documentId,i)}i.updatedBlockCount+=1,i.sampleBlocks.length<3&&i.sampleBlocks.push(rw(s))}return{documents:[...n.values()],containsLowLevelBlocks:r}}function Xn(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;return le({action:t.action,...r?{id:r}:{},...s?{parentID:s}:{},...a?{previousID:a}:{},...i?{nextID:i}:{},dataType:t.dataType})}function aw(e,t){const o={success:!0,id:t.id,dataType:t.dataType};if(t.dataType==="markdown"&&(o.markdown=Kn(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."),g(o)}function iw(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}}function cw(e,t){return e.map(o=>({...o,nextID:o.nextID??t.nextID,previousID:o.previousID??t.previousID,parentID:o.parentID??t.parentID}))}function uw(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 lw(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 dw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Gi.parse(o);if(n.blocks){const i=cw(n.blocks,{parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),c=new Set;for(const[d,f]of i.entries()){const h=f.nextID||f.previousID||f.parentID;if(!h)return iw(d);const{denied:m,context:k}=await S(e,t,h,"write");if(m)return m;c.add(k.documentId)}const u=await hy(e,i),l=uw(u);return l.length===0?lw(i.length,u):T(e,g({success:!0,action:"insert",count:i.length,createdBlockIDs:l,transactions:u}),[...c].map(d=>({type:"reloadProtyle",id:d})))}const r=n.nextID||n.previousID||n.parentID;let s;if(r){const{denied:i,context:c}=await S(e,t,r,"write");if(i)return i;s=c.documentId}const a=await ry(e,n.dataType,n.data,n.nextID,n.previousID,n.parentID);return T(e,Xn(a,{action:"insert",dataType:n.dataType,parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),s?[{type:"reloadProtyle",id:s}]:[])},pw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ji.parse(o),{denied:r,context:s}=await S(e,t,n.parentID,"write");if(r)return r;const a=await sy(e,n.dataType,n.data,n.parentID);return T(e,Xn(a,{action:"prepend",dataType:n.dataType,parentID:n.parentID}),[{type:"reloadProtyle",id:s.documentId}])},fw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Wi.parse(o),{denied:r,context:s}=await S(e,t,n.parentID,"write");if(r)return r;const a=await cu(e,n.dataType,n.data,n.parentID);return T(e,Xn(a,{action:"append",dataType:n.dataType,parentID:n.parentID}),[{type:"reloadProtyle",id:s.documentId}])},hw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ki.parse(o);if(n.items){const i=new Set;for(const u of n.items){const{denied:l,context:d}=await S(e,t,u.id,"write");if(l)return l;i.add(d.documentId)}const c=await my(e,n.items);return T(e,g({success:!0,action:"update",count:n.items.length,transactions:c}),[...i].map(u=>({type:"reloadProtyle",id:u})))}const{denied:r,context:s}=await S(e,t,n.id,"write");if(r)return r;const a=await uu(e,n.dataType,n.data,n.id);return T(e,aw(a,{id:n.id,dataType:n.dataType,data:n.data}),[{type:"reloadProtyle",id:s.documentId}])},mw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Qi.parse(o),{denied:r,context:s}=await S(e,t,n.id,"write");if(r)return r;const a=Iu(await du(e,n.id)),i=typeof a.kramdown=="string"?a.kramdown:"",c=Array.isArray(n.edit)?n.edit:[n.edit],{content:u,summary:l}=Qo(i,c,"block.replace"),d=u!==i;return d&&await uu(e,"markdown",u,n.id),T(e,g({success:!0,action:"replace",id:n.id,changed:d,editsApplied:l.length,replacements:l}),d?[{type:"reloadProtyle",id:s.documentId}]:[])},gw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Xi.parse(o),{denied:r,context:s}=await S(e,t,n.id,"delete");return r||(await lu(e,n.id),T(e,g({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId}]))},yw=async({client:e,permMgr:t,rawArgs:o})=>{const n=ec.parse(o),r=await S(e,t,n.id,"write");if(r.denied)return r.denied;if(n.parentID){const i=await S(e,t,n.parentID,"write");if(i.denied)return i.denied}if(n.previousID){const i=await S(e,t,n.previousID,"write");if(i.denied)return i.denied}const s=await ay(e,n.id,n.previousID,n.parentID),a=[{type:"reloadProtyle",id:r.context.documentId}];if(n.parentID){const i=await S(e,t,n.parentID,"write");if(i.denied)return i.denied;a.push({type:"reloadProtyle",id:i.context.documentId})}if(n.previousID){const i=await S(e,t,n.previousID,"write");if(i.denied)return i.denied;a.push({type:"reloadProtyle",id:i.context.documentId})}return T(e,le({id:n.id,...n.previousID?{previousID:n.previousID}:{},...n.parentID?{parentID:n.parentID}:{}},s),a)},bw=async({client:e,permMgr:t,rawArgs:o})=>{const n=tc.parse(o),{denied:r,context:s}=await S(e,t,n.id,"write");return r||(n.folded?await iy(e,n.id):await cy(e,n.id),T(e,g({success:!0,id:n.id,folded:n.folded}),[{type:"reloadProtyle",id:s.documentId}]))},kw=async({client:e,permMgr:t,rawArgs:o})=>{const n=oc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=Iu(await du(e,n.id));return g(s)},ww=async({client:e,permMgr:t,rawArgs:o})=>{const n=nc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=await Hn(e,n.id),a=Array.isArray(s)?s:[],i=su(a,n.page??1,n.pageSize??50);return ct(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.'}:{}})},_w=async({client:e,permMgr:t,rawArgs:o})=>{const n=rc.parse(o),r=await S(e,t,n.fromID,"write");if(r.denied)return r.denied;const s=await S(e,t,n.toID,"write");return s.denied?s.denied:(await uy(e,n.fromID,n.toID,n.refIDs),T(e,g({success:!0,fromID:n.fromID,toID:n.toID}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId}]))},vw=async({client:e,permMgr:t,rawArgs:o})=>{const n=sc.parse(o),{denied:r,context:s}=await S(e,t,n.id,"write");return r||(await de(e,[{doOperations:[{action:"setAttrs",id:n.id,data:JSON.stringify(n.attrs)}],undoOperations:[]}]),T(e,g({success:!0,id:n.id,attrs:n.attrs}),[{type:"reloadProtyle",id:s.documentId}]))},Iw=async({client:e,permMgr:t,rawArgs:o})=>{const n=ac.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=await fu(e,n.id);return g(s)},Dw=async({client:e,permMgr:t,rawArgs:o})=>{const n=ic.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=await ly(e,n.id);return g(s)},Sw=async({client:e,permMgr:t,rawArgs:o})=>{const n=cc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=await dy(e,n.id,n.excludeTypes);return g(s)},Aw=async({client:e,permMgr:t,rawArgs:o})=>{const n=uc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=await pu(e,n.id);return g(s)},Tw=async({client:e,permMgr:t,rawArgs:o})=>{const n=lc.parse(o),r=await py(e),s=Array.isArray(r)?r:[],a=await eo(e,s,t),i=typeof n.count=="number"?n.count:void 0,c=typeof i=="number"?a.items.slice(0,i):a.items,u=await sw(e,c);return g({documents:u.documents,documentCount:u.documents.length,count:c.length,containsLowLevelBlocks:u.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"}:{}})},Pw=async({client:e,permMgr:t,rawArgs:o})=>{const n=dc.parse(o);for(const s of n.ids){const{denied:a}=await S(e,t,s,"read");if(a)return a}const r=await fy(e,n.ids);return g(r)},Ew=async({client:e,permMgr:t,rawArgs:o})=>{const n=pc.parse(o),r=await q(t,n.notebook,"write");if(r)return r;const s=n.position==="append"?await gy(e,n.notebook,n.dataType,n.data):await yy(e,n.notebook,n.dataType,n.data);return T(e,g({success:!0,action:"add_to_daily_note",notebook:n.notebook,dataType:n.dataType,position:n.position,transactions:s}),[{type:"reloadFiletree"}])},Cw=async({client:e,permMgr:t,rawArgs:o})=>{const n=fc.parse(o),r=n.ids??[n.id];for(const a of r){const{denied:i}=await S(e,t,a,"read");if(i)return i}const s=await by(e,r,n.refCount??!1,n.av??!1);return g(s)},Ow={insert:dw,prepend:pw,append:fw,update:hw,replace:mw,delete:gw,move:yw,set_fold_state:bw,get_kramdown:kw,get_children:ww,transfer_references:_w,set_attrs:vw,get_attrs:Iw,info:Dw,breadcrumb:Sw,dom:Aw,recent_updated:Tw,word_count:Pw,add_to_daily_note:Ew,docs_info:Cw},xw=[w("insert",Gi,"Insert one or more blocks at the specified position."),w("prepend",Ji,"Insert a block at the beginning of a parent."),w("append",Wi,"Insert a block at the end of a parent."),w("update",Ki,"Update one or more blocks."),w("replace",Qi,"Apply exact old/new text replacement edits inside one block."),w("delete",Xi,"Delete a block by ID."),w("move",ec,"Move a block to a new position."),w("set_fold_state",tc,"Set the fold state of a foldable block."),w("get_kramdown",oc,"Get block content in kramdown format."),w("get_children",nc,"Get child blocks of a parent with pagination support."),w("transfer_references",rc,"Transfer block references from one block to another."),w("set_attrs",sc,"Set block attributes."),w("get_attrs",ac,"Get block attributes."),w("info",ic,"Get block position and root document metadata."),w("breadcrumb",cc,"Get the breadcrumb path for a block."),w("dom",uc,"Get rendered DOM for a block."),w("recent_updated",lc,"Get recently updated blocks."),w("word_count",dc,"Get word-count statistics for blocks."),w("add_to_daily_note",pc,"Add a block to today's daily note, creating the note if needed."),w("docs_info",fc,"Get document info for one or more documents.")],Cu=ae({name:"block",description:"🧱 Grouped block operations.",variants:xw,actionSchema:lg,aggregateOptions:{guidance:Us,actionHints:Ks,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:Ow}),Nw=Cu.listTools,$w=Cu.callTool;async function Rw(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 yt(e,t){const o={id:t};return e.request("/api/export/exportMdContent",o)}async function zw(e,t,o){const n={paths:t,name:o};return e.request("/api/export/exportResources",n)}async function Fw(e){return e.request("/api/asset/getUnusedAssets",{})}async function Bw(e,t){return e.request("/api/asset/getDocAssets",{id:t})}async function jw(e,t){return e.request("/api/asset/getDocImageAssets",{id:t})}async function Uw(e,t){return e.request("/api/asset/getImageOCRText",t?{path:t}:{})}async function qw(e){return e.request("/api/asset/removeUnusedAssets",{})}async function Mw(e,t,o){return e.request("/api/asset/renameAsset",{oldPath:t,newName:o})}async function Lw(e,t){return e.request("/api/asset/deleteAsset",{path:t})}const qo=[120,240],Zw=["path","hpath"];function Hw(e){return e==="/"||/\.sy(?:\/|$)/.test(e)}async function Ou(e,t,o){await de(e,[{doOperations:[{action:"setAttrs",id:t,data:JSON.stringify(o)}],undoOperations:[]}])}function Vw(e){return e instanceof Error&&/SiYuan API error:\s*-1\s*-\s*indexing/i.test(e.message)}async function Yw(e,t){let o;for(let r=0;r<=qo.length;r+=1)try{return await To(e,t)}catch(s){if(!Vw(s)||r===qo.length){o=s;break}o=s,await Zt(qo[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 Kt(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:{notebook:t,path:o}}}function Gw(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 Jw(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Ww(e){return/(?:^|\/)\d{14}-[a-z0-9]{7}\.sy$/i.test(e)}async function Kw(e,t,o){const n=o==="/"?"/":o.replace(/\/+$/,"");return Ww(n)?Vn(e,t,n):n}function tn(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:tn(r.children,t,o+1)}:r}):e}async function on(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=Je(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 on(e,r.children,o)),s})):t}function Qw(e,t){if(Array.isArray(e))return to({backmentions:e},t).backmentions;if(!e||typeof e!="object")return e;const o=e;return Array.isArray(o.files)?{...o,files:to({backmentions:o.files},t).backmentions}:Array.isArray(o.docs)?{...o,docs:to({backmentions:o.docs},t).backmentions}:e}async function Xw(e,t,o,n){if(Array.isArray(t)){const s=await Bo(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 Bo(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 Bo(e,r.docs,o,n);return{data:{...r,docs:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}return{data:Qw(t,o),permissionFilteredOutCount:0,pathFilteredOutCount:0}}const e_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ii.parse(o);if(await t.reload(),!t.canWrite(n.notebook))return Ln(n.notebook,t.get(n.notebook),"write");const r=n.markdown??"",s=n.parentPath?await Kw(e,n.notebook,n.parentPath):void 0,a=n.path??Jw(s,n.title),i=await hu(e,n.notebook,a,r);return n.icon&&await Ou(e,i,{icon:n.icon}),T(e,g({success:!0,notebook:n.notebook,path:a,...n.parentPath?{parentPath:n.parentPath}:{},...s&&s!==n.parentPath?{resolvedParentPath:s}:{},...n.title?{title:n.title}:{},id:i,iconHint:Mn("document",!!n.icon)}),n.icon?[{type:"reloadIcon"}]:[{type:"reloadProtyle",id:i},{type:"reloadFiletree"}])},t_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Di.parse(o),r=n.hpath??n.hPath,s=new Set(n.include??Zw),a={source:n.id?{id:n.id}:n.path?{notebook:n.notebook,path:n.path}:{notebook:n.notebook}};if(n.id){const{denied:d,context:f}=await S(e,t,n.id,"read");if(d)return d;a.id=n.id,a.notebook=f.notebook,a.path=f.path,s.has("path")&&(a.path=await At(e,n.id)),a.hPath=await Yw(e,n.id),s.has("docInfo")&&(a.docInfo=await Je(e,n.id));const h=await Xo(e,f.notebook);return h&&(a.notebookName=h),g(Kt(a))}const i=await q(t,n.notebook,"read");if(i)return i;const c=await Xo(e,n.notebook);if(n.path){if(a.notebook=n.notebook,c&&(a.notebookName=c),a.path=n.path,!Hw(n.path)){const f=await Xt(e,n.path,n.notebook),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 At(e,h)),h&&s.has("docInfo")&&(a.docInfo=await Je(e,h)),g(Kt(a))}const d=await Vn(e,n.notebook,n.path);if(a.hPath=d,s.has("id")||s.has("ids")){const f=await Xt(e,d??n.path,n.notebook);a.ids=f,s.has("id")&&(a.id=f[0])}return s.has("docInfo")&&typeof a.id=="string"&&(a.docInfo=await Je(e,a.id)),g(Kt(a))}const u=await Xt(e,r,n.notebook);a.notebook=n.notebook,c&&(a.notebookName=c),a.hPath=r,(s.has("ids")||s.has("id"))&&(a.ids=u,s.has("id")&&(a.id=u[0]));const l=u[0];if(l){const{denied:d}=await S(e,t,l,"read");if(d)return d;a.path=await At(e,l)}if(l&&s.has("docInfo")){const{denied:d}=await S(e,t,l,"read");if(d)return d;a.docInfo=await Je(e,l)}return g(Kt(a))},o_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Si.parse(o);if(n.id){const{denied:r,context:s}=await S(e,t,n.id,"write");return r||(await mu(e,n.id,n.title),T(e,g({success:!0,id:n.id,title:n.title}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await q(t,n.notebook,"write");if(r)return r}return await Ey(e,n.notebook,n.path,n.title),T(e,g({success:!0,notebook:n.notebook,path:n.path,title:n.title}),[{type:"reloadFiletree"}])},n_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ai.parse(o);if(n.ids){const r=[];for(const s of n.ids){const{denied:a,context:i}=await S(e,t,s,"delete");if(a)return a;r.push(i.documentId)}for(const s of n.ids)await Wo(e,s);return T(e,g({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 Ft(e,r);if(!s)throw new Error(`Unable to resolve notebook for storage path "${r}" while checking permissions.`);const a=await q(t,s,"delete");if(a)return a}return await Fy(e,n.paths),T(e,g({success:!0,paths:n.paths,count:n.paths.length}),[{type:"reloadFiletree"}])}if(n.id){const{denied:r,context:s}=await S(e,t,n.id,"delete");return r||(await Wo(e,n.id),T(e,g({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await q(t,n.notebook,"delete");if(r)return r}return await Cy(e,n.notebook,n.path),T(e,g({success:!0,notebook:n.notebook,path:n.path}),[{type:"reloadFiletree"}])},r_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ti.parse(o);if(n.toNotebook){const r=await q(t,n.toNotebook,"write");if(r)return r}if(n.toID){const r=await eb(e,n.toID),s=await q(t,r,"write");if(s)return s}if(n.fromIDs){const r=[];for(const s of n.fromIDs){const{denied:a,context:i}=await S(e,t,s,"write");if(a)return a;r.push(i.documentId)}return await gu(e,n.fromIDs,n.toID),T(e,g({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 Ft(e,r);if(!s)throw new Error(`Unable to resolve source notebook for storage path "${r}" while checking permissions.`);const a=await q(t,s,"write");if(a)return a}return await Oy(e,n.fromPaths,n.toNotebook,n.toPath),T(e,g({success:!0,fromPaths:n.fromPaths,toNotebook:n.toNotebook,toPath:n.toPath}),[{type:"reloadFiletree"}])},s_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Pi.parse(o),{denied:r,context:s}=await S(e,t,n.id,"read");if(r)return r;const a=await Hn(e,s.documentId);return g(a)},a_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ei.parse(o),{denied:r,context:s}=await S(e,t,n.id,"read");if(r)return r;const a=await Po(e,s.notebook,s.path);return g(a)},i_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ci.parse(o),{denied:r,context:s}=await S(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 u=n.attrs.cover;if(!u)a["title-img"]="",i.clearedCover=!0;else{const l=Gw(u);a["title-img"]=l.titleImg,i.cover=l.source,i.titleImg=l.titleImg}c.push({type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"})}return await Ou(e,n.id,a),T(e,g(i),c)},c_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Oi.parse(o),r=await q(t,n.notebook,"read");if(r)return r;const s=n.maxDepth??3,a=await Qe(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 u=await on(e,a.tree);return g({...a,tree:tn(u,s),maxDepth:s,depthHint:i})}const c=await on(e,a);return g({tree:tn(c,s),maxDepth:s,depthHint:i})},u_=async({client:e,permMgr:t,rawArgs:o})=>{const n=xi.parse(o),r=await q(t,n.notebook,"read");if(r)return r;const s=await Ny(e,n.query),a=await Xw(e,s,t,n.path),i=a.permissionFilteredOutCount+a.pathFilteredOutCount;return g({...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}:{}})},l_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ni.parse(o),{denied:r,context:s}=await S(e,t,n.id,"read");if(r)return r;const a=await Xo(e,s.notebook);if(n.mode==="html"){const v=await $y(e,n.id,0,n.size);return g({id:n.id,mode:"html",notebook:s.notebook,...a?{notebookName:a}:{},...v&&typeof v=="object"?v:{content:v}})}const i=Ht(await yt(e,n.id)),c=typeof i.content=="string"?i.content:"",u=n.page??1,l=n.pageSize??8e3,d=Math.max(1,Math.ceil(c.length/l)),f=Math.min(u,d),h=(f-1)*l,m=c.slice(h,h+l),k=c.length>l;return g({id:n.id,mode:"markdown",notebook:s.notebook,...a?{notebookName:a}:{},hPath:i.hPath,content:m,...k?{truncated:!0,contentLength:c.length,showing:m.length,page:f,pageSize:l,pageCount:d,hasNextPage:f<d,hint:'Use page/pageSize to read the next markdown chunk. For structured reads, use document(action="get_child_blocks") or block(action="get_kramdown").'}:{}})},d_=async({client:e,permMgr:t,rawArgs:o})=>{const n=$i.parse(o),r=await q(t,n.notebook,"write");if(r)return r;const s=await Ry(e,n.notebook,n.app);let a;try{a=await To(e,s.id)}catch{a=void 0}return T(e,g({success:!0,notebook:n.notebook,...s,...a?{hPath:a}:{},iconHint:Mn("document")}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}])},p_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ri.parse(o),{denied:r,context:s}=await S(e,t,n.id,"write");if(r)return r;const a=await zy(e,n.id);return T(e,g({success:!0,sourceID:n.id,...a}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}])},f_=async({client:e,permMgr:t,rawArgs:o})=>{const n=zi.parse(o),r=await S(e,t,n.headingID,"write");if(r.denied)return r.denied;const s=await q(t,n.targetNotebook,"write");return s||(await By(e,n.headingID,n.targetNotebook,n.targetPath,n.previousPath),T(e,g({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"}]))},h_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Fi.parse(o),r=await S(e,t,n.srcID,"write");if(r.denied)return r.denied;const s=await S(e,t,n.targetID,"write");if(s.denied)return s.denied;const a=await jy(e,n.srcID,n.targetID,n.after??!1);return T(e,g({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"}])},m_={create:e_,lookup:t_,rename:o_,remove:n_,move:r_,get_child_blocks:s_,get_child_docs:a_,set_attr:i_,list_tree:c_,search_docs:u_,get_doc:l_,create_daily_note:d_,duplicate:p_,heading_to_doc:f_,doc_to_heading:h_},g_=[w("create",Ii,"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."),w("lookup",Di,"Look up document IDs, storage paths, human-readable paths, and document metadata from one document reference."),w("rename",Si,"Rename a document"),w("remove",Ai,"Delete a document"),w("move",Ti,"Move a document to another location"),w("get_child_blocks",Pi,"Get top-level blocks of a document"),w("get_child_docs",Ei,"Get child documents"),w("set_attr",Ci,"Set document metadata such as icon and cover image."),w("list_tree",Oi,"Get document tree"),w("search_docs",xi,"Search documents by title"),w("get_doc",Ni,"Get full document content"),w("create_daily_note",$i,"Create or open today's daily note"),w("duplicate",Ri,"Duplicate a document"),w("heading_to_doc",zi,"Convert a heading to a separate document"),w("doc_to_heading",Fi,"Merge a document into another as a heading")],xu=ae({name:"document",description:"📝 Grouped document operations.",variants:g_,actionSchema:ug,aggregateOptions:{guidance:js,actionHints:Ws,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:m_});function y_(e){return xu.listTools(e)}async function b_(e,t,o,n){return xu.callTool(e,t,o,n)}async function k_(e,t,o){const n={id:t,path:o};return e.request("/api/template/render",n)}async function w_(e,t){const o={template:t};return e.request("/api/template/renderSprig",o)}const __="file",nn=10;function v_(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 I_(e){return[...new Set(e.map(v_).filter(Boolean))]}function D_(e){return F.isAbsolute(e)?e:F.resolve(process.cwd(),e)}function S_(e){return F.isAbsolute(e)?e:F.resolve(process.cwd(),e)}function A_(e){return e instanceof Error&&/is not in workspace/i.test(e.message)}const T_=(e,t)=>async({client:o,rawArgs:n})=>{const r=Pc.parse(n),s=S_(r.localFilePath);if(!j.existsSync(s))throw new Error(`Local file does not exist: ${s}`);const a=j.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 g({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=F.basename(s),c=j.readFileSync(s),u=await Rw(o,r.assetsDirPath,c,i);return g({...u,localFilePath:s,uploadedFileName:i,...a.size>t?{largeFileConfirmed:!0}:{}})},P_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ec.parse(o);if(n.engine==="sprig"){const s=await w_(e,n.template);return g(s)}const{denied:r}=await S(e,t,n.id,"read");if(r)return r;try{const s=await k_(e,n.id,n.path);return g(s)}catch(s){if(A_(s))return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:__,action:"render",message:s.message,reason:"path_not_in_workspace",workspacePathRequired:!0,hint:"The template path must point to a file inside the SiYuan workspace, not an arbitrary local path such as /tmp/... or your repo checkout."}},null,2)}],isError:!0};throw s}},E_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Cc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=Ht(await yt(e,n.id));return g(s)},C_=async({client:e,rawArgs:t})=>{const o=Oc.parse(t),n=I_(o.paths);if(n.length===0)throw new Error("export_resources requires at least one non-empty resource path.");let r;try{r=await zw(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=D_(o.outputPath),a=await e.readFileBinary(r.path);return j.mkdirSync(F.dirname(s),{recursive:!0}),j.writeFileSync(s,a),g({...r,outputPath:s,bytes:a.byteLength})}return g(r)},O_=async({client:e,rawArgs:t})=>{xc.parse(t);const o=await Fw(e);return g({assets:o,count:Array.isArray(o)?o.length:void 0})},x_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Nc.parse(o),{denied:r}=await S(e,t,n.id,"read");if(r)return r;const s=n.assetType==="image"?await jw(e,n.id):await Bw(e,n.id);return g({id:n.id,assetType:n.assetType??"all",assets:s,count:Array.isArray(s)?s.length:void 0})},N_=async({client:e,rawArgs:t})=>{const o=$c.parse(t),n=await Uw(e,o.path);return g({path:o.path??null,...n})},$_=async({client:e,rawArgs:t})=>{Rc.parse(t);const o=await qw(e);return g({success:!0,...o&&typeof o=="object"&&!Array.isArray(o)?o:{result:o}})},R_=async({client:e,rawArgs:t})=>{const o=zc.parse(t),n=await Mw(e,o.oldPath,o.newName);return g({success:!0,oldPath:o.oldPath,newName:o.newName,...n})},z_=async({client:e,rawArgs:t})=>{const o=Fc.parse(t),n=await Lw(e,o.path);return g({success:!0,path:o.path,...n&&typeof n=="object"&&!Array.isArray(n)?n:{}})},F_=async({client:e,rawArgs:t})=>{var C;const o=Bc.parse(t),n=await yt(e,o.id),r=typeof n.content=="string"?n.content:"",a=((C=(typeof n.hPath=="string"?n.hPath:"").split("/").filter(Boolean).pop())==null?void 0:C.replace(/\.sy$/,""))||o.id,i=o.id.slice(-7),c=`${a}-${i}`,u=process.env.USERPROFILE||process.env.HOME||"",l=o.outputDir?F.resolve(o.outputDir):F.join(u,"siyuan-extracted"),d=F.join(l,c),f=F.join(d,"assets");j.existsSync(l)&&j.rmSync(l,{recursive:!0,force:!0}),j.mkdirSync(f,{recursive:!0});const h=F.join(d,`${a}.md`);j.writeFileSync(h,r,"utf-8");const m=[...r.matchAll(/\]\(assets\/([^\s)"']+)(?:\s+"[^"]*")?\)/g)],k=[`${a}.md`];let v=0,E=0;for(const $ of m){const I=$[1],A=F.join(f,I);try{j.mkdirSync(F.dirname(A),{recursive:!0});const B=await e.readFileBinary(`data/assets/${I}`);j.writeFileSync(A,B),k.push(`assets/${I}`),v++}catch{E++}}return g({extractedDir:d,docMdFile:`${a}.md`,extractedAssetCount:v,skippedAssetCount:E,structure:k})};function B_(e,t){return{upload_asset:T_(e,t),render:P_,export_md:E_,export_resources:C_,list_unused_assets:O_,get_doc_assets:x_,get_image_ocr_text:N_,remove_unused_assets:$_,rename_asset:R_,delete_asset:z_,extract_doc:F_}}const j_=[w("upload_asset",Pc,"Read a local file and upload it to the specified assets directory."),w("render",Ec,"Render a SiYuan workspace template (.action{.title}) or an inline Sprig template ({{...}})."),w("export_md",Cc,"Export document content as Markdown."),w("export_resources",Oc,"Export resources as a ZIP archive."),w("list_unused_assets",xc,"List unused asset files."),w("get_doc_assets",Nc,"List assets directly referenced by the current document tree. Use extract_doc for complete document asset inspection."),w("get_image_ocr_text",$c,"Get stored OCR text for an image asset."),w("remove_unused_assets",Rc,"Remove all unused asset files."),w("rename_asset",zc,"Rename an asset file."),w("delete_asset",Fc,"Delete an asset file."),w("extract_doc",Bc,"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 Nu(e,t){return ae({name:"file",description:"📁 Grouped file and asset operations.",variants:j_,actionSchema:pg,aggregateOptions:{guidance:Ms,actionHints:Xs},handlers:B_(e,t)})}const U_=Nu(nn,nn*1024*1024);function q_(e){return U_.listTools(e)}async function M_(e,t,o,n){const r="uploadLargeFileThresholdMB"in o&&typeof o.uploadLargeFileThresholdMB=="number"?o.uploadLargeFileThresholdMB:nn,s=r*1024*1024;return Nu(r,s).callTool(e,t,o,n)}function er(){const e=(process.env.SIYUAN_MCP_TRANSPORT??"").toLowerCase();return e==="cli"||e==="http"?e:"stdio"}const $u="Uq2KRv7t",L_="https://f-api.wps.cn/ksform/api/v3/campaign",Z_=`https://f.wps.cn/ksform/w/write/${$u}`,H_="0.4.8",Le={description:"v5nhl6",impact:"bbev5x",suggestion:"6wxpgj",source:"8dcnsl",agent:"fu27dr",pluginVersion:"yl3by8"},V_={settings:{value:"用户"},cli:{value:"CLI"},stdio:{value:"STDIO"},http:{value:"HTTP"}},Ru="无";function oo(e){return(e==null?void 0:e.trim())||Ru}function He(e){return{type:"input",strValue:e,isManualInput:!0}}function Y_(e){const t=V_[e];return He(t.value)}function G_(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 J_(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=er();return o==="cli"||o==="http"?o:"stdio"}function W_(e){const t=oo(e);return t!==Ru?t:"0.4.8".trim()?"0.4.8".trim():H_}function K_(e,t){var l,d,f,h;const o=(h=(f=(d=(l=t==null?void 0:t.setting)==null?void 0:l.baseSetting)==null?void 0:d.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=oo(e.impact),s=oo(e.suggestion),a=oo(e.agent),i=W_(e.pluginVersion),c=J_(e.source),u=G_(t,"来源",Le.source);return{answerJson:{answers:{[Le.description]:He(n),[Le.impact]:He(r),[Le.suggestion]:He(s),[u]:Y_(c),[Le.agent]:He(a),[Le.pluginVersion]:He(i)},answersProperty:{commitInfo:{optionId:o.id,optionText:""}},consumeTime:2},phoneNumber:"",editVersion:t.editVersion??1,token:t.token,channel:c}}function Jr(e){return{Accept:"application/json, text/plain, */*",Origin:"https://f.wps.cn",Referer:Z_,"User-Agent":"siyuan-plugin-mcp-sisyphus feedback",...e}}async function Wr(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 Kr(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 Q_(e,t=fetch){var l,d,f,h,m,k;const o=e.description.trim();if(!o)throw new Error("Feedback description is required.");const n=`${L_}/${$u}`,r=await t(n,{method:"GET",headers:Jr()});if(!r.ok)throw await Kr(r,"Feedback metadata request");const s=await Wr(r,"Feedback metadata request");if(s.code!==0||!s.data)throw new Error(`Feedback metadata request failed: ${s.result||s.code}`);if((d=(l=s.data.setting)==null?void 0:l.baseSetting)!=null&&d.checkLogin)throw new Error("Feedback form currently requires WPS login.");const a=`sisyphus${Math.random().toString(36).slice(2)}`,i=K_({...e,description:o},s.data),c=await t(n,{method:"POST",headers:Jr({"Content-Type":"application/json",Cookie:`csrf=${a}`}),body:JSON.stringify({...i,csrfmiddlewaretoken:a})});if(!c.ok)throw await Kr(c,"Feedback submit");const u=await Wr(c,"Feedback submit");if(u.code!==0)throw new Error(`Feedback submit failed: ${u.result||u.code}`);return{success:!0,aid:(f=u.data)==null?void 0:f.aid,answerShareId:(m=(h=u.data)==null?void 0:h.answerShare)==null?void 0:m.asid,createdTs:(k=u.data)==null?void 0:k.createdTs}}const X_="feedback",ev=[w("submit",qi,"Submit plain-text GitHub Issue-style feedback to the developer.")],zu=ae({name:X_,description:"💬 Submit plain-text GitHub Issue-style feedback, suggestions, or experience reports to the plugin developer.",variants:ev,actionSchema:mg,aggregateOptions:{guidance:Ys,actionHints:aa},handlers:{submit:async({rawArgs:e})=>{const t=qi.parse(e),o=await Q_({description:t.description,impact:t.impact,suggestion:t.suggestion,agent:t.agent,source:t.source});return g({action:"submit",...o})}}});function tv(e){return zu.listTools(e)}async function ov(e,t,o,n){return zu.callTool(e,t,o,n)}async function Fu(e){return e.request("/api/riff/getRiffDecks",{})}async function Qr(e,t,o){return e.request("/api/riff/getRiffDueCards",{deckID:t??"",...o!==void 0?{reviewedCards:o}:{}})}async function nv(e,t,o){return e.request("/api/riff/getNotebookRiffDueCards",{notebook:t,...o!==void 0?{reviewedCards:o}:{}})}async function rv(e,t,o){return e.request("/api/riff/getTreeRiffDueCards",{rootID:t,...o!==void 0?{reviewedCards:o}:{}})}async function sv(e,t,o,n,r){return e.request("/api/riff/reviewRiffCard",{deckID:t,cardID:o,rating:n,...r!==void 0?{reviewedCards:r}:{}})}async function av(e,t,o){return e.request("/api/riff/skipReviewRiffCard",{deckID:t,cardID:o})}async function iv(e,t,o){return e.request("/api/riff/addRiffCards",{deckID:t,blockIDs:o})}async function cv(e,t,o){return e.request("/api/riff/removeRiffCards",{deckID:t,blockIDs:o})}async function Xr(e,t,o,n){return e.request("/api/riff/getRiffCards",{id:t,page:o,...n!==void 0?{pageSize:n}:{}})}async function uv(e,t){return e.request("/api/riff/getRiffCardsByBlockIDs",{blockIDs:t})}const De="20230218211946-2kw8jgx",es="custom-riff-decks",lv="Built-in Deck",dv=5,pv=300,ts=6,fv=300;function hv(e){return typeof e=="string"?["new","0"].includes(e.toLowerCase()):e===0}function mv(e){return typeof e=="string"?["old","1","review"].includes(e.toLowerCase()):e===1}function gv(e,t){return t==="due"?e:t==="new"?e.filter(o=>hv(o.state)):e.filter(o=>mv(o.state))}function Bu(e){return e===""?De:e}function yv(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function bv(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 ju(e,t){const o=await fu(e,t);return o&&typeof o=="object"?o:{}}async function kv(e,t){for(const o of t)if((await ju(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 Uu(e,t,o){if(t===De)return;const n=await Fu(e);if(!Array.isArray(n)||!n.some(r=>bv(r)===t))throw new Error(`flashcard/${o} requires an existing deckID. Deck "${t}" was not found.`)}async function wv(e,t,o,n){for(const r of t){const s=await ju(e,r);if(!yv(s[es]).includes(o))throw new Error(`flashcard/${n} did not persist a valid deck binding for block "${r}". Expected ${es} to include "${o}".`)}}function _v(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:[]}function vv(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 os(e){return!e||typeof e!="object"?!1:typeof e.riffCardID=="string"&&e.riffCardID.length>0?!0:!!e.riffCard}async function qu(e,t,o,n){const r=new Set(t);for(let s=0;s<ts;s+=1){const a=await uv(e,t),i=new Map;for(const u of _v(a)){const l=vv(u);l&&i.set(l,u)}if([...r].every(u=>{const l=i.get(u);return o==="present"?os(l):!os(l)}))return;s<ts-1&&await Zt(fv)}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 Mu(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:Array.isArray(e==null?void 0:e.cards)?e.cards:[]}function Iv(e){return(!e.type||e.type==="")&&typeof e.content=="string"&&e.content.includes("不存在符合条件的内容块")}function Dv(e){return e.length>0&&e.some(Iv)}async function Sv(e,t,o,n){let r=await Xr(e,t,o,n);for(let s=1;s<dv;s+=1){if(!Dv(Mu(r)))return r;await Zt(pv),r=await Xr(e,t,o,n)}return r}const Av=async({client:e,rawArgs:t})=>{const o=Mi.parse(t),r=(o.scope==="all"?await Qr(e,"",o.reviewedCards):o.scope==="deck"?await Qr(e,o.deckID,o.reviewedCards):o.scope==="notebook"?await nv(e,o.notebook,o.reviewedCards):await rv(e,o.rootID,o.reviewedCards))??{};return g({...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:gv(Array.isArray(r.cards)?r.cards:[],o.filter)})},Tv=async({client:e,rawArgs:t})=>{Li.parse(t);const o=await Fu(e),n=Array.isArray(o)?[...o]:[];return n.some(s=>{if(!s||typeof s!="object")return!1;const a=s;return a.id===De||a.deckID===De})||n.unshift({id:De,deckID:De,name:lv,builtin:!0}),g({action:"get_decks",decks:n})},Pv=async({client:e,rawArgs:t})=>{const o=Yi.parse(t),n=await Sv(e,o.deckID,o.page??1,o.pageSize);return g({action:"get_cards",deckID:o.deckID,page:o.page??1,...o.pageSize!==void 0?{pageSize:o.pageSize}:{},cards:Mu(n),total:n==null?void 0:n.total,pageCount:n==null?void 0:n.pageCount})},Ev=async({client:e,rawArgs:t})=>{const o=Zi.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 av(e,o.deckID,o.cardID);return g({action:"review_card",skip:!0,deckID:o.deckID,cardID:o.cardID,result:r})}const n=await sv(e,o.deckID,o.cardID,o.rating,o.reviewedCards);return g({action:"review_card",deckID:o.deckID,cardID:o.cardID,rating:o.rating,...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},result:n})},Cv=async({client:e,rawArgs:t})=>{const o=Hi.parse(t),n=Bu(o.deckID);await kv(e,o.blockIDs),await Uu(e,n,"create_card");const r=o.mode??"full",s=await iv(e,n,o.blockIDs);return await wv(e,o.blockIDs,n,"create_card"),n===De&&await qu(e,o.blockIDs,"present","create_card"),g({action:"create_card",mode:r,deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:s})},Ov=async({client:e,rawArgs:t})=>{const o=Vi.parse(t),n=Bu(o.deckID);await Uu(e,n,"remove_card");const r=await cv(e,n,o.blockIDs);return n===De&&await qu(e,o.blockIDs,"absent","remove_card"),g({action:"remove_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})},xv={list_cards:Av,get_decks:Tv,get_cards:Pv,review_card:Ev,create_card:Cv,remove_card:Ov},Nv=[w("list_cards",Mi,"List due flashcards and optionally filter to new/old cards."),w("get_decks",Li,"Get flashcard deck definitions."),w("get_cards",Yi,"List all cards in a deck with pagination (not limited to due cards)."),w("review_card",Zi,"Submit a review result or skip one flashcard."),w("create_card",Hi,"Turn existing blocks into flashcards or attach existing blocks to a deck."),w("remove_card",Vi,"Remove existing blocks from a flashcard deck.")],Lu=ae({name:"flashcard",description:"🃏 Grouped flashcard review and deck operations.",variants:Nv,actionSchema:fg,aggregateOptions:{guidance:Hs,actionHints:ra},handlers:xv}),$v=Lu.listTools,Rv=Lu.callTool;function tr(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 zv(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function ns(e){return e.split("/").filter(Boolean).at(-1)??""}function rs(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Tt(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function Fv(e,t,o){return o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t)}async function Zu(e){return(await Ne(e)).notebooks.map(o=>({id:o.id,name:o.name,closed:o.closed}))}async function rn(e,t,o){let n;try{n=await Xt(e,o,t.id)}catch{return null}const r=n[0];if(!r)return null;const s=await At(e,r),a=await To(e,r).catch(()=>o),i=tr(a),c=ns(i)||zv(ns(s.path))||r;return{type:"document",id:r,notebook:s.notebook||t.id,notebookName:t.name,hPath:i,storagePath:s.path,canonicalPath:Tt(t.name,i),name:c}}function Bv(e){return e.map(t=>t.canonicalPath).join(", ")}function Ie(e,t){const o=new Error(t);return Object.assign(o,{code:e}),o}async function pe(e,t,o,n="read"){const r=tr(o);if(r==="/")return{type:"root",canonicalPath:"/"};await t.reload();const s=await Zu(e),a=r.split("/").filter(Boolean),i=a[0],c=s.find(l=>l.name===i);if(c){const l=a.length===1?"/":`/${a.slice(1).join("/")}`;if(l==="/")return{type:"notebook",notebook:c.id,notebookName:c.name,hPath:"/",storagePath:"/",canonicalPath:Tt(c.name,"/")};const d=await rn(e,c,l);if(!d)throw Ie("not_found",`No document found at "${r}".`);return d}const u=[];for(const l of s)if(Fv(t,l.id,n))try{const d=await rn(e,l,r);d&&u.push(d)}catch{}if(u.length===1)return u[0];throw u.length>1?Ie("ambiguous_path",`Ambiguous fs path "${r}". Candidates: ${Bv(u)}.`):Ie("not_found",`No document found at "${r}". Use /<notebook name>/<document path> for an unambiguous path.`)}async function Hu(e,t,o){const n=tr(o);if(n==="/")throw Ie("invalid_path",'Cannot create a document at "/". Use /<notebook name>/<title>.');const r=n.split("/").filter(Boolean),s=r.at(-1);if(!s)throw Ie("invalid_path",`Cannot create a document at "${n}".`);await t.reload();const i=(await Zu(e)).find(d=>d.name===r[0]);if(i){const d=r.slice(1,-1),f=d.length===0?"/":`/${d.join("/")}`;let h="/",m;if(f!=="/"){const v=await rn(e,i,f);if(!v)throw Ie("not_found",`Parent document not found at "${Tt(i.name,f)}".`);h=v.storagePath,m=v.id}const k=rs(f,s);return{notebook:i.id,notebookName:i.name,title:s,parentHPath:f,parentStoragePath:h,parentId:m,hPath:k,canonicalPath:Tt(i.name,k)}}if(r.length===1)throw Ie("invalid_path","Root-level create must use /<notebook name>/<title>.");const c=`/${r.slice(0,-1).join("/")}`,u=await pe(e,t,c,"write");if(u.type!=="document")throw Ie("invalid_path",`Parent path "${c}" must resolve to a document folder.`);const l=rs(u.hPath,s);return{notebook:u.notebook,notebookName:u.notebookName,title:s,parentHPath:u.hPath,parentStoragePath:u.storagePath,parentId:u.id,hPath:l,canonicalPath:Tt(u.notebookName,l)}}async function jv(e,t,o){return Hu(e,t,o)}function Fe(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Bt(e){if(e)return e.split("/").filter(Boolean).at(-1)}function Vu(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Yu(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 ke(e){return Yu(e)===Q}function sn(e){return Yu(e).startsWith(`${Q}/`)}function Me(e){if(sn(e))throw new Error(`${Q} is a virtual file and has no children.`)}function Uv(){return{name:Q.slice(1),path:Q,children:0,virtual:!0}}function qv(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function Mv(e,t){const o=Fe(t.name)??Fe(Bt(t.path))??t.path;return{name:o,path:Vu(e,o),children:t.subFileCount??t.count??0}}async function or(e,t){return await t.reload(),(await Ne(e)).notebooks.filter(n=>t.canRead(n.id))}async function Lv(e,t){return t.type==="root"?[]:(await Po(e,t.notebook,t.storagePath)).map(n=>Mv(t.canonicalPath,n))}function Zv(e,t){const o=Fe(typeof e.name=="string"?e.name:void 0)??Fe(Bt(typeof e.hPath=="string"?e.hPath:void 0))??Fe(Bt(typeof e.path=="string"?e.path:void 0))??(typeof e.id=="string"?e.id:"Untitled");return{name:o,path:Vu(t,o)}}async function an(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:{},u=Zv(c,o);let l=u.name,d=u.path;const f=typeof c.id=="string"?c.id:void 0;if(f)try{let k=a.get(f);k||(k=To(e,f),a.set(f,k));const v=await k,E=Fe(Bt(v));E&&(l=E,d=qv(n,v))}catch{}const h=Array.isArray(c.children)?c.children:[],m={name:l,path:d};return s>=r?m.children=h.length:m.children=await an(e,h,m.path,n,r,s+1,a),m})):[]}function Pt(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.tree)?e.tree:[]}function no(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(...no(n.children))}return t}function ss(e,t=1,o=8e3){const n=Math.max(1,Math.ceil(e.length/o)),r=Math.min(t,n),s=(r-1)*o,a=e.slice(s,s+o);return{content:a,truncated:e.length>o,contentLength:e.length,showing:a.length,page:r,pageSize:o,pageCount:n,hasNextPage:r<n}}function Hv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vv(e){const t=Fe(Bt(e));return typeof t=="string"&&t.length>0?t:void 0}function Yv(e){let t=e.content;const o=Vv(e.hPath);if(t.startsWith(`---
164
- `)){const n=t.match(/^---\n[\s\S]*?\n---\n*/);n&&(t=t.slice(n[0].length))}if(o){const n=new RegExp(`^# ${Hv(o)}\\s*\\n+`);t=t.replace(n,"")}return t}async function Gu(e,t,o){const n=await Hn(e,t);for(const r of n)typeof r.id=="string"&&await lu(e,r.id);o.trim().length>0&&await cu(e,"markdown",o,t)}async function Gv(e,t,o){if(o.type==="document"){const s=Pt(await Qe(e,o.notebook,o.storagePath));return[...new Set([o.id,...no(s)])].map(a=>({id:a,notebookName:o.notebookName}))}if(o.type==="notebook"){const s=Pt(await Qe(e,o.notebook,"/"));return[...new Set(no(s))].map(a=>({id:a,notebookName:o.notebookName}))}const n=await or(e,t),r=[];for(const s of n){const a=Pt(await Qe(e,s.id,"/"));r.push(...[...new Set(no(a))].map(i=>({id:i,notebookName:s.name})))}return r}function Jv(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 as(e,t){const o=[];return e.split(/\r?\n/).forEach((n,r)=>{t(n)&&o.push({path:Q,line:r+1,text:n.length>300?`${n.slice(0,297)}...`:n})}),o}async function bo(e){const t=await Rs(e);return{content:t.agentSiyuanMemoryText??"",updatedAt:t.agentSiyuanMemoryUpdatedAt??""}}const Wv=async({client:e,permMgr:t,rawArgs:o})=>{const n=ri.parse(o);if(Me(n.path),ke(n.path))throw new Error(`${Q} is a virtual file and has no children.`);const r=await pe(e,t,n.path,"read");if(r.type==="root"){const a=await or(e,t),i=[Uv()];for(const c of a){let u=0;try{u=(await Po(e,c.id,"/")).length}catch{u=0}i.push({name:c.name,path:`/${c.name}`,children:u})}return g({path:"/",items:i})}const s=await q(t,r.notebook,"read");return s||g({path:r.canonicalPath,items:await Lv(e,r)})},Kv=async({client:e,permMgr:t,rawArgs:o})=>{const n=si.parse(o);if(Me(n.path),ke(n.path))return g({path:Q,tree:[],virtual:!0,maxDepth:n.maxDepth??3});const r=await pe(e,t,n.path,"read"),s=n.maxDepth??3;if(r.type==="root"){const c=await or(e,t),u=[{name:Q.slice(1),path:Q,children:[],virtual:!0}];for(const l of c){const d=await Qe(e,l.id,"/");u.push({name:l.name,path:`/${l.name}`,children:await an(e,Pt(d),`/${l.name}`,l.name,s)})}return g({path:"/",tree:u,maxDepth:s})}const a=await q(t,r.notebook,"read");if(a)return a;const i=await Qe(e,r.notebook,r.storagePath);return g({path:r.canonicalPath,tree:await an(e,Pt(i),r.canonicalPath,r.notebookName,s),maxDepth:s})},Qv=async({client:e,permMgr:t,rawArgs:o})=>{const n=ai.parse(o);if(Me(n.path),ke(n.path)){const u=await bo(e),l=ss(u.content,n.page,n.pageSize);return g({path:Q,virtual:!0,updatedAt:u.updatedAt||null,content:l.content,...l.truncated?{truncated:!0,contentLength:l.contentLength,showing:l.showing,page:l.page,pageSize:l.pageSize,pageCount:l.pageCount,hasNextPage:l.hasNextPage}:{}})}const r=await pe(e,t,n.path,"read");if(r.type!=="document")throw new Error(`fs.read requires a document path, got "${n.path}".`);const s=await q(t,r.notebook,"read");if(s)return s;const a=Ht(await yt(e,r.id)),i=typeof a.content=="string"?a.content:"",c=ss(i,n.page,n.pageSize);return g({path:r.canonicalPath,content:c.content,...c.truncated?{truncated:!0,contentLength:c.contentLength,showing:c.showing,page:c.page,pageSize:c.pageSize,pageCount:c.pageCount,hasNextPage:c.hasNextPage}:{}})},Xv=async({client:e,permMgr:t,rawArgs:o})=>{const n=ii.parse(o);if(Me(n.path),ke(n.path)){const i=await Pn(e,n.markdown);return g({success:!0,path:Q,virtual:!0,overwritten:!0,updatedAt:i.agentSiyuanMemoryUpdatedAt||null})}const r=await Hu(e,t,n.path),s=await q(t,r.notebook,"write");if(s)return s;let a=null;try{const i=await pe(e,t,r.canonicalPath,"write");a=i.type==="document"?i:null}catch{a=null}if(!a){const i=await hu(e,r.notebook,r.hPath,n.markdown);return T(e,g({success:!0,path:r.canonicalPath,created:!0}),[{type:"reloadProtyle",id:i},{type:"reloadFiletree"}])}if(!n.overwrite)throw new Error(`Document already exists at "${a.canonicalPath}". Pass overwrite=true to replace its body.`);return await Gu(e,a.id,n.markdown),T(e,g({success:!0,path:a.canonicalPath,overwritten:!0}),[{type:"reloadProtyle",id:a.id},{type:"reloadFiletree"}])},eI=async({client:e,permMgr:t,rawArgs:o})=>{const n=ci.parse(o);if(Me(n.path),ke(n.path)){const f=await bo(e),h=f.content,m=Array.isArray(n.edit)?n.edit:[n.edit],{content:k,summary:v}=Qo(h,m,"fs.replace"),E=k!==h;let C=f.updatedAt;return E&&(C=(await Pn(e,k)).agentSiyuanMemoryUpdatedAt),g({success:!0,path:Q,virtual:!0,changed:E,editsApplied:v.length,replacements:v,updatedAt:C||null})}const r=await pe(e,t,n.path,"write");if(r.type!=="document")throw new Error(`fs.replace requires a document path, got "${n.path}".`);const s=await q(t,r.notebook,"write");if(s)return s;const a=Ht(await yt(e,r.id)),i=Yv({content:typeof a.content=="string"?a.content:"",hPath:typeof a.hPath=="string"?a.hPath:void 0}),c=Array.isArray(n.edit)?n.edit:[n.edit],{content:u,summary:l}=Qo(i,c,"fs.replace"),d=u!==i;return d&&await Gu(e,r.id,u),T(e,g({success:!0,path:r.canonicalPath,changed:d,editsApplied:l.length,replacements:l}),d?[{type:"reloadProtyle",id:r.id},{type:"reloadFiletree"}]:[])},tI=async({client:e,permMgr:t,rawArgs:o})=>{const n=ui.parse(o);if(Me(n.path),ke(n.path)){const a=await Pn(e,"");return g({success:!0,path:Q,virtual:!0,cleared:!0,updatedAt:a.agentSiyuanMemoryUpdatedAt||null})}const r=await pe(e,t,n.path,"delete");if(r.type!=="document")throw new Error(`fs.rm requires a document path, got "${n.path}".`);const s=await q(t,r.notebook,"delete");return s||(await Wo(e,r.id),T(e,g({success:!0,path:r.canonicalPath}),[{type:"reloadProtyle",id:r.id},{type:"reloadFiletree"}]))},oI=async({client:e,permMgr:t,rawArgs:o})=>{const n=li.parse(o);if(ke(n.from)||ke(n.to)||sn(n.from)||sn(n.to))throw new Error(`${Q} is a fixed virtual file and cannot be moved or renamed.`);const r=await pe(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 jv(e,t,n.to),a=await q(t,r.notebook,"write");if(a)return a;const i=await q(t,s.notebook,"write");if(i)return i;try{const c=await pe(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 gu(e,[r.id],s.parentId??s.notebook),r.name!==s.title&&await mu(e,r.id,s.title),T(e,g({success:!0,path:r.canonicalPath,movedTo:s.canonicalPath}),[{type:"reloadProtyle",id:r.id},{type:"reloadFiletree"}])},nI=async({client:e,permMgr:t,rawArgs:o})=>{const n=di.parse(o);Me(n.path);const r=Jv(n.query,n.regex,n.caseSensitive);if(ke(n.path)){const k=await bo(e),v=as(k.content,r),E=n.page??1,C=n.pageSize??50,$=Math.max(1,Math.ceil(v.length/C)),I=Math.min(E,$),A=(I-1)*C;return ct(v.slice(A,A+C),{total:v.length,page:I,pageSize:C,pageCount:$,hasNextPage:I<$},{path:Q,virtual:!0,updatedAt:k.updatedAt||null,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}const s=await pe(e,t,n.path,"read");if(s.type!=="root"){const k=await q(t,s.notebook,"read");if(k)return k}const a=await Gv(e,t,s),i=s.type==="root"?as((await bo(e)).content,r):[];for(const k of a){const v=Ht(await yt(e,k.id)),E=typeof v.content=="string"?v.content:"",C=typeof v.hPath=="string"?v.hPath:`/${k.id}`,$=`/${k.notebookName}${C}`;E.split(/\r?\n/).forEach((I,A)=>{r(I)&&i.push({path:$,line:A+1,text:I.length>300?`${I.slice(0,297)}...`:I})})}const c=new Set,u=i.filter(k=>{const v=`${k.path}\0${k.line}\0${k.text}`;return c.has(v)?!1:(c.add(v),!0)}),l=n.page??1,d=n.pageSize??50,f=Math.max(1,Math.ceil(u.length/d)),h=Math.min(l,f),m=(h-1)*d;return ct(u.slice(m,m+d),{total:u.length,page:h,pageSize:d,pageCount:f,hasNextPage:h<f},{path:s.canonicalPath,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})},rI={ls:Wv,tree:Kv,read:Qv,write:Xv,replace:eI,rm:tI,mv:oI,search:nI},sI=[w("ls",ri,"List direct child documents using human-readable paths."),w("tree",si,"List a recursive document tree using human-readable paths."),w("read",ai,"Read a document as plain Markdown by human-readable path."),w("write",ii,"Create a document or replace an existing document body when overwrite=true."),w("replace",ci,"Apply exact old/new text replacement edits inside one Markdown document."),w("rm",ui,"Delete a document by human-readable path."),w("mv",li,"Move or rename a document by human-readable paths."),w("search",di,"Search Markdown lines under a human-readable path.")],Ju=ae({name:"fs",description:"📂 Simplified filesystem-style document operations.",variants:sI,actionSchema:ig,aggregateOptions:{guidance:Fs,actionHints:Gs},handlers:rI});function aI(e){return Ju.listTools(e)}async function iI(e,t,o,n){return Ju.callTool(e,t,o,n)}const cI="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyEvents.json",Wu="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyStats.json";function jt(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function uI(e){if(!e)return{totalCalls:0,balance:0,updatedAt:0};try{const t=JSON.parse(e),o=jt(t.totalCalls),n=t.balance===void 0?o:jt(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 Ut(e){try{return uI(await e.readFile(Wu))}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function Ku(e,t){const o={totalCalls:jt(t.totalCalls),balance:jt(t.balance),updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:Date.now(),...t.lastAction?{lastAction:t.lastAction}:{}};return await e.writeFile(Wu,JSON.stringify(o)),o}async function lI(e,t){const o=await Ut(e);try{return await Ku(e,{totalCalls:o.totalCalls+1,balance:o.balance+1,updatedAt:Date.now(),lastAction:t})}catch{return o}}async function dI(e,t,o){const n=await Ut(e),r=jt(t);if(n.balance<r)throw new Error(`Insufficient mascot balance. Need ${r}, have ${n.balance}.`);return Ku(e,{totalCalls:n.totalCalls,balance:n.balance-r,updatedAt:Date.now(),lastAction:o})}async function is(e,t){try{const o=JSON.stringify({...t,seq:Date.now(),ts:Date.now()});await e.writeFile(cI,o)}catch{}}const Eo=[{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:"🧀"}];Eo[0];Eo[1];function pI(e){return Eo.find(t=>t.id===e)??null}const fI=[w("get_balance",Bi,"Get the mascot balance. Every successful MCP tool call earns 1 coin."),w("shop",ji,"List the mascot shop inventory."),w("buy",Ui,"Buy one item from the mascot shop.")],Qu=ae({name:"mascot",description:"🐾 Grouped mascot balance and care operations. Every successful MCP tool call earns 1 coin for the mascot.",variants:fI,actionSchema:hg,aggregateOptions:{guidance:Vs,actionHints:sa},handlers:{get_balance:async({client:e,rawArgs:t})=>{Bi.parse(t);const o=await Ut(e);return g({action:"get_balance",balance:o.balance,totalEarned:o.totalCalls})},shop:async({rawArgs:e})=>(ji.parse(e),g({action:"shop",items:Eo})),buy:async({client:e,rawArgs:t})=>{const o=Ui.parse(t),n=pI(o.item_id);if(!n)throw new Error(`Unknown mascot shop item: ${o.item_id}.`);const r=await dI(e,n.cost,`buy:${n.id}`);return g({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 hI(e){return Qu.listTools(e)}async function mI(e,t,o,n){return Qu.callTool(e,t,o,n)}const Xu="notebook";function cs(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 gI(e){const t=e instanceof Error?e.message:String(e);return/initializing|kernel still initializing|notebook is currently closed/i.test(t)}async function yI(e,t,o,n){let r=0;for(;r<=o;){r+=1;try{return{children:await Po(e,t,"/"),attempts:r}}catch(s){if(r>o||!gI(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 bI(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Xu,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 kI=async({client:e,rawArgs:t})=>{pi.parse(t);const o=await Ne(e);return g(o.notebooks)},wI=async({client:e,rawArgs:t})=>{const o=fi.parse(t),n=await My(e,o.name);return o.icon&&(await yu(e,n.notebook.id,o.icon),n.notebook.icon=o.icon),T(e,g({...n.notebook,iconHint:Mn("notebook",!!o.icon)}),o.icon?[{type:"reloadIcon"}]:[{type:"reloadFiletree"}])},_I=async({client:e,permMgr:t,rawArgs:o})=>{const n=hi.parse(o),r=await q(t,n.notebook,"read");return r||(n.opened?await Uy(e,n.notebook):await qy(e,n.notebook),T(e,g({success:!0,notebook:n.notebook,opened:n.opened}),[{type:"reloadFiletree"}]))},vI=async({client:e,permMgr:t,rawArgs:o})=>{const n=mi.parse(o),r=await q(t,n.notebook,"delete");return r||(await Ly(e,n.notebook),T(e,g({success:!0,notebook:n.notebook}),[{type:"reloadFiletree"}]))},II=async({client:e,permMgr:t,rawArgs:o})=>{const n=gi.parse(o),r=await q(t,n.notebook,"write");return r||(await Zy(e,n.notebook,n.name),T(e,g({success:!0,notebook:n.notebook,name:n.name}),[{type:"reloadFiletree"}]))},DI=async({client:e,permMgr:t,rawArgs:o})=>{const n=yi.parse(o),r=await q(t,n.notebook,"read");if(r)return r;const s=await Hy(e,n.notebook);return g(s)},SI=async({client:e,permMgr:t,rawArgs:o})=>{const n=bi.parse(o),r=await q(t,n.notebook,"write");if(r)return r;const s=await Vy(e,n.notebook,n.conf);return T(e,g(s),[{type:"reloadFiletree"}])},AI=async({client:e,permMgr:t,rawArgs:o})=>{const n=ki.parse(o),r=await q(t,n.notebook,"write");return r||(await yu(e,n.notebook,n.icon),T(e,g({success:!0,notebook:n.notebook,icon:n.icon}),[{type:"reloadIcon"}]))},TI=async({client:e,permMgr:t,rawArgs:o})=>{const n=wi.parse(o);await t.reload();const s=(await Ne(e)).notebooks.map(i=>({id:i.id,name:i.name,permission:t.get(i.id)}));if(!n.notebook||n.notebook==="all")return g({notebooks:s});const a=s.find(i=>i.id===n.notebook);return a?g({notebook:a}):yo(new Error(`Notebook "${n.notebook}" not found.`),{tool:Xu,action:"get_permissions",rawArgs:o})},PI=async({client:e,permMgr:t,rawArgs:o})=>{const n=_i.parse(o);return await t.set(n.notebook,n.permission),T(e,g({success:!0,notebook:n.notebook,permission:n.permission}),[{type:"reloadFiletree"}])},EI=async({client:e,permMgr:t,rawArgs:o})=>{const n=vi.parse(o),r=2,s=150,a=await q(t,n.notebook,"read");if(a)return a;const c=(await Ne(e)).notebooks.find(f=>f.id===n.notebook);if(!c)throw cs(new Error("Notebook not found in lsNotebooks result."),n.notebook,!1,!1);const u=await yI(e,n.notebook,r,s);if(u.error){const f=cs(u.error,n.notebook,!0,!!c.closed);if(c.closed)return bI(n.notebook,f.message,u.attempts,r*s);throw f}const l=u.children??[],d=su(l,n.page??1,n.pageSize??50);return ct(d.items,d,{notebook:n.notebook})},CI={list:kI,create:wI,set_open_state:_I,remove:vI,rename:II,get_conf:DI,set_conf:SI,set_icon:AI,get_permissions:TI,set_permission:PI,get_child_docs:EI},OI=[w("list",pi,"List all notebooks in the workspace."),w("create",fi,"Create a new notebook."),w("set_open_state",hi,"Set notebook open state (open or close)."),w("remove",mi,"Remove a notebook."),w("rename",gi,"Rename a notebook."),w("get_conf",yi,"Get notebook configuration."),w("set_conf",bi,"Set notebook configuration."),w("set_icon",ki,"Set the icon for a notebook."),w("get_permissions",wi,'Get permission levels for notebooks. Omit notebook or pass "all" to return every notebook; pass a specific notebook ID to return only that notebook.'),w("set_permission",_i,"Set the permission level for a notebook."),w("get_child_docs",vi,"Get direct child documents at the notebook root. Returns a paginated { data, total, page, pageSize, pageCount, hasNextPage } payload.")],el=ae({name:"notebook",description:"📚 Grouped notebook operations.",variants:OI,actionSchema:cg,aggregateOptions:{guidance:Bs,actionHints:Js},handlers:CI});function xI(e){return el.listTools(e)}function NI(e,t,o,n){return el.callTool(e,t,o,n)}async function $I(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushMsg",n)}async function RI(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushErrMsg",n)}const zI=1,FI=12;function us(e,t,o,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(o,Math.min(n,Math.trunc(e)))}function BI(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 jI(e,t){const o=BI(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 ko(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=>ko(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,ko(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 UI(e,t,o,n,r){if(t==="get"){if(!o)throw new Error('keyPath is required when mode="get".');const i=jI(e,o);return{mode:t,keyPath:o,value:ko(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:ko(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 qI=async({client:e,rawArgs:t})=>(Kc.parse(t),g(await tb(e))),MI=async({client:e,rawArgs:t})=>(Qc.parse(t),g(await ob(e))),LI=async({client:e,rawArgs:t})=>{const o=Xc.parse(t),n=await nb(e),r=o.mode??"summary",s=us(o.maxDepth,zI,0,5),a=us(o.maxItems,FI,1,100);return g(UI(n,r,o.keyPath,s,a))},ZI=async({client:e,rawArgs:t})=>{const o=eu.parse(t),n=o.level==="error"?await RI(e,o.msg,o.timeout):await $I(e,o.msg,o.timeout);return g({level:o.level,...n})},HI=async({client:e,rawArgs:t})=>(tu.parse(t),g({version:await rb(e)})),VI=async({client:e,rawArgs:t})=>{ou.parse(t);const o=await sb(e);return g({currentTime:o,iso:new Date(o).toISOString()})},YI={workspace_info:qI,network:MI,conf:LI,notify:ZI,get_version:HI,get_current_time:VI},GI=[w("workspace_info",Kc,"Get SiYuan workspace metadata. High-risk: exposes the absolute workspace path."),w("network",Qc,"Get current network proxy information."),w("conf",Xc,"Get masked system configuration with summary-first progressive reading."),w("notify",eu,"Push a notification message."),w("get_version",tu,"Get the SiYuan system version."),w("get_current_time",ou,"Get the current system time.")],tl=ae({name:"system",description:"🖥️ Grouped system and notification operations.",variants:GI,actionSchema:Dg,aggregateOptions:{guidance:Zs,actionHints:na},handlers:YI});function JI(e){return tl.listTools(e)}function WI(e,t,o,n){return tl.callTool(e,t,o,n)}async function KI(e,t={}){const o={...t,app:t.app||"siyuan-mcp-sisyphus"};return e.request("/api/tag/getTag",o)}async function QI(e,t,o){return e.request("/api/tag/renameTag",{oldLabel:t,newLabel:o})}async function XI(e,t){return e.request("/api/tag/removeTag",{label:t})}const eD=[w("list",Gc,"List tags in the workspace."),w("rename",Jc,"Rename a tag."),w("remove",Wc,"Remove a tag.")],ol=ae({name:"tag",description:"🏷️ Grouped tag operations.",variants:eD,actionSchema:Ig,aggregateOptions:{guidance:Ls,actionHints:oa},handlers:{list:async({client:e,rawArgs:t})=>{const o=Gc.parse(t),n=o.query??o.keyword;if(n&&n.trim().length>0){const s=await wy(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.tags)?a.tags:[];return g({...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 KI(e,o);return g(r)},rename:async({client:e,rawArgs:t})=>{const o=Jc.parse(t);return await QI(e,o.oldLabel,o.newLabel),T(e,g({success:!0,oldLabel:o.oldLabel,newLabel:o.newLabel}),[{type:"reloadTag"}])},remove:async({client:e,rawArgs:t})=>{const o=Wc.parse(t);return await XI(e,o.label),T(e,g({success:!0,label:o.label}),[{type:"reloadTag"}])}}}),tD=ol.listTools,oD=ol.callTool,qt={fs:{category:"fs",listTools:aI,callTool:iI},notebook:{category:"notebook",listTools:xI,callTool:NI},document:{category:"document",listTools:y_,callTool:b_},block:{category:"block",listTools:Nw,callTool:$w},av:{category:"av",listTools:tk,callTool:ok},file:{category:"file",listTools:q_,callTool:M_},feedback:{category:"feedback",listTools:tv,callTool:ov},search:{category:"search",listTools:tw,callTool:ow},tag:{category:"tag",listTools:tD,callTool:oD},system:{category:"system",listTools:JI,callTool:WI},flashcard:{category:"flashcard",listTools:$v,callTool:Rv},mascot:{category:"mascot",listTools:hI,callTool:mI}};function nr(e){return Pe.includes(e)?e:null}const nD="approx_context_v1";function rD(e){return Math.ceil(Math.max(0,e)/4)}function cn(e){const t=typeof e=="string"?e:"";return{chars:t.length,approxTokens:rD(t.length)}}function sD(e){const t=(e??[]).map(o=>o.text??"").join("");return cn(t)}const vt="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl",nl="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl.1",aD=2*1024*1024,ls=2e4;function ds(e){const t=typeof e=="string"?e:"";return t.length<=ls?{text:t,truncated:!1}:{text:t.slice(0,ls),truncated:!0}}function rl(e){return e==="cli"||e==="http"?e:"stdio"}function iD(){return{cli:0,stdio:0,http:0}}function cD(e){return typeof Buffer<"u"?Buffer.byteLength(e,"utf8"):new TextEncoder().encode(e).length}function ps(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:rl(s.transport)})}catch{}}return t}async function uD(e,t){const o={...t,seq:Date.now(),ts:Date.now()},n=JSON.stringify(o);try{const r=await e.readFile(vt);if(r){const s=`${r}
165
- ${n}`;cD(s)>aD?(await e.writeFile(nl,r),await e.writeFile(vt,n)):await e.writeFile(vt,s);return}}catch{}try{await e.writeFile(vt,n)}catch{}}function lD(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 dD(e){if(e){if(e.includes("McpError")){const t=e.match(/McpError\s*\(?([^:)]{1,40})\)?/);return t?`McpError:${t[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":"UnknownError"}}const pD=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","created","updated","removed","overwritten","folded","partial","reason","warning"]),fD=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"]),hD=new Set(["markdown","content","blockPath","rootID","root_id","parentID","parent_id","box","ial","sort","sortMode","icon","newFlashcardCount","dueFlashcardCount","flashcardCount"]);function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mD(e,t){const o=e.content[0];return{...e,content:[{...o??{type:"text"},type:"text",text:JSON.stringify(t,null,2)}]}}function gD(e){return e.action==="help"||e.category==="system"&&e.action==="conf"}function yD(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 bD(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:rr(e)}function rr(e){const t={};for(const[o,n]of Object.entries(e))hD.has(o)||(t[o]=Co(n));return t}function kD(e){return e.plainContent!==void 0||e.excerpt!==void 0||e.rootID!==void 0||e.root_id!==void 0||e.blockPath!==void 0}function Co(e){return Array.isArray(e)?e.map(t=>pt(t)?kD(t)?bD(t):rr(t):Co(t)):pt(e)?al(e):e}function sl(e){if(pt(e)&&"partialFailure"in e)return{partialFailure:e.partialFailure}}function wD(e,t){const o={};for(const r of pD)e[r]!==void 0&&(o[r]=e[r]);const n=sl(e.uiRefresh);return n!==void 0&&(o.uiRefresh=n),Object.keys(o).length>0?o:e}function al(e,t){if(pt(e.error))return{error:yD(e.error)};if(e.success===!0)return wD(e);const o={};for(const[n,r]of Object.entries(e)){if(n==="uiRefresh"){const s=sl(r);s!==void 0&&(o.uiRefresh=s);continue}fD.has(n)||(o[n]=Co(r))}return o}function _D(e,t){if(gD(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=>pt(s)?rr(s):Co(s)):pt(n)?al(n):n;return mD(e,r)}const vD="telemetryConfig",il=`/data/storage/petal/siyuan-plugins-mcp-sisyphus/${vD}`;function cl(){return{enabled:!1,lastReportAt:0,reportIntervalHours:24}}function ul(e){const t=cl();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 ID(e){try{const t=await e.readFile(il);if(t)return ul(JSON.parse(t))}catch{}return cl()}async function fs(e,t){const o=ul(t);try{await e.writeFile(il,JSON.stringify(o))}catch{}return o}async function DD(e){const t=[];try{const o=await e.readFile(vt);o&&t.push(...ps(o))}catch{}try{const o=await e.readFile(nl);o&&t.push(...ps(o))}catch{}return t}async function SD(e,t){const n=(await DD(e)).filter(d=>d.ts>=t);if(n.length===0)return null;const r=n.length,s=n.filter(d=>d.status==="error").length,a=n.reduce((d,f)=>d+(f.durationMs||0),0),i=new Map,c=new Array(24).fill(0),u=iD();for(const d of n){const f=`${d.tool}/${d.action}`,h=i.get(f);h?(h.count+=1,h.errorCount+=d.status==="error"?1:0,h.totalDuration+=d.durationMs||0):i.set(f,{tool:d.tool,action:d.action,count:1,errorCount:d.status==="error"?1:0,totalDuration:d.durationMs||0});const m=new Date(d.ts).getHours();m>=0&&m<24&&(c[m]+=1),u[rl(d.transport)]+=1}const l=Array.from(i.values()).map(d=>({tool:d.tool,action:d.action,count:d.count,errorCount:d.errorCount,avgDurationMs:d.count>0?Math.round(d.totalDuration/d.count):0})).sort((d,f)=>f.count-d.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:l,hourlyDistribution:c,transportDistribution:u},meta:{pluginVersion:process.env.SIYUAN_MCP_PLUGIN_VERSION,nodeVersion:process.version,platform:process.platform}}}async function hs(e){const t=await ID(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 SD(e,t.lastReportAt||Date.now()-o);if(!r){await fs(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 fs(e,{...t,lastReportAt:Date.now()})}catch{}}function ms(e,t,o,n,r,s,a,i){const c=cn(n),u=i?sD(i):cn(a),l=i?i.map(m=>m.text??"").join(""):a??"",d=ds(n),f=ds(l),h=o&&typeof o=="object"?Object.keys(o).filter(m=>m!=="action"):[];return{tool:e,action:t,status:r,durationMs:s,errorCode:r==="error"?dD(a):void 0,paramKeys:h,resultSizeHint:lD(i),transport:er(),requestChars:c.chars,responseChars:u.chars,requestApproxTokens:c.approxTokens,responseApproxTokens:u.approxTokens,totalApproxTokens:c.approxTokens+u.approxTokens,tokenMode:nD,requestText:d.text,responseText:f.text,requestTextTruncated:d.truncated,responseTextTruncated:f.truncated}}function AD(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 TD(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 gs(e,t){const o=uD(e,t).catch(()=>{});er()==="cli"&&await o}async function PD(e,t){var m;const{client:o,category:n,name:r,action:s,args:a}=e,i=e.requestText,c=Date.now(),u=n==="mascot"?await Ut(o):await lI(o,`${r}/${s}`);await is(o,{tool:r,action:s,status:"running",totalCalls:u.totalCalls,balance:u.balance});let l;try{l=await t()}catch(k){const v=Date.now()-c,E=k instanceof Error?k.message:String(k);throw await gs(o,ms(r,s,a,i,"error",v,E)),hs(o).catch(()=>{}),k}e.slimResponses?l=_D(l,{category:n,action:s}):e.slimResponses===void 0&&(l=TD(l,e.includeUiRefreshMetadata));const d=n==="mascot"?await Ut(o):u,f=n==="mascot"?AD(l):{};await is(o,{tool:r,action:s,status:l.isError?"error":"success",totalCalls:d.totalCalls,balance:d.balance,...f});const h=Date.now()-c;return await gs(o,ms(r,s,a,i,l.isError?"error":"success",h,(m=l.content[0])==null?void 0:m.text,l.content)),hs(o).catch(()=>{}),l}function ED(e,t){const o=CD(t),n=new Map,r=new Set,s=new Set;for(const[f,h]of Object.entries(o)){if(f==="action"||f==="topic")continue;const m=bs(f);for(const v of m)n.set(v.toLowerCase(),f);if(wo(h)==="boolean")for(const v of m)r.add(v);else for(const v of m)s.add(v)}const a=[];for(const f of Object.keys(o))if(!(f==="action"||f==="topic"))for(const h of bs(f))a.push(`${h}-json`);const i=_s(e,{boolean:[...r],string:[...s,...a]}),c=ND(e),u={},l=[],d={};for(const[f,h]of Object.entries(i))if(f!=="_"&&f.endsWith("-json")){const m=f.slice(0,-5),k=n.get(m.toLowerCase());if(!k){l.push(`Unknown flag --${f}.`);continue}if(typeof h!="string"||h.length===0)continue;try{d[k]=JSON.parse(h)}catch(v){throw new Error(`--${f} must be valid JSON: ${v instanceof Error?v.message:String(v)}`)}}for(const[f,h]of Object.entries(i)){if(f==="_"||f.endsWith("-json"))continue;const m=n.get(f.toLowerCase());if(!m){l.push(`Unknown flag --${f}; ignored.`);continue}if(m in d||m in u)continue;const k=o[m];wo(k)==="boolean"&&h===!1&&!c.has(f.toLowerCase())||(u[m]=OD(m,h,k))}return i._.length>0&&l.push(`Extra positional arguments ignored: ${i._.join(" ")}`),{args:{...u,...d},warnings:l}}function CD(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 OD(e,t,o){const n=wo(o);if(n==="array")return Array.isArray(t)?t.map(r=>ys(r,o.items)):typeof t=="string"?t.split(",").map(r=>ys(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(`--${Mo(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(`--${Mo(e)} expects JSON for an object field. Use --${Mo(e)}-json '{"..."}'.`)}return t}return typeof t=="string"?t:String(t)}function ys(e,t){if(!t)return e;const o=wo(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 wo(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 bs(e){const t=ll(e),o=new Set([e]);return t.length===0?[...o]:(o.add(t.join("-")),o.add(t.join("_")),o.add(xD(t)),[...o])}function ll(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 xD(e){return e.length===0?"":e[0]+e.slice(1).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Mo(e){const t=ll(e);return t.length>0?t.join("-"):e.toLowerCase()}function ND(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 $D{constructor(t={}){me(this,"baseUrl");me(this,"timeout");me(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 l=await fetch(t,{...o,signal:i.signal});if(clearTimeout(c),!l.ok){if(l.status>=400&&l.status<500&&l.status!==429)throw new Error(`HTTP error: ${l.status} ${l.statusText}`);if(await l.arrayBuffer().catch(()=>{}),s=new Error(`HTTP error: ${l.status} ${l.statusText}`),a<3)continue;throw s}return l}catch(l){if(clearTimeout(c),l instanceof Error&&l.name==="AbortError"?s=new Error(`Request timeout after ${this.timeout}ms`):s=l instanceof Error?l:new Error(String(l)),a>=3)throw s}const u=300*(a+1);await new Promise(l=>setTimeout(l,u))}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 RD=["none","r","rw","rwd"],ks={none:"none",readonly:"r",write:"rw"},ro="/data/storage/petal/siyuan-plugins-mcp-sisyphus/notebookPermissions",zD=process.env.SIYUAN_MCP_DEBUG_PERMISSIONS==="1";function Qt(...e){zD&&console.error("[MCP]",...e)}function dl(e){return typeof e=="string"&&RD.includes(e)}function FD(e){return dl(e)?e:typeof e=="string"&&e in ks?ks[e]:"none"}function BD(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,FD(o)]))}class jD{constructor(t){me(this,"permissions",{});me(this,"client",null);me(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(ro)}catch(n){throw Qt("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,Qt("Permissions not found in API, using empty state");return}let o;try{o=JSON.parse(t)}catch(n){throw Qt("Failed to parse permissions JSON from API:",n),new Error(`[Permissions] Permissions file at ${ro} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}this.permissions=BD(o),this.loaded=!0,Qt("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(ro,t),this.loaded=!0}get(t){const o=this.permissions[t];return dl(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"}}const Vt="siyuan-plugins-mcp-sisyphus",pl=`/data/plugins/${Vt}/plugin.json`;function Lo(){return[`This CLI requires the SiYuan plugin "${Vt}".`,"Install and enable the plugin in SiYuan first, then open the plugin settings panel and configure permissions before retrying."].join(" ")}function UD(e){const t=e?` Details: ${e}`:"";return[`The required SiYuan plugin "${Vt}" 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 ws(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 qD(e){try{return JSON.parse(e)}catch(t){throw new Error(`Found "${Vt}" at ${pl}, but its plugin.json is invalid JSON: ${t instanceof Error?t.message:String(t)}`)}}async function MD(e){let t="";try{t=await e.readFile(pl)}catch(n){throw ws(n)?n:new Error(Lo())}if(!t.trim())throw new Error(Lo());if(qD(t).name!==Vt)throw new Error(Lo());try{await e.readFile(ro)}catch(n){throw ws(n)?n:new Error(UD(n instanceof Error?n.message:String(n)))}}async function sr(e,t={}){const o=ft(e.configPath),n=Pl(o,{cliUrl:e.url,cliToken:e.token,profile:e.profile});El(n);const r=new $D({baseUrl:n.apiUrl});n.token&&r.setToken(n.token),await MD(r);const s=await LD(r),a=new jD(r);return t.loadPermissions!==!1&&await a.load(),{client:r,toolConfig:s,permMgr:a}}async function LD(e){try{const t=await e.readFile(io);if(!t)return xt();const o=JSON.parse(t);return hd(o,{source:`SiYuan API file "${io}"`}),Tn(o)}catch{return xt()}}async function ZD(e){const{tool:t,action:o,rest:n}=e;if(!t||!o)throw new Error("runDispatch requires both tool and action.");const r=nr(t);if(!r)throw XD(t);const s=zs(r,o);if(!vo[r].includes(s)&&s!=="help")throw eS(r,s);const i=process.env.SIYUAN_MCP_TRANSPORT;process.env.SIYUAN_MCP_TRANSPORT="cli";try{const{client:c,toolConfig:u,permMgr:l}=await sr(e);if(!u[r].enabled)return Ct({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const d=qt[r],f=QD(r,u),h=HD(r,s,n),{args:m,warnings:k}=ED(h,f);if(k.length>0&&e.debug)for(const A of k)process.stderr.write(`[warn] ${A}
166
- `);const v={action:s,...m},E=[P,t,o,...n].join(" ").trim(),C=async A=>{const B=A===void 0?v:{...v,page:A};return PD({client:c,category:r,name:t,action:s,args:B,requestText:E,slimResponses:u.debug.slimResponses&&!e.debug},()=>d.callTool(c,B,u[r],l))},$=await C(),I=Ct($,{json:e.json,debug:e.debug});return I!==0||e.json||await GD($,C,{json:e.json,debug:e.debug}),I}catch(c){return Se(c,{debug:e.debug}),1}finally{i===void 0?delete process.env.SIYUAN_MCP_TRANSPORT:process.env.SIYUAN_MCP_TRANSPORT=i}}function HD(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 wt(o,"path",n[0]);if(t==="search")return wt(wt(o,"path",n[0]),"query",n[1]);if(t==="mv")return wt(wt(o,"from",n[0]),"to",n[1])}return o}function wt(e,t,o){return!o||VD(e,t)?e:[`--${t}`,o,...YD(e,o)]}function VD(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 YD(e,t){let o=!1;return e.filter(n=>!o&&n===t&&!n.startsWith("-")?(o=!0,!1):!0)}async function GD(e,t,o){var i,c;if(!JD())return;let n=dr(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(`
167
- Paging: Enter/n next, p previous, q quit › `);const u=await KD();if(s.write(`
168
- `),u===""||u==="\x1B"||u.toLowerCase()==="q")return;const l=WD(u,n.page,n.pageCount);if(l===null)continue;const d=await t(l);Ct(d,o);const f=dr(d);if(!f)return;n=f}}finally{(c=r.setRawMode)==null||c.call(r,a),r.pause()}}function JD(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function WD(e,t,o){const n=e.toLowerCase();return(e==="\r"||e===`
169
- `||n==="n")&&t<o?t+1:n==="p"&&t>1?t-1:null}function KD(){return new Promise(e=>{process.stdin.once("data",t=>{e(String(t))})})}function QD(e,t){const n=qt[e].listTools(t[e])[0];if(!n)throw new Error(`Tool "${e}" has no aggregated descriptor — this is a bug.`);return n.inputSchema}function XD(e){const t=Pe.join(", ");return new Error(`Unknown tool "${e}". Available tools: ${t}. Try "${P} list".`)}function eS(e,t){const o=vo[e].join(", ");return new Error(`Unknown action "${t}" for tool "${e}". Available actions: ${o}. Try "${P} help ${e}".`)}class tS{constructor(){me(this,"rl");me(this,"closed",!1);this.rl=yl.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 oS(e){const t=Ds(e??ln()),o=ft(e),n=je(o),r=new tS;try{Te("SiYuan CLI setup"),ne("Path",t),ne("Tip","Press Enter to accept the default shown in brackets."),process.stdout.write(`
170
- `);const s=await r.ask("Profile name [default]: ")||"default";if(n.profiles[s]){const d=(await r.ask(`Profile "${s}" already exists. Overwrite it? [y/N] `)).toLowerCase();if(d!=="y"&&d!=="yes"){ee("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(),l=Ss(o,s,{apiUrl:a,token:i},{makeCurrent:!c||c==="y"||c==="yes"});dn(l,e),process.stdout.write(`
171
- `),ee("success","Config written."),fe([{key:"path",value:t},{key:"profile",value:s},{key:"current",value:l.currentProfile},{key:"apiUrl",value:a},{key:"token",value:i?"configured":"empty"}]),process.stdout.write(`
172
- `),ne("Next","Run `siyuan-sisyphus notebook list` to verify the connection, or `siyuan-sisyphus config list` to inspect all profiles.")}finally{r.close()}}async function nS(e){const t=process.stdout,o=e.tool?nr(e.tool):null,{toolConfig:n}=await sr(e,{loadPermissions:!1});if(!o){e.tool&&Se(`Unknown tool "${e.tool}". Showing all tools instead.`);const r=Pe.filter(s=>qt[s].listTools(n[s]).length>0);return Te("SiYuan tools",t),ie(r.map(s=>{const a=Nt(n[s]),i=a.filter(u=>Ot(s,u)==="basic").length,c=a.length-i;return`${s} — ${a.length} actions (${i} common, ${c} advanced)`}),t),G("Next Step",t),ne("Tip",`Run \`${P} list <tool>\` to see a tool’s actions.`,t),0}return qt[o].listTools(n[o]).length===0?(Se(`Tool "${o}" is disabled.`),1):(Te(`${o} actions`,t),ie(Nt(n[o]).map(r=>{const s=Ot(o,r)==="basic"?"common":"advanced",a=ot(o,r)?" · confirmation required":"";return`${r} — ${s}${a}`}),t),G("Next Step",t),ne("Tip",`Run \`${P} help ${o} <action>\` for fields and examples.`,t),0)}async function rS(e){const t=e.tool;if(!t)return Se(`Missing tool. Usage: ${P} help <tool> [action]`),2;const o=nr(t);if(!o)return Se(`Unknown tool "${t}". Available: ${Pe.join(", ")}.`),2;try{const{client:n,toolConfig:r,permMgr:s}=await sr(e,{loadPermissions:!1});if(!r[o].enabled)return Ct({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const a=qt[o],i={action:"help"};e.action&&(i.topic=e.action);const c=await a.callTool(n,i,r[o],s);return Ct(c,{json:e.json,debug:e.debug})}catch(n){return Se(n,{debug:e.debug}),1}}const It="siyuan-sisyphus";function sS(e){switch(e.skillAction){case"list":return aS(e);case"read":return iS(e);case"install":return cS(e);case"uninstall":return uS(e);default:throw new Error("Unknown skill action.")}}function aS(e){const t=Oo();if(e.json)return process.stdout.write(JSON.stringify({skills:t})+`
173
- `),0;Te("Bundled SiYuan Sisyphus skills");for(const o of t)process.stdout.write(` ${o.name}
174
- `);return ne("Next","Run `siyuan-sisyphus skill install` to install them."),0}function iS(e){const t=dS(e.skillName);return process.stdout.write(t),t.endsWith(`
163
+ `.trim())}async function Yk(e,t,o,n){const r=await Ty(e,t,o,n);if(jk(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([Vk(e,t,o,n),Nu(e,t,o,n)]);return{backlinks:s,backmentions:a,fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}async function Gk(e,t,o,n){const r=await Py(e,t,o,n);return r&&typeof r=="object"&&Array.isArray(r.backmentions)?{backmentions:r.backmentions}:{backmentions:await Nu(e,t,o,n),fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}const Jk="search";function Wk(e){return typeof e=="string"&&e.trim().length>0}function Zo(e,t){return Wk(t)?t:e}function Xt(e){const t=Object.entries(e).filter(([,o])=>o!==void 0);return t.length===0?{}:{resolvedArgs:Object.fromEntries(t)}}function sr(e,t){return t?{showing:t.showing,truncated:t.truncated,hint:t.hint}:{showing:e,truncated:!1}}function wt(e){return Array.isArray(e)?Ok(e):[]}function Kk(e){let t=e.types?fk(e.types):e.types;return e.typeShortcodes&&e.typeShortcodes.length>0&&(t={...pk(e.typeShortcodes),...t}),t}function Qk(e){return e.parentId?Math.min((e.pageSize??32)*3,128):e.pageSize}function Xk(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 ew(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 Ho(e){const t=hk(e.methodName,e.method);return{...t!==void 0?{method:t}:{},...t!==void 0?{methodName:mk(t)}:{}}}function tw(e,t,o,n){const r=Array.isArray(e.blocks)?e.blocks:[],s=t.page??1,a=t.pageSize??32,i=Gn(r,20,`Use page/pageSize parameters to paginate. Current page: ${s}.`),c=r.length,u=typeof o.pageCount=="number"?o.pageCount:1,l=typeof e.filteredOutBlockCount=="number"?e.filteredOutBlockCount:0,d=l>0||!!t.parentId||t.hasTags!==void 0,h={total:d?c:typeof o.matchedBlockCount=="number"?o.matchedBlockCount:c,page:s,pageSize:a,pageCount:d?1:u,hasNextPage:d?!1:s<u},{blocks:m,pageCount:_,...v}=e;return Fe(i.items,h,{...v,...Be(l),...sr(c,i.meta),returnedTotal:c,returnedPageCount:1,returnedHasNextPage:!1,...o.matchedBlockCount!==void 0?{kernelMatchedBlockCount:o.matchedBlockCount}:{},...o.matchedRootCount!==void 0?{kernelMatchedRootCount:o.matchedRootCount}:{},kernelPageCount:u,kernelHasNextPage:s<u,...d?{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 ow(e,t,o){const n=Gn(e,50,"Add LIMIT and OFFSET to your SQL for pagination."),r=e.length;return g({data:n.items,total:r,totalRows:r,...sr(r,n.meta),...Be(t),...o?{resolvedArgs:o}:{}})}function nw(e,t,o,n){const r=Gn(t,20,"Use page/pageSize parameters to paginate asset content results."),s=t.length;return g({...e,assetContents:r.items,data:r.items,total:s,...sr(s,r.meta),...Be(o),...n?{resolvedArgs:n}:{}})}const rw={fulltext:async({client:e,permMgr:t,rawArgs:o})=>{const n=Hc.parse(o);if(n.parentId){const{denied:f}=await T(e,t,n.parentId,"read");if(f)return f}const r=Ho(n),s=nn(n.sortBy,n.orderBy),a=await Sy(e,{query:n.query,method:r.method,types:Kk(n),paths:n.paths,groupBy:n.groupBy,orderBy:s,page:n.page,pageSize:Qk(n)}),c=es(a,t),u={...c,blocks:wt(Array.isArray(c.blocks)?c.blocks:[])};n.parentId&&Xk(u,n.parentId),n.hasTags!==void 0&&ew(u,n.hasTags),Array.isArray(u.blocks)&&(u.blocks=await $k(e,u.blocks));const d=n.methodName!==void 0||n.sortBy!==void 0?Xt({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:Wr(s)}:{}}).resolvedArgs:void 0;return tw(u,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},d)},query_sql:async({client:e,permMgr:t,rawArgs:o})=>{const n=Vc.parse(o),r=Zo(n.stmt,n.sql);try{Zk(r??"")}catch(u){return wo(u,{tool:Jk,action:"query_sql",rawArgs:o})}const s=await yt(e,r??""),a=Array.isArray(s)?s:[],i=await ro(e,a,t),c=n.sql!==void 0?Xt({stmt:r}).resolvedArgs:void 0;return ow(i.items,i.removedCount,c)},get_backlinks:async({client:e,permMgr:t,rawArgs:o})=>{const n=Yc.parse(o),r=Zo(n.refTreeID,n.scopeRootId),s=n.mode??"both",{denied:a}=await T(e,t,n.id,"read");if(a)return a;try{const i=s!=="mentions"?await Yk(e,n.id,n.keyword,r):{},c=s!=="links"?await Gk(e,n.id,n.keyword,r):{},u={...i,...c},l=so(u,t);return g({...l,mode:s,backlinks:s!=="mentions"?wt(Array.isArray(l.backlinks)?l.backlinks:[]):[],backmentions:s!=="links"?wt(Array.isArray(l.backmentions)?l.backmentions:[]):[],...u.sourcePayloadMissing?{sourcePayloadMissing:!0}:{},...u.fallbackQuery?{fallbackQuery:u.fallbackQuery}:{},...u.resultConfidence?{resultConfidence:u.resultConfidence}:{},...n.scopeRootId!==void 0?{resolvedArgs:{refTreeID:r}}:{},...u.fallbackUsed?{warning:"SiYuan returned no backlink/backmention payload; SQL fallback results are shown."}:{}})}catch(i){if(Fk(i))return g({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:Be(1).permissionSummary});throw i}},search_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=Gc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=await Ey(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.blocks)?a.blocks:[],c=await ro(e,i,t),u=wt(c.items);return g({...a,blocks:u,data:u,total:u.length,showing:u.length,truncated:!1,...Be(c.removedCount)})},find_replace:async({client:e,permMgr:t,rawArgs:o})=>{const n=Jc.parse(o);for(const i of n.ids){const{denied:c}=await T(e,t,i,"write");if(c)return c}if(Array.isArray(n.paths))for(const i of n.paths){const c=await jt(e,i);if(!c)continue;const u=await q(t,c,"write");if(u)return u}const r=Ho(n),s=nn(n.sortBy,n.orderBy);await Cy(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 g({success:!0,replaced:!0,ids:n.ids,k:n.k,r:n.r,...n.paths?{paths:n.paths}:{},...a?{resolvedArgs:Xt({...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:Wr(s)}:{}}).resolvedArgs}:{}})},search_assets:async({client:e,rawArgs:t})=>{const o=Wc.parse(t),n=Zo(o.k,o.query)??"",r=await Oy(e,n,o.exts);return o.query===void 0?g(r):g({...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=Kc.parse(o);if(n.assetId){const d=await xy(e,n.assetId,n.query??"",n.queryMethod??0);return g(d)}const r=Ho(n),s=wk(n.sortBy,n.orderBy),a=await Ny(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:[],u=await ro(e,c,t),l=n.methodName!==void 0||n.sortBy!==void 0;return nw(i,u.items,u.removedCount,l?Xt({query:n.query,...r,...s!==void 0?{orderBy:s}:{},...s!==void 0?{sortBy:_k(s)}:{}}).resolvedArgs:void 0)},list_invalid_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=Qc.parse(o),r=await Ry(e,n.page,n.pageSize),a=es(r??{},t),i=Array.isArray(a.blocks)?a.blocks:[],c=wt(i);return g({...a,blocks:c,data:c,total:c.length,showing:c.length,truncated:!1,...Be(typeof a.filteredOutBlockCount=="number"?a.filteredOutBlockCount:0)})}},sw="search",aw=[k("fulltext",Hc,"Full-text search across all blocks."),k("query_sql",Vc,"Execute a read-only SQL query against the database."),k("get_backlinks",Yc,"Find documents/blocks that link to or mention the given block."),k("search_refs",Gc,"Search blocks that reference a given block or document."),k("find_replace",Jc,"Find and replace text in documents or blocks."),k("search_assets",Wc,"Search asset files by filename."),k("fulltext_asset_content",Kc,"Full-text search indexed asset contents."),k("list_invalid_refs",Qc,"List invalid block references.")],Ru=ae({name:sw,description:"🔍 Grouped search and query operations.",variants:aw,actionSchema:Tg,aggregateOptions:{guidance:sa,actionHints:aa,guidanceInlineLimit:5},handlers:rw});function iw(e){return Ru.listTools(e)}async function cw(e,t,o,n){return Ru.callTool(e,t,o,n)}function uw(e){return typeof e!="string"?!1:e!=="d"}function lw(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 dw(e,t){const o=Ht(),n=new Map;let r=!1;for(const s of t){s&&typeof s=="object"&&uw(s.type)&&(r=!0);const a=await Vt(e,s,o);if(!(a!=null&&a.documentId)||!a.notebook||!a.path)continue;let i=n.get(a.documentId);if(!i){let c,u;try{const l=await Ue(e,a.documentId);c=l.name,u=l.hPath}catch{c=void 0,u=void 0}i={documentId:a.documentId,notebook:a.notebook,path:a.path,...u?{hPath:u}:{},...c?{name:c}:{},updatedBlockCount:0,sampleBlocks:[]},n.set(a.documentId,i)}i.updatedBlockCount+=1,i.sampleBlocks.length<3&&i.sampleBlocks.push(lw(s))}return{documents:[...n.values()],containsLowLevelBlocks:r}}function ar(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;return le({action:t.action,...r?{id:r}:{},...s?{parentID:s}:{},...a?{previousID:a}:{},...i?{nextID:i}:{},dataType:t.dataType})}function pw(e,t){const o={success:!0,id:t.id,dataType:t.dataType};if(t.dataType==="markdown"&&(o.markdown=rr(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."),g(o)}function fw(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}}function hw(e,t){return e.map(o=>({...o,nextID:o.nextID??t.nextID,previousID:o.previousID??t.previousID,parentID:o.parentID??t.parentID}))}function mw(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 gw(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 yw=async({client:e,permMgr:t,rawArgs:o})=>{const n=Xi.parse(o);if(n.blocks){const i=hw(n.blocks,{parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),c=new Set;for(const[d,f]of i.entries()){const h=f.nextID||f.previousID||f.parentID;if(!h)return fw(d);const{denied:m,context:_}=await T(e,t,h,"write");if(m)return m;c.add(_.documentId)}const u=await wy(e,i),l=mw(u);return l.length===0?gw(i.length,u):P(e,g({success:!0,action:"insert",count:i.length,createdBlockIDs:l,transactions:u}),[...c].map(d=>({type:"reloadProtyle",id:d})))}const r=n.nextID||n.previousID||n.parentID;let s;if(r){const{denied:i,context:c}=await T(e,t,r,"write");if(i)return i;s=c.documentId}const a=await ly(e,n.dataType,n.data,n.nextID,n.previousID,n.parentID);return P(e,ar(a,{action:"insert",dataType:n.dataType,parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),s?[{type:"reloadProtyle",id:s}]:[])},bw=async({client:e,permMgr:t,rawArgs:o})=>{const n=ec.parse(o),{denied:r,context:s}=await T(e,t,n.parentID,"write");if(r)return r;const a=await dy(e,n.dataType,n.data,n.parentID);return P(e,ar(a,{action:"prepend",dataType:n.dataType,parentID:n.parentID}),[{type:"reloadProtyle",id:s.documentId}])},kw=async({client:e,permMgr:t,rawArgs:o})=>{const n=tc.parse(o),{denied:r,context:s}=await T(e,t,n.parentID,"write");if(r)return r;const a=await fu(e,n.dataType,n.data,n.parentID);return P(e,ar(a,{action:"append",dataType:n.dataType,parentID:n.parentID}),[{type:"reloadProtyle",id:s.documentId}])},ww=async({client:e,permMgr:t,rawArgs:o})=>{const n=oc.parse(o);if(n.items){const i=new Set;for(const u of n.items){const{denied:l,context:d}=await T(e,t,u.id,"write");if(l)return l;i.add(d.documentId)}const c=await _y(e,n.items);return P(e,g({success:!0,action:"update",count:n.items.length,transactions:c}),[...i].map(u=>({type:"reloadProtyle",id:u})))}const{denied:r,context:s}=await T(e,t,n.id,"write");if(r)return r;const a=await hu(e,n.dataType,n.data,n.id);return P(e,pw(a,{id:n.id,dataType:n.dataType,data:n.data}),[{type:"reloadProtyle",id:s.documentId}])},_w=async({client:e,permMgr:t,rawArgs:o})=>{const n=nc.parse(o),{denied:r,context:s}=await T(e,t,n.id,"write");if(r)return r;const a=Pu(await gu(e,n.id)),i=typeof a.kramdown=="string"?a.kramdown:"",c=Array.isArray(n.edit)?n.edit:[n.edit],{content:u,summary:l}=rn(i,c,"block.replace"),d=u!==i;return d&&await hu(e,"markdown",u,n.id),P(e,g({success:!0,action:"replace",id:n.id,changed:d,editsApplied:l.length,replacements:l}),d?[{type:"reloadProtyle",id:s.documentId}]:[])},vw=async({client:e,permMgr:t,rawArgs:o})=>{const n=rc.parse(o),{denied:r,context:s}=await T(e,t,n.id,"delete");return r||(await mu(e,n.id),P(e,g({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId}]))},Iw=async({client:e,permMgr:t,rawArgs:o})=>{const n=sc.parse(o),r=await T(e,t,n.id,"write");if(r.denied)return r.denied;if(n.parentID){const i=await T(e,t,n.parentID,"write");if(i.denied)return i.denied}if(n.previousID){const i=await T(e,t,n.previousID,"write");if(i.denied)return i.denied}const s=await py(e,n.id,n.previousID,n.parentID),a=[{type:"reloadProtyle",id:r.context.documentId}];if(n.parentID){const i=await T(e,t,n.parentID,"write");if(i.denied)return i.denied;a.push({type:"reloadProtyle",id:i.context.documentId})}if(n.previousID){const i=await T(e,t,n.previousID,"write");if(i.denied)return i.denied;a.push({type:"reloadProtyle",id:i.context.documentId})}return P(e,le({id:n.id,...n.previousID?{previousID:n.previousID}:{},...n.parentID?{parentID:n.parentID}:{}},s),a)},Dw=async({client:e,permMgr:t,rawArgs:o})=>{const n=ac.parse(o),{denied:r,context:s}=await T(e,t,n.id,"write");return r||(n.folded?await fy(e,n.id):await hy(e,n.id),P(e,g({success:!0,id:n.id,folded:n.folded}),[{type:"reloadProtyle",id:s.documentId}]))},Sw=async({client:e,permMgr:t,rawArgs:o})=>{const n=ic.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=Pu(await gu(e,n.id));return g(s)},Aw=async({client:e,permMgr:t,rawArgs:o})=>{const n=cc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=await Qn(e,n.id),a=Array.isArray(s)?s:[],i=lu(a,n.page??1,n.pageSize??50);return Fe(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.'}:{}})},Tw=async({client:e,permMgr:t,rawArgs:o})=>{const n=uc.parse(o),r=await T(e,t,n.fromID,"write");if(r.denied)return r.denied;const s=await T(e,t,n.toID,"write");return s.denied?s.denied:(await my(e,n.fromID,n.toID,n.refIDs),P(e,g({success:!0,fromID:n.fromID,toID:n.toID}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId}]))},Pw=async({client:e,permMgr:t,rawArgs:o})=>{const n=lc.parse(o),{denied:r,context:s}=await T(e,t,n.id,"write");return r||(await de(e,[{doOperations:[{action:"setAttrs",id:n.id,data:JSON.stringify(n.attrs)}],undoOperations:[]}]),P(e,g({success:!0,id:n.id,attrs:n.attrs}),[{type:"reloadProtyle",id:s.documentId}]))},Ew=async({client:e,permMgr:t,rawArgs:o})=>{const n=dc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=await bu(e,n.id);return g(s)},Cw=async({client:e,permMgr:t,rawArgs:o})=>{const n=pc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=await gy(e,n.id);return g(s)},Ow=async({client:e,permMgr:t,rawArgs:o})=>{const n=fc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=await yy(e,n.id,n.excludeTypes);return g(s)},xw=async({client:e,permMgr:t,rawArgs:o})=>{const n=hc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=await yu(e,n.id);return g(s)},Nw=async({client:e,permMgr:t,rawArgs:o})=>{const n=mc.parse(o),r=await by(e),s=Array.isArray(r)?r:[],a=await ro(e,s,t),i=typeof n.count=="number"?n.count:void 0,c=typeof i=="number"?a.items.slice(0,i):a.items,u=await dw(e,c);return g({documents:u.documents,documentCount:u.documents.length,count:c.length,containsLowLevelBlocks:u.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"}:{}})},Rw=async({client:e,permMgr:t,rawArgs:o})=>{const n=gc.parse(o);for(const s of n.ids){const{denied:a}=await T(e,t,s,"read");if(a)return a}const r=await ky(e,n.ids);return g(r)},$w=async({client:e,permMgr:t,rawArgs:o})=>{const n=yc.parse(o),r=await q(t,n.notebook,"write");if(r)return r;const s=n.position==="append"?await vy(e,n.notebook,n.dataType,n.data):await Iy(e,n.notebook,n.dataType,n.data);return P(e,g({success:!0,action:"add_to_daily_note",notebook:n.notebook,dataType:n.dataType,position:n.position,transactions:s}),[{type:"reloadFiletree"}])},zw=async({client:e,permMgr:t,rawArgs:o})=>{const n=bc.parse(o),r=n.ids??[n.id];for(const a of r){const{denied:i}=await T(e,t,a,"read");if(i)return i}const s=await Dy(e,r,n.refCount??!1,n.av??!1);return g(s)},Fw={insert:yw,prepend:bw,append:kw,update:ww,replace:_w,delete:vw,move:Iw,set_fold_state:Dw,get_kramdown:Sw,get_children:Aw,transfer_references:Tw,set_attrs:Pw,get_attrs:Ew,info:Cw,breadcrumb:Ow,dom:xw,recent_updated:Nw,word_count:Rw,add_to_daily_note:$w,docs_info:zw},Bw=[k("insert",Xi,"Insert one or more blocks at the specified position."),k("prepend",ec,"Insert a block at the beginning of a parent."),k("append",tc,"Insert a block at the end of a parent."),k("update",oc,"Update one or more blocks."),k("replace",nc,"Apply exact old/new text replacement edits inside one block."),k("delete",rc,"Delete a block by ID."),k("move",sc,"Move a block to a new position."),k("set_fold_state",ac,"Set the fold state of a foldable block."),k("get_kramdown",ic,"Get block content in kramdown format."),k("get_children",cc,"Get child blocks of a parent with pagination support."),k("transfer_references",uc,"Transfer block references from one block to another."),k("set_attrs",lc,"Set block attributes."),k("get_attrs",dc,"Get block attributes."),k("info",pc,"Get block position and root document metadata."),k("breadcrumb",fc,"Get the breadcrumb path for a block."),k("dom",hc,"Get rendered DOM for a block."),k("recent_updated",mc,"Get recently updated blocks."),k("word_count",gc,"Get word-count statistics for blocks."),k("add_to_daily_note",yc,"Add a block to today's daily note, creating the note if needed."),k("docs_info",bc,"Get document info for one or more documents.")],$u=ae({name:"block",description:"🧱 Grouped block operations.",variants:Bw,actionSchema:gg,aggregateOptions:{guidance:Hs,actionHints:oa,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:Fw}),jw=$u.listTools,Uw=$u.callTool;async function qw(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 bt(e,t){const o={id:t};return e.request("/api/export/exportMdContent",o)}async function Mw(e,t,o){const n={paths:t,name:o};return e.request("/api/export/exportResources",n)}async function Lw(e){return e.request("/api/asset/getUnusedAssets",{})}async function Zw(e,t){return e.request("/api/asset/getDocAssets",{id:t})}async function Hw(e,t){return e.request("/api/asset/getDocImageAssets",{id:t})}async function Vw(e,t){return e.request("/api/asset/getImageOCRText",t?{path:t}:{})}async function Yw(e){return e.request("/api/asset/removeUnusedAssets",{})}async function Gw(e,t,o){return e.request("/api/asset/renameAsset",{oldPath:t,newName:o})}async function Jw(e,t){return e.request("/api/asset/deleteAsset",{path:t})}const Vo=[120,240],Ww=["path","hpath"];function Kw(e){return e==="/"||/\.sy(?:\/|$)/.test(e)}async function zu(e,t,o){await de(e,[{doOperations:[{action:"setAttrs",id:t,data:JSON.stringify(o)}],undoOperations:[]}])}function Qw(e){return e instanceof Error&&/SiYuan API error:\s*-1\s*-\s*indexing/i.test(e.message)}async function Xw(e,t){let o;for(let r=0;r<=Vo.length;r+=1)try{return await Oo(e,t)}catch(s){if(!Qw(s)||r===Vo.length){o=s;break}o=s,await Yt(Vo[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 eo(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:{notebook:t,path:o}}}function e_(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 t_(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function o_(e){return/(?:^|\/)\d{14}-[a-z0-9]{7}\.sy$/i.test(e)}async function n_(e,t,o){const n=o==="/"?"/":o.replace(/\/+$/,"");return o_(n)?Xn(e,t,n):n}function cn(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:cn(r.children,t,o+1)}:r}):e}async function un(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=Ke(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 un(e,r.children,o)),s})):t}function r_(e,t){if(Array.isArray(e))return so({backmentions:e},t).backmentions;if(!e||typeof e!="object")return e;const o=e;return Array.isArray(o.files)?{...o,files:so({backmentions:o.files},t).backmentions}:Array.isArray(o.docs)?{...o,docs:so({backmentions:o.docs},t).backmentions}:e}async function s_(e,t,o,n){if(Array.isArray(t)){const s=await Lo(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 Lo(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 Lo(e,r.docs,o,n);return{data:{...r,docs:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}return{data:r_(t,o),permissionFilteredOutCount:0,pathFilteredOutCount:0}}const a_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Pi.parse(o);if(await t.reload(),!t.canWrite(n.notebook))return Wn(n.notebook,t.get(n.notebook),"write");const r=n.markdown??"",s=n.parentPath?await n_(e,n.notebook,n.parentPath):void 0,a=n.path??t_(s,n.title),i=await ku(e,n.notebook,a,r);return n.icon&&await zu(e,i,{icon:n.icon}),P(e,g({success:!0,notebook:n.notebook,path:a,...n.parentPath?{parentPath:n.parentPath}:{},...s&&s!==n.parentPath?{resolvedParentPath:s}:{},...n.title?{title:n.title}:{},id:i,iconHint:Jn("document",!!n.icon)}),n.icon?[{type:"reloadIcon"}]:[{type:"reloadProtyle",id:i},{type:"reloadFiletree"}])},i_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ei.parse(o),r=n.hpath??n.hPath,s=new Set(n.include??Ww),a={source:n.id?{id:n.id}:n.path?{notebook:n.notebook,path:n.path}:{notebook:n.notebook}};if(n.id){const{denied:d,context:f}=await T(e,t,n.id,"read");if(d)return d;a.id=n.id,a.notebook=f.notebook,a.path=f.path,s.has("path")&&(a.path=await Tt(e,n.id)),a.hPath=await Xw(e,n.id),s.has("docInfo")&&(a.docInfo=await Ke(e,n.id));const h=await sn(e,f.notebook);return h&&(a.notebookName=h),g(eo(a))}const i=await q(t,n.notebook,"read");if(i)return i;const c=await sn(e,n.notebook);if(n.path){if(a.notebook=n.notebook,c&&(a.notebookName=c),a.path=n.path,!Kw(n.path)){const f=await no(e,n.path,n.notebook),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 Tt(e,h)),h&&s.has("docInfo")&&(a.docInfo=await Ke(e,h)),g(eo(a))}const d=await Xn(e,n.notebook,n.path);if(a.hPath=d,s.has("id")||s.has("ids")){const f=await no(e,d??n.path,n.notebook);a.ids=f,s.has("id")&&(a.id=f[0])}return s.has("docInfo")&&typeof a.id=="string"&&(a.docInfo=await Ke(e,a.id)),g(eo(a))}const u=await no(e,r,n.notebook);a.notebook=n.notebook,c&&(a.notebookName=c),a.hPath=r,(s.has("ids")||s.has("id"))&&(a.ids=u,s.has("id")&&(a.id=u[0]));const l=u[0];if(l){const{denied:d}=await T(e,t,l,"read");if(d)return d;a.path=await Tt(e,l)}if(l&&s.has("docInfo")){const{denied:d}=await T(e,t,l,"read");if(d)return d;a.docInfo=await Ke(e,l)}return g(eo(a))},c_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ci.parse(o);if(n.id){const{denied:r,context:s}=await T(e,t,n.id,"write");return r||(await wu(e,n.id,n.title),P(e,g({success:!0,id:n.id,title:n.title}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await q(t,n.notebook,"write");if(r)return r}return await $y(e,n.notebook,n.path,n.title),P(e,g({success:!0,notebook:n.notebook,path:n.path,title:n.title}),[{type:"reloadFiletree"}])},u_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Oi.parse(o);if(n.ids){const r=[];for(const s of n.ids){const{denied:a,context:i}=await T(e,t,s,"delete");if(a)return a;r.push(i.documentId)}for(const s of n.ids)await on(e,s);return P(e,g({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 jt(e,r);if(!s)throw new Error(`Unable to resolve notebook for storage path "${r}" while checking permissions.`);const a=await q(t,s,"delete");if(a)return a}return await Ly(e,n.paths),P(e,g({success:!0,paths:n.paths,count:n.paths.length}),[{type:"reloadFiletree"}])}if(n.id){const{denied:r,context:s}=await T(e,t,n.id,"delete");return r||(await on(e,n.id),P(e,g({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await q(t,n.notebook,"delete");if(r)return r}return await zy(e,n.notebook,n.path),P(e,g({success:!0,notebook:n.notebook,path:n.path}),[{type:"reloadFiletree"}])},l_=async({client:e,permMgr:t,rawArgs:o})=>{const n=xi.parse(o);if(n.toNotebook){const r=await q(t,n.toNotebook,"write");if(r)return r}if(n.toID){const r=await ab(e,n.toID),s=await q(t,r,"write");if(s)return s}if(n.fromIDs){const r=[];for(const s of n.fromIDs){const{denied:a,context:i}=await T(e,t,s,"write");if(a)return a;r.push(i.documentId)}return await _u(e,n.fromIDs,n.toID),P(e,g({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 jt(e,r);if(!s)throw new Error(`Unable to resolve source notebook for storage path "${r}" while checking permissions.`);const a=await q(t,s,"write");if(a)return a}return await Fy(e,n.fromPaths,n.toNotebook,n.toPath),P(e,g({success:!0,fromPaths:n.fromPaths,toNotebook:n.toNotebook,toPath:n.toPath}),[{type:"reloadFiletree"}])},d_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ni.parse(o),{denied:r,context:s}=await T(e,t,n.id,"read");if(r)return r;const a=await Qn(e,s.documentId);return g(a)},p_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ri.parse(o),{denied:r,context:s}=await T(e,t,n.id,"read");if(r)return r;const a=await xo(e,s.notebook,s.path);return g(a)},f_=async({client:e,permMgr:t,rawArgs:o})=>{const n=$i.parse(o),{denied:r,context:s}=await T(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 u=n.attrs.cover;if(!u)a["title-img"]="",i.clearedCover=!0;else{const l=e_(u);a["title-img"]=l.titleImg,i.cover=l.source,i.titleImg=l.titleImg}c.push({type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"})}return await zu(e,n.id,a),P(e,g(i),c)},h_=async({client:e,permMgr:t,rawArgs:o})=>{const n=zi.parse(o),r=await q(t,n.notebook,"read");if(r)return r;const s=n.maxDepth??3,a=await et(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 u=await un(e,a.tree);return g({...a,tree:cn(u,s),maxDepth:s,depthHint:i})}const c=await un(e,a);return g({tree:cn(c,s),maxDepth:s,depthHint:i})},m_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Fi.parse(o),r=await q(t,n.notebook,"read");if(r)return r;const s=await jy(e,n.query),a=await s_(e,s,t,n.path),i=a.permissionFilteredOutCount+a.pathFilteredOutCount;return g({...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}:{}})},g_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Bi.parse(o),{denied:r,context:s}=await T(e,t,n.id,"read");if(r)return r;const a=await sn(e,s.notebook);if(n.mode==="html"){const v=await Uy(e,n.id,0,n.size);return g({id:n.id,mode:"html",notebook:s.notebook,...a?{notebookName:a}:{},...v&&typeof v=="object"?v:{content:v}})}const i=Gt(await bt(e,n.id)),c=typeof i.content=="string"?i.content:"",u=n.page??1,l=n.pageSize??8e3,d=Math.max(1,Math.ceil(c.length/l)),f=Math.min(u,d),h=(f-1)*l,m=c.slice(h,h+l),_=c.length>l;return g({id:n.id,mode:"markdown",notebook:s.notebook,...a?{notebookName:a}:{},hPath:i.hPath,content:m,..._?{truncated:!0,contentLength:c.length,showing:m.length,page:f,pageSize:l,pageCount:d,hasNextPage:f<d,hint:'Use page/pageSize to read the next markdown chunk. For structured reads, use document(action="get_child_blocks") or block(action="get_kramdown").'}:{}})},y_=async({client:e,permMgr:t,rawArgs:o})=>{const n=ji.parse(o),r=await q(t,n.notebook,"write");if(r)return r;const s=await qy(e,n.notebook,n.app);let a;try{a=await Oo(e,s.id)}catch{a=void 0}return P(e,g({success:!0,notebook:n.notebook,...s,...a?{hPath:a}:{},iconHint:Jn("document")}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}])},b_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ui.parse(o),{denied:r,context:s}=await T(e,t,n.id,"write");if(r)return r;const a=await My(e,n.id);return P(e,g({success:!0,sourceID:n.id,...a}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}])},k_=async({client:e,permMgr:t,rawArgs:o})=>{const n=qi.parse(o),r=await T(e,t,n.headingID,"write");if(r.denied)return r.denied;const s=await q(t,n.targetNotebook,"write");return s||(await Zy(e,n.headingID,n.targetNotebook,n.targetPath,n.previousPath),P(e,g({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"}]))},w_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Mi.parse(o),r=await T(e,t,n.srcID,"write");if(r.denied)return r.denied;const s=await T(e,t,n.targetID,"write");if(s.denied)return s.denied;const a=await Hy(e,n.srcID,n.targetID,n.after??!1);return P(e,g({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"}])},__={create:a_,lookup:i_,rename:c_,remove:u_,move:l_,get_child_blocks:d_,get_child_docs:p_,set_attr:f_,list_tree:h_,search_docs:m_,get_doc:g_,create_daily_note:y_,duplicate:b_,heading_to_doc:k_,doc_to_heading:w_},v_=[k("create",Pi,"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."),k("lookup",Ei,"Look up document IDs, storage paths, human-readable paths, and document metadata from one document reference."),k("rename",Ci,"Rename a document"),k("remove",Oi,"Delete a document"),k("move",xi,"Move a document to another location"),k("get_child_blocks",Ni,"Get top-level blocks of a document"),k("get_child_docs",Ri,"Get child documents"),k("set_attr",$i,"Set document metadata such as icon and cover image."),k("list_tree",zi,"Get document tree"),k("search_docs",Fi,"Search documents by title"),k("get_doc",Bi,"Get full document content"),k("create_daily_note",ji,"Create or open today's daily note"),k("duplicate",Ui,"Duplicate a document"),k("heading_to_doc",qi,"Convert a heading to a separate document"),k("doc_to_heading",Mi,"Merge a document into another as a heading")],Fu=ae({name:"document",description:"📝 Grouped document operations.",variants:v_,actionSchema:mg,aggregateOptions:{guidance:Zs,actionHints:ta,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:__});function I_(e){return Fu.listTools(e)}async function D_(e,t,o,n){return Fu.callTool(e,t,o,n)}async function S_(e,t,o){const n={id:t,path:o};return e.request("/api/template/render",n)}async function A_(e,t){const o={template:t};return e.request("/api/template/renderSprig",o)}const T_="file",ln=10;function P_(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 E_(e){return[...new Set(e.map(P_).filter(Boolean))]}function C_(e){return B.isAbsolute(e)?e:B.resolve(process.cwd(),e)}function O_(e){return B.isAbsolute(e)?e:B.resolve(process.cwd(),e)}function x_(e){return e instanceof Error&&/is not in workspace/i.test(e.message)}const N_=(e,t)=>async({client:o,rawArgs:n})=>{const r=Nc.parse(n),s=O_(r.localFilePath);if(!j.existsSync(s))throw new Error(`Local file does not exist: ${s}`);const a=j.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 g({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=B.basename(s),c=j.readFileSync(s),u=await qw(o,r.assetsDirPath,c,i);return g({...u,localFilePath:s,uploadedFileName:i,...a.size>t?{largeFileConfirmed:!0}:{}})},R_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Rc.parse(o);if(n.engine==="sprig"){const s=await A_(e,n.template);return g(s)}const{denied:r}=await T(e,t,n.id,"read");if(r)return r;try{const s=await S_(e,n.id,n.path);return g(s)}catch(s){if(x_(s))return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:T_,action:"render",message:s.message,reason:"path_not_in_workspace",workspacePathRequired:!0,hint:"The template path must point to a file inside the SiYuan workspace, not an arbitrary local path such as /tmp/... or your repo checkout."}},null,2)}],isError:!0};throw s}},$_=async({client:e,permMgr:t,rawArgs:o})=>{const n=$c.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=Gt(await bt(e,n.id));return g(s)},z_=async({client:e,rawArgs:t})=>{const o=zc.parse(t),n=E_(o.paths);if(n.length===0)throw new Error("export_resources requires at least one non-empty resource path.");let r;try{r=await Mw(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=C_(o.outputPath),a=await e.readFileBinary(r.path);return j.mkdirSync(B.dirname(s),{recursive:!0}),j.writeFileSync(s,a),g({...r,outputPath:s,bytes:a.byteLength})}return g(r)},F_=async({client:e,rawArgs:t})=>{Fc.parse(t);const o=await Lw(e);return g({assets:o,count:Array.isArray(o)?o.length:void 0})},B_=async({client:e,permMgr:t,rawArgs:o})=>{const n=Bc.parse(o),{denied:r}=await T(e,t,n.id,"read");if(r)return r;const s=n.assetType==="image"?await Hw(e,n.id):await Zw(e,n.id);return g({id:n.id,assetType:n.assetType??"all",assets:s,count:Array.isArray(s)?s.length:void 0})},j_=async({client:e,rawArgs:t})=>{const o=jc.parse(t),n=await Vw(e,o.path);return g({path:o.path??null,...n})},U_=async({client:e,rawArgs:t})=>{Uc.parse(t);const o=await Yw(e);return g({success:!0,...o&&typeof o=="object"&&!Array.isArray(o)?o:{result:o}})},q_=async({client:e,rawArgs:t})=>{const o=qc.parse(t),n=await Gw(e,o.oldPath,o.newName);return g({success:!0,oldPath:o.oldPath,newName:o.newName,...n})},M_=async({client:e,rawArgs:t})=>{const o=Mc.parse(t),n=await Jw(e,o.path);return g({success:!0,path:o.path,...n&&typeof n=="object"&&!Array.isArray(n)?n:{}})},L_=async({client:e,rawArgs:t})=>{var x;const o=Lc.parse(t),n=await bt(e,o.id),r=typeof n.content=="string"?n.content:"",a=((x=(typeof n.hPath=="string"?n.hPath:"").split("/").filter(Boolean).pop())==null?void 0:x.replace(/\.sy$/,""))||o.id,i=o.id.slice(-7),c=`${a}-${i}`,u=process.env.USERPROFILE||process.env.HOME||"",l=o.outputDir?B.resolve(o.outputDir):B.join(u,"siyuan-extracted"),d=B.join(l,c),f=B.join(d,"assets");j.existsSync(l)&&j.rmSync(l,{recursive:!0,force:!0}),j.mkdirSync(f,{recursive:!0});const h=B.join(d,`${a}.md`);j.writeFileSync(h,r,"utf-8");const m=[...r.matchAll(/\]\(assets\/([^\s)"']+)(?:\s+"[^"]*")?\)/g)],_=[`${a}.md`];let v=0,A=0;for(const C of m){const I=C[1],D=B.join(f,I);try{j.mkdirSync(B.dirname(D),{recursive:!0});const $=await e.readFileBinary(`data/assets/${I}`);j.writeFileSync(D,$),_.push(`assets/${I}`),v++}catch{A++}}return g({extractedDir:d,docMdFile:`${a}.md`,extractedAssetCount:v,skippedAssetCount:A,structure:_})};function Z_(e,t){return{upload_asset:N_(e,t),render:R_,export_md:$_,export_resources:z_,list_unused_assets:F_,get_doc_assets:B_,get_image_ocr_text:j_,remove_unused_assets:U_,rename_asset:q_,delete_asset:M_,extract_doc:L_}}const H_=[k("upload_asset",Nc,"Read a local file and upload it to the specified assets directory."),k("render",Rc,"Render a SiYuan workspace template (.action{.title}) or an inline Sprig template ({{...}})."),k("export_md",$c,"Export document content as Markdown."),k("export_resources",zc,"Export resources as a ZIP archive."),k("list_unused_assets",Fc,"List unused asset files."),k("get_doc_assets",Bc,"List assets directly referenced by the current document tree. Use extract_doc for complete document asset inspection."),k("get_image_ocr_text",jc,"Get stored OCR text for an image asset."),k("remove_unused_assets",Uc,"Remove all unused asset files."),k("rename_asset",qc,"Rename an asset file."),k("delete_asset",Mc,"Delete an asset file."),k("extract_doc",Lc,"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 Bu(e,t){return ae({name:"file",description:"📁 Grouped file and asset operations.",variants:H_,actionSchema:bg,aggregateOptions:{guidance:Ys,actionHints:ra},handlers:Z_(e,t)})}const V_=Bu(ln,ln*1024*1024);function Y_(e){return V_.listTools(e)}async function G_(e,t,o,n){const r="uploadLargeFileThresholdMB"in o&&typeof o.uploadLargeFileThresholdMB=="number"?o.uploadLargeFileThresholdMB:ln,s=r*1024*1024;return Bu(r,s).callTool(e,t,o,n)}function ir(){const e=(process.env.SIYUAN_MCP_TRANSPORT??"").toLowerCase();return e==="cli"||e==="http"?e:"stdio"}const ju="Uq2KRv7t",J_="https://f-api.wps.cn/ksform/api/v3/campaign",W_=`https://f.wps.cn/ksform/w/write/${ju}`,K_="0.4.9",He={description:"v5nhl6",impact:"bbev5x",suggestion:"6wxpgj",source:"8dcnsl",agent:"fu27dr",pluginVersion:"yl3by8"},Q_={settings:{value:"用户"},cli:{value:"CLI"},stdio:{value:"STDIO"},http:{value:"HTTP"}},Uu="无";function ao(e){return(e==null?void 0:e.trim())||Uu}function Ye(e){return{type:"input",strValue:e,isManualInput:!0}}function X_(e){const t=Q_[e];return Ye(t.value)}function ev(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 tv(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=ir();return o==="cli"||o==="http"?o:"stdio"}function ov(e){const t=ao(e);return t!==Uu?t:"0.4.9".trim()?"0.4.9".trim():K_}function nv(e,t){var l,d,f,h;const o=(h=(f=(d=(l=t==null?void 0:t.setting)==null?void 0:l.baseSetting)==null?void 0:d.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=ao(e.impact),s=ao(e.suggestion),a=ao(e.agent),i=ov(e.pluginVersion),c=tv(e.source),u=ev(t,"来源",He.source);return{answerJson:{answers:{[He.description]:Ye(n),[He.impact]:Ye(r),[He.suggestion]:Ye(s),[u]:X_(c),[He.agent]:Ye(a),[He.pluginVersion]:Ye(i)},answersProperty:{commitInfo:{optionId:o.id,optionText:""}},consumeTime:2},phoneNumber:"",editVersion:t.editVersion??1,token:t.token,channel:c}}function os(e){return{Accept:"application/json, text/plain, */*",Origin:"https://f.wps.cn",Referer:W_,"User-Agent":"siyuan-plugin-mcp-sisyphus feedback",...e}}async function ns(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 rs(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 rv(e,t=fetch){var l,d,f,h,m,_;const o=e.description.trim();if(!o)throw new Error("Feedback description is required.");const n=`${J_}/${ju}`,r=await t(n,{method:"GET",headers:os()});if(!r.ok)throw await rs(r,"Feedback metadata request");const s=await ns(r,"Feedback metadata request");if(s.code!==0||!s.data)throw new Error(`Feedback metadata request failed: ${s.result||s.code}`);if((d=(l=s.data.setting)==null?void 0:l.baseSetting)!=null&&d.checkLogin)throw new Error("Feedback form currently requires WPS login.");const a=`sisyphus${Math.random().toString(36).slice(2)}`,i=nv({...e,description:o},s.data),c=await t(n,{method:"POST",headers:os({"Content-Type":"application/json",Cookie:`csrf=${a}`}),body:JSON.stringify({...i,csrfmiddlewaretoken:a})});if(!c.ok)throw await rs(c,"Feedback submit");const u=await ns(c,"Feedback submit");if(u.code!==0)throw new Error(`Feedback submit failed: ${u.result||u.code}`);return{success:!0,aid:(f=u.data)==null?void 0:f.aid,answerShareId:(m=(h=u.data)==null?void 0:h.answerShare)==null?void 0:m.asid,createdTs:(_=u.data)==null?void 0:_.createdTs}}const sv="feedback",av=[k("submit",Vi,"Submit plain-text GitHub Issue-style feedback to the developer.")],qu=ae({name:sv,description:"💬 Submit plain-text GitHub Issue-style feedback, suggestions, or experience reports to the plugin developer.",variants:av,actionSchema:_g,aggregateOptions:{guidance:Qs,actionHints:da},handlers:{submit:async({rawArgs:e})=>{const t=Vi.parse(e),o=await rv({description:t.description,impact:t.impact,suggestion:t.suggestion,agent:t.agent,source:t.source});return g({action:"submit",...o})}}});function iv(e){return qu.listTools(e)}async function cv(e,t,o,n){return qu.callTool(e,t,o,n)}async function Mu(e){return e.request("/api/riff/getRiffDecks",{})}async function ss(e,t,o){return e.request("/api/riff/getRiffDueCards",{deckID:t??"",...o!==void 0?{reviewedCards:o}:{}})}async function uv(e,t,o){return e.request("/api/riff/getNotebookRiffDueCards",{notebook:t,...o!==void 0?{reviewedCards:o}:{}})}async function lv(e,t,o){return e.request("/api/riff/getTreeRiffDueCards",{rootID:t,...o!==void 0?{reviewedCards:o}:{}})}async function dv(e,t,o,n,r){return e.request("/api/riff/reviewRiffCard",{deckID:t,cardID:o,rating:n,...r!==void 0?{reviewedCards:r}:{}})}async function pv(e,t,o){return e.request("/api/riff/skipReviewRiffCard",{deckID:t,cardID:o})}async function fv(e,t,o){return e.request("/api/riff/addRiffCards",{deckID:t,blockIDs:o})}async function hv(e,t,o){return e.request("/api/riff/removeRiffCards",{deckID:t,blockIDs:o})}async function as(e,t,o,n){return e.request("/api/riff/getRiffCards",{id:t,page:o,...n!==void 0?{pageSize:n}:{}})}async function mv(e,t){return e.request("/api/riff/getRiffCardsByBlockIDs",{blockIDs:t})}const Se="20230218211946-2kw8jgx",is="custom-riff-decks",gv="Built-in Deck",yv=5,bv=300,cs=6,kv=300;function wv(e){return typeof e=="string"?["new","0"].includes(e.toLowerCase()):e===0}function _v(e){return typeof e=="string"?["old","1","review"].includes(e.toLowerCase()):e===1}function vv(e,t){return t==="due"?e:t==="new"?e.filter(o=>wv(o.state)):e.filter(o=>_v(o.state))}function Lu(e){return e===""?Se:e}function Iv(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Dv(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 Zu(e,t){const o=await bu(e,t);return o&&typeof o=="object"?o:{}}async function Sv(e,t){for(const o of t)if((await Zu(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 Hu(e,t,o){if(t===Se)return;const n=await Mu(e);if(!Array.isArray(n)||!n.some(r=>Dv(r)===t))throw new Error(`flashcard/${o} requires an existing deckID. Deck "${t}" was not found.`)}async function Av(e,t,o,n){for(const r of t){const s=await Zu(e,r);if(!Iv(s[is]).includes(o))throw new Error(`flashcard/${n} did not persist a valid deck binding for block "${r}". Expected ${is} to include "${o}".`)}}function Tv(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:[]}function Pv(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 us(e){return!e||typeof e!="object"?!1:typeof e.riffCardID=="string"&&e.riffCardID.length>0?!0:!!e.riffCard}async function Vu(e,t,o,n){const r=new Set(t);for(let s=0;s<cs;s+=1){const a=await mv(e,t),i=new Map;for(const u of Tv(a)){const l=Pv(u);l&&i.set(l,u)}if([...r].every(u=>{const l=i.get(u);return o==="present"?us(l):!us(l)}))return;s<cs-1&&await Yt(kv)}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 Yu(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:Array.isArray(e==null?void 0:e.cards)?e.cards:[]}function Ev(e){return(!e.type||e.type==="")&&typeof e.content=="string"&&e.content.includes("不存在符合条件的内容块")}function Cv(e){return e.length>0&&e.some(Ev)}async function Ov(e,t,o,n){let r=await as(e,t,o,n);for(let s=1;s<yv;s+=1){if(!Cv(Yu(r)))return r;await Yt(bv),r=await as(e,t,o,n)}return r}const xv=async({client:e,rawArgs:t})=>{const o=Yi.parse(t),r=(o.scope==="all"?await ss(e,"",o.reviewedCards):o.scope==="deck"?await ss(e,o.deckID,o.reviewedCards):o.scope==="notebook"?await uv(e,o.notebook,o.reviewedCards):await lv(e,o.rootID,o.reviewedCards))??{};return g({...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:vv(Array.isArray(r.cards)?r.cards:[],o.filter)})},Nv=async({client:e,rawArgs:t})=>{Gi.parse(t);const o=await Mu(e),n=Array.isArray(o)?[...o]:[];return n.some(s=>{if(!s||typeof s!="object")return!1;const a=s;return a.id===Se||a.deckID===Se})||n.unshift({id:Se,deckID:Se,name:gv,builtin:!0}),g({action:"get_decks",decks:n})},Rv=async({client:e,rawArgs:t})=>{const o=Qi.parse(t),n=await Ov(e,o.deckID,o.page??1,o.pageSize);return g({action:"get_cards",deckID:o.deckID,page:o.page??1,...o.pageSize!==void 0?{pageSize:o.pageSize}:{},cards:Yu(n),total:n==null?void 0:n.total,pageCount:n==null?void 0:n.pageCount})},$v=async({client:e,rawArgs:t})=>{const o=Ji.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 pv(e,o.deckID,o.cardID);return g({action:"review_card",skip:!0,deckID:o.deckID,cardID:o.cardID,result:r})}const n=await dv(e,o.deckID,o.cardID,o.rating,o.reviewedCards);return g({action:"review_card",deckID:o.deckID,cardID:o.cardID,rating:o.rating,...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},result:n})},zv=async({client:e,rawArgs:t})=>{const o=Wi.parse(t),n=Lu(o.deckID);await Sv(e,o.blockIDs),await Hu(e,n,"create_card");const r=o.mode??"full",s=await fv(e,n,o.blockIDs);return await Av(e,o.blockIDs,n,"create_card"),n===Se&&await Vu(e,o.blockIDs,"present","create_card"),g({action:"create_card",mode:r,deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:s})},Fv=async({client:e,rawArgs:t})=>{const o=Ki.parse(t),n=Lu(o.deckID);await Hu(e,n,"remove_card");const r=await hv(e,n,o.blockIDs);return n===Se&&await Vu(e,o.blockIDs,"absent","remove_card"),g({action:"remove_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})},Bv={list_cards:xv,get_decks:Nv,get_cards:Rv,review_card:$v,create_card:zv,remove_card:Fv},jv=[k("list_cards",Yi,"List due flashcards and optionally filter to new/old cards."),k("get_decks",Gi,"Get flashcard deck definitions."),k("get_cards",Qi,"List all cards in a deck with pagination (not limited to due cards)."),k("review_card",Ji,"Submit a review result or skip one flashcard."),k("create_card",Wi,"Turn existing blocks into flashcards or attach existing blocks to a deck."),k("remove_card",Ki,"Remove existing blocks from a flashcard deck.")],Gu=ae({name:"flashcard",description:"🃏 Grouped flashcard review and deck operations.",variants:jv,actionSchema:kg,aggregateOptions:{guidance:Ws,actionHints:ua},handlers:Bv}),Uv=Gu.listTools,qv=Gu.callTool;function cr(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 Mv(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function ls(e){return e.split("/").filter(Boolean).at(-1)??""}function ds(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Pt(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function Lv(e,t,o){return o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t)}async function Ju(e){return(await Re(e)).notebooks.map(o=>({id:o.id,name:o.name,closed:o.closed}))}async function dn(e,t,o){let n;try{n=await no(e,o,t.id)}catch{return null}const r=n[0];if(!r)return null;const s=await Tt(e,r),a=await Oo(e,r).catch(()=>o),i=cr(a),c=ls(i)||Mv(ls(s.path))||r;return{type:"document",id:r,notebook:s.notebook||t.id,notebookName:t.name,hPath:i,storagePath:s.path,canonicalPath:Pt(t.name,i),name:c}}function Zv(e){return e.map(t=>t.canonicalPath).join(", ")}function De(e,t){const o=new Error(t);return Object.assign(o,{code:e}),o}async function pe(e,t,o,n="read"){const r=cr(o);if(r==="/")return{type:"root",canonicalPath:"/"};await t.reload();const s=await Ju(e),a=r.split("/").filter(Boolean),i=a[0],c=s.find(l=>l.name===i);if(c){const l=a.length===1?"/":`/${a.slice(1).join("/")}`;if(l==="/")return{type:"notebook",notebook:c.id,notebookName:c.name,hPath:"/",storagePath:"/",canonicalPath:Pt(c.name,"/")};const d=await dn(e,c,l);if(!d)throw De("not_found",`No document found at "${r}".`);return d}const u=[];for(const l of s)if(Lv(t,l.id,n))try{const d=await dn(e,l,r);d&&u.push(d)}catch{}if(u.length===1)return u[0];throw u.length>1?De("ambiguous_path",`Ambiguous fs path "${r}". Candidates: ${Zv(u)}.`):De("not_found",`No document found at "${r}". Use /<notebook name>/<document path> for an unambiguous path.`)}async function Wu(e,t,o){const n=cr(o);if(n==="/")throw De("invalid_path",'Cannot create a document at "/". Use /<notebook name>/<title>.');const r=n.split("/").filter(Boolean),s=r.at(-1);if(!s)throw De("invalid_path",`Cannot create a document at "${n}".`);await t.reload();const i=(await Ju(e)).find(d=>d.name===r[0]);if(i){const d=r.slice(1,-1),f=d.length===0?"/":`/${d.join("/")}`;let h="/",m;if(f!=="/"){const v=await dn(e,i,f);if(!v)throw De("not_found",`Parent document not found at "${Pt(i.name,f)}".`);h=v.storagePath,m=v.id}const _=ds(f,s);return{notebook:i.id,notebookName:i.name,title:s,parentHPath:f,parentStoragePath:h,parentId:m,hPath:_,canonicalPath:Pt(i.name,_)}}if(r.length===1)throw De("invalid_path","Root-level create must use /<notebook name>/<title>.");const c=`/${r.slice(0,-1).join("/")}`,u=await pe(e,t,c,"write");if(u.type!=="document")throw De("invalid_path",`Parent path "${c}" must resolve to a document folder.`);const l=ds(u.hPath,s);return{notebook:u.notebook,notebookName:u.notebookName,title:s,parentHPath:u.hPath,parentStoragePath:u.storagePath,parentId:u.id,hPath:l,canonicalPath:Pt(u.notebookName,l)}}async function Hv(e,t,o){return Wu(e,t,o)}function je(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function Ut(e){if(e)return e.split("/").filter(Boolean).at(-1)}function Ku(e,t){return`${e==="/"?"":e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`}function Qu(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 No=[K,ye];function fe(e){const t=Qu(e);return No.find(o=>t===o)??null}function _o(e){const t=Qu(e);return No.find(o=>t.startsWith(`${o}/`))??null}function Ze(e){const t=_o(e);if(t)throw new Error(`${t} is a virtual file and has no children.`)}function qt(e){if((fe(e)??_o(e))===ye)throw new Error(`${ye} is a read-only virtual file. Edit user rules in the plugin settings.`)}function Vv(e){return{name:e.slice(1),path:e,children:0,virtual:!0}}function Yv(e){return{name:e.slice(1),path:e,children:[],virtual:!0}}function Gv(e,t){return t==="/"?`/${e}`:`/${e}${t}`}function Jv(e,t){const o=je(t.name)??je(Ut(t.path))??t.path;return{name:o,path:Ku(e,o),children:t.subFileCount??t.count??0}}async function ur(e,t){return await t.reload(),(await Re(e)).notebooks.filter(n=>t.canRead(n.id))}async function Wv(e,t){return t.type==="root"?[]:(await xo(e,t.notebook,t.storagePath)).map(n=>Jv(t.canonicalPath,n))}function Kv(e,t){const o=je(typeof e.name=="string"?e.name:void 0)??je(Ut(typeof e.hPath=="string"?e.hPath:void 0))??je(Ut(typeof e.path=="string"?e.path:void 0))??(typeof e.id=="string"?e.id:"Untitled");return{name:o,path:Ku(t,o)}}async function pn(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:{},u=Kv(c,o);let l=u.name,d=u.path;const f=typeof c.id=="string"?c.id:void 0;if(f)try{let _=a.get(f);_||(_=Oo(e,f),a.set(f,_));const v=await _,A=je(Ut(v));A&&(l=A,d=Gv(n,v))}catch{}const h=Array.isArray(c.children)?c.children:[],m={name:l,path:d};return s>=r?m.children=h.length:m.children=await pn(e,h,m.path,n,r,s+1,a),m})):[]}function Et(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.tree)?e.tree:[]}function io(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(...io(n.children))}return t}function Yo(e,t=1,o=8e3){const n=Math.max(1,Math.ceil(e.length/o)),r=Math.min(t,n),s=(r-1)*o,a=e.slice(s,s+o);return{content:a,truncated:e.length>o,contentLength:e.length,showing:a.length,page:r,pageSize:o,pageCount:n,hasNextPage:r<n}}function Qv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xv(e){const t=je(Ut(e));return typeof t=="string"&&t.length>0?t:void 0}function eI(e){let t=e.content;const o=Xv(e.hPath);if(t.startsWith(`---
164
+ `)){const n=t.match(/^---\n[\s\S]*?\n---\n*/);n&&(t=t.slice(n[0].length))}if(o){const n=new RegExp(`^# ${Qv(o)}\\s*\\n+`);t=t.replace(n,"")}return t}async function Xu(e,t,o){const n=await Qn(e,t);for(const r of n)typeof r.id=="string"&&await mu(e,r.id);o.trim().length>0&&await fu(e,"markdown",o,t)}async function tI(e,t,o){if(o.type==="document"){const s=Et(await et(e,o.notebook,o.storagePath));return[...new Set([o.id,...io(s)])].map(a=>({id:a,notebookName:o.notebookName}))}if(o.type==="notebook"){const s=Et(await et(e,o.notebook,"/"));return[...new Set(io(s))].map(a=>({id:a,notebookName:o.notebookName}))}const n=await ur(e,t),r=[];for(const s of n){const a=Et(await et(e,s.id,"/"));r.push(...[...new Set(io(a))].map(i=>({id:i,notebookName:s.name})))}return r}function oI(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 to(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 vo(e){const t=await Rn(e);return{content:t.agentSiyuanMemoryText??"",updatedAt:t.agentSiyuanMemoryUpdatedAt??""}}async function fn(e){return{content:(await Rn(e)).userRulesText??""}}const nI=async({client:e,permMgr:t,rawArgs:o})=>{const n=ui.parse(o);Ze(n.path);const r=fe(n.path);if(r)throw new Error(`${r} is a virtual file and has no children.`);const s=await pe(e,t,n.path,"read");if(s.type==="root"){const i=await ur(e,t),c=No.map(u=>Vv(u));for(const u of i){let l=0;try{l=(await xo(e,u.id,"/")).length}catch{l=0}c.push({name:u.name,path:`/${u.name}`,children:l})}return g({path:"/",items:c})}const a=await q(t,s.notebook,"read");return a||g({path:s.canonicalPath,items:await Wv(e,s)})},rI=async({client:e,permMgr:t,rawArgs:o})=>{const n=li.parse(o);Ze(n.path);const r=fe(n.path);if(r)return g({path:r,tree:[],virtual:!0,maxDepth:n.maxDepth??3});const s=await pe(e,t,n.path,"read"),a=n.maxDepth??3;if(s.type==="root"){const u=await ur(e,t),l=No.map(d=>Yv(d));for(const d of u){const f=await et(e,d.id,"/");l.push({name:d.name,path:`/${d.name}`,children:await pn(e,Et(f),`/${d.name}`,d.name,a)})}return g({path:"/",tree:l,maxDepth:a})}const i=await q(t,s.notebook,"read");if(i)return i;const c=await et(e,s.notebook,s.storagePath);return g({path:s.canonicalPath,tree:await pn(e,Et(c),s.canonicalPath,s.notebookName,a),maxDepth:a})},sI=async({client:e,permMgr:t,rawArgs:o})=>{const n=di.parse(o);Ze(n.path);const r=fe(n.path);if(r===K){const l=await vo(e),d=Yo(l.content,n.page,n.pageSize);return g({path:K,virtual:!0,updatedAt:l.updatedAt||null,content:d.content,...d.truncated?{truncated:!0,contentLength:d.contentLength,showing:d.showing,page:d.page,pageSize:d.pageSize,pageCount:d.pageCount,hasNextPage:d.hasNextPage}:{}})}if(r===ye){const l=await fn(e),d=Yo(l.content,n.page,n.pageSize);return g({path:ye,virtual:!0,content:d.content,...d.truncated?{truncated:!0,contentLength:d.contentLength,showing:d.showing,page:d.page,pageSize:d.pageSize,pageCount:d.pageCount,hasNextPage:d.hasNextPage}:{}})}const s=await pe(e,t,n.path,"read");if(s.type!=="document")throw new Error(`fs.read requires a document path, got "${n.path}".`);const a=await q(t,s.notebook,"read");if(a)return a;const i=Gt(await bt(e,s.id)),c=typeof i.content=="string"?i.content:"",u=Yo(c,n.page,n.pageSize);return g({path:s.canonicalPath,content:u.content,...u.truncated?{truncated:!0,contentLength:u.contentLength,showing:u.showing,page:u.page,pageSize:u.pageSize,pageCount:u.pageCount,hasNextPage:u.hasNextPage}:{}})},aI=async({client:e,permMgr:t,rawArgs:o})=>{const n=pi.parse(o);if(qt(n.path),Ze(n.path),fe(n.path)===K){const c=await $n(e,n.markdown);return g({success:!0,path:K,virtual:!0,overwritten:!0,updatedAt:c.agentSiyuanMemoryUpdatedAt||null})}const s=await Wu(e,t,n.path),a=await q(t,s.notebook,"write");if(a)return a;let i=null;try{const c=await pe(e,t,s.canonicalPath,"write");i=c.type==="document"?c:null}catch{i=null}if(!i){const c=await ku(e,s.notebook,s.hPath,n.markdown);return P(e,g({success:!0,path:s.canonicalPath,created:!0}),[{type:"reloadProtyle",id:c},{type:"reloadFiletree"}])}if(!n.overwrite)throw new Error(`Document already exists at "${i.canonicalPath}". Pass overwrite=true to replace its body.`);return await Xu(e,i.id,n.markdown),P(e,g({success:!0,path:i.canonicalPath,overwritten:!0}),[{type:"reloadProtyle",id:i.id},{type:"reloadFiletree"}])},iI=async({client:e,permMgr:t,rawArgs:o})=>{const n=fi.parse(o);if(qt(n.path),Ze(n.path),fe(n.path)===K){const h=await vo(e),m=h.content,_=Array.isArray(n.edit)?n.edit:[n.edit],{content:v,summary:A}=rn(m,_,"fs.replace"),x=v!==m;let C=h.updatedAt;return x&&(C=(await $n(e,v)).agentSiyuanMemoryUpdatedAt),g({success:!0,path:K,virtual:!0,changed:x,editsApplied:A.length,replacements:A,updatedAt:C||null})}const s=await pe(e,t,n.path,"write");if(s.type!=="document")throw new Error(`fs.replace requires a document path, got "${n.path}".`);const a=await q(t,s.notebook,"write");if(a)return a;const i=Gt(await bt(e,s.id)),c=eI({content:typeof i.content=="string"?i.content:"",hPath:typeof i.hPath=="string"?i.hPath:void 0}),u=Array.isArray(n.edit)?n.edit:[n.edit],{content:l,summary:d}=rn(c,u,"fs.replace"),f=l!==c;return f&&await Xu(e,s.id,l),P(e,g({success:!0,path:s.canonicalPath,changed:f,editsApplied:d.length,replacements:d}),f?[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}]:[])},cI=async({client:e,permMgr:t,rawArgs:o})=>{const n=hi.parse(o);if(qt(n.path),Ze(n.path),fe(n.path)===K){const i=await $n(e,"");return g({success:!0,path:K,virtual:!0,cleared:!0,updatedAt:i.agentSiyuanMemoryUpdatedAt||null})}const s=await pe(e,t,n.path,"delete");if(s.type!=="document")throw new Error(`fs.rm requires a document path, got "${n.path}".`);const a=await q(t,s.notebook,"delete");return a||(await on(e,s.id),P(e,g({success:!0,path:s.canonicalPath}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}]))},uI=async({client:e,permMgr:t,rawArgs:o})=>{const n=mi.parse(o);if(qt(n.from),qt(n.to),fe(n.from)===K||fe(n.to)===K||_o(n.from)===K||_o(n.to)===K)throw new Error(`${K} is a fixed virtual file and cannot be moved or renamed.`);const r=await pe(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 Hv(e,t,n.to),a=await q(t,r.notebook,"write");if(a)return a;const i=await q(t,s.notebook,"write");if(i)return i;try{const c=await pe(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 _u(e,[r.id],s.parentId??s.notebook),r.name!==s.title&&await wu(e,r.id,s.title),P(e,g({success:!0,path:r.canonicalPath,movedTo:s.canonicalPath}),[{type:"reloadProtyle",id:r.id},{type:"reloadFiletree"}])},lI=async({client:e,permMgr:t,rawArgs:o})=>{const n=gi.parse(o);Ze(n.path);const r=oI(n.query,n.regex,n.caseSensitive),s=fe(n.path);if(s===K){const v=await vo(e),A=to(v.content,r,K),x=n.page??1,C=n.pageSize??50,I=Math.max(1,Math.ceil(A.length/C)),D=Math.min(x,I),$=(D-1)*C;return Fe(A.slice($,$+C),{total:A.length,page:D,pageSize:C,pageCount:I,hasNextPage:D<I},{path:K,virtual:!0,updatedAt:v.updatedAt||null,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}if(s===ye){const v=await fn(e),A=to(v.content,r,ye),x=n.page??1,C=n.pageSize??50,I=Math.max(1,Math.ceil(A.length/C)),D=Math.min(x,I),$=(D-1)*C;return Fe(A.slice($,$+C),{total:A.length,page:D,pageSize:C,pageCount:I,hasNextPage:D<I},{path:ye,virtual:!0,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})}const a=await pe(e,t,n.path,"read");if(a.type!=="root"){const v=await q(t,a.notebook,"read");if(v)return v}const i=await tI(e,t,a),c=[];a.type==="root"&&(c.push(...to((await vo(e)).content,r,K)),c.push(...to((await fn(e)).content,r,ye)));for(const v of i){const A=Gt(await bt(e,v.id)),x=typeof A.content=="string"?A.content:"",C=typeof A.hPath=="string"?A.hPath:`/${v.id}`,I=`/${v.notebookName}${C}`;x.split(/\r?\n/).forEach((D,$)=>{r(D)&&c.push({path:I,line:$+1,text:D.length>300?`${D.slice(0,297)}...`:D})})}const u=new Set,l=c.filter(v=>{const A=`${v.path}\0${v.line}\0${v.text}`;return u.has(A)?!1:(u.add(A),!0)}),d=n.page??1,f=n.pageSize??50,h=Math.max(1,Math.ceil(l.length/f)),m=Math.min(d,h),_=(m-1)*f;return Fe(l.slice(_,_+f),{total:l.length,page:m,pageSize:f,pageCount:h,hasNextPage:m<h},{path:a.canonicalPath,query:n.query,regex:n.regex??!1,caseSensitive:n.caseSensitive??!1})},dI={ls:nI,tree:rI,read:sI,write:aI,replace:iI,rm:cI,mv:uI,search:lI},pI=[k("ls",ui,"List direct child documents using human-readable paths."),k("tree",li,"List a recursive document tree using human-readable paths."),k("read",di,"Read a document as plain Markdown by human-readable path."),k("write",pi,"Create a document or replace an existing document body when overwrite=true."),k("replace",fi,"Apply exact old/new text replacement edits inside one Markdown document."),k("rm",hi,"Delete a document by human-readable path."),k("mv",mi,"Move or rename a document by human-readable paths."),k("search",gi,"Search Markdown lines under a human-readable path.")],el=ae({name:"fs",description:"📂 Simplified filesystem-style document operations.",variants:pI,actionSchema:fg,aggregateOptions:{guidance:Ms,actionHints:Xs},handlers:dI});function fI(e){return el.listTools(e)}async function hI(e,t,o,n){return el.callTool(e,t,o,n)}const mI="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyEvents.json",tl="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyStats.json";function Mt(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function gI(e){if(!e)return{totalCalls:0,balance:0,updatedAt:0};try{const t=JSON.parse(e),o=Mt(t.totalCalls),n=t.balance===void 0?o:Mt(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 Lt(e){try{return gI(await e.readFile(tl))}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function ol(e,t){const o={totalCalls:Mt(t.totalCalls),balance:Mt(t.balance),updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:Date.now(),...t.lastAction?{lastAction:t.lastAction}:{}};return await e.writeFile(tl,JSON.stringify(o)),o}async function yI(e,t){const o=await Lt(e);try{return await ol(e,{totalCalls:o.totalCalls+1,balance:o.balance+1,updatedAt:Date.now(),lastAction:t})}catch{return o}}async function bI(e,t,o){const n=await Lt(e),r=Mt(t);if(n.balance<r)throw new Error(`Insufficient mascot balance. Need ${r}, have ${n.balance}.`);return ol(e,{totalCalls:n.totalCalls,balance:n.balance-r,updatedAt:Date.now(),lastAction:o})}async function ps(e,t){try{const o=JSON.stringify({...t,seq:Date.now(),ts:Date.now()});await e.writeFile(mI,o)}catch{}}const Ro=[{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:"🧀"}];Ro[0];Ro[1];function kI(e){return Ro.find(t=>t.id===e)??null}const wI=[k("get_balance",Li,"Get the mascot balance. Every successful MCP tool call earns 1 coin."),k("shop",Zi,"List the mascot shop inventory."),k("buy",Hi,"Buy one item from the mascot shop.")],nl=ae({name:"mascot",description:"🐾 Grouped mascot balance and care operations. Every successful MCP tool call earns 1 coin for the mascot.",variants:wI,actionSchema:wg,aggregateOptions:{guidance:Ks,actionHints:la},handlers:{get_balance:async({client:e,rawArgs:t})=>{Li.parse(t);const o=await Lt(e);return g({action:"get_balance",balance:o.balance,totalEarned:o.totalCalls})},shop:async({rawArgs:e})=>(Zi.parse(e),g({action:"shop",items:Ro})),buy:async({client:e,rawArgs:t})=>{const o=Hi.parse(t),n=kI(o.item_id);if(!n)throw new Error(`Unknown mascot shop item: ${o.item_id}.`);const r=await bI(e,n.cost,`buy:${n.id}`);return g({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 _I(e){return nl.listTools(e)}async function vI(e,t,o,n){return nl.callTool(e,t,o,n)}const rl="notebook";function fs(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 II(e){const t=e instanceof Error?e.message:String(e);return/initializing|kernel still initializing|notebook is currently closed/i.test(t)}async function DI(e,t,o,n){let r=0;for(;r<=o;){r+=1;try{return{children:await xo(e,t,"/"),attempts:r}}catch(s){if(r>o||!II(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 SI(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:rl,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 AI=async({client:e,rawArgs:t})=>{yi.parse(t);const o=await Re(e);return g(o.notebooks)},TI=async({client:e,rawArgs:t})=>{const o=bi.parse(t),n=await Gy(e,o.name);return o.icon&&(await vu(e,n.notebook.id,o.icon),n.notebook.icon=o.icon),P(e,g({...n.notebook,iconHint:Jn("notebook",!!o.icon)}),o.icon?[{type:"reloadIcon"}]:[{type:"reloadFiletree"}])},PI=async({client:e,permMgr:t,rawArgs:o})=>{const n=ki.parse(o),r=await q(t,n.notebook,"read");return r||(n.opened?await Vy(e,n.notebook):await Yy(e,n.notebook),P(e,g({success:!0,notebook:n.notebook,opened:n.opened}),[{type:"reloadFiletree"}]))},EI=async({client:e,permMgr:t,rawArgs:o})=>{const n=wi.parse(o),r=await q(t,n.notebook,"delete");return r||(await Jy(e,n.notebook),P(e,g({success:!0,notebook:n.notebook}),[{type:"reloadFiletree"}]))},CI=async({client:e,permMgr:t,rawArgs:o})=>{const n=_i.parse(o),r=await q(t,n.notebook,"write");return r||(await Wy(e,n.notebook,n.name),P(e,g({success:!0,notebook:n.notebook,name:n.name}),[{type:"reloadFiletree"}]))},OI=async({client:e,permMgr:t,rawArgs:o})=>{const n=vi.parse(o),r=await q(t,n.notebook,"read");if(r)return r;const s=await Ky(e,n.notebook);return g(s)},xI=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ii.parse(o),r=await q(t,n.notebook,"write");if(r)return r;const s=await Qy(e,n.notebook,n.conf);return P(e,g(s),[{type:"reloadFiletree"}])},NI=async({client:e,permMgr:t,rawArgs:o})=>{const n=Di.parse(o),r=await q(t,n.notebook,"write");return r||(await vu(e,n.notebook,n.icon),P(e,g({success:!0,notebook:n.notebook,icon:n.icon}),[{type:"reloadIcon"}]))},RI=async({client:e,permMgr:t,rawArgs:o})=>{const n=Si.parse(o);await t.reload();const s=(await Re(e)).notebooks.map(i=>({id:i.id,name:i.name,permission:t.get(i.id)}));if(!n.notebook||n.notebook==="all")return g({notebooks:s});const a=s.find(i=>i.id===n.notebook);return a?g({notebook:a}):wo(new Error(`Notebook "${n.notebook}" not found.`),{tool:rl,action:"get_permissions",rawArgs:o})},$I=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ai.parse(o);return await t.set(n.notebook,n.permission),P(e,g({success:!0,notebook:n.notebook,permission:n.permission}),[{type:"reloadFiletree"}])},zI=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ti.parse(o),r=2,s=150,a=await q(t,n.notebook,"read");if(a)return a;const c=(await Re(e)).notebooks.find(f=>f.id===n.notebook);if(!c)throw fs(new Error("Notebook not found in lsNotebooks result."),n.notebook,!1,!1);const u=await DI(e,n.notebook,r,s);if(u.error){const f=fs(u.error,n.notebook,!0,!!c.closed);if(c.closed)return SI(n.notebook,f.message,u.attempts,r*s);throw f}const l=u.children??[],d=lu(l,n.page??1,n.pageSize??50);return Fe(d.items,d,{notebook:n.notebook})},FI={list:AI,create:TI,set_open_state:PI,remove:EI,rename:CI,get_conf:OI,set_conf:xI,set_icon:NI,get_permissions:RI,set_permission:$I,get_child_docs:zI},BI=[k("list",yi,"List all notebooks in the workspace."),k("create",bi,"Create a new notebook."),k("set_open_state",ki,"Set notebook open state (open or close)."),k("remove",wi,"Remove a notebook."),k("rename",_i,"Rename a notebook."),k("get_conf",vi,"Get notebook configuration."),k("set_conf",Ii,"Set notebook configuration."),k("set_icon",Di,"Set the icon for a notebook."),k("get_permissions",Si,'Get permission levels for notebooks. Omit notebook or pass "all" to return every notebook; pass a specific notebook ID to return only that notebook.'),k("set_permission",Ai,"Set the permission level for a notebook."),k("get_child_docs",Ti,"Get direct child documents at the notebook root. Returns a paginated { data, total, page, pageSize, pageCount, hasNextPage } payload.")],sl=ae({name:"notebook",description:"📚 Grouped notebook operations.",variants:BI,actionSchema:hg,aggregateOptions:{guidance:Ls,actionHints:ea},handlers:FI});function jI(e){return sl.listTools(e)}function UI(e,t,o,n){return sl.callTool(e,t,o,n)}async function qI(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushMsg",n)}async function MI(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushErrMsg",n)}const LI=1,ZI=12;function hs(e,t,o,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(o,Math.min(n,Math.trunc(e)))}function HI(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 VI(e,t){const o=HI(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 Io(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=>Io(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,Io(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 YI(e,t,o,n,r){if(t==="get"){if(!o)throw new Error('keyPath is required when mode="get".');const i=VI(e,o);return{mode:t,keyPath:o,value:Io(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:Io(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 GI=async({client:e,rawArgs:t})=>(ou.parse(t),g(await ib(e))),JI=async({client:e,rawArgs:t})=>(nu.parse(t),g(await cb(e))),WI=async({client:e,rawArgs:t})=>{const o=ru.parse(t),n=await ub(e),r=o.mode??"summary",s=hs(o.maxDepth,LI,0,5),a=hs(o.maxItems,ZI,1,100);return g(YI(n,r,o.keyPath,s,a))},KI=async({client:e,rawArgs:t})=>{const o=su.parse(t),n=o.level==="error"?await MI(e,o.msg,o.timeout):await qI(e,o.msg,o.timeout);return g({level:o.level,...n})},QI=async({client:e,rawArgs:t})=>(au.parse(t),g({version:await lb(e)})),XI=async({client:e,rawArgs:t})=>{iu.parse(t);const o=await db(e);return g({currentTime:o,iso:new Date(o).toISOString()})},eD={workspace_info:GI,network:JI,conf:WI,notify:KI,get_version:QI,get_current_time:XI},tD=[k("workspace_info",ou,"Get SiYuan workspace metadata. High-risk: exposes the absolute workspace path."),k("network",nu,"Get current network proxy information."),k("conf",ru,"Get masked system configuration with summary-first progressive reading."),k("notify",su,"Push a notification message."),k("get_version",au,"Get the SiYuan system version."),k("get_current_time",iu,"Get the current system time.")],al=ae({name:"system",description:"🖥️ Grouped system and notification operations.",variants:tD,actionSchema:Cg,aggregateOptions:{guidance:Js,actionHints:ca},handlers:eD});function oD(e){return al.listTools(e)}function nD(e,t,o,n){return al.callTool(e,t,o,n)}async function rD(e,t={}){const o={...t,app:t.app||"siyuan-mcp-sisyphus"};return e.request("/api/tag/getTag",o)}async function sD(e,t,o){return e.request("/api/tag/renameTag",{oldLabel:t,newLabel:o})}async function aD(e,t){return e.request("/api/tag/removeTag",{label:t})}const iD=[k("list",Xc,"List tags in the workspace."),k("rename",eu,"Rename a tag."),k("remove",tu,"Remove a tag.")],il=ae({name:"tag",description:"🏷️ Grouped tag operations.",variants:iD,actionSchema:Eg,aggregateOptions:{guidance:Gs,actionHints:ia},handlers:{list:async({client:e,rawArgs:t})=>{const o=Xc.parse(t),n=o.query??o.keyword;if(n&&n.trim().length>0){const s=await Ay(e,n),a=s&&typeof s=="object"?s:{},i=Array.isArray(a.tags)?a.tags:[];return g({...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 rD(e,o);return g(r)},rename:async({client:e,rawArgs:t})=>{const o=eu.parse(t);return await sD(e,o.oldLabel,o.newLabel),P(e,g({success:!0,oldLabel:o.oldLabel,newLabel:o.newLabel}),[{type:"reloadTag"}])},remove:async({client:e,rawArgs:t})=>{const o=tu.parse(t);return await aD(e,o.label),P(e,g({success:!0,label:o.label}),[{type:"reloadTag"}])}}}),cD=il.listTools,uD=il.callTool,Zt={fs:{category:"fs",listTools:fI,callTool:hI},notebook:{category:"notebook",listTools:jI,callTool:UI},document:{category:"document",listTools:I_,callTool:D_},block:{category:"block",listTools:jw,callTool:Uw},av:{category:"av",listTools:ik,callTool:ck},file:{category:"file",listTools:Y_,callTool:G_},feedback:{category:"feedback",listTools:iv,callTool:cv},search:{category:"search",listTools:iw,callTool:cw},tag:{category:"tag",listTools:cD,callTool:uD},system:{category:"system",listTools:oD,callTool:nD},flashcard:{category:"flashcard",listTools:Uv,callTool:qv},mascot:{category:"mascot",listTools:_I,callTool:vI}};function lr(e){return Ee.includes(e)?e:null}const lD="approx_context_v1";function dD(e){return Math.ceil(Math.max(0,e)/4)}function hn(e){const t=typeof e=="string"?e:"";return{chars:t.length,approxTokens:dD(t.length)}}function pD(e){const t=(e??[]).map(o=>o.text??"").join("");return hn(t)}const It="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl",cl="/data/storage/petal/siyuan-plugins-mcp-sisyphus/analytics.jsonl.1",fD=2*1024*1024,ms=2e4;function gs(e){const t=typeof e=="string"?e:"";return t.length<=ms?{text:t,truncated:!1}:{text:t.slice(0,ms),truncated:!0}}function ul(e){return e==="cli"||e==="http"?e:"stdio"}function hD(){return{cli:0,stdio:0,http:0}}function mD(e){return typeof Buffer<"u"?Buffer.byteLength(e,"utf8"):new TextEncoder().encode(e).length}function ys(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:ul(s.transport)})}catch{}}return t}async function gD(e,t){const o={...t,seq:Date.now(),ts:Date.now()},n=JSON.stringify(o);try{const r=await e.readFile(It);if(r){const s=`${r}
165
+ ${n}`;mD(s)>fD?(await e.writeFile(cl,r),await e.writeFile(It,n)):await e.writeFile(It,s);return}}catch{}try{await e.writeFile(It,n)}catch{}}function yD(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 bD(e){if(e){if(e.includes("McpError")){const t=e.match(/McpError\s*\(?([^:)]{1,40})\)?/);return t?`McpError:${t[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":"UnknownError"}}const kD=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","created","updated","removed","overwritten","folded","partial","reason","warning"]),wD=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"]),_D=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 vD(e,t){const o=e.content[0];return{...e,content:[{...o??{type:"text"},type:"text",text:JSON.stringify(t,null,2)}]}}function ID(e){return e.action==="help"||e.category==="system"&&e.action==="conf"}function DD(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 SD(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:dr(e)}function dr(e){const t={};for(const[o,n]of Object.entries(e))_D.has(o)||(t[o]=$o(n));return t}function AD(e){return e.plainContent!==void 0||e.excerpt!==void 0||e.rootID!==void 0||e.root_id!==void 0||e.blockPath!==void 0}function $o(e){return Array.isArray(e)?e.map(t=>ft(t)?AD(t)?SD(t):dr(t):$o(t)):ft(e)?dl(e):e}function ll(e){if(ft(e)&&"partialFailure"in e)return{partialFailure:e.partialFailure}}function TD(e,t){const o={};for(const r of kD)e[r]!==void 0&&(o[r]=e[r]);const n=ll(e.uiRefresh);return n!==void 0&&(o.uiRefresh=n),Object.keys(o).length>0?o:e}function dl(e,t){if(ft(e.error))return{error:DD(e.error)};if(e.success===!0)return TD(e);const o={};for(const[n,r]of Object.entries(e)){if(n==="uiRefresh"){const s=ll(r);s!==void 0&&(o.uiRefresh=s);continue}wD.has(n)||(o[n]=$o(r))}return o}function PD(e,t){if(ID(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)?dr(s):$o(s)):ft(n)?dl(n):n;return vD(e,r)}const ED="telemetryConfig",pl=`/data/storage/petal/siyuan-plugins-mcp-sisyphus/${ED}`;function fl(){return{enabled:!1,lastReportAt:0,reportIntervalHours:24}}function hl(e){const t=fl();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 CD(e){try{const t=await e.readFile(pl);if(t)return hl(JSON.parse(t))}catch{}return fl()}async function bs(e,t){const o=hl(t);try{await e.writeFile(pl,JSON.stringify(o))}catch{}return o}async function OD(e){const t=[];try{const o=await e.readFile(It);o&&t.push(...ys(o))}catch{}try{const o=await e.readFile(cl);o&&t.push(...ys(o))}catch{}return t}async function xD(e,t){const n=(await OD(e)).filter(d=>d.ts>=t);if(n.length===0)return null;const r=n.length,s=n.filter(d=>d.status==="error").length,a=n.reduce((d,f)=>d+(f.durationMs||0),0),i=new Map,c=new Array(24).fill(0),u=hD();for(const d of n){const f=`${d.tool}/${d.action}`,h=i.get(f);h?(h.count+=1,h.errorCount+=d.status==="error"?1:0,h.totalDuration+=d.durationMs||0):i.set(f,{tool:d.tool,action:d.action,count:1,errorCount:d.status==="error"?1:0,totalDuration:d.durationMs||0});const m=new Date(d.ts).getHours();m>=0&&m<24&&(c[m]+=1),u[ul(d.transport)]+=1}const l=Array.from(i.values()).map(d=>({tool:d.tool,action:d.action,count:d.count,errorCount:d.errorCount,avgDurationMs:d.count>0?Math.round(d.totalDuration/d.count):0})).sort((d,f)=>f.count-d.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:l,hourlyDistribution:c,transportDistribution:u},meta:{pluginVersion:process.env.SIYUAN_MCP_PLUGIN_VERSION,nodeVersion:process.version,platform:process.platform}}}async function ks(e){const t=await CD(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 xD(e,t.lastReportAt||Date.now()-o);if(!r){await bs(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 bs(e,{...t,lastReportAt:Date.now()})}catch{}}function ws(e,t,o,n,r,s,a,i){const c=hn(n),u=i?pD(i):hn(a),l=i?i.map(m=>m.text??"").join(""):a??"",d=gs(n),f=gs(l),h=o&&typeof o=="object"?Object.keys(o).filter(m=>m!=="action"):[];return{tool:e,action:t,status:r,durationMs:s,errorCode:r==="error"?bD(a):void 0,paramKeys:h,resultSizeHint:yD(i),transport:ir(),requestChars:c.chars,responseChars:u.chars,requestApproxTokens:c.approxTokens,responseApproxTokens:u.approxTokens,totalApproxTokens:c.approxTokens+u.approxTokens,tokenMode:lD,requestText:d.text,responseText:f.text,requestTextTruncated:d.truncated,responseTextTruncated:f.truncated}}function ND(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 RD(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 _s(e,t){const o=gD(e,t).catch(()=>{});ir()==="cli"&&await o}async function $D(e,t){var m;const{client:o,category:n,name:r,action:s,args:a}=e,i=e.requestText,c=Date.now(),u=n==="mascot"?await Lt(o):await yI(o,`${r}/${s}`);await ps(o,{tool:r,action:s,status:"running",totalCalls:u.totalCalls,balance:u.balance});let l;try{l=await t()}catch(_){const v=Date.now()-c,A=_ instanceof Error?_.message:String(_);throw await _s(o,ws(r,s,a,i,"error",v,A)),ks(o).catch(()=>{}),_}e.slimResponses?l=PD(l,{category:n,action:s}):e.slimResponses===void 0&&(l=RD(l,e.includeUiRefreshMetadata));const d=n==="mascot"?await Lt(o):u,f=n==="mascot"?ND(l):{};await ps(o,{tool:r,action:s,status:l.isError?"error":"success",totalCalls:d.totalCalls,balance:d.balance,...f});const h=Date.now()-c;return await _s(o,ws(r,s,a,i,l.isError?"error":"success",h,(m=l.content[0])==null?void 0:m.text,l.content)),ks(o).catch(()=>{}),l}function zD(e,t){const o=FD(t),n=new Map,r=new Set,s=new Set;for(const[f,h]of Object.entries(o)){if(f==="action"||f==="topic")continue;const m=Is(f);for(const v of m)n.set(v.toLowerCase(),f);if(Do(h)==="boolean")for(const v of m)r.add(v);else for(const v of m)s.add(v)}const a=[];for(const f of Object.keys(o))if(!(f==="action"||f==="topic"))for(const h of Is(f))a.push(`${h}-json`);const i=As(e,{boolean:[...r],string:[...s,...a]}),c=UD(e),u={},l=[],d={};for(const[f,h]of Object.entries(i))if(f!=="_"&&f.endsWith("-json")){const m=f.slice(0,-5),_=n.get(m.toLowerCase());if(!_){l.push(`Unknown flag --${f}.`);continue}if(typeof h!="string"||h.length===0)continue;try{d[_]=JSON.parse(h)}catch(v){throw new Error(`--${f} must be valid JSON: ${v instanceof Error?v.message:String(v)}`)}}for(const[f,h]of Object.entries(i)){if(f==="_"||f.endsWith("-json"))continue;const m=n.get(f.toLowerCase());if(!m){l.push(`Unknown flag --${f}; ignored.`);continue}if(m in d||m in u)continue;const _=o[m];Do(_)==="boolean"&&h===!1&&!c.has(f.toLowerCase())||(u[m]=BD(m,h,_))}return i._.length>0&&l.push(`Extra positional arguments ignored: ${i._.join(" ")}`),{args:{...u,...d},warnings:l}}function FD(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 BD(e,t,o){const n=Do(o);if(n==="array")return Array.isArray(t)?t.map(r=>vs(r,o.items)):typeof t=="string"?t.split(",").map(r=>vs(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(`--${Go(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(`--${Go(e)} expects JSON for an object field. Use --${Go(e)}-json '{"..."}'.`)}return t}return typeof t=="string"?t:String(t)}function vs(e,t){if(!t)return e;const o=Do(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 Do(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 Is(e){const t=ml(e),o=new Set([e]);return t.length===0?[...o]:(o.add(t.join("-")),o.add(t.join("_")),o.add(jD(t)),[...o])}function ml(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 jD(e){return e.length===0?"":e[0]+e.slice(1).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Go(e){const t=ml(e);return t.length>0?t.join("-"):e.toLowerCase()}function UD(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 qD{constructor(t={}){ge(this,"baseUrl");ge(this,"timeout");ge(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 l=await fetch(t,{...o,signal:i.signal});if(clearTimeout(c),!l.ok){if(l.status>=400&&l.status<500&&l.status!==429)throw new Error(`HTTP error: ${l.status} ${l.statusText}`);if(await l.arrayBuffer().catch(()=>{}),s=new Error(`HTTP error: ${l.status} ${l.statusText}`),a<3)continue;throw s}return l}catch(l){if(clearTimeout(c),l instanceof Error&&l.name==="AbortError"?s=new Error(`Request timeout after ${this.timeout}ms`):s=l instanceof Error?l:new Error(String(l)),a>=3)throw s}const u=300*(a+1);await new Promise(l=>setTimeout(l,u))}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 MD=["none","r","rw","rwd"],Ds={none:"none",readonly:"r",write:"rw"},co="/data/storage/petal/siyuan-plugins-mcp-sisyphus/notebookPermissions",LD=process.env.SIYUAN_MCP_DEBUG_PERMISSIONS==="1";function oo(...e){LD&&console.error("[MCP]",...e)}function gl(e){return typeof e=="string"&&MD.includes(e)}function ZD(e){return gl(e)?e:typeof e=="string"&&e in Ds?Ds[e]:"none"}function HD(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,ZD(o)]))}class VD{constructor(t){ge(this,"permissions",{});ge(this,"client",null);ge(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(co)}catch(n){throw oo("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,oo("Permissions not found in API, using empty state");return}let o;try{o=JSON.parse(t)}catch(n){throw oo("Failed to parse permissions JSON from API:",n),new Error(`[Permissions] Permissions file at ${co} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}this.permissions=HD(o),this.loaded=!0,oo("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(co,t),this.loaded=!0}get(t){const o=this.permissions[t];return gl(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"}}const Jt="siyuan-plugins-mcp-sisyphus",yl=`/data/plugins/${Jt}/plugin.json`;function Jo(){return[`This CLI requires the SiYuan plugin "${Jt}".`,"Install and enable the plugin in SiYuan first, then open the plugin settings panel and configure permissions before retrying."].join(" ")}function YD(e){const t=e?` Details: ${e}`:"";return[`The required SiYuan plugin "${Jt}" 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 Ss(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 GD(e){try{return JSON.parse(e)}catch(t){throw new Error(`Found "${Jt}" at ${yl}, but its plugin.json is invalid JSON: ${t instanceof Error?t.message:String(t)}`)}}async function JD(e){let t="";try{t=await e.readFile(yl)}catch(n){throw Ss(n)?n:new Error(Jo())}if(!t.trim())throw new Error(Jo());if(GD(t).name!==Jt)throw new Error(Jo());try{await e.readFile(co)}catch(n){throw Ss(n)?n:new Error(YD(n instanceof Error?n.message:String(n)))}}async function pr(e,t={}){const o=ht(e.configPath),n=Nl(o,{cliUrl:e.url,cliToken:e.token,profile:e.profile});Rl(n);const r=new qD({baseUrl:n.apiUrl});n.token&&r.setToken(n.token),await JD(r);const s=await WD(r),a=new VD(r);return t.loadPermissions!==!1&&await a.load(),{client:r,toolConfig:s,permMgr:a}}async function WD(e){try{const t=await e.readFile(xt);if(!t)return Rt();const o=JSON.parse(t);return Us(o,{source:`SiYuan API file "${xt}"`}),Nn(o)}catch{return Rt()}}async function KD(e){const{tool:t,action:o,rest:n}=e;if(!t||!o)throw new Error("runDispatch requires both tool and action.");const r=lr(t);if(!r)throw aS(t);const s=qs(r,o);if(!Ao[r].includes(s)&&s!=="help")throw iS(r,s);const i=process.env.SIYUAN_MCP_TRANSPORT;process.env.SIYUAN_MCP_TRANSPORT="cli";try{const{client:c,toolConfig:u,permMgr:l}=await pr(e);if(!u[r].enabled)return Ot({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const d=Zt[r],f=sS(r,u),h=QD(r,s,n),{args:m,warnings:_}=zD(h,f);if(_.length>0&&e.debug)for(const D of _)process.stderr.write(`[warn] ${D}
166
+ `);const v={action:s,...m},A=[E,t,o,...n].join(" ").trim(),x=async D=>{const $=D===void 0?v:{...v,page:D};return $D({client:c,category:r,name:t,action:s,args:$,requestText:A,slimResponses:u.debug.slimResponses&&!e.debug},()=>d.callTool(c,$,u[r],l))},C=await x(),I=Ot(C,{json:e.json,debug:e.debug});return I!==0||e.json||await tS(C,x,{json:e.json,debug:e.debug}),I}catch(c){return Ae(c,{debug:e.debug}),1}finally{i===void 0?delete process.env.SIYUAN_MCP_TRANSPORT:process.env.SIYUAN_MCP_TRANSPORT=i}}function QD(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 _t(o,"path",n[0]);if(t==="search")return _t(_t(o,"path",n[0]),"query",n[1]);if(t==="mv")return _t(_t(o,"from",n[0]),"to",n[1])}return o}function _t(e,t,o){return!o||XD(e,t)?e:[`--${t}`,o,...eS(e,o)]}function XD(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 eS(e,t){let o=!1;return e.filter(n=>!o&&n===t&&!n.startsWith("-")?(o=!0,!1):!0)}async function tS(e,t,o){var i,c;if(!oS())return;let n=br(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(`
167
+ Paging: Enter/n next, p previous, q quit › `);const u=await rS();if(s.write(`
168
+ `),u===""||u==="\x1B"||u.toLowerCase()==="q")return;const l=nS(u,n.page,n.pageCount);if(l===null)continue;const d=await t(l);Ot(d,o);const f=br(d);if(!f)return;n=f}}finally{(c=r.setRawMode)==null||c.call(r,a),r.pause()}}function oS(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function nS(e,t,o){const n=e.toLowerCase();return(e==="\r"||e===`
169
+ `||n==="n")&&t<o?t+1:n==="p"&&t>1?t-1:null}function rS(){return new Promise(e=>{process.stdin.once("data",t=>{e(String(t))})})}function sS(e,t){const n=Zt[e].listTools(t[e])[0];if(!n)throw new Error(`Tool "${e}" has no aggregated descriptor — this is a bug.`);return n.inputSchema}function aS(e){const t=Ee.join(", ");return new Error(`Unknown tool "${e}". Available tools: ${t}. Try "${E} list".`)}function iS(e,t){const o=Ao[e].join(", ");return new Error(`Unknown action "${t}" for tool "${e}". Available actions: ${o}. Try "${E} help ${e}".`)}class cS{constructor(){ge(this,"rl");ge(this,"closed",!1);this.rl=vl.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 uS(e){const t=Es(e??gn()),o=ht(e),n=qe(o),r=new cS;try{Pe("SiYuan CLI setup"),ne("Path",t),ne("Tip","Press Enter to accept the default shown in brackets."),process.stdout.write(`
170
+ `);const s=await r.ask("Profile name [default]: ")||"default";if(n.profiles[s]){const d=(await r.ask(`Profile "${s}" already exists. Overwrite it? [y/N] `)).toLowerCase();if(d!=="y"&&d!=="yes"){ee("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(),l=Cs(o,s,{apiUrl:a,token:i},{makeCurrent:!c||c==="y"||c==="yes"});yn(l,e),process.stdout.write(`
171
+ `),ee("success","Config written."),he([{key:"path",value:t},{key:"profile",value:s},{key:"current",value:l.currentProfile},{key:"apiUrl",value:a},{key:"token",value:i?"configured":"empty"}]),process.stdout.write(`
172
+ `),ne("Next","Run `siyuan-sisyphus notebook list` to verify the connection, or `siyuan-sisyphus config list` to inspect all profiles.")}finally{r.close()}}async function lS(e){const t=process.stdout,o=e.tool?lr(e.tool):null,{toolConfig:n}=await pr(e,{loadPermissions:!1});if(!o){e.tool&&Ae(`Unknown tool "${e.tool}". Showing all tools instead.`);const r=Ee.filter(s=>Zt[s].listTools(n[s]).length>0);return Pe("SiYuan tools",t),ie(r.map(s=>{const a=$t(n[s]),i=a.filter(u=>Nt(s,u)==="basic").length,c=a.length-i;return`${s} — ${a.length} actions (${i} common, ${c} advanced)`}),t),G("Next Step",t),ne("Tip",`Run \`${E} list <tool>\` to see a tool’s actions.`,t),0}return Zt[o].listTools(n[o]).length===0?(Ae(`Tool "${o}" is disabled.`),1):(Pe(`${o} actions`,t),ie($t(n[o]).map(r=>{const s=Nt(o,r)==="basic"?"common":"advanced",a=rt(o,r)?" · confirmation required":"";return`${r} — ${s}${a}`}),t),G("Next Step",t),ne("Tip",`Run \`${E} help ${o} <action>\` for fields and examples.`,t),0)}async function dS(e){const t=e.tool;if(!t)return Ae(`Missing tool. Usage: ${E} help <tool> [action]`),2;const o=lr(t);if(!o)return Ae(`Unknown tool "${t}". Available: ${Ee.join(", ")}.`),2;try{const{client:n,toolConfig:r,permMgr:s}=await pr(e,{loadPermissions:!1});if(!r[o].enabled)return Ot({content:[{type:"text",text:`Tool "${t}" is disabled.`}],isError:!0},{json:e.json,debug:e.debug});const a=Zt[o],i={action:"help"};e.action&&(i.topic=e.action);const c=await a.callTool(n,i,r[o],s);return Ot(c,{json:e.json,debug:e.debug})}catch(n){return Ae(n,{debug:e.debug}),1}}const Dt="siyuan-sisyphus";function pS(e){switch(e.skillAction){case"list":return fS(e);case"read":return hS(e);case"install":return mS(e);case"uninstall":return gS(e);default:throw new Error("Unknown skill action.")}}function fS(e){const t=zo();if(e.json)return process.stdout.write(JSON.stringify({skills:t})+`
173
+ `),0;Pe("Bundled SiYuan Sisyphus skills");for(const o of t)process.stdout.write(` ${o.name}
174
+ `);return ne("Next","Run `siyuan-sisyphus skill install` to install them."),0}function hS(e){const t=bS(e.skillName);return process.stdout.write(t),t.endsWith(`
175
175
  `)||process.stdout.write(`
176
- `),0}function cS(e){const t=fS({target:e.target,local:e.local,dryRun:e.dryRun});return e.json||e.dryRun?(process.stdout.write(JSON.stringify(t,null,2)+`
177
- `),0):(ee("success","Bundled skills installed."),fe([{key:"target",value:t.target},{key:"count",value:t.skills.length}]),0)}function uS(e){const t=hS({target:e.target,local:e.local});return e.json?(process.stdout.write(JSON.stringify(t,null,2)+`
178
- `),0):(ee("success","Bundled skills removed."),fe([{key:"target",value:t.target},{key:"count",value:t.removed.length}]),0)}function lS(e=F.dirname(bl.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:xo&&xo.tagName.toUpperCase()==="SCRIPT"&&xo.src||new URL("cli.cjs",document.baseURI).href)),t=j.existsSync){const o=[F.resolve(e,"skills",It),F.resolve(e,"../skills",It),F.resolve(e,"../../skills",It),F.resolve(e,"../../../skills",It)];for(const n of o)if(t(F.join(n,"siyuan-sisyphus","SKILL.md")))return n;for(const n of o)if(t(n))return n;return o[0]}function Oo(e=lS()){return j.readdirSync(e).map(t=>({name:t,path:F.join(e,t)})).filter(t=>{try{return j.statSync(t.path).isDirectory()&&j.existsSync(F.join(t.path,"SKILL.md"))}catch{return!1}}).sort((t,o)=>t.name.localeCompare(o.name))}function dS(e){const t=(e==null?void 0:e.trim())||It;hl(t);const o=Oo().find(n=>n.name===t);if(!o)throw new Error(`Unknown bundled skill "${t}". Run \`siyuan-sisyphus skill list\` to see available skills.`);return j.readFileSync(F.join(o.path,"SKILL.md"),"utf8")}function pS(e){const t=(e??"agents").trim();return t?(hl(t),t==="agents"||t==="claude"||t.startsWith(".")?t:`.${t}`):"agents"}function fl(e={}){const t=pS(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 F.join(Dt.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 F.join(Dt.homedir(),".claude","skills")}const o=e.local?e.cwd??process.cwd():Dt.homedir();return F.join(o,t,"skills")}function fS(e={}){const t=Oo(),o=fl(e),n=t.map(r=>({op:j.existsSync(F.join(o,r.name))?"update":"install",from:r.path,to:F.join(o,r.name)}));if(e.dryRun)return{target:o,dryRun:!0,skills:t.map(r=>r.name),operations:n};j.mkdirSync(o,{recursive:!0});for(const r of n)j.rmSync(r.to,{recursive:!0,force:!0}),j.cpSync(r.from,r.to,{recursive:!0,force:!0});return{target:o,dryRun:!1,skills:t.map(r=>r.name)}}function hS(e={}){const t=Oo(),o=fl(e),n=[];for(const r of t){const s=F.join(o,r.name);j.existsSync(s)&&(j.rmSync(s,{recursive:!0,force:!0}),n.push(F.basename(s)))}return{target:o,removed:n}}function hl(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 mS(){let e;try{e=Dl(process.argv.slice(2))}catch(t){return Se(t),2}switch(e.command){case"show-help":return process.stdout.write(Al()),0;case"version":return process.stdout.write(`0.1.13
179
- `),0;case"init":return await oS(e.configPath),0;case"config":return rd(e);case"skill":return sS(e);case"list":return await nS(e);case"help":return await rS(e);case"dispatch":return await ZD(e);default:throw new Error(`Unknown command: ${String(e.command)}`)}}mS().then(e=>process.exit(e)).catch(e=>{Se(e,{debug:process.env.SIYUAN_MCP_DEBUG==="1"}),process.exit(1)});
176
+ `),0}function mS(e){const t=wS({target:e.target,local:e.local,dryRun:e.dryRun});return e.json||e.dryRun?(process.stdout.write(JSON.stringify(t,null,2)+`
177
+ `),0):(ee("success","Bundled skills installed."),he([{key:"target",value:t.target},{key:"count",value:t.skills.length}]),0)}function gS(e){const t=_S({target:e.target,local:e.local});return e.json?(process.stdout.write(JSON.stringify(t,null,2)+`
178
+ `),0):(ee("success","Bundled skills removed."),he([{key:"target",value:t.target},{key:"count",value:t.removed.length}]),0)}function yS(e=B.dirname(Il.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Fo&&Fo.tagName.toUpperCase()==="SCRIPT"&&Fo.src||new URL("cli.cjs",document.baseURI).href)),t=j.existsSync){const o=[B.resolve(e,"skills",Dt),B.resolve(e,"../skills",Dt),B.resolve(e,"../../skills",Dt),B.resolve(e,"../../../skills",Dt)];for(const n of o)if(t(B.join(n,"siyuan-sisyphus","SKILL.md")))return n;for(const n of o)if(t(n))return n;return o[0]}function zo(e=yS()){return j.readdirSync(e).map(t=>({name:t,path:B.join(e,t)})).filter(t=>{try{return j.statSync(t.path).isDirectory()&&j.existsSync(B.join(t.path,"SKILL.md"))}catch{return!1}}).sort((t,o)=>t.name.localeCompare(o.name))}function bS(e){const t=(e==null?void 0:e.trim())||Dt;kl(t);const o=zo().find(n=>n.name===t);if(!o)throw new Error(`Unknown bundled skill "${t}". Run \`siyuan-sisyphus skill list\` to see available skills.`);return j.readFileSync(B.join(o.path,"SKILL.md"),"utf8")}function kS(e){const t=(e??"agents").trim();return t?(kl(t),t==="agents"||t==="claude"||t.startsWith(".")?t:`.${t}`):"agents"}function bl(e={}){const t=kS(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 B.join(St.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 B.join(St.homedir(),".claude","skills")}const o=e.local?e.cwd??process.cwd():St.homedir();return B.join(o,t,"skills")}function wS(e={}){const t=zo(),o=bl(e),n=t.map(r=>({op:j.existsSync(B.join(o,r.name))?"update":"install",from:r.path,to:B.join(o,r.name)}));if(e.dryRun)return{target:o,dryRun:!0,skills:t.map(r=>r.name),operations:n};j.mkdirSync(o,{recursive:!0});for(const r of n)j.rmSync(r.to,{recursive:!0,force:!0}),j.cpSync(r.from,r.to,{recursive:!0,force:!0});return{target:o,dryRun:!1,skills:t.map(r=>r.name)}}function _S(e={}){const t=zo(),o=bl(e),n=[];for(const r of t){const s=B.join(o,r.name);j.existsSync(s)&&(j.rmSync(s,{recursive:!0,force:!0}),n.push(B.basename(s)))}return{target:o,removed:n}}function kl(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 vS(){let e;try{e=El(process.argv.slice(2))}catch(t){return Ae(t),2}switch(e.command){case"show-help":return process.stdout.write(Ol()),0;case"version":return process.stdout.write(`0.1.14
179
+ `),0;case"init":return await uS(e.configPath),0;case"config":return ud(e);case"skill":return pS(e);case"list":return await lS(e);case"help":return await dS(e);case"dispatch":return await KD(e);default:throw new Error(`Unknown command: ${String(e.command)}`)}}vS().then(e=>process.exit(e)).catch(e=>{Ae(e,{debug:process.env.SIYUAN_MCP_DEBUG==="1"}),process.exit(1)});