siyuan-sisyphus 0.1.0

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 (3) hide show
  1. package/README.md +133 -0
  2. package/dist/cli.cjs +133 -0
  3. package/package.json +34 -0
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # siyuan-sisyphus
2
+
3
+ [English](./README.md) | [中文](./README_zh_CN.md)
4
+
5
+ Direct command-line control for [SiYuan Note](https://b3log.org/siyuan). Think of it like `obsidian-cli` but for SiYuan — every MCP tool (block, document, notebook, av, search, tag, file, system, flashcard, mascot) is exposed as a subcommand you can call directly from a shell.
6
+
7
+ The published npm package is `siyuan-sisyphus`. It installs the primary command `siyuan-sisyphus`, and also provides the shorter alias `siyuan`.
8
+
9
+ ```bash
10
+ siyuan-sisyphus notebook list
11
+ siyuan-sisyphus document create --notebook 20240318... --path "/Inbox/Test" --markdown "# Hello"
12
+ siyuan-sisyphus block append --parent-id 20240318abc --data-type markdown --data "- item"
13
+ siyuan-sisyphus search fulltext --query "keyword" --page-size 10 --json | jq '.data[].hPath'
14
+ ```
15
+
16
+ ## Requirements
17
+
18
+ - Node.js 18+
19
+ - A running SiYuan instance reachable over HTTP (local or remote)
20
+ - The SiYuan API token (`SiYuan > Settings > About > API token`)
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ # Global install; this installs both `siyuan-sisyphus` and `siyuan`
26
+ npm i -g siyuan-sisyphus
27
+
28
+ # Or run once without installing
29
+ npx -p siyuan-sisyphus siyuan-sisyphus --help
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ ```bash
35
+ siyuan-sisyphus init
36
+ # …answer the two prompts (API URL + token). This writes ~/.siyuan-sisyphus/config.json (0600).
37
+
38
+ siyuan-sisyphus notebook list # verify connectivity
39
+ siyuan-sisyphus list # see all available tools
40
+ siyuan-sisyphus list block # see all actions for a tool
41
+ siyuan-sisyphus help block append
42
+ ```
43
+
44
+ ## Command shape
45
+
46
+ ```
47
+ siyuan-sisyphus <tool> <action> [--flag value ...] Execute any MCP tool-action
48
+ siyuan-sisyphus list [tool] List tools or a tool's actions
49
+ siyuan-sisyphus help <tool> [action] Detailed help for a tool or action
50
+ siyuan-sisyphus init Interactive config setup
51
+ siyuan-sisyphus --help | -h Top-level help
52
+ siyuan-sisyphus --version | -v Print version
53
+ ```
54
+
55
+ ### Flag conventions
56
+
57
+ - **Kebab, camel, or snake**: `--parent-id`, `--parentID`, `--parentId`, and `--item_id` all map to the schema field they spell.
58
+ - **Action names**: `set_open_state` or `set-open-state` — either form works.
59
+ - **Booleans**: `--opened` (true), `--opened=false`, or `--no-opened` (false).
60
+ - **Arrays**: repeat the flag (`--ids a --ids b`), use comma-separated (`--ids a,b`), or pass exact JSON with `--<key>-json '["a","b"]'`.
61
+ - **Complex objects**: use a JSON sidecar flag such as `--assets-json '[{...}]'`.
62
+ - **`-json` precedence**: if both plain flags and `--<key>-json` are provided, the JSON sidecar wins.
63
+
64
+ ### Global flags
65
+
66
+ | Flag | Purpose |
67
+ |---|---|
68
+ | `--config <file>` | Load config from `<file>` instead of `~/.siyuan-sisyphus/config.json` |
69
+ | `--url <url>` | Override SiYuan API URL |
70
+ | `--token <token>` | Override SiYuan API token |
71
+ | `--json` | Emit compact single-line JSON (for scripting with `jq`, etc.) |
72
+ | `--debug` | Include stack traces and ignored-flag warnings |
73
+
74
+ ## Examples
75
+
76
+ ```bash
77
+ # Notebooks
78
+ siyuan-sisyphus notebook list
79
+ siyuan-sisyphus notebook create --name "Work" --icon 1f4d4
80
+
81
+ # Documents
82
+ siyuan-sisyphus document create --notebook 20240318... --path "/Inbox/Daily" --markdown "# Today"
83
+ siyuan-sisyphus document list-tree --notebook 20240318... --max-depth 2
84
+ siyuan-sisyphus document get-doc --id 20240318xyz --mode markdown
85
+
86
+ # Blocks
87
+ siyuan-sisyphus block info --id 20240318xyz
88
+ siyuan-sisyphus block append --parent-id 20240318abc --data-type markdown --data "- new item"
89
+ siyuan-sisyphus block get-kramdown --id 20240318xyz
90
+
91
+ # Search
92
+ siyuan-sisyphus search fulltext --query "TODO" --page-size 20
93
+ siyuan-sisyphus search query-sql --stmt "SELECT id, content FROM blocks WHERE type='h' LIMIT 5"
94
+
95
+ # Piping to jq
96
+ siyuan-sisyphus notebook list --json | jq '.[] | select(.closed==false) | .name'
97
+ siyuan-sisyphus document search-docs --notebook <id> --query "proposal" --json | jq '.data[].hPath'
98
+ ```
99
+
100
+ ## Configuration
101
+
102
+ Precedence: **CLI flag > environment variable > config file > default**.
103
+
104
+ ### Environment variables
105
+
106
+ | Variable | Purpose |
107
+ |---|---|
108
+ | `SIYUAN_API_URL` | SiYuan base URL (default `http://127.0.0.1:6806`) |
109
+ | `SIYUAN_TOKEN` | SiYuan API token |
110
+
111
+ ### Config file shape (`~/.siyuan-sisyphus/config.json`)
112
+
113
+ ```json
114
+ {
115
+ "apiUrl": "http://127.0.0.1:6806",
116
+ "token": "<siyuan-token>"
117
+ }
118
+ ```
119
+
120
+ ## Relation to the SiYuan plugin
121
+
122
+ The CLI and the SiYuan plugin (`siyuan-plugins-mcp-sisyphus`) share the same tool-handler code under the hood, but the two entry points are independent:
123
+
124
+ - The **plugin** runs an MCP server inside SiYuan and talks to AI clients over stdio/HTTP (configured in the plugin's settings panel).
125
+ - The **CLI** connects to SiYuan over the HTTP API and executes one operation per invocation — no server, no long-running process.
126
+
127
+ If you already used the older config path `~/.siyuan-mcp/config.json`, the CLI still reads it as a fallback until you create a new config under `~/.siyuan-sisyphus/config.json`.
128
+
129
+ If the plugin has notebook-level permissions configured, the CLI respects them (it reads the same `/data/storage/petal/...` configuration through the API). Any action disabled in the plugin UI is still runnable from the CLI — the CLI user is assumed to have full control over what they type.
130
+
131
+ ## License
132
+
133
+ MIT © Taihong Yang
package/dist/cli.cjs ADDED
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var zs=Object.defineProperty;var xs=(e,t,o)=>t in e?zs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var ae=(e,t,o)=>xs(e,typeof t!="symbol"?t+"":t,o);const Ze=require("fs"),$e=require("path"),ue=require("node:fs"),Tn=require("node:os"),Xt=require("node:path"),Bs=require("node:readline");function Fs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function qs(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 $o(e){return typeof e=="number"||/^0x[0-9a-f]+$/i.test(e)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function Eo(e,t){return t==="constructor"&&typeof e[t]=="function"||t==="__proto__"}var js=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(D){o.bools[D]=!0});var n={};function r(D){return n[D].some(function(P){return o.bools[P]})}Object.keys(t.alias||{}).forEach(function(D){n[D]=[].concat(t.alias[D]),n[D].forEach(function(P){n[P]=[D].concat(n[D].filter(function(U){return P!==U}))})}),[].concat(t.string).filter(Boolean).forEach(function(D){o.strings[D]=!0,n[D]&&[].concat(n[D]).forEach(function(P){o.strings[P]=!0})});var s=t.default||{},i={_:[]};function a(D,P){return o.allBools&&/^--[^=]+$/.test(P)||o.strings[D]||o.bools[D]||n[D]}function c(D,P,U){for(var C=D,ge=0;ge<P.length-1;ge++){var oe=P[ge];if(Eo(C,oe))return;C[oe]===void 0&&(C[oe]={}),(C[oe]===Object.prototype||C[oe]===Number.prototype||C[oe]===String.prototype)&&(C[oe]={}),C[oe]===Array.prototype&&(C[oe]=[]),C=C[oe]}var ie=P[P.length-1];Eo(C,ie)||((C===Object.prototype||C===Number.prototype||C===String.prototype)&&(C={}),C===Array.prototype&&(C=[]),C[ie]===void 0||o.bools[ie]||typeof C[ie]=="boolean"?C[ie]=U:Array.isArray(C[ie])?C[ie].push(U):C[ie]=[C[ie],U])}function u(D,P,U){if(!(U&&o.unknownFn&&!a(D,U)&&o.unknownFn(U)===!1)){var C=!o.strings[D]&&$o(P)?Number(P):P;c(i,D.split("."),C),(n[D]||[]).forEach(function(ge){c(i,ge.split("."),C)})}}Object.keys(o.bools).forEach(function(D){u(D,s[D]===void 0?!1:s[D])});var d=[];e.indexOf("--")!==-1&&(d=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var p=0;p<e.length;p++){var f=e[p],k,_;if(/^--.+=/.test(f)){var w=f.match(/^--([^=]+)=([\s\S]*)$/);k=w[1];var T=w[2];o.bools[k]&&(T=T!=="false"),u(k,T,f)}else if(/^--no-.+/.test(f))k=f.match(/^--no-(.+)/)[1],u(k,!1,f);else if(/^--.+/.test(f))k=f.match(/^--(.+)/)[1],_=e[p+1],_!==void 0&&!/^(-|--)[^-]/.test(_)&&!o.bools[k]&&!o.allBools&&(!n[k]||!r(k))?(u(k,_,f),p+=1):/^(true|false)$/.test(_)?(u(k,_==="true",f),p+=1):u(k,o.strings[k]?"":!0,f);else if(/^-[^-]+/.test(f)){for(var z=f.slice(1,-1).split(""),j=!1,M=0;M<z.length;M++){if(_=f.slice(M+2),_==="-"){u(z[M],_,f);continue}if(/[A-Za-z]/.test(z[M])&&_[0]==="="){u(z[M],_.slice(1),f),j=!0;break}if(/[A-Za-z]/.test(z[M])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(_)){u(z[M],_,f),j=!0;break}if(z[M+1]&&z[M+1].match(/\W/)){u(z[M],f.slice(M+2),f),j=!0;break}else u(z[M],o.strings[z[M]]?"":!0,f)}k=f.slice(-1)[0],!j&&k!=="-"&&(e[p+1]&&!/^(-|--)[^-]/.test(e[p+1])&&!o.bools[k]&&(!n[k]||!r(k))?(u(k,e[p+1],f),p+=1):e[p+1]&&/^(true|false)$/.test(e[p+1])?(u(k,e[p+1]==="true",f),p+=1):u(k,o.strings[k]?"":!0,f))}else if((!o.unknownFn||o.unknownFn(f)!==!1)&&i._.push(o.strings._||!$o(f)?f:Number(f)),t.stopEarly){i._.push.apply(i._,e.slice(p+1));break}}return Object.keys(s).forEach(function(D){qs(i,D.split("."))||(c(i,D.split("."),s[D]),(n[D]||[]).forEach(function(P){c(i,P.split("."),s[D])}))}),t["--"]?i["--"]=d.slice():d.forEach(function(D){i._.push(D)}),i};const Pn=Fs(js),N="siyuan-sisyphus",Us="siyuan",Zs=`${N} — Direct command-line control for SiYuan Note
3
+
4
+ Commands:
5
+ ${N} <tool> <action> [--flag value ...] Execute a SiYuan operation
6
+ ${N} list [tool] List tools or a tool's actions
7
+ ${N} help <tool> [action] Show terminal-friendly help
8
+ ${N} init Create ~/.siyuan-sisyphus/config.json
9
+ ${N} --help | -h Show this help
10
+ ${N} --version | -v Show version
11
+
12
+ Tools:
13
+ notebook, document, block, av, file, search, tag, system, flashcard, mascot
14
+
15
+ Alias:
16
+ ${Us} Same CLI, shorter command name
17
+
18
+ Global options:
19
+ --config <file> Load config from <file> instead of ~/.siyuan-sisyphus/config.json
20
+ --url <url> SiYuan API base URL (default http://127.0.0.1:6806)
21
+ --token <token> SiYuan API token
22
+ --json Emit compact JSON for scripts and pipes
23
+ --debug Include stack traces and extra diagnostics
24
+
25
+ Examples:
26
+ ${N} notebook list
27
+ ${N} help document create
28
+ ${N} document create --notebook <id> --path "/Inbox/Test" --markdown "# Hello"
29
+ ${N} block append --parent-id <id> --data-type markdown --data "- item"
30
+ ${N} search fulltext --query "keyword" --page-size 10
31
+ ${N} document list-tree --notebook <id> --json | jq '.data[].title'
32
+
33
+ Config precedence:
34
+ CLI flags > environment variables > config file > defaults
35
+
36
+ Environment:
37
+ SIYUAN_API_URL, SIYUAN_TOKEN
38
+
39
+ Flag naming:
40
+ Use kebab-case or camelCase freely: --parent-id, --parentID, --parentId all work.
41
+ Action names accept either form: set_open_state or set-open-state.
42
+ Boolean flags: use --flag, --flag=false, or --no-flag.
43
+ For complex object/array values, use --<key>-json '<json>'.
44
+ `,Cn=["json","debug","help","version"],On=["config","url","token"];function Ls(e){const t=Pn(e,{boolean:Cn,string:On,alias:{h:"help",v:"version"},stopEarly:!1});if(t.help)return Nt("show-help");if(t.version)return Nt("version");const o=t._,n=o[0];if(n==="init")return{command:"init",rest:[],configPath:t.config||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,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,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug};if(typeof n!="string"||!n)return Nt("show-help");const r=typeof o[1]=="string"?o[1]:void 0;if(!r)throw new Error(`Missing action for tool "${n}". Try "${N} help ${n}".`);const s=Ms(e);return{command:"dispatch",tool:n,action:r,rest:s,configPath:t.config||void 0,url:t.url||void 0,token:t.token||void 0,json:!!t.json,debug:!!t.debug}}function Nt(e){return{command:e,rest:[],json:!1,debug:!1}}function Ms(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("="),i=s===-1?r.replace(/^-+/,""):r.slice(r.startsWith("--")?2:1,s);if(On.includes(i)){s===-1&&n++;continue}Cn.includes(i)||i==="h"||i==="v"||t.push(r)}return t}function Vs(){return Zs}class $n{constructor(t={}){ae(this,"baseUrl");ae(this,"timeout");ae(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||3e4}setToken(t){this.token=t}getBaseUrl(){return this.baseUrl}getAuthHeaders(){const t={};return this.token&&(t.Authorization=`Token ${this.token}`),t}async fetchWithTimeout(t,o){const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout);try{const s=await fetch(t,{...o,signal:n.signal});if(!s.ok)throw new Error(`HTTP error: ${s.status} ${s.statusText}`);return s}catch(s){throw s instanceof Error&&s.name==="AbortError"?new Error(`Request timeout after ${this.timeout}ms`):s}finally{clearTimeout(r)}}async readFile(t){return await(await this.fetchWithTimeout(`${this.baseUrl}/api/file/getFile`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify({path:t})})).text()}async readFileBinary(t){const o=await this.fetchWithTimeout(`${this.baseUrl}/api/file/getFile`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify({path: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);const i=await(await this.fetchWithTimeout(`${this.baseUrl}/api/file/putFile`,{method:"POST",headers:this.getAuthHeaders(),body:n})).json();if(i.code!==0)throw new Error(`SiYuan API error: ${i.code} - ${i.msg}`)}async request(t,o){const r=await(await this.fetchWithTimeout(`${this.baseUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(o??{})})).json();if(r.code!==0)throw new Error(`SiYuan API error: ${r.code} - ${r.msg}`);return r.data}}const qe=["notebook","document","block","av","file","search","tag","system","flashcard","mascot"],eo=["list","create","set_open_state","remove","rename","get_conf","set_conf","set_icon","get_permissions","set_permission","get_child_docs"],to=["create","rename","remove","move","get_path","get_hpath","get_ids","get_child_blocks","get_child_docs","set_icon","set_cover","list_tree","search_docs","get_doc","create_daily_note","duplicate","remove_batch","create_empty","heading_to_doc","doc_to_heading"],oo=["insert","prepend","append","update","delete","move","set_fold_state","get_kramdown","get_children","transfer_ref","set_attrs","get_attrs","exists","info","breadcrumb","dom","recent_updated","word_count","batch_insert","batch_update","append_daily_note","prepend_daily_note","doc_info","docs_info"],no=["get","render_attribute_view","get_attribute_view_keys","get_attribute_view_filter_sort","search","add_rows","remove_rows","add_column","remove_column","set_cell","batch_set_cells","duplicate_block","get_primary_key_values"],ro=["upload_asset","render_template","render_sprig","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","set_image_alpha"],so=["fulltext","query_sql","search_tag","get_backlinks","get_backmentions","search_refs","find_replace","search_assets","get_asset_content","fulltext_asset_content","list_invalid_refs"],io=["list","rename","remove"],ao=["workspace_info","network","changelog","conf","sys_fonts","boot_progress","push_msg","push_err_msg","get_version","get_current_time"],co=["list_cards","get_decks","get_cards","review_card","skip_review_card","create_card","add_card","remove_card"],uo=["get_balance","shop","buy"],Ee={notebook:eo,document:to,block:oo,av:no,file:ro,search:so,tag:io,system:ao,flashcard:co,mascot:uo},Gs={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",get_doc:"basic",get_path:"basic",get_hpath:"basic",get_ids:"basic",get_child_blocks:"basic",get_child_docs:"basic",search_docs:"basic",rename:"basic",remove:"advanced",move:"advanced",set_icon:"advanced",set_cover:"advanced",list_tree:"advanced",create_daily_note:"advanced",duplicate:"advanced",remove_batch:"advanced",create_empty:"advanced",heading_to_doc:"advanced",doc_to_heading:"advanced"},block:{get_kramdown:"basic",get_children:"basic",get_attrs:"basic",exists:"basic",info:"basic",append:"basic",prepend:"basic",insert:"basic",update:"basic",delete:"advanced",move:"advanced",set_fold_state:"advanced",transfer_ref:"advanced",set_attrs:"advanced",breadcrumb:"advanced",dom:"advanced",recent_updated:"advanced",word_count:"advanced",batch_insert:"advanced",batch_update:"advanced",append_daily_note:"advanced",prepend_daily_note:"advanced",doc_info:"advanced",docs_info:"advanced"},av:{get:"basic",render_attribute_view:"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_cell:"advanced",batch_set_cells:"advanced",duplicate_block:"advanced"},file:{export_md:"basic",upload_asset:"basic",get_doc_assets:"basic",render_template:"advanced",render_sprig:"advanced",export_resources:"advanced",list_unused_assets:"advanced",get_image_ocr_text:"advanced",remove_unused_assets:"advanced",rename_asset:"advanced",delete_asset:"advanced",set_image_alpha:"advanced"},search:{fulltext:"basic",query_sql:"basic",search_tag:"basic",get_backlinks:"basic",get_backmentions:"basic",search_refs:"advanced",find_replace:"advanced",search_assets:"advanced",get_asset_content:"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",boot_progress:"basic",workspace_info:"advanced",network:"advanced",changelog:"advanced",sys_fonts:"advanced",push_msg:"advanced",push_err_msg:"advanced"},flashcard:{list_cards:"basic",get_decks:"basic",get_cards:"basic",review_card:"advanced",skip_review_card:"advanced",create_card:"advanced",add_card:"advanced",remove_card:"advanced"},mascot:{get_balance:"basic",shop:"basic",buy:"basic"}};function He(e,t){var o;return((o=Gs[e])==null?void 0:o[t])??"advanced"}const Hs={notebook:new Set(["remove","set_permission"]),document:new Set(["remove","move","remove_batch"]),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},ne=(e,t)=>{const o=new Set(t);return e.reduce((n,r)=>(n[r]=o.has(r),n),{})};function En(){return{notebook:{enabled:!0,actions:ne(eo,["list","create","set_open_state","rename","get_conf","set_conf","set_icon","get_permissions","get_child_docs"])},document:{enabled:!0,actions:ne(to,["create","rename","move","get_path","get_hpath","get_ids","get_child_blocks","get_child_docs","set_icon","set_cover","list_tree","search_docs","get_doc","create_daily_note","duplicate","remove_batch","create_empty","heading_to_doc","doc_to_heading"])},block:{enabled:!0,actions:ne(oo,["insert","prepend","append","update","move","set_fold_state","get_kramdown","get_children","transfer_ref","set_attrs","get_attrs","exists","info","breadcrumb","dom","recent_updated","word_count","batch_insert","batch_update","append_daily_note","prepend_daily_note","doc_info","docs_info"])},av:{enabled:!0,actions:ne(no,["get","render_attribute_view","get_attribute_view_keys","get_attribute_view_filter_sort","search","add_rows","remove_rows","add_column","remove_column","set_cell","batch_set_cells","duplicate_block","get_primary_key_values"])},file:{enabled:!0,actions:ne(ro,["upload_asset","render_template","render_sprig","export_md","export_resources","list_unused_assets","get_doc_assets","get_image_ocr_text","remove_unused_assets","rename_asset","delete_asset","set_image_alpha"]),uploadLargeFileThresholdMB:10},search:{enabled:!0,actions:ne(so,["fulltext","query_sql","search_tag","get_backlinks","get_backmentions","search_refs","find_replace","search_assets","get_asset_content","fulltext_asset_content","list_invalid_refs"])},tag:{enabled:!0,actions:ne(io,["list","rename","remove"])},system:{enabled:!0,actions:ne(ao,["network","changelog","conf","sys_fonts","boot_progress","push_msg","push_err_msg","get_version","get_current_time"])},flashcard:{enabled:!0,actions:ne(co,["list_cards","get_decks","get_cards","review_card","skip_review_card","create_card","add_card","remove_card"])},mascot:{enabled:!0,actions:ne(uo,["get_balance","shop","buy"])},userRulesText:"创建文档/日记后主动设图标"}}function Nn(e){return Object.entries(e.actions).filter(([,t])=>t).map(([t])=>t)}function Ne(e,t){return Hs[e].has(t)}const Ys=["none","r","rw","rwd"],No={none:"none",readonly:"r",write:"rw"},Rt="/data/storage/petal/siyuan-plugins-mcp-sisyphus/notebookPermissions",Ws=process.env.SIYUAN_MCP_DEBUG_PERMISSIONS==="1";function st(...e){Ws&&console.error("[MCP]",...e)}function Rn(e){return typeof e=="string"&&Ys.includes(e)}function Js(e){return Rn(e)?e:typeof e=="string"&&e in No?No[e]:"none"}function Ks(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Js(o)]))}function Qs(e,t){if(!e||typeof e!="object"||Array.isArray(e))return!1;const o=Object.entries(e);return o.length!==Object.keys(t).length?!0:o.some(([n,r])=>t[n]!==r)}class zn{constructor(t){ae(this,"permissions",{});ae(this,"client",null);ae(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(Rt)}catch(n){throw st("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,st("Permissions not found in API, using empty state");return}let o;try{o=JSON.parse(t)}catch(n){throw st("Failed to parse permissions JSON from API:",n),new Error(`[Permissions] Permissions file at ${Rt} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}this.permissions=Ks(o),this.loaded=!0,Qs(o,this.permissions)&&await this.save(),st("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(Rt,t),this.loaded=!0}get(t){const o=this.permissions[t];return Rn(o)?o:"rwd"}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 xn=["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.'],Bn=['document(action="create") uses a human-readable target path such as /Inbox/Weekly Note.','Other document actions that use notebook + path expect storage paths returned by document(action="get_path").',"A safe path-based workflow is get_path -> rename/remove/move/get_hpath.",'document(action="get_child_blocks") and document(action="get_child_docs") return direct children for a document ID.',`document(action="set_cover") is a semantic wrapper around the document root block's "title-img" attribute. Omit source 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, get_ids may briefly lag behind create because it depends on SiYuan indexing; retry if needed.",'document(action="get_hpath", 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.'],Fn=['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="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.'],qn=["AV actions operate on real SiYuan attribute views (database blocks), not Markdown tables.","The current MCP AV tool supports operating on existing AVs and duplicating database blocks, but it does not create a brand-new AV from scratch.",'Use strong typed fields such as valueType=text/number/date/checkbox/select when calling av(action="set_cell") or av(action="batch_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 are resolved from existing row/block context; a completely empty AV may be unreadable or unwritable until its owning context can be resolved.",'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.'],jn=['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_template") requires a template path inside the SiYuan workspace; arbitrary local paths like /tmp/... are rejected by the kernel.'],Un=["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 search_tag or tag list results; retry briefly before treating that as a failure."],Zn=["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].','Use system(action="sys_fonts", mode="summary") first, then mode="list" with offset/limit/query for paginated inspection.'],Ln=["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".',"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 writes the "custom-riff-decks" binding first, then calls the riff add-card registration step.',"add_card and remove_card are lower-level deck registration operations on existing content block IDs such as paragraphs or headings; document blocks are rejected.",'flashcard(action="remove_card") requires explicit user confirmation before execution.'],Mn=["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.'],Vn={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."},Gn={create:"Use notebook + path + markdown, where path is human-readable.",rename:"Use either id + title or notebook + path + title.",remove:"Use either id or notebook + path. This action requires explicit user confirmation.",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_hpath:"Use either id or notebook + path. Right after create, a short retry may still be needed while SiYuan indexing catches up.",get_ids:'Use notebook + path, where path is human-readable (same format as action="create"). This is the recommended way to resolve document IDs from paths. Right after create, a short retry may be needed while SiYuan indexing catches up.',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_icon:'Use a document ID + icon. Prefer a Unicode hex code string such as "1f4d4" for 📔; raw emoji characters may not render correctly.',set_cover:'Use a document ID + source, where source is either an http(s) URL or a SiYuan asset path like /assets/foo.png. MCP stores it in the "title-img" attribute. Omit source to clear the cover.',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."},Hn={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#.',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.",exists:"Returns a boolean existence check for a block ID.",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."},Yn={get:"Use an attribute view ID. Returns the full AV payload after permission checks.",render_attribute_view:"Use id plus optional blockID/viewID/page/pageSize/query to render database rows with the active view context.",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 rows. MCP now polls briefly after insertion and only reports success when each source blockID resolves to exactly one writable rowID. Optional blockID/viewID/groupID/previousID refine the insertion target. To add a row with initial cell values, follow add_rows with av(action="batch_set_cells", avID, items=[{rowID, columnID, valueType, ...}, ...]); reuse the rowID returned by add_rows (each blockID maps to exactly one rowID).',remove_rows:"Use avID + srcIDs to remove rows from the AV.",add_column:'Use avID + keyName + keyType, and optionally keyID. MCP generates keyID automatically when omitted. Supported keyType values match the 16 SiYuan addable column types, including keyType="mSelect", keyType="mAsset", and keyType="lineNumber".',remove_column:"Use avID + keyID. removeRelationDest only matters for relation columns.",set_cell:'Use avID + rowID + columnID + valueType and the matching typed field. rowID must be the AV row item ID stored in value.blockID, not value.id or the bound source block ID. valueType="mAsset" accepts assets[] plus optional text markdown.',batch_set_cells:'Use avID + items[]. Each item requires rowID + columnID + valueType and its matching typed field. MCP rejects cell value IDs and source block IDs, and suggests the matching row item ID when it can. valueType="mAsset" accepts assets[].',duplicate_block:"MCP first calls the kernel duplicate API, then inserts the duplicated NodeAttributeView block into the document tree. By default it inserts after the source database block; provide previousID to override the insertion target.",get_primary_key_values:"Returns the AV name plus primary-key rows, with optional keyword/page/pageSize filtering."},Wn={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_template:"Use id + path, where path points to a template file inside the SiYuan workspace. Local filesystem paths outside the workspace are rejected by the kernel.",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.",get_doc_assets:'Use a document ID to list assets referenced by the document after read-permission checks. Use assetType="image" to return only 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."},Jn=["All search actions are read-only and do not modify any data.",'search(action="query_sql") only accepts SELECT statements; mutation queries will be rejected, and returned rows are filtered by notebook permission.',"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. sortBy ("relevance", "date") is a shorthand for numeric 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."],Kn={fulltext:'Pass a query string. Supports keyword, query syntax, SQL, and regex modes via the method parameter. Set stripHtml=true to add plain-text fields. 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. Always use LIMIT to control result size. MCP returns rows plus metadata such as rowCount and possible permission-filtering info.",search_tag:"Returns all tags matching the given keyword prefix. Real tags must be written as #tag# in markdown, and very recent tags may need a brief retry while indexing catches up.",get_backlinks:"Returns documents/blocks that contain a reference ((ref)) to the given block ID. Partial permission-filtered results include machine-readable metadata.",get_backmentions:"Returns documents/blocks that mention the name of the given block (text mention, not ref link). Partial permission-filtered results include machine-readable metadata."},Qn={list:"Optional sort, ignoreMaxListHint, and app are passed through to SiYuan.",rename:"Renames a workspace tag label everywhere it appears.",remove:"Deletes a workspace tag label. This action requires explicit user confirmation."},Xn={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.",changelog:"Returns show/html fields for the current version changelog when available.",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].',sys_fonts:'Defaults to a summary. Use mode="list" with offset/limit/query to page through font names.',boot_progress:"Returns progress plus human-readable details.",push_msg:"Show a notification in the SiYuan UI. Optional timeout is in milliseconds.",push_err_msg:"Show an 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."},er={list_cards:'Use scope="all" | "deck" | "notebook" | "tree" plus filter="due" | "new" | "old". For scope="deck", pass deckID. For scope="notebook", pass notebook. For scope="tree", pass rootID.',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. reviewedCards is optional and passed through to the kernel as-is.",skip_review_card:"Use deckID + cardID to skip the current card in a review flow.",create_card:"Use deckID + blockIDs to turn existing blocks into flashcards. MCP writes custom-riff-decks first, then registers the riff cards.",add_card:"Use deckID + blockIDs for the lower-level riff registration step. If you want the block to become a real flashcard end-to-end, prefer create_card.",remove_card:"Use deckID + blockIDs to remove existing blocks from a deck. This action requires explicit user confirmation."},tr={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."},or={notebook:xn,document:Bn,block:Fn,av:qn,file:jn,search:Jn,tag:Un,system:Zn,flashcard:Ln,mascot:Mn},Ye={notebook:Vn,document:Gn,block:Hn,av:Yn,file:Wn,search:Kn,tag:Qn,system:Xn,flashcard:er,mascot:tr};function Xs(e,t){var o;if(!(!e||!t)&&e in Ye)return(o=Ye[e])==null?void 0:o[t]}function m(e,t,o){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const u=i.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){const f=d[p];f in a||(a[f]=u[f].bind(a))}}const r=(o==null?void 0:o.Parent)??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function i(a){var c;const u=o!=null&&o.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>{var c,u;return o!=null&&o.Parent&&a instanceof o.Parent?!0:(u=(c=a==null?void 0:a._zod)==null?void 0:c.traits)==null?void 0:u.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}class Oe extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nr extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const rr={};function pe(e){return rr}function sr(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 Mt(e,t){return typeof t=="bigint"?t.toString():t}function lo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function po(e){return e==null}function fo(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function ei(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,i=Number.parseInt(e.toFixed(s).replace(".","")),a=Number.parseInt(t.toFixed(s).replace(".",""));return i%a/10**s}const Ro=Symbol("evaluating");function O(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==Ro)return n===void 0&&(n=Ro,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function De(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function he(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function zo(e){return JSON.stringify(e)}function ti(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ir="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const oi=lo(()=>{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 Re(e){if(lt(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(lt(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function ar(e){return Re(e)?{...e}:Array.isArray(e)?[...e]:e}const ni=new Set(["string","number","symbol"]);function ze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function me(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 I(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 ri(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const si={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 ii(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=he(e._zod.def,{get shape(){const i={};for(const a in t){if(!(a in o.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=o.shape[a])}return De(this,"shape",i),i},checks:[]});return me(e,s)}function ai(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=he(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const a in t){if(!(a in o.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete i[a]}return De(this,"shape",i),i},checks:[]});return me(e,s)}function ci(e,t){if(!Re(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 i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=he(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return De(this,"shape",s),s}});return me(e,r)}function ui(e,t){if(!Re(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=he(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return De(this,"shape",n),n}});return me(e,o)}function di(e,t){const o=he(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return De(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return me(e,o)}function li(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 i=he(t._zod.def,{get shape(){const a=t._zod.def.shape,c={...a};if(o)for(const u in o){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);o[u]&&(c[u]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(const u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return De(this,"shape",c),c},checks:[]});return me(t,i)}function pi(e,t,o){const n=he(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(o)for(const i in o){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);o[i]&&(s[i]=new e({type:"nonoptional",innerType:r[i]}))}else for(const i in r)s[i]=new e({type:"nonoptional",innerType:r[i]});return De(this,"shape",s),s}});return me(t,n)}function Ae(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 Te(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function it(e){return typeof e=="string"?e:e==null?void 0:e.message}function fe(e,t,o){var r,s,i,a,c,u;const n={...e,path:e.path??[]};if(!e.message){const d=it((i=(s=(r=e.inst)==null?void 0:r._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,e))??it((a=t==null?void 0:t.error)==null?void 0:a.call(t,e))??it((c=o.customError)==null?void 0:c.call(o,e))??it((u=o.localeError)==null?void 0:u.call(o,e))??"Invalid input";n.message=d}return delete n.inst,delete n.continue,t!=null&&t.reportInput||delete n.input,n}function ho(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function We(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const cr=(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,Mt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ur=m("$ZodError",cr),dr=m("$ZodError",cr,{Parent:Error});function fi(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 hi(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(i=>n({issues:i}));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 i=o,a=0;for(;a<s.path.length;){const c=s.path[a];a===s.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(t(s))):i[c]=i[c]||{_errors:[]},i=i[c],a++}}};return n(e),o}const mo=e=>(t,o,n,r)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:o,issues:[]},s);if(i instanceof Promise)throw new Oe;if(i.issues.length){const a=new((r==null?void 0:r.Err)??e)(i.issues.map(c=>fe(c,s,pe())));throw ir(a,r==null?void 0:r.callee),a}return i.value},yo=e=>async(t,o,n,r)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:o,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new((r==null?void 0:r.Err)??e)(i.issues.map(c=>fe(c,s,pe())));throw ir(a,r==null?void 0:r.callee),a}return i.value},vt=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 Oe;return s.issues.length?{success:!1,error:new(e??ur)(s.issues.map(i=>fe(i,r,pe())))}:{success:!0,data:s.value}},mi=vt(dr),Dt=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(i=>fe(i,r,pe())))}:{success:!0,data:s.value}},yi=Dt(dr),gi=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return mo(e)(t,o,r)},bi=e=>(t,o,n)=>mo(e)(t,o,n),ki=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return yo(e)(t,o,r)},_i=e=>async(t,o,n)=>yo(e)(t,o,n),wi=e=>(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return vt(e)(t,o,r)},Ii=e=>(t,o,n)=>vt(e)(t,o,n),vi=e=>async(t,o,n)=>{const r=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Dt(e)(t,o,r)},Di=e=>async(t,o,n)=>Dt(e)(t,o,n),Si=/^[cC][^\s-]{8,}$/,Ai=/^[0-9a-z]+$/,Ti=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Pi=/^[0-9a-vA-V]{20}$/,Ci=/^[A-Za-z0-9]{27}$/,Oi=/^[a-zA-Z0-9_-]{21}$/,$i=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ei=/^([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})$/,xo=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)$/,Ni=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ri="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function zi(){return new RegExp(Ri,"u")}const xi=/^(?:(?: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])$/,Bi=/^(([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}|:))$/,Fi=/^((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])$/,qi=/^(([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])$/,ji=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,lr=/^[A-Za-z0-9_-]*$/,Ui=/^\+[1-9]\d{6,14}$/,pr="(?:(?:\\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])))",Zi=new RegExp(`^${pr}$`);function fr(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 Li(e){return new RegExp(`^${fr(e)}$`)}function Mi(e){const t=fr({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(`^${pr}T(?:${n})$`)}const Vi=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}$`)},Gi=/^-?\d+$/,hr=/^-?\d+(?:\.\d+)?$/,Hi=/^(?:true|false)$/i,Yi=/^[^A-Z]*$/,Wi=/^[^a-z]*$/,J=m("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),mr={number:"number",bigint:"bigint",object:"date"},yr=m("$ZodCheckLessThan",(e,t)=>{J.init(e,t);const o=mr[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})}}),gr=m("$ZodCheckGreaterThan",(e,t)=>{J.init(e,t);const o=mr[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})}}),Ji=m("$ZodCheckMultipleOf",(e,t)=>{J.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):ei(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})}}),Ki=m("$ZodCheckNumberFormat",(e,t)=>{var i;J.init(e,t),t.format=t.format||"float64";const o=(i=t.format)==null?void 0:i.includes("int"),n=o?"int":"number",[r,s]=si[t.format];e._zod.onattach.push(a=>{const c=a._zod.bag;c.format=t.format,c.minimum=r,c.maximum=s,o&&(c.pattern=Gi)}),e._zod.check=a=>{const c=a.value;if(o){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.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}):a.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&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>s&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Qi=m("$ZodCheckMaxLength",(e,t)=>{var o;J.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!po(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 i=ho(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Xi=m("$ZodCheckMinLength",(e,t)=>{var o;J.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!po(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 i=ho(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ea=m("$ZodCheckLengthEquals",(e,t)=>{var o;J.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!po(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 i=ho(r),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),St=m("$ZodCheckStringFormat",(e,t)=>{var o,n;J.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=()=>{})}),ta=m("$ZodCheckRegex",(e,t)=>{St.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})}}),oa=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Yi),St.init(e,t)}),na=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Wi),St.init(e,t)}),ra=m("$ZodCheckIncludes",(e,t)=>{J.init(e,t);const o=ze(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})}}),sa=m("$ZodCheckStartsWith",(e,t)=>{J.init(e,t);const o=new RegExp(`^${ze(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})}}),ia=m("$ZodCheckEndsWith",(e,t)=>{J.init(e,t);const o=new RegExp(`.*${ze(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})}}),aa=m("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class ca{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(`
45
+ `).filter(i=>i),r=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}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(`
46
+ `))}}const ua={major:4,minor:3,patch:6},B=m("$ZodType",(e,t)=>{var r;var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ua;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const s of n)for(const i of s._zod.onattach)i(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=(a,c,u)=>{let d=Ae(a),p;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(a))continue}else if(d)continue;const k=a.issues.length,_=f._zod.check(a);if(_ instanceof Promise&&(u==null?void 0:u.async)===!1)throw new Oe;if(p||_ instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await _,a.issues.length!==k&&(d||(d=Ae(a,k)))});else{if(a.issues.length===k)continue;d||(d=Ae(a,k))}}return p?p.then(()=>a):a},i=(a,c,u)=>{if(Ae(a))return a.aborted=!0,a;const d=s(c,n,u);if(d instanceof Promise){if(u.async===!1)throw new Oe;return d.then(p=>e._zod.parse(p,u))}return e._zod.parse(d,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){const d=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(p=>i(p,a,c)):i(d,a,c)}const u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new Oe;return u.then(d=>s(d,n,c))}return s(u,n,c)}}O(e,"~standard",()=>({validate:s=>{var i;try{const a=mi(e,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return yi(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}))}),go=m("$ZodString",(e,t)=>{var o;B.init(e,t),e._zod.pattern=[...((o=e==null?void 0:e._zod.bag)==null?void 0:o.patterns)??[]].pop()??Vi(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}}),R=m("$ZodStringFormat",(e,t)=>{St.init(e,t),go.init(e,t)}),da=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ei),R.init(e,t)}),la=m("$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=xo(n))}else t.pattern??(t.pattern=xo());R.init(e,t)}),pa=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ni),R.init(e,t)}),fa=m("$ZodURL",(e,t)=>{R.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})}}}),ha=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=zi()),R.init(e,t)}),ma=m("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Oi),R.init(e,t)}),ya=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Si),R.init(e,t)}),ga=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ai),R.init(e,t)}),ba=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ti),R.init(e,t)}),ka=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Pi),R.init(e,t)}),_a=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ci),R.init(e,t)}),wa=m("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Mi(t)),R.init(e,t)}),Ia=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Zi),R.init(e,t)}),va=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Li(t)),R.init(e,t)}),Da=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=$i),R.init(e,t)}),Sa=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=xi),R.init(e,t),e._zod.bag.format="ipv4"}),Aa=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Bi),R.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})}}}),Ta=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fi),R.init(e,t)}),Pa=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=qi),R.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 i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>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 br(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Ca=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ji),R.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{br(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function Oa(e){if(!lr.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return br(o)}const $a=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=lr),R.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{Oa(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),Ea=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ui),R.init(e,t)});function Na(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 Ra=m("$ZodJWT",(e,t)=>{R.init(e,t),e._zod.check=o=>{Na(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),kr=m("$ZodNumber",(e,t)=>{B.init(e,t),e._zod.pattern=e._zod.bag.pattern??hr,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}}),za=m("$ZodNumberFormat",(e,t)=>{Ki.init(e,t),kr.init(e,t)}),xa=m("$ZodBoolean",(e,t)=>{B.init(e,t),e._zod.pattern=Hi,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}}),Ba=m("$ZodUnknown",(e,t)=>{B.init(e,t),e._zod.parse=o=>o}),Fa=m("$ZodNever",(e,t)=>{B.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function Bo(e,t,o){e.issues.length&&t.issues.push(...Te(o,e.issues)),t.value[o]=e.value}const qa=m("$ZodArray",(e,t)=>{B.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 i=0;i<r.length;i++){const a=r[i],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Bo(u,o,i))):Bo(c,o,i)}return s.length?Promise.all(s).then(()=>o):o}});function pt(e,t,o,n,r){if(e.issues.length){if(r&&!(o in n))return;t.issues.push(...Te(o,e.issues))}e.value===void 0?o in n&&(t.value[o]=void 0):t.value[o]=e.value}function _r(e){var n,r,s,i;const t=Object.keys(e.shape);for(const a of t)if(!((i=(s=(r=(n=e.shape)==null?void 0:n[a])==null?void 0:r._zod)==null?void 0:s.traits)!=null&&i.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const o=ri(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function wr(e,t,o,n,r,s){const i=[],a=r.keySet,c=r.catchall._zod,u=c.def.type,d=c.optout==="optional";for(const p in t){if(a.has(p))continue;if(u==="never"){i.push(p);continue}const f=c.run({value:t[p],issues:[]},n);f instanceof Promise?e.push(f.then(k=>pt(k,o,p,t,d))):pt(f,o,p,t,d)}return i.length&&o.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>o):o}const ja=m("$ZodObject",(e,t)=>{B.init(e,t);const o=Object.getOwnPropertyDescriptor(t,"shape");if(!(o!=null&&o.get)){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=lo(()=>_r(t));O(e._zod,"propValues",()=>{const a=t.shape,c={};for(const u in a){const d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(const p of d.values)c[u].add(p)}}return c});const r=lt,s=t.catchall;let i;e._zod.parse=(a,c)=>{i??(i=n.value);const u=a.value;if(!r(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};const d=[],p=i.shape;for(const f of i.keys){const k=p[f],_=k._zod.optout==="optional",w=k._zod.run({value:u[f],issues:[]},c);w instanceof Promise?d.push(w.then(T=>pt(T,a,f,u,_))):pt(w,a,f,u,_)}return s?wr(d,u,a,c,n.value,e):d.length?Promise.all(d).then(()=>a):a}}),Ua=m("$ZodObjectJIT",(e,t)=>{ja.init(e,t);const o=e._zod.parse,n=lo(()=>_r(t)),r=f=>{var M;const k=new ca(["shape","payload","ctx"]),_=n.value,w=D=>{const P=zo(D);return`shape[${P}]._zod.run({ value: input[${P}], issues: [] }, ctx)`};k.write("const input = payload.value;");const T=Object.create(null);let z=0;for(const D of _.keys)T[D]=`key_${z++}`;k.write("const newResult = {};");for(const D of _.keys){const P=T[D],U=zo(D),C=f[D],ge=((M=C==null?void 0:C._zod)==null?void 0:M.optout)==="optional";k.write(`const ${P} = ${w(D)};`),ge?k.write(`
47
+ if (${P}.issues.length) {
48
+ if (${U} in input) {
49
+ payload.issues = payload.issues.concat(${P}.issues.map(iss => ({
50
+ ...iss,
51
+ path: iss.path ? [${U}, ...iss.path] : [${U}]
52
+ })));
53
+ }
54
+ }
55
+
56
+ if (${P}.value === undefined) {
57
+ if (${U} in input) {
58
+ newResult[${U}] = undefined;
59
+ }
60
+ } else {
61
+ newResult[${U}] = ${P}.value;
62
+ }
63
+
64
+ `):k.write(`
65
+ if (${P}.issues.length) {
66
+ payload.issues = payload.issues.concat(${P}.issues.map(iss => ({
67
+ ...iss,
68
+ path: iss.path ? [${U}, ...iss.path] : [${U}]
69
+ })));
70
+ }
71
+
72
+ if (${P}.value === undefined) {
73
+ if (${U} in input) {
74
+ newResult[${U}] = undefined;
75
+ }
76
+ } else {
77
+ newResult[${U}] = ${P}.value;
78
+ }
79
+
80
+ `)}k.write("payload.value = newResult;"),k.write("return payload;");const j=k.compile();return(D,P)=>j(f,D,P)};let s;const i=lt,a=!rr.jitless,u=a&&oi.value,d=t.catchall;let p;e._zod.parse=(f,k)=>{p??(p=n.value);const _=f.value;return i(_)?a&&u&&(k==null?void 0:k.async)===!1&&k.jitless!==!0?(s||(s=r(t.shape)),f=s(f,k),d?wr([],_,f,k,p,e):f):o(f,k):(f.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),f)}});function Fo(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=>!Ae(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(i=>fe(i,n,pe())))}),t)}const Za=m("$ZodUnion",(e,t)=>{B.init(e,t),O(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),O(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),O(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),O(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=>fo(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 i=!1;const a=[];for(const c of t.options){const u=c._zod.run({value:r.value,issues:[]},s);if(u instanceof Promise)a.push(u),i=!0;else{if(u.issues.length===0)return u;a.push(u)}}return i?Promise.all(a).then(c=>Fo(c,r,e,s)):Fo(a,r,e,s)}}),La=m("$ZodIntersection",(e,t)=>{B.init(e,t),e._zod.parse=(o,n)=>{const r=o.value,s=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>qo(o,c,u)):qo(o,s,i)}});function Vt(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(Re(e)&&Re(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 i=Vt(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r[s]=i.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],i=Vt(r,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};o.push(i.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function qo(e,t,o){const n=new Map;let r;for(const a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(const c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(const a of o.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);const s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&r&&e.issues.push({...r,keys:s}),Ae(e))return e;const i=Vt(t.value,o.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const Ma=m("$ZodRecord",(e,t)=>{B.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Re(r))return o.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),o;const s=[],i=t.keyType._zod.values;if(i){o.value={};const a=new Set;for(const u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);const d=t.valueType._zod.run({value:r[u],issues:[]},n);d instanceof Promise?s.push(d.then(p=>{p.issues.length&&o.issues.push(...Te(u,p.issues)),o.value[u]=p.value})):(d.issues.length&&o.issues.push(...Te(u,d.issues)),o.value[u]=d.value)}let c;for(const u in r)a.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 a of Reflect.ownKeys(r)){if(a==="__proto__")continue;let c=t.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&hr.test(a)&&c.issues.length){const p=t.keyType._zod.run({value:Number(a),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(c=p)}if(c.issues.length){t.mode==="loose"?o.value[a]=r[a]:o.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(p=>fe(p,n,pe())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:r[a],issues:[]},n);d instanceof Promise?s.push(d.then(p=>{p.issues.length&&o.issues.push(...Te(a,p.issues)),o.value[c.value]=p.value})):(d.issues.length&&o.issues.push(...Te(a,d.issues)),o.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>o):o}}),Va=m("$ZodEnum",(e,t)=>{B.init(e,t);const o=sr(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>ni.has(typeof r)).map(r=>typeof r=="string"?ze(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:o,input:i,inst:e}),r}}),Ga=m("$ZodLiteral",(e,t)=>{if(B.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"?ze(n):n?ze(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}}),Ha=m("$ZodTransform",(e,t)=>{B.init(e,t),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new nr(e.constructor.name);const r=t.transform(o.value,o);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(o.value=i,o));if(r instanceof Promise)throw new Oe;return o.value=r,o}});function jo(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Ir=m("$ZodOptional",(e,t)=>{B.init(e,t),e._zod.optin="optional",e._zod.optout="optional",O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),O(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${fo(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=>jo(s,o.value)):jo(r,o.value)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),Ya=m("$ZodExactOptional",(e,t)=>{Ir.init(e,t),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),Wa=m("$ZodNullable",(e,t)=>{B.init(e,t),O(e._zod,"optin",()=>t.innerType._zod.optin),O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${fo(o.source)}|null)$`):void 0}),O(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)}),Ja=m("$ZodDefault",(e,t)=>{B.init(e,t),e._zod.optin="optional",O(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=>Uo(s,t)):Uo(r,t)}});function Uo(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ka=m("$ZodPrefault",(e,t)=>{B.init(e,t),e._zod.optin="optional",O(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))}),Qa=m("$ZodNonOptional",(e,t)=>{B.init(e,t),O(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=>Zo(s,e)):Zo(r,e)}});function Zo(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 Xa=m("$ZodCatch",(e,t)=>{B.init(e,t),O(e._zod,"optin",()=>t.innerType._zod.optin),O(e._zod,"optout",()=>t.innerType._zod.optout),O(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(i=>fe(i,n,pe()))},input:o.value}),o.issues=[]),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(s=>fe(s,n,pe()))},input:o.value}),o.issues=[]),o)}}),ec=m("$ZodPipe",(e,t)=>{B.init(e,t),O(e._zod,"values",()=>t.in._zod.values),O(e._zod,"optin",()=>t.in._zod.optin),O(e._zod,"optout",()=>t.out._zod.optout),O(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(i=>at(i,t.in,n)):at(s,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(s=>at(s,t.out,n)):at(r,t.out,n)}});function at(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},o)}const tc=m("$ZodReadonly",(e,t)=>{B.init(e,t),O(e._zod,"propValues",()=>t.innerType._zod.propValues),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"optin",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optin}),O(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(Lo):Lo(r)}});function Lo(e){return e.value=Object.freeze(e.value),e}const oc=m("$ZodCustom",(e,t)=>{J.init(e,t),B.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=>Mo(s,o,n,e));Mo(r,o,n,e)}});function Mo(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(We(r))}}var Vo;class nc{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 rc(){return new nc}(Vo=globalThis).__zod_globalRegistry??(Vo.__zod_globalRegistry=rc());const Me=globalThis.__zod_globalRegistry;function sc(e,t){return new e({type:"string",...I(t)})}function ic(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...I(t)})}function Go(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...I(t)})}function ac(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...I(t)})}function cc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(t)})}function uc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(t)})}function dc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(t)})}function lc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...I(t)})}function pc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...I(t)})}function fc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(t)})}function hc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...I(t)})}function mc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(t)})}function yc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...I(t)})}function gc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...I(t)})}function bc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(t)})}function kc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(t)})}function _c(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(t)})}function wc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(t)})}function Ic(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(t)})}function vc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...I(t)})}function Dc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...I(t)})}function Sc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...I(t)})}function Ac(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...I(t)})}function Tc(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(t)})}function Pc(e,t){return new e({type:"string",format:"date",check:"string_format",...I(t)})}function Cc(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...I(t)})}function Oc(e,t){return new e({type:"string",format:"duration",check:"string_format",...I(t)})}function $c(e,t){return new e({type:"number",checks:[],...I(t)})}function Ec(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...I(t)})}function Nc(e,t){return new e({type:"boolean",...I(t)})}function Rc(e){return new e({type:"unknown"})}function zc(e,t){return new e({type:"never",...I(t)})}function Ho(e,t){return new yr({check:"less_than",...I(t),value:e,inclusive:!1})}function zt(e,t){return new yr({check:"less_than",...I(t),value:e,inclusive:!0})}function Yo(e,t){return new gr({check:"greater_than",...I(t),value:e,inclusive:!1})}function xt(e,t){return new gr({check:"greater_than",...I(t),value:e,inclusive:!0})}function Wo(e,t){return new Ji({check:"multiple_of",...I(t),value:e})}function vr(e,t){return new Qi({check:"max_length",...I(t),maximum:e})}function ft(e,t){return new Xi({check:"min_length",...I(t),minimum:e})}function Dr(e,t){return new ea({check:"length_equals",...I(t),length:e})}function xc(e,t){return new ta({check:"string_format",format:"regex",...I(t),pattern:e})}function Bc(e){return new oa({check:"string_format",format:"lowercase",...I(e)})}function Fc(e){return new na({check:"string_format",format:"uppercase",...I(e)})}function qc(e,t){return new ra({check:"string_format",format:"includes",...I(t),includes:e})}function jc(e,t){return new sa({check:"string_format",format:"starts_with",...I(t),prefix:e})}function Uc(e,t){return new ia({check:"string_format",format:"ends_with",...I(t),suffix:e})}function je(e){return new aa({check:"overwrite",tx:e})}function Zc(e){return je(t=>t.normalize(e))}function Lc(){return je(e=>e.trim())}function Mc(){return je(e=>e.toLowerCase())}function Vc(){return je(e=>e.toUpperCase())}function Gc(){return je(e=>ti(e))}function Hc(e,t,o){return new e({type:"array",element:t,...I(o)})}function Yc(e,t,o){return new e({type:"custom",check:"custom",fn:t,...I(o)})}function Wc(e){const t=Jc(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(We(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(We(r))}},e(o.value,o)));return t}function Jc(e,t){const o=new J({check:"custom",...I(t)});return o._zod.check=e,o}function Sr(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)??Me,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 L(e,t,o={path:[],schemaPath:[]}){var d,p;var n;const r=e._zod.def,s=t.seen.get(e);if(s)return s.count++,o.schemaPath.includes(e)&&(s.cycle=o.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:o.path};t.seen.set(e,i);const a=(p=(d=e._zod).toJSONSchema)==null?void 0:p.call(d);if(a)i.schema=a;else{const f={...o,schemaPath:[...o.schemaPath,e],path:o.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,f);else{const _=i.schema,w=t.processors[r.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);w(e,t,_,f)}const k=e._zod.parent;k&&(i.ref||(i.ref=k),L(k,t,f),t.seen.get(k).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&Y(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Ar(e,t){var i,a,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 d of e.seen.entries()){const p=(i=e.metadataRegistry.get(d[0]))==null?void 0:i.id;if(p){const f=n.get(p);if(f&&f!==d[0])throw new Error(`Duplicate schema id "${p}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(p,d[0])}}const r=d=>{var w;const p=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const T=(w=e.external.registry.get(d[0]))==null?void 0:w.id,z=e.external.uri??(M=>M);if(T)return{ref:z(T)};const j=d[1].defId??d[1].schema.id??`schema${e.counter++}`;return d[1].defId=j,{defId:j,ref:`${z("__shared")}#/${p}/${j}`}}if(d[1]===o)return{ref:"#"};const k=`#/${p}/`,_=d[1].schema.id??`__schema${e.counter++}`;return{defId:_,ref:k+_}},s=d=>{if(d[1].schema.$ref)return;const p=d[1],{ref:f,defId:k}=r(d);p.def={...p.schema},k&&(p.defId=k);const _=p.schema;for(const w in _)delete _[w];_.$ref=f};if(e.cycles==="throw")for(const d of e.seen.entries()){const p=d[1];if(p.cycle)throw new Error(`Cycle detected: #/${(a=p.cycle)==null?void 0:a.join("/")}/<root>
81
+
82
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of e.seen.entries()){const p=d[1];if(t===d[0]){s(d);continue}if(e.external){const k=(c=e.external.registry.get(d[0]))==null?void 0:c.id;if(t!==d[0]&&k){s(d);continue}}if((u=e.metadataRegistry.get(d[0]))==null?void 0:u.id){s(d);continue}if(p.cycle){s(d);continue}if(p.count>1&&e.reused==="ref"){s(d);continue}}}function Tr(e,t){var i,a,c;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=u=>{const d=e.seen.get(u);if(d.ref===null)return;const p=d.def??d.schema,f={...p},k=d.ref;if(d.ref=null,k){n(k);const w=e.seen.get(k),T=w.schema;if(T.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(T)):Object.assign(p,T),Object.assign(p,f),u._zod.parent===k)for(const j in p)j==="$ref"||j==="allOf"||j in f||delete p[j];if(T.$ref&&w.def)for(const j in p)j==="$ref"||j==="allOf"||j in w.def&&JSON.stringify(p[j])===JSON.stringify(w.def[j])&&delete p[j]}const _=u._zod.parent;if(_&&_!==k){n(_);const w=e.seen.get(_);if(w!=null&&w.schema.$ref&&(p.$ref=w.schema.$ref,w.def))for(const T in p)T==="$ref"||T==="allOf"||T in w.def&&JSON.stringify(p[T])===JSON.stringify(w.def[T])&&delete p[T]}e.override({zodSchema:u,jsonSchema:p,path:d.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,(i=e.external)!=null&&i.uri){const u=(a=e.external.registry.get(t))==null?void 0:a.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 d=u[1];d.def&&d.defId&&(s[d.defId]=d.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:ht(t,"input",e.processors),output:ht(t,"output",e.processors)}},enumerable:!1,writable:!1}),u}catch{throw new Error("Error converting schema to JSON.")}}function Y(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 Y(n.element,o);if(n.type==="set")return Y(n.valueType,o);if(n.type==="lazy")return Y(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 Y(n.innerType,o);if(n.type==="intersection")return Y(n.left,o)||Y(n.right,o);if(n.type==="record"||n.type==="map")return Y(n.keyType,o)||Y(n.valueType,o);if(n.type==="pipe")return Y(n.in,o)||Y(n.out,o);if(n.type==="object"){for(const r in n.shape)if(Y(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(Y(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(Y(r,o))return!0;return!!(n.rest&&Y(n.rest,o))}return!1}const Kc=(e,t={})=>o=>{const n=Sr({...o,processors:t});return L(e,n),Ar(n,e),Tr(n,e)},ht=(e,t,o={})=>n=>{const{libraryOptions:r,target:s}=n??{},i=Sr({...r??{},target:s,io:t,processors:o});return L(e,i),Ar(i,e),Tr(i,e)},Qc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xc=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof i=="number"&&(r.maxLength=i),a&&(r.format=Qc[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),u&&(r.contentEncoding=u),c&&c.size>0){const d=[...c];d.length===1?r.pattern=d[0].source:d.length>1&&(r.allOf=[...d.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},eu=(e,t,o,n)=>{const r=o,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number",typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d),typeof s=="number"&&(r.minimum=s,typeof d=="number"&&t.target!=="draft-04"&&(d>=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 i=="number"&&(r.maximum=i,typeof u=="number"&&t.target!=="draft-04"&&(u<=i?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},tu=(e,t,o,n)=>{o.type="boolean"},ou=(e,t,o,n)=>{o.not={}},nu=(e,t,o,n)=>{},ru=(e,t,o,n)=>{const r=e._zod.def,s=sr(r.entries);s.every(i=>typeof i=="number")&&(o.type="number"),s.every(i=>typeof i=="string")&&(o.type="string"),o.enum=s},su=(e,t,o,n)=>{const r=e._zod.def,s=[];for(const i of r.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];o.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?o.enum=[i]:o.const=i}else s.every(i=>typeof i=="number")&&(o.type="number"),s.every(i=>typeof i=="string")&&(o.type="string"),s.every(i=>typeof i=="boolean")&&(o.type="boolean"),s.every(i=>i===null)&&(o.type="null"),o.enum=s},iu=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},au=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},cu=(e,t,o,n)=>{const r=o,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(r.minItems=i),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=L(s.element,t,{...n,path:[...n.path,"items"]})},uu=(e,t,o,n)=>{var u;const r=o,s=e._zod.def;r.type="object",r.properties={};const i=s.shape;for(const d in i)r.properties[d]=L(i[d],t,{...n,path:[...n.path,"properties",d]});const a=new Set(Object.keys(i)),c=new Set([...a].filter(d=>{const p=s.shape[d]._zod;return t.io==="input"?p.optin===void 0:p.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=L(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},du=(e,t,o,n)=>{const r=e._zod.def,s=r.inclusive===!1,i=r.options.map((a,c)=>L(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?o.oneOf=i:o.anyOf=i},lu=(e,t,o,n)=>{const r=e._zod.def,s=L(r.left,t,{...n,path:[...n.path,"allOf",0]}),i=L(r.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];o.allOf=c},pu=(e,t,o,n)=>{const r=o,s=e._zod.def;r.type="object";const i=s.keyType,a=i._zod.bag,c=a==null?void 0:a.patterns;if(s.mode==="loose"&&c&&c.size>0){const d=L(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const p of c)r.patternProperties[p.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=L(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=L(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const u=i._zod.values;if(u){const d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(r.required=d)}},fu=(e,t,o,n)=>{const r=e._zod.def,s=L(r.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=r.innerType,o.nullable=!0):o.anyOf=[s,{type:"null"}]},hu=(e,t,o,n)=>{const r=e._zod.def;L(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},mu=(e,t,o,n)=>{const r=e._zod.def;L(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},yu=(e,t,o,n)=>{const r=e._zod.def;L(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)))},gu=(e,t,o,n)=>{const r=e._zod.def;L(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}o.default=i},bu=(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;L(s,t,n);const i=t.seen.get(e);i.ref=s},ku=(e,t,o,n)=>{const r=e._zod.def;L(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.readOnly=!0},Pr=(e,t,o,n)=>{const r=e._zod.def;L(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},_u=m("ZodISODateTime",(e,t)=>{wa.init(e,t),q.init(e,t)});function wu(e){return Tc(_u,e)}const Iu=m("ZodISODate",(e,t)=>{Ia.init(e,t),q.init(e,t)});function vu(e){return Pc(Iu,e)}const Du=m("ZodISOTime",(e,t)=>{va.init(e,t),q.init(e,t)});function Su(e){return Cc(Du,e)}const Au=m("ZodISODuration",(e,t)=>{Da.init(e,t),q.init(e,t)});function Tu(e){return Oc(Au,e)}const Cr=(e,t)=>{ur.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>hi(e,o)},flatten:{value:o=>fi(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,Mt,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,Mt,2)}},isEmpty:{get(){return e.issues.length===0}}})},Pu=m("ZodError",Cr),X=m("ZodError",Cr,{Parent:Error}),Cu=mo(X),Ou=yo(X),$u=vt(X),Eu=Dt(X),Nu=gi(X),Ru=bi(X),zu=ki(X),xu=_i(X),Bu=wi(X),Fu=Ii(X),qu=vi(X),ju=Di(X),F=m("ZodType",(e,t)=>(B.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ht(e,"input"),output:ht(e,"output")}}),e.toJSONSchema=Kc(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...o)=>e.clone(he(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)=>me(e,o,n),e.brand=()=>e,e.register=(o,n)=>(o.add(e,n),e),e.parse=(o,n)=>Cu(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>$u(e,o,n),e.parseAsync=async(o,n)=>Ou(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>Eu(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>Nu(e,o,n),e.decode=(o,n)=>Ru(e,o,n),e.encodeAsync=async(o,n)=>zu(e,o,n),e.decodeAsync=async(o,n)=>xu(e,o,n),e.safeEncode=(o,n)=>Bu(e,o,n),e.safeDecode=(o,n)=>Fu(e,o,n),e.safeEncodeAsync=async(o,n)=>qu(e,o,n),e.safeDecodeAsync=async(o,n)=>ju(e,o,n),e.refine=(o,n)=>e.check(Nd(o,n)),e.superRefine=o=>e.check(Rd(o)),e.overwrite=o=>e.check(je(o)),e.optional=()=>Qo(e),e.exactOptional=()=>_d(e),e.nullable=()=>Xo(e),e.nullish=()=>Qo(Xo(e)),e.nonoptional=o=>Ad(e,o),e.array=()=>E(e),e.or=o=>Gt([e,o]),e.and=o=>hd(e,o),e.transform=o=>en(e,bd(o)),e.default=o=>vd(e,o),e.prefault=o=>Sd(e,o),e.catch=o=>Pd(e,o),e.pipe=o=>en(e,o),e.readonly=()=>$d(e),e.describe=o=>{const n=e.clone();return Me.add(n,{description:o}),n},Object.defineProperty(e,"description",{get(){var o;return(o=Me.get(e))==null?void 0:o.description},configurable:!0}),e.meta=(...o)=>{if(o.length===0)return Me.get(e);const n=e.clone();return Me.add(n,o[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=o=>o(e),e)),Or=m("_ZodString",(e,t)=>{go.init(e,t),F.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Xc(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(xc(...n)),e.includes=(...n)=>e.check(qc(...n)),e.startsWith=(...n)=>e.check(jc(...n)),e.endsWith=(...n)=>e.check(Uc(...n)),e.min=(...n)=>e.check(ft(...n)),e.max=(...n)=>e.check(vr(...n)),e.length=(...n)=>e.check(Dr(...n)),e.nonempty=(...n)=>e.check(ft(1,...n)),e.lowercase=n=>e.check(Bc(n)),e.uppercase=n=>e.check(Fc(n)),e.trim=()=>e.check(Lc()),e.normalize=(...n)=>e.check(Zc(...n)),e.toLowerCase=()=>e.check(Mc()),e.toUpperCase=()=>e.check(Vc()),e.slugify=()=>e.check(Gc())}),Uu=m("ZodString",(e,t)=>{go.init(e,t),Or.init(e,t),e.email=o=>e.check(ic(Zu,o)),e.url=o=>e.check(lc(Lu,o)),e.jwt=o=>e.check(Ac(rd,o)),e.emoji=o=>e.check(pc(Mu,o)),e.guid=o=>e.check(Go(Jo,o)),e.uuid=o=>e.check(ac(ct,o)),e.uuidv4=o=>e.check(cc(ct,o)),e.uuidv6=o=>e.check(uc(ct,o)),e.uuidv7=o=>e.check(dc(ct,o)),e.nanoid=o=>e.check(fc(Vu,o)),e.guid=o=>e.check(Go(Jo,o)),e.cuid=o=>e.check(hc(Gu,o)),e.cuid2=o=>e.check(mc(Hu,o)),e.ulid=o=>e.check(yc(Yu,o)),e.base64=o=>e.check(vc(td,o)),e.base64url=o=>e.check(Dc(od,o)),e.xid=o=>e.check(gc(Wu,o)),e.ksuid=o=>e.check(bc(Ju,o)),e.ipv4=o=>e.check(kc(Ku,o)),e.ipv6=o=>e.check(_c(Qu,o)),e.cidrv4=o=>e.check(wc(Xu,o)),e.cidrv6=o=>e.check(Ic(ed,o)),e.e164=o=>e.check(Sc(nd,o)),e.datetime=o=>e.check(wu(o)),e.date=o=>e.check(vu(o)),e.time=o=>e.check(Su(o)),e.duration=o=>e.check(Tu(o))});function l(e){return sc(Uu,e)}const q=m("ZodStringFormat",(e,t)=>{R.init(e,t),Or.init(e,t)}),Zu=m("ZodEmail",(e,t)=>{pa.init(e,t),q.init(e,t)}),Jo=m("ZodGUID",(e,t)=>{da.init(e,t),q.init(e,t)}),ct=m("ZodUUID",(e,t)=>{la.init(e,t),q.init(e,t)}),Lu=m("ZodURL",(e,t)=>{fa.init(e,t),q.init(e,t)}),Mu=m("ZodEmoji",(e,t)=>{ha.init(e,t),q.init(e,t)}),Vu=m("ZodNanoID",(e,t)=>{ma.init(e,t),q.init(e,t)}),Gu=m("ZodCUID",(e,t)=>{ya.init(e,t),q.init(e,t)}),Hu=m("ZodCUID2",(e,t)=>{ga.init(e,t),q.init(e,t)}),Yu=m("ZodULID",(e,t)=>{ba.init(e,t),q.init(e,t)}),Wu=m("ZodXID",(e,t)=>{ka.init(e,t),q.init(e,t)}),Ju=m("ZodKSUID",(e,t)=>{_a.init(e,t),q.init(e,t)}),Ku=m("ZodIPv4",(e,t)=>{Sa.init(e,t),q.init(e,t)}),Qu=m("ZodIPv6",(e,t)=>{Aa.init(e,t),q.init(e,t)}),Xu=m("ZodCIDRv4",(e,t)=>{Ta.init(e,t),q.init(e,t)}),ed=m("ZodCIDRv6",(e,t)=>{Pa.init(e,t),q.init(e,t)}),td=m("ZodBase64",(e,t)=>{Ca.init(e,t),q.init(e,t)}),od=m("ZodBase64URL",(e,t)=>{$a.init(e,t),q.init(e,t)}),nd=m("ZodE164",(e,t)=>{Ea.init(e,t),q.init(e,t)}),rd=m("ZodJWT",(e,t)=>{Ra.init(e,t),q.init(e,t)}),$r=m("ZodNumber",(e,t)=>{kr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(n,r,s)=>eu(e,n,r),e.gt=(n,r)=>e.check(Yo(n,r)),e.gte=(n,r)=>e.check(xt(n,r)),e.min=(n,r)=>e.check(xt(n,r)),e.lt=(n,r)=>e.check(Ho(n,r)),e.lte=(n,r)=>e.check(zt(n,r)),e.max=(n,r)=>e.check(zt(n,r)),e.int=n=>e.check(Ko(n)),e.safe=n=>e.check(Ko(n)),e.positive=n=>e.check(Yo(0,n)),e.nonnegative=n=>e.check(xt(0,n)),e.negative=n=>e.check(Ho(0,n)),e.nonpositive=n=>e.check(zt(0,n)),e.multipleOf=(n,r)=>e.check(Wo(n,r)),e.step=(n,r)=>e.check(Wo(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 A(e){return $c($r,e)}const sd=m("ZodNumberFormat",(e,t)=>{za.init(e,t),$r.init(e,t)});function Ko(e){return Ec(sd,e)}const id=m("ZodBoolean",(e,t)=>{xa.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>tu(e,o,n)});function Z(e){return Nc(id,e)}const ad=m("ZodUnknown",(e,t)=>{Ba.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>nu()});function mt(){return Rc(ad)}const cd=m("ZodNever",(e,t)=>{Fa.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ou(e,o,n)});function ud(e){return zc(cd,e)}const dd=m("ZodArray",(e,t)=>{qa.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>cu(e,o,n,r),e.element=t.element,e.min=(o,n)=>e.check(ft(o,n)),e.nonempty=o=>e.check(ft(1,o)),e.max=(o,n)=>e.check(vr(o,n)),e.length=(o,n)=>e.check(Dr(o,n)),e.unwrap=()=>e.element});function E(e,t){return Hc(dd,e,t)}const ld=m("ZodObject",(e,t)=>{Ua.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>uu(e,o,n,r),O(e,"shape",()=>t.shape),e.keyof=()=>$(Object.keys(e._zod.def.shape)),e.catchall=o=>e.clone({...e._zod.def,catchall:o}),e.passthrough=()=>e.clone({...e._zod.def,catchall:mt()}),e.loose=()=>e.clone({...e._zod.def,catchall:mt()}),e.strict=()=>e.clone({...e._zod.def,catchall:ud()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=o=>ci(e,o),e.safeExtend=o=>ui(e,o),e.merge=o=>di(e,o),e.pick=o=>ii(e,o),e.omit=o=>ai(e,o),e.partial=(...o)=>li(Er,e,o[0]),e.required=(...o)=>pi(Nr,e,o[0])});function h(e,t){const o={type:"object",shape:e??{},...I(t)};return new ld(o)}const pd=m("ZodUnion",(e,t)=>{Za.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>du(e,o,n,r),e.options=t.options});function Gt(e,t){return new pd({type:"union",options:e,...I(t)})}const fd=m("ZodIntersection",(e,t)=>{La.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>lu(e,o,n,r)});function hd(e,t){return new fd({type:"intersection",left:e,right:t})}const md=m("ZodRecord",(e,t)=>{Ma.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>pu(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,o){return new md({type:"record",keyType:e,valueType:t,...I(o)})}const Ht=m("ZodEnum",(e,t)=>{Va.init(e,t),F.init(e,t),e._zod.processJSONSchema=(n,r,s)=>ru(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 i of n)if(o.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ht({...t,checks:[],...I(r),entries:s})},e.exclude=(n,r)=>{const s={...t.entries};for(const i of n)if(o.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ht({...t,checks:[],...I(r),entries:s})}});function $(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ht({type:"enum",entries:o,...I(t)})}const yd=m("ZodLiteral",(e,t)=>{Ga.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>su(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 b(e,t){return new yd({type:"literal",values:Array.isArray(e)?e:[e],...I(t)})}const gd=m("ZodTransform",(e,t)=>{Ha.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>au(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new nr(e.constructor.name);o.addIssue=s=>{if(typeof s=="string")o.issues.push(We(s,o.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=e),o.issues.push(We(i))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(s=>(o.value=s,o)):(o.value=r,o)}});function bd(e){return new gd({type:"transform",transform:e})}const Er=m("ZodOptional",(e,t)=>{Ir.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Pr(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Qo(e){return new Er({type:"optional",innerType:e})}const kd=m("ZodExactOptional",(e,t)=>{Ya.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Pr(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function _d(e){return new kd({type:"optional",innerType:e})}const wd=m("ZodNullable",(e,t)=>{Wa.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>fu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Xo(e){return new wd({type:"nullable",innerType:e})}const Id=m("ZodDefault",(e,t)=>{Ja.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>mu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function vd(e,t){return new Id({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ar(t)}})}const Dd=m("ZodPrefault",(e,t)=>{Ka.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>yu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e,t){return new Dd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ar(t)}})}const Nr=m("ZodNonOptional",(e,t)=>{Qa.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>hu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Ad(e,t){return new Nr({type:"nonoptional",innerType:e,...I(t)})}const Td=m("ZodCatch",(e,t)=>{Xa.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>gu(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pd(e,t){return new Td({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Cd=m("ZodPipe",(e,t)=>{ec.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>bu(e,o,n,r),e.in=t.in,e.out=t.out});function en(e,t){return new Cd({type:"pipe",in:e,out:t})}const Od=m("ZodReadonly",(e,t)=>{tc.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ku(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function $d(e){return new Od({type:"readonly",innerType:e})}const Ed=m("ZodCustom",(e,t)=>{oc.init(e,t),F.init(e,t),e._zod.processJSONSchema=(o,n,r)=>iu(e,o)});function Nd(e,t={}){return Yc(Ed,e,t)}function Rd(e){return Wc(e)}const Q={custom:"custom"},zd=h({name:l().optional(),closed:Z().optional(),refCreateSavePath:l().optional(),createDocNameTemplate:l().optional(),dailyNoteSavePath:l().optional(),dailyNoteTemplatePath:l().optional()}),xd=h({id:l().optional(),notebook:l().optional(),path:l().optional()}),bo=xd.superRefine((e,t)=>{const o=typeof e.id=="string",n=typeof e.notebook=="string"||typeof e.path=="string";if(o===n){t.addIssue({code:Q.custom,message:"Provide either id or notebook + path."});return}n&&(!e.notebook||!e.path)&&t.addIssue({code:Q.custom,message:"Both notebook and path are required when id is not provided."})}),Bd=h({fromPaths:E(l()).optional(),toNotebook:l().optional(),toPath:l().optional(),fromIDs:E(l()).optional(),toID:l().optional()}).superRefine((e,t)=>{const o=Array.isArray(e.fromPaths)||typeof e.toNotebook=="string"||typeof e.toPath=="string",n=Array.isArray(e.fromIDs)||typeof e.toID=="string";if(o===n){t.addIssue({code:Q.custom,message:"Provide either fromPaths + toNotebook + toPath or fromIDs + toID."});return}o&&(!e.fromPaths||!e.toNotebook||!e.toPath)&&t.addIssue({code:Q.custom,message:"fromPaths, toNotebook, and toPath are required for path-based moves."}),n&&(!e.fromIDs||!e.toID)&&t.addIssue({code:Q.custom,message:"fromIDs and toID are required for ID-based moves."})}),Fd=$(eo),qd=$(to),jd=$(oo),Ud=$(no),Zd=$(ro),Ld=$(co),Md=$(uo),Vd=h({action:b("list")}),Gd=h({action:b("create"),name:l().describe("Notebook name"),icon:l().optional().describe("Optional notebook icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}),Hd=h({action:b("set_open_state"),notebook:l().describe("Notebook ID"),opened:Z().describe("true to open, false to close")}),Yd=h({action:b("remove"),notebook:l().describe("Notebook ID")}),Wd=h({action:b("rename"),notebook:l().describe("Notebook ID"),name:l().describe("New notebook name")}),Jd=h({action:b("get_conf"),notebook:l().describe("Notebook ID")}),Kd=h({action:b("set_conf"),notebook:l().describe("Notebook ID"),conf:zd.describe("Notebook configuration")}),Qd=h({action:b("set_icon"),notebook:l().describe("Notebook ID"),icon:l().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.")}),Xd=h({action:b("get_permissions"),notebook:l().optional().describe('Notebook ID, or "all" to return every notebook permission entry. Omit to return all notebooks.')}),el=h({action:b("set_permission"),notebook:l().describe("Notebook ID"),permission:$(["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 (default for new notebooks)')}),tl=h({action:b("get_child_docs"),notebook:l().describe("Notebook ID"),page:A().int().positive().optional().describe("Page number (1-based), default 1"),pageSize:A().int().positive().optional().describe("Rows per page, default 50")}),ol=h({action:b("create"),notebook:l().describe("Notebook ID"),path:l().describe("Human-readable target path, must start with / (e.g., /foo/bar). Parent paths must already exist."),markdown:l().describe("Markdown content"),icon:l().optional().describe("Optional document icon. Prefer a Unicode hex code string such as '1f4d4' for 📔 instead of a raw emoji character.")}),nl=h({action:b("rename"),title:l().describe("New document title")}).and(bo),rl=h({action:b("remove")}).and(bo),sl=h({action:b("move")}).and(Bd),il=h({action:b("get_path"),id:l().describe("Document ID")}),al=h({action:b("get_hpath")}).and(bo),cl=h({action:b("get_ids"),path:l().describe("Human-readable path (e.g., /foo/bar)"),notebook:l().describe("Notebook ID")}),ul=h({action:b("get_child_blocks"),id:l().describe("Document ID")}),dl=h({action:b("get_child_docs"),id:l().describe("Document ID")}),ll=h({action:b("set_icon"),id:l().describe("Document ID"),icon:l().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.")}),pl=h({action:b("set_cover"),id:l().describe("Document ID"),source:l().optional().describe("Cover image source. Accepts http(s) URLs or SiYuan asset paths like /assets/foo.png. Omit or pass empty string to clear the cover.")}),fl=h({action:b("list_tree"),notebook:l().describe("Notebook ID"),path:l().describe("Storage path or / for the notebook root"),maxDepth:A().optional().describe("Max tree depth to return (default 3). Deeper nodes are collapsed to childCount.")}),hl=h({action:b("search_docs"),notebook:l().describe("Notebook ID"),query:l().describe("Keyword to search in document titles"),path:l().optional().describe("Optional storage path to narrow the search scope after permission filtering")}),ml=h({action:b("get_doc"),id:l().describe("Document ID"),mode:$(["markdown","html"]).optional().describe('Return mode: "markdown" (default) or "html"'),size:A().optional().describe("Optional maximum content size hint"),page:A().int().min(1).optional().describe("Page number for markdown pagination (1-based)"),pageSize:A().int().min(1).max(2e4).optional().describe("Characters per page for markdown pagination (default 8000)")}),yl=h({action:b("create_daily_note"),notebook:l().describe("Notebook ID"),app:l().optional().describe("Optional app identifier passed through to SiYuan")}),gl=h({action:b("duplicate"),id:l().describe("Source document ID")}),bl=h({action:b("remove_batch"),paths:E(l()).min(1).describe("One or more storage paths to remove in batch")}),kl=h({action:b("create_empty"),notebook:l().describe("Notebook ID"),path:l().describe("Parent human-readable path, must start with /"),title:l().describe("New document title"),markdown:l().optional().describe("Optional initial markdown content, defaults to empty"),sorts:E(l()).optional().describe("Optional sorting path segments passed through to SiYuan")}),_l=h({action:b("heading_to_doc"),headingID:l().describe("Heading block ID to convert into a document"),targetNotebook:l().describe("Target notebook ID"),targetPath:l().optional().describe("Optional target storage path"),previousPath:l().optional().describe("Optional previous sibling storage path")}),wl=h({action:b("doc_to_heading"),srcID:l().describe("Source document ID"),targetID:l().describe("Target document or heading block ID"),after:Z().optional().describe("When true, insert after the target heading instead of before it")}),Il=h({action:b("get_balance")}),vl=h({action:b("shop")}),Dl=h({action:b("buy"),item_id:l().describe('Stable shop item ID returned by mascot(action="shop")')}),Sl=$(["all","deck","notebook","tree"]),Al=$(["due","new","old"]),Tl=h({action:b("list_cards"),scope:Sl.describe('Query scope: "all", "deck", "notebook", or "tree"'),filter:Al.describe('Filter returned cards: "due", "new", or "old"'),deckID:l().optional().describe("Deck ID, required when scope=deck"),notebook:l().optional().describe("Notebook ID, required when scope=notebook"),rootID:l().optional().describe("Root document/block ID, required when scope=tree")}).superRefine((e,t)=>{const o=typeof e.deckID=="string",n=typeof e.notebook=="string",r=typeof e.rootID=="string";e.scope==="all"&&(o||n||r)&&t.addIssue({code:Q.custom,message:'scope="all" does not accept deckID, notebook, or rootID.'}),e.scope==="deck"&&!o&&t.addIssue({code:Q.custom,path:["deckID"],message:'deckID is required when scope="deck".'}),e.scope==="notebook"&&!n&&t.addIssue({code:Q.custom,path:["notebook"],message:'notebook is required when scope="notebook".'}),e.scope==="tree"&&!r&&t.addIssue({code:Q.custom,path:["rootID"],message:'rootID is required when scope="tree".'})}),Pl=h({action:b("get_decks")}),Cl=h({action:b("review_card"),deckID:l().describe("Deck ID"),cardID:l().describe("Card ID"),rating:A().describe("Review rating passed through to the kernel"),reviewedCards:E(ve(l(),mt())).optional().describe("Optional reviewedCards payload passed through to the kernel")}),Ol=h({action:b("skip_review_card"),deckID:l().describe("Deck ID"),cardID:l().describe("Card ID")}),$l=h({action:b("create_card"),deckID:l().describe("Deck ID"),blockIDs:E(l()).min(1).describe("Existing block IDs to turn into flashcards")}),El=h({action:b("add_card"),deckID:l().describe("Deck ID"),blockIDs:E(l()).min(1).describe("Existing block IDs to add as flashcards")}),Nl=h({action:b("remove_card"),deckID:l().describe("Deck ID"),blockIDs:E(l()).min(1).describe("Existing block IDs to remove from flashcards")}),Rl=h({action:b("get_cards"),deckID:l().describe("Deck ID (use empty string to query across all decks)"),page:A().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:A().int().min(1).max(512).optional().describe("Cards per page, default 32")}),zl=h({action:b("insert"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Block content"),nextID:l().optional().describe("Next block ID"),previousID:l().optional().describe("Previous block ID"),parentID:l().optional().describe("Parent block or document ID")}),xl=h({action:b("prepend"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Block content"),parentID:l().describe("Parent block or document ID")}),Bl=h({action:b("append"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Block content"),parentID:l().describe("Parent block or document ID")}),Fl=h({action:b("update"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("New block content"),id:l().describe("Block ID")}),ql=h({action:b("delete"),id:l().describe("Block ID")}),jl=h({action:b("move"),id:l().describe("Block ID"),previousID:l().optional().describe("Previous block ID"),parentID:l().optional().describe("New parent block ID")}).superRefine((e,t)=>{!e.previousID&&!e.parentID&&t.addIssue({code:Q.custom,message:"Provide previousID, parentID, or both to describe the destination.",path:["previousID"]})}),Ul=h({action:b("set_fold_state"),id:l().describe("Foldable block ID"),folded:Z().describe("true to fold, false to unfold")}),Zl=h({action:b("get_kramdown"),id:l().describe("Block ID or document ID")}),Ll=h({action:b("get_children"),id:l().describe("Block ID or document ID"),page:A().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:A().int().min(1).max(200).optional().describe("Items per page, default 50")}),Ml=h({action:b("transfer_ref"),fromID:l().describe("Source block ID"),toID:l().describe("Target block ID"),refIDs:E(l()).optional().describe("Reference block IDs")}),Vl=h({action:b("set_attrs"),id:l().describe("Block ID"),attrs:ve(l(),l()).describe("Block attributes")}),Gl=h({action:b("get_attrs"),id:l().describe("Block ID")}),Hl=h({action:b("exists"),id:l().describe("Block ID")}),Yl=h({action:b("info"),id:l().describe("Block ID")}),Wl=h({action:b("breadcrumb"),id:l().describe("Block ID"),excludeTypes:E(l()).optional().describe("Optional block types to exclude from the breadcrumb")}),Jl=h({action:b("dom"),id:l().describe("Block ID")}),Kl=h({action:b("recent_updated"),count:A().optional().describe("Maximum number of recent readable blocks to return after permission filtering")}),Ql=h({action:b("word_count"),ids:E(l()).describe("One or more block IDs")}),Xl=h({dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Block content"),nextID:l().optional().describe("Next block ID"),previousID:l().optional().describe("Previous block ID"),parentID:l().optional().describe("Parent block or document ID")}),ep=h({id:l().describe("Block ID"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Replacement block content")}),tp=h({action:b("batch_insert"),blocks:E(Xl).min(1).describe("Blocks to insert")}),op=h({action:b("batch_update"),blocks:E(ep).min(1).describe("Blocks to update")}),np=h({action:b("append_daily_note"),notebook:l().describe("Notebook ID"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Block content")}),rp=h({action:b("prepend_daily_note"),notebook:l().describe("Notebook ID"),dataType:$(["markdown","dom"]).describe("Data format"),data:l().describe("Block content")}),sp=h({action:b("doc_info"),id:l().describe("Block or document ID")}),ip=h({action:b("docs_info"),ids:E(l()).min(1).describe("Document IDs"),refCount:Z().optional().describe("When true, include reference counts"),av:Z().optional().describe("When true, include AV metadata")}),ap=$(["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"]),cp=h({type:$(["image","file"]).describe("Asset entry type"),content:l().describe("Asset path stored by SiYuan, e.g. assets/foo.png"),name:l().optional().describe("Optional display name")}),Rr=h({valueType:ap.describe("Cell value type"),text:l().optional().describe("Text value for valueType=text"),number:A().optional().describe("Number value for valueType=number"),numberFormat:l().optional().describe("Optional number format such as commas, percent, USD, or CNY"),date:Gt([l(),A()]).optional().describe("Date/time value as ISO text or epoch milliseconds for valueType=date"),endDate:Gt([l(),A()]).optional().describe("Optional end date as ISO text or epoch milliseconds for ranged dates"),includeTime:Z().optional().describe("When false, store the date without a time component"),checked:Z().optional().describe("Checkbox state for valueType=checkbox"),option:l().optional().describe("Selected option label for valueType=select"),options:E(l()).optional().describe("Selected option labels for valueType=multi_select"),relationBlockIDs:E(l()).optional().describe("Related block IDs for valueType=relation"),url:l().optional().describe("URL value for valueType=url"),email:l().optional().describe("Email value for valueType=email"),phone:l().optional().describe("Phone value for valueType=phone"),assets:E(cp).optional().describe("Asset entries for valueType=mAsset")}).superRefine((e,t)=>{const n={text:"text",number:"number",date:"date",checkbox:"checked",select:"option",multi_select:"options",relation:"relationBlockIDs",url:"url",email:"email",phone:"phone",mAsset:"assets"}[e.valueType];e[n]===void 0&&t.addIssue({code:Q.custom,message:`${String(n)} is required when valueType="${e.valueType}".`,path:[n]})}),up=h({rowID:l().describe("Row item ID"),columnID:l().describe("Column key ID")}).and(Rr),dp=h({action:b("get"),id:l().describe("Attribute view ID")}),lp=h({action:b("render_attribute_view"),id:l().describe("Attribute view ID"),blockID:l().optional().describe("Optional database block ID"),viewID:l().optional().describe("Optional target view ID"),page:A().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:A().int().optional().describe("Rows per page; use -1 or omit for kernel default"),query:l().optional().describe("Optional row query filter"),groupPaging:ve(l(),mt()).optional().describe("Optional group paging map passed through to SiYuan"),createIfNotExist:Z().optional().describe("Create the default view if none exists; defaults to true")}),pp=h({action:b("get_attribute_view_keys"),id:l().describe("Attribute view ID")}),fp=h({action:b("get_attribute_view_filter_sort"),id:l().describe("Attribute view ID"),blockID:l().optional().describe("Database block ID (optional)")}),hp=h({action:b("search"),keyword:l().describe("Keyword to search in attribute view names"),excludes:E(l()).optional().describe("Optional AV IDs to exclude")}),mp=h({action:b("add_rows"),avID:l().describe("Attribute view ID"),blockIDs:E(l()).describe("Existing block IDs to add as rows"),blockID:l().optional().describe("Optional database block ID"),viewID:l().optional().describe("Optional target view ID"),groupID:l().optional().describe("Optional target group ID"),previousID:l().optional().describe("Optional previous row item ID"),ignoreDefaultFill:Z().optional().describe("When true, skip view/group default value filling")}),yp=h({action:b("remove_rows"),avID:l().describe("Attribute view ID"),srcIDs:E(l()).min(1).describe("Bound row block/item IDs to remove")}),gp=h({action:b("add_column"),avID:l().describe("Attribute view ID"),keyID:l().optional().describe("Optional new column key ID; MCP generates one when omitted"),keyName:l().describe("New column name"),keyType:$(["text","number","date","select","mSelect","url","email","phone","mAsset","template","created","updated","checkbox","relation","rollup","lineNumber"]).describe("Column type"),keyIcon:l().optional().describe("Optional column icon"),previousKeyID:l().optional().describe("Insert after this existing column key ID")}),bp=h({action:b("remove_column"),avID:l().describe("Attribute view ID"),keyID:l().optional().describe("Column key ID"),columnID:l().optional().describe("Alias of keyID"),removeRelationDest:Z().optional().describe("Also remove reverse relation metadata when deleting a relation column")}).superRefine((e,t)=>{!e.keyID&&!e.columnID&&t.addIssue({code:Q.custom,message:"Provide keyID or columnID.",path:["keyID"]})}),kp=h({action:b("set_cell"),avID:l().describe("Attribute view ID"),rowID:l().describe("Row item ID"),columnID:l().describe("Column key ID")}).and(Rr),_p=h({action:b("batch_set_cells"),avID:l().describe("Attribute view ID"),items:E(up).min(1).describe("Batch cell updates")}),wp=h({action:b("duplicate_block"),avID:l().describe("Source attribute view ID"),previousID:l().optional().describe("Optional block ID to insert the duplicated database block after, overriding the default source-block insertion target")}),Ip=h({action:b("get_primary_key_values"),avID:l().describe("Attribute view ID"),keyword:l().optional().describe("Optional keyword filter for primary key values"),page:A().int().min(1).optional().describe("Page number (1-based), default 1"),pageSize:A().int().min(1).optional().describe("Rows per page, default all")}),vp=h({action:b("upload_asset"),assetsDirPath:l().describe("Asset directory path (e.g., /assets/)"),localFilePath:l().describe("Local file path to read and upload into the assets directory"),confirmLargeFile:Z().optional().describe("Set to true only after the user explicitly confirms uploading a file larger than the configured safety threshold.")}),Dp=h({action:b("render_template"),id:l().describe("Document ID for template context"),path:l().describe("Template file path inside the SiYuan workspace; arbitrary local filesystem paths are not supported")}),Sp=h({action:b("render_sprig"),template:l().describe("Sprig template content")}),Ap=h({action:b("export_md"),id:l().describe("Document ID to export")}),Tp=h({action:b("export_resources"),paths:E(l()).describe("Paths to export"),name:l().optional().describe("Export file name"),outputPath:l().optional().describe("Optional local absolute or relative filesystem path to save the exported ZIP")}),Pp=h({action:b("list_unused_assets")}),Cp=h({action:b("get_doc_assets"),id:l().describe("Document ID"),assetType:$(["all","image"]).optional().describe("Filter asset type: 'all' (default) returns all assets, 'image' returns only image assets.")}),Op=h({action:b("get_image_ocr_text"),path:l().optional().describe("Asset path; omit to receive an empty OCR text payload")}),$p=h({action:b("remove_unused_assets")}),Ep=h({action:b("rename_asset"),oldPath:l().describe("Existing asset path"),newName:l().describe("New asset file name")}),Np=h({action:b("delete_asset"),path:l().describe("Asset path to delete")}),Rp=h({action:b("set_image_alpha"),path:l().describe("Asset path to update"),alpha:A().describe("Alpha value passed through to SiYuan")}),zp=$(so),xp=h({action:b("fulltext"),query:l().describe("Search query string"),method:A().optional().describe("Search method: 0=keyword (default), 1=query syntax, 2=SQL, 3=regex"),types:ve(l(),Z()).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:E(l()).optional().describe('Alternative shorthand type filter as array: ["h","p"]. Merged with types if both provided.'),paths:E(l()).optional().describe("Restrict search to specific notebook paths"),groupBy:A().optional().describe("0=no grouping (default), 1=group by document"),orderBy:A().optional().describe("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:l().optional().describe('Named sort alias: "relevance", "date", "updated_desc", "updated_asc", "created_desc", "created_asc", "type". Overrides orderBy if both provided.'),page:A().optional().describe("Page number (1-based), default 1"),pageSize:A().optional().describe("Results per page, default 32, max 128"),parentId:l().optional().describe("Post-filter results to blocks whose root_id or parent_id matches this ID, scoping search within a document subtree."),hasTags:Z().optional().describe("When true, only return blocks that have tags. When false, only return blocks without tags."),stripHtml:Z().optional().describe("When true, preserves highlighted HTML while adding plain-text fields for easier downstream parsing")}),Bp=h({action:b("query_sql"),stmt:l().describe("SQL SELECT statement to execute against the blocks/spans/assets tables; returned rows are permission-filtered")}),Fp=h({action:b("search_tag"),k:l().describe("Tag keyword to search for")}),qp=h({action:b("get_backlinks"),id:l().describe("Block or document ID to find backlinks for"),keyword:l().optional().describe("Filter backlinks by keyword"),refTreeID:l().optional().describe("Optional document tree ID to narrow backlink scope")}),jp=h({action:b("get_backmentions"),id:l().describe("Block or document ID to find backmentions for"),keyword:l().optional().describe("Filter backmentions by keyword"),refTreeID:l().optional().describe("Optional document tree ID to narrow backmention scope")}),Up=h({action:b("search_refs"),id:l().describe("Referenced block or document ID"),rootID:l().optional().describe("Optional current root document ID"),k:l().optional().describe("Keyword filter"),beforeLen:A().int().min(0).optional().describe("Context length before the reference, default 512"),isSquareBrackets:Z().optional().describe("Search in square-bracket reference mode"),isDatabase:Z().optional().describe("Whether the reference target is a database"),reqId:l().optional().describe("Optional passthrough request ID")}),Zp=h({action:b("find_replace"),k:l().describe("Find keyword"),r:l().describe("Replacement text; use empty string to delete matches"),ids:E(l()).min(1).describe("Document or block IDs to mutate"),paths:E(l()).optional().describe("Optional path scope list"),types:ve(l(),Z()).optional().describe("Optional block type filter"),method:A().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),orderBy:A().optional().describe("Sort order"),groupBy:A().optional().describe("Grouping mode"),replaceTypes:ve(l(),Z()).optional().describe("Replace target kinds such as text, code, docTitle, blockRef")}),Lp=h({action:b("search_assets"),k:l().describe("Asset filename keyword"),exts:E(l()).optional().describe("Optional extension filters")}),Mp=h({action:b("get_asset_content"),id:l().describe("Asset content ID"),query:l().describe("Matched query text"),queryMethod:A().optional().describe("Query method: 0=keyword, 1=query syntax, 2=SQL, 3=regex")}),Vp=h({action:b("fulltext_asset_content"),query:l().describe("Search query string"),types:ve(l(),Z()).optional().describe("Asset type filter"),method:A().optional().describe("Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"),orderBy:A().optional().describe("Sort order: 0=relevance DESC, 1=relevance ASC, 2=updated ASC, 3=updated DESC"),page:A().int().min(1).optional().describe("Page number (1-based)"),pageSize:A().int().min(1).max(128).optional().describe("Results per page")}),Gp=h({action:b("list_invalid_refs"),page:A().int().min(1).optional().describe("Page number (1-based)"),pageSize:A().int().min(1).max(128).optional().describe("Results per page")}),Hp=$(io),Yp=h({action:b("list"),sort:A().optional().describe("Optional tag sort mode"),ignoreMaxListHint:Z().optional().describe("Ignore the maximum list hint from SiYuan"),app:l().optional().describe("Optional app identifier passed through to SiYuan")}),Wp=h({action:b("rename"),oldLabel:l().describe("Existing tag label"),newLabel:l().describe("New tag label")}),Jp=h({action:b("remove"),label:l().describe("Tag label to remove")}),Kp=$(ao),Qp=h({action:b("workspace_info")}),Xp=h({action:b("network")}),ef=h({action:b("changelog")}),tf=h({action:b("conf"),mode:$(["summary","get"]).optional().describe('Read mode: "summary" returns a navigable overview, "get" reads a specific key path'),keyPath:l().optional().describe('Dot/bracket path to a specific config field, e.g. "conf.appearance.mode" or "conf.langs[0]"'),maxDepth:A().int().min(0).max(5).optional().describe("Maximum object traversal depth for summary/get responses"),maxItems:A().int().min(1).max(100).optional().describe("Maximum keys/items to include per level")}),of=h({action:b("sys_fonts"),mode:$(["summary","list"]).optional().describe('Read mode: "summary" returns counts and samples, "list" returns paginated items'),offset:A().int().min(0).optional().describe("Pagination offset for list mode"),limit:A().int().min(1).max(200).optional().describe("Pagination size for list mode"),query:l().optional().describe("Optional keyword filter for font names")}),nf=h({action:b("boot_progress")}),rf=h({action:b("push_msg"),msg:l().describe("Message content"),timeout:A().optional().describe("Display timeout in milliseconds")}),sf=h({action:b("push_err_msg"),msg:l().describe("Error message content"),timeout:A().optional().describe("Display timeout in milliseconds")}),af=h({action:b("get_version")}),cf=h({action:b("get_current_time")}),uf=[{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="get_path") 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:"The SiYuan kernel is unreachable. Make sure SiYuan is running and the MCP plugin is connected."}];function zr(e){const t=e.message??"";for(const o of uf)if(o.patterns.some(n=>n.test(t)))return{code:o.code,hint:o.hint};return null}function yt(e){var t;return e instanceof Error?((t=zr(e))==null?void 0:t.code)==="block_not_found":!1}function df(e){return typeof e.description=="string"?e.description:null}function At(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function xr(e){return Array.isArray(e.required)?e.required.filter(t=>typeof t=="string"):[]}function lf(e,t={}){const o={},n=new Map,r=new Map,s=new Map,i=new Map;for(const a of e){const c=new Set(xr(a.schema));for(const[u,d]of Object.entries(At(a.schema))){if(u==="action"||!d||typeof d!="object")continue;o[u]={...o[u],...d};const p=df(d);if(p){const w=n.get(u)??new Set;w.add(p),n.set(u,w)}const f=d.enum;if(Array.isArray(f)){const w=r.get(u)??new Set;for(const T of f)w.add(T);r.set(u,w)}const k=c.has(u)?s:i,_=k.get(u)??new Set;_.add(a.action),k.set(u,_)}}for(const[a,c]of Object.entries(o)){const u=n.get(a),d=t[a]??(u&&u.size>0?[...u].join(" / "):void 0),p=[...s.get(a)??[]].sort(),f=[...i.get(a)??[]].sort(),k=[...p.length>0?[`Required by: ${p.join(", ")}`]:[],...f.length>0?[`Optional in: ${f.join(", ")}`]:[]],_=k.length>0?`[${k.join("; ")}]`:"";c.description=d?_?`${d} ${_}`:d:_||void 0;const w=r.get(a);w&&w.size>0&&(c.enum=[...w])}return o}function be(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return t.type==="array"&&(t.items=be(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,be(n)]))),t.additionalProperties&&typeof t.additionalProperties=="object"&&!Array.isArray(t.additionalProperties)&&(t.additionalProperties=be(t.additionalProperties)),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(o=>be(o))),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(o=>be(o))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(o=>be(o))),t}function pf(e){return be(e)}function Br(e){return xr(e).filter(t=>t!=="action")}function Je(e,t){const o=new Set(Br(e));return Object.entries(At(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 Yt(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
83
+
84
+ - 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"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[Yt(`${e}Item`,r)]}if(t.type==="object"){const r=At(t),s=Object.keys(r)[0];return s?{[s]:Yt(s,r[s])}:{}}return t.type==="number"?1:t.type==="boolean"?!1:`<${e}>`}function ff(e,t){return e.filter(n=>n.action===t).map(n=>{const r=At(n.schema),s={action:t};for(const i of Br(n.schema))s[i]=Yt(i,r[i]??{});return s})}function hf(e){return e.length>0?e.join(", "):"no additional fields"}function mf(e){const t=new Map;for(const o of e){const n=hf(Je(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 yf(e,t){const o=new Set;return t.flatMap(n=>{if(o.has(n.action))return[];o.add(n.action);const r=Je(n.schema,!0),s=Je(n.schema,!1);return[`${e}.${n.action}: required ${r.length>0?`[${r.join(", ")}]`:"[]"} | optional ${s.length>0?`[${s.join(", ")}]`:"[]"}`]}).join(`
85
+ `)}function gf(e,t,o){var c;const n={basic:[],advanced:[]};for(const u of t)n[He(e,u)].push(u);const r={},s={},i=new Set;for(const u of o){if(i.has(u.action))continue;i.add(u.action);const d=(c=Ye[e])==null?void 0:c[u.action],p=Je(u.schema,!0);r[u.action]=d??(p.length>0?`requires: ${p.join(", ")}`:"no extra fields"),s[u.action]={...d?{hint:d}:{},requiresConfirmation:Ne(e,u.action)}}const a=t.filter(u=>Ne(e,u));return{tool:e,commonActions:n.basic,advancedActions:n.advanced,guidance:or[e]??[],actions:s,actionSummaries:r,...a.length>0?{requiresConfirmation:a}:{},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 bf(e,t,o){var s;const n=o.filter(i=>i.action===t),r=n.map(i=>Je(i.schema,!0));return{tool:e,action:t,...(s=Ye[e])!=null&&s[t]?{hint:Ye[e][t]}:{},shapes:r.map(i=>i.length>0?i.join(" + "):"action only"),requiredFields:r.length===1?r[0]:r,example:(()=>{const i=ff(n,t);return i.length===1?i[0]:i})(),guidance:or[e]??[],requiresConfirmation:Ne(e,t),fullDocResource:`siyuan://help/action/${e}/${t}`}}function g(e,t,o,n){return{type:"object",additionalProperties:!1,description:n,properties:{action:{type:"string",const:e,description:"Action to perform"},...t},required:["action",...o]}}function kf(e,t,o){const n=[],r=o.guidance??[];n.push(...r.slice(0,2));const s=t.filter(i=>Ne(e,i));return s.length>0&&n.push(`Requires user confirmation before: ${s.join(", ")}.`),n}function Fr(e){return e.map(t=>typeof t=="number"?`[${t}]`:String(t)).join(".").replace(/\.\[/g,"[")}function _f(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 wf(e,t){const o=Fr(e.path),n=o?_f(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 If(e,t){return e.issues.map(o=>({path:Fr(o.path),message:wf(o,t)}))}function vf(e,t){return e&&t?`Invalid arguments for ${e}(action="${t}").`:e?`Invalid arguments for tool "${e}".`:"Invalid arguments."}function Bt(e){return(e==null?void 0:e.hint)??Xs(e==null?void 0:e.tool,e==null?void 0:e.action)}function Ke(e,t=!0){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:t}}function Df(e){return e.name==="SiYuanError"||e.message.startsWith("SiYuan API error:")||e.message.startsWith("HTTP error:")||e.message.startsWith("Request timeout")}function Sf(){return process.env.SIYUAN_MCP_DEBUG_ERRORS==="1"}function Af(e,t,o,n,r){const s=o.filter(f=>He(e,f)==="basic"),i=o.filter(f=>He(e,f)==="advanced"),a=n.filter(f=>s.includes(f.action)),c=mf(a),u=[`${t} Use the "action" field to select the operation.`];s.length>0&&u.push(`Common actions: ${s.join(", ")}. Required fields: ${c}.`),i.length>0&&u.push(`Additional actions: ${i.join(", ")}. Read siyuan://help/action/${e}/{action} for details, or call action="help" if resources are unavailable.`);const d=yf(e,n);d.length>0&&u.push(`Parameter contract per action (fields outside the action's optional list should not be sent):
86
+ ${d}`);const p=kf(e,o,r);return p.length>0&&u.push(p.join(" ")),u.join(`
87
+
88
+ `)}function Tf(e,t,o,n,r={}){if(!o.enabled)return[];const s=Nn(o),i=new Set(s),a=n.filter(p=>i.has(p.action));if(a.length===0)return[];const c=Af(e,t,s,a,r),u=s.filter(p=>Ne(e,p)),d=lf(a,r.propertyDescriptionOverrides);return"topic"in d||(d.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.'}),[{name:e,description:c,inputSchema:pf({type:"object",additionalProperties:!1,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(", ")}.`:""}`},...d},required:["action"]})}]}function Pf(e,t,o,n){if(t.action!=="help")return null;const r=Nn(o),s=new Set(r),i=n.filter(u=>s.has(u.action)),a=typeof t.topic=="string"?t.topic.trim():"",c=a&&a!=="overview"?a:null;return c?s.has(c)?y(bf(e,c,i)):Ke({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.`}}):y(gf(e,r,i))}function ko(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 qr(e,t,o){const n=e.length,r=Math.max(1,Math.ceil(n/o)),s=Math.min(t,r),i=(s-1)*o,a=e.slice(i,i+o);return{items:a,total:n,page:s,pageSize:o,pageCount:r,showing:a.length,truncated:r>1,hasNextPage:s<r}}function ot(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 y(n)}function y(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function Tt(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_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_icon") to set the document icon. Prefer a Unicode hex code string like "1f4d4" instead of a raw emoji character.'}function re(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?y({success:!0,...t,...e}):y({success:!0,...e})}function gt(e,t){if(e instanceof Pu){const a=If(e,t==null?void 0:t.rawArgs),c={error:{type:"validation_error",message:vf(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}:{},...a.length>0?{fields:a}:{},...Bt(t)?{hint:Bt(t)}:{}}};return Ke(c)}const o=e instanceof Error?e:new Error(String(e)),n=zr(o),r=Bt(t),s=n&&r?`${n.hint} ${r}`:(n==null?void 0:n.hint)??r,i={error:{type:Df(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}:{},...Sf()&&o.stack?{details:o.stack}:{}}};return Ke(i)}function _o(e,t,o){return Ke({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 Cf(e,t){return Ke({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 se(e){const{name:t,description:o,variants:n,handlers:r,actionSchema:s,aggregateOptions:i}=e;return{listTools(a){return Tf(t,o,a,n,i)},async callTool(a,c,u,d){const p=c??{},f=typeof p.action=="string"?p.action:void 0,k=Pf(t,p,u,n);if(k)return k;try{const _=s.parse(p.action);if(!u.enabled||!u.actions[_])return Cf(t,_);const w=r[_];return w?await w({client:a,rawArgs:p,permMgr:d}):gt(new Error(`No handler registered for action "${_}" on tool "${t}".`),{tool:t,action:_,rawArgs:p})}catch(_){return gt(_,{tool:t,action:f,rawArgs:p})}}}}async function wo(e,t){return e.request("/api/av/getAttributeView",{id:t})}async function Of(e,t){return e.request("/api/av/renderAttributeView",t)}async function $f(e,t){return e.request("/api/av/getAttributeViewKeys",{id:t})}async function Ef(e,t){return e.request("/api/av/getAttributeViewFilterSort",t)}async function Nf(e,t,o){return e.request("/api/av/searchAttributeView",{keyword:t,excludes:o})}async function Rf(e,t){return e.request("/api/av/addAttributeViewBlocks",t)}async function zf(e,t,o){return e.request("/api/av/removeAttributeViewBlocks",{avID:t,srcIDs:o})}async function xf(e,t){return e.request("/api/av/addAttributeViewKey",{keyIcon:"",previousKeyID:"",...t})}async function Bf(e,t,o,n){return e.request("/api/av/removeAttributeViewKey",{avID:t,keyID:o,removeRelationDest:n})}async function Ff(e,t){return e.request("/api/av/setAttributeViewBlockAttr",t)}async function qf(e,t,o){return e.request("/api/av/batchSetAttributeViewBlockAttrs",{avID:t,values:o})}async function jf(e,t){return e.request("/api/av/duplicateAttributeViewBlock",{avID:t})}async function jr(e,t){return e.request("/api/av/getMirrorDatabaseBlocks",{avID:t})}async function Ur(e,t){return e.request("/api/av/getAttributeViewPrimaryKeyValues",t)}async function Uf(e,t,o,n,r,s){const i={dataType:t,data:o,nextID:n,previousID:r,parentID:s};return e.request("/api/block/insertBlock",i)}async function Zf(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/prependBlock",r)}async function Lf(e,t,o,n){const r={dataType:t,data:o,parentID:n};return e.request("/api/block/appendBlock",r)}async function Mf(e,t,o,n){const r={dataType:t,data:o,id:n};return e.request("/api/block/updateBlock",r)}async function Vf(e,t){const o={id:t};return e.request("/api/block/deleteBlock",o)}async function Gf(e,t,o,n){const r={id:t,previousID:o,parentID:n};return e.request("/api/block/moveBlock",r)}async function Hf(e,t){const o={id:t};return e.request("/api/block/foldBlock",o)}async function Yf(e,t){const o={id:t};return e.request("/api/block/unfoldBlock",o)}async function Wf(e,t){const o={id:t};return e.request("/api/block/getBlockKramdown",o)}async function Zr(e,t){const o={id:t};return e.request("/api/block/getChildBlocks",o)}async function Io(e,t){const o={id:t};return e.request("/api/block/getDocInfo",o)}async function Jf(e,t,o,n){const r={fromID:t,toID:o,refIDs:n};return e.request("/api/block/transferBlockRef",r)}async function Lr(e,t){return e.request("/api/block/checkBlockExist",{id:t})}async function Kf(e,t){return e.request("/api/block/getBlockInfo",{id:t})}async function Qf(e,t,o){return e.request("/api/block/getBlockBreadcrumb",{id:t,excludeTypes:o})}async function Xf(e,t){return e.request("/api/block/getBlockDOM",{id:t})}async function eh(e){return e.request("/api/block/getRecentUpdatedBlocks",{})}async function th(e,t){return e.request("/api/block/getBlocksWordCount",{ids:t})}async function oh(e,t){return e.request("/api/block/batchInsertBlock",{blocks:t})}async function nh(e,t){return e.request("/api/block/batchUpdateBlock",{blocks:t})}async function rh(e,t,o,n){return e.request("/api/block/appendDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function sh(e,t,o,n){return e.request("/api/block/prependDailyNoteBlock",{notebook:t,dataType:o,data:n})}async function ih(e,t,o=!1,n=!1){return e.request("/api/block/getDocsInfo",{ids:t,refCount:o,av:n})}async function ah(e,t,o={}){return e.request("/api/transactions",{transactions:t,reqId:o.reqId??Date.now(),app:o.app??"",session:o.session??""})}async function ch(e,t,o,n){return e.request("/api/filetree/createDocWithMd",{notebook:t,path:o,markdown:n})}async function uh(e,t,o,n){return e.request("/api/filetree/renameDoc",{notebook:t,path:o,title:n})}async function dh(e,t,o){return e.request("/api/filetree/renameDocByID",{id:t,title:o})}async function lh(e,t,o){return e.request("/api/filetree/removeDoc",{notebook:t,path:o})}async function ph(e,t){return e.request("/api/filetree/removeDocByID",{id:t})}async function fh(e,t,o,n){return e.request("/api/filetree/moveDocs",{fromPaths:t,toNotebook:o,toPath:n})}async function hh(e,t,o){return e.request("/api/filetree/moveDocsByID",{fromIDs:t,toID:o})}async function Mr(e,t,o){return e.request("/api/filetree/getHPathByPath",{notebook:t,path:o})}async function Vr(e,t){return e.request("/api/filetree/getHPathByID",{id:t})}async function Gr(e,t){return e.request("/api/filetree/getPathByID",{id:t})}async function mh(e,t,o){return e.request("/api/filetree/getIDsByHPath",{path:t,notebook:o})}async function yh(e,t,o){return e.request("/api/filetree/listDocsByPath",{notebook:t,path:o})}async function gh(e,t,o){return e.request("/api/filetree/listDocTree",{notebook:t,path:o})}async function bh(e,t,o,n){return e.request("/api/filetree/searchDocs",{k:t,flashcard:o,excludeIDs:n})}async function kh(e,t,o,n){return e.request("/api/filetree/getDoc",{id:t,mode:o,size:n})}async function _h(e,t,o){return e.request("/api/filetree/createDailyNote",{notebook:t,app:o})}async function wh(e,t){return e.request("/api/filetree/duplicateDoc",{id:t})}async function Ih(e,t){return e.request("/api/filetree/removeDocs",{paths:t})}async function vh(e,t,o,n,r="",s){return e.request("/api/filetree/createDoc",{notebook:t,path:o,title:n,md:r,sorts:s})}async function Dh(e,t,o,n,r){return e.request("/api/filetree/heading2Doc",{srcHeadingID:t,targetNoteBook:o,targetPath:n,previousPath:r})}async function Sh(e,t,o,n=!1){return e.request("/api/filetree/doc2Heading",{srcID:t,targetID:o,after:n})}async function Ve(e){return e.request("/api/notebook/lsNotebooks")}async function Ah(e,t){return e.request("/api/notebook/openNotebook",{notebook:t})}async function Th(e,t){return e.request("/api/notebook/closeNotebook",{notebook:t})}async function Ph(e,t){return e.request("/api/notebook/createNotebook",{name:t})}async function Ch(e,t){return e.request("/api/notebook/removeNotebook",{notebook:t})}async function Oh(e,t,o){return e.request("/api/notebook/renameNotebook",{notebook:t,name:o})}async function $h(e,t){return e.request("/api/notebook/getNotebookConf",{notebook:t})}async function Eh(e,t,o){return e.request("/api/notebook/setNotebookConf",{notebook:t,conf:o})}async function tn(e,t,o){return e.request("/api/notebook/setNotebookIcon",{notebook:t,icon:o})}async function Nh(e,t){return e.request("/api/search/fullTextSearchBlock",t)}async function nt(e,t){const o={stmt:t},n=await e.request("/api/query/sql",o);return Array.isArray(n)?n:[]}async function Rh(e,t){const o={k:t};return e.request("/api/search/searchTag",o)}async function zh(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBacklinkDoc",r)}async function xh(e,t,o,n){const r={defID:t,keyword:o,refTreeID:n};return e.request("/api/ref/getBackmentionDoc",r)}async function Bh(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 Fh(e,t){return e.request("/api/search/findReplace",t)}async function qh(e,t,o){return e.request("/api/search/searchAsset",{k:t,exts:o})}async function jh(e,t,o,n=0){return e.request("/api/search/getAssetContent",{id:t,query:o,queryMethod:n})}async function Uh(e,t){return e.request("/api/search/fullTextSearchAssetContent",t)}async function Zh(e,t,o){return e.request("/api/search/listInvalidBlockRefs",{page:t,pageSize:o})}function Lh(e){return typeof e=="string"?e.replace(/\.sy$/,""):void 0}function le(e){return e.startsWith("/")?e:`/${e}`}function Mh(e){const t=le(e).split("/").filter(Boolean).at(-1)??"";return t.endsWith(".sy")?t.slice(0,-3):t}function de(e){return e.replace(/\0/g,"").replace(/'/g,"''")}async function Vh(e,t){const o=await nt(e,`SELECT id, root_id, box, path, hpath, content, type FROM blocks WHERE id = '${de(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 i=typeof n.root_id=="string"&&n.root_id.length>0?n.root_id:typeof n.id=="string"&&n.id.length>0?n.id:t,a=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:i,notebook:r,path:le(s),hPath:a,name:c}}async function xe(e,t){try{const s=await Vh(e,t);if(s)return s}catch{}const o=await Io(e,t),n=o.rootID||o.id,r=await Gr(e,n);return{documentId:n,notebook:r.notebook,path:le(r.path),name:o.name}}const Gh=500;function Hr(e,t,o){if(e.size>=Gh){const n=e.keys().next().value;n!==void 0&&e.delete(n)}e.set(t,o)}function rt(){return{documentContextById:new Map,notebookByPath:new Map}}async function Hh(e,t,o){if(!o)return xe(e,t);let n=o.documentContextById.get(t);return n||(n=xe(e,t),Hr(o.documentContextById,t,n)),n}async function Yh(e,t,o){const n=le(t);if(!o)return Qe(e,n);let r=o.notebookByPath.get(n);return r||(r=Qe(e,n),Hr(o.notebookByPath,n,r)),r}async function Ue(e,t,o){if(!t||typeof t!="object")return null;const n=t,r=[n.notebook,n.box,n.boxID,n.notebookId].find(a=>typeof a=="string"&&a.length>0),s=[n.path].find(a=>typeof a=="string"&&a.length>0),i=[n.blockID,n.blockId,n.rootID,n.rootId,n.root_id,n.docID,n.docId,n.id].find(a=>typeof a=="string"&&a.length>0);if(r&&s)return{notebook:r,path:le(s),documentId:i};if(i)try{const a=await Hh(e,i,o);return{notebook:a.notebook,path:a.path,documentId:a.documentId}}catch{}if(s){const a=await Yh(e,s,o);if(a)return{notebook:r??a,path:le(s),documentId:i}}return r?{notebook:r,path:s?le(s):void 0,documentId:i}:null}async function Wh(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t.notebook):o==="write"?e.canWrite(t.notebook):e.canRead(t.notebook))?null:_o(t.notebook,e.get(t.notebook),o)}async function v(e,t,o,n){const r=await xe(e,o),s=await Wh(t,r,n);return{context:r,denied:s}}async function x(e,t,o){return await e.reload(),(o==="delete"?e.canDelete(t):o==="write"?e.canWrite(t):e.canRead(t))?null:_o(t,e.get(t),o)}async function Jh(e,t){const n=(await Ve(e)).notebooks.find(s=>s.id===t);return n?n.id:(await xe(e,t)).notebook}async function Qe(e,t){const o=await Ve(e);for(const n of o.notebooks)try{return await Mr(e,n.id,t),n.id}catch{continue}return null}async function Yr(e,t,o){const n=await yh(e,t,o);return n.files.map(r=>({id:typeof r.id=="string"&&r.id.length>0?r.id:Mh(r.path),notebook:r.box||n.box||t,path:le(r.path),hPath:r.hPath,name:Lh(r.name),icon:r.icon,subFileCount:r.subFileCount??r.count}))}async function Kh(e){return e.request("/api/system/getWorkspaceInfo",{})}async function Qh(e){return e.request("/api/system/getNetwork",{})}async function Xh(e){return e.request("/api/system/getChangelog",{})}async function em(e){return e.request("/api/system/getConf",{})}async function tm(e){return e.request("/api/system/getSysFonts",{})}async function om(e){return e.request("/api/system/bootProgress",{})}async function nm(e){return e.request("/api/ui/reloadIcon",{})}async function rm(e){return e.request("/api/ui/reloadFiletree",{})}async function sm(e,t){return e.request("/api/ui/reloadProtyle",{id:t})}async function im(e,t){return e.request("/api/ui/reloadAttributeView",{id:t})}async function am(e){return e.request("/api/ui/reloadTag",{})}function cm(){const e=parseInt(process.env.SIYUAN_MCP_PARENT_PID??"",10);return Number.isInteger(e)&&e>1}function um(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 dm(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 lm(e,t){switch(t.type){case"reloadProtyle":await sm(e,t.id);return;case"reloadAttributeView":await im(e,t.id);return;case"reloadIcon":await nm(e);return;case"reloadFiletree":await rm(e);return;case"reloadTag":await am(e);return;default:{const o=t;throw new Error(`Unknown UI refresh operation: ${String(o)}`)}}}async function S(e,t,o){if(t.isError||o.length===0||!cm()||!e||typeof e.request!="function")return t;const n=um(t);if(!n)return t;const r=dm(o),s=[];for(const i of r)try{await lm(e,i)}catch(a){s.push({type:i.type,..."id"in i?{id:i.id}:{},message:a instanceof Error?a.message:String(a)})}return n.uiRefresh={applied:!0,operations:r.map(i=>({type:i.type,..."id"in i?{id:i.id}:{}})),...s.length>0?{partialFailure:s}:{}},{...t,content:[{type:"text",text:JSON.stringify(n,null,2)}]}}const Pe="av";function pm(e=new Date){const t=(s,i=2)=>String(s).padStart(i,"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 on=6,fm=500,hm="/data/storage/av",mm=/^\d{14}-[a-z0-9]{7}$/;function ym(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 i=s.values.find(a=>{var c;return typeof((c=a==null?void 0:a.block)==null?void 0:c.id)=="string"&&a.block.id.length>0});if((n=i==null?void 0:i.block)!=null&&n.id)return i.block.id}}function gm(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 vo(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 Wr(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 bm(e){return vo(e,["blockID","itemId","itemID","rowID"])??Wr(e,["block","blockID"])}function km(e){return Wr(e,["block","id"])??vo(e,["srcID","srcId"])}function _m(e){return vo(e,["id"])}function Pt(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,d=u.values;Array.isArray(d)&&d.forEach(p=>{var T;const f=bm(p);if(!f)return;let k=t.get(f);k||(k={rowID:f,valueIDs:[]},t.set(f,k),o.push(k));const _=_m(p),w=((T=u.key)==null?void 0:T.type)==="block"?km(p):void 0;w&&(k.sourceBlockID=w),_&&!k.valueIDs.includes(_)&&k.valueIDs.push(_)})}const r=o.filter(c=>c.rowID||c.sourceBlockID||c.valueIDs.length>0),s=new Set,i=new Map,a=new Map;for(const c of r){if(c.rowID&&s.add(c.rowID),c.sourceBlockID&&c.rowID){const u=i.get(c.sourceBlockID)??[];u.includes(c.rowID)||(u.push(c.rowID),i.set(c.sourceBlockID,u))}if(c.rowID)for(const u of c.valueIDs){const d=a.get(u)??[];d.includes(c.rowID)||(d.push(c.rowID),a.set(u,d))}}return{rows:r,rowIDs:s,sourceBlockToRowIDs:i,valueIdToRowIDs:a}}function Le(e,t){return{content:[{type:"text",text:JSON.stringify({error:{type:"validation_error",tool:Pe,action:e,...t}},null,2)}],isError:!0}}function wm(e,t,o){return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:Pe,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,blockIDs:t,rows:o.rows,unresolvedBlockIDs:o.unresolvedBlockIDs,hint:'Retry av(action="add_rows") or wait briefly and re-read the database. Only call set_cell after add_rows returns rows[].rowID.'}},null,2)}],isError:!0}}function Im(e){return new Promise(t=>{setTimeout(t,e)})}function vm(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}}async function Dm(e,t,o){let n={rows:o.map(r=>({blockID:r})),unresolvedBlockIDs:[...o]};for(let r=0;r<on;r+=1){const s=await wo(e,t);if(n=vm(Pt(s.av),o),n.unresolvedBlockIDs.length===0)return n;r<on-1&&await Im(fm)}return n}function Jr(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:Le(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_cell responses as rowID.'})};if(s&&s.length>1)return{ok:!1,result:Le(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 i=o.sourceBlockToRowIDs.get(n);return i&&i.length===1?{ok:!1,result:Le(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:i[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.'})}:i&&i.length>1?{ok:!1,result:Le(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:i,...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:Le(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 Kr(e,t){const o=await Ue(e,t);if(o!=null&&o.documentId)return{avData:t,blockID:o.documentId};const n=ym(t);return{avData:t,blockID:n}}async function K(e,t,o,n){const s=(await wo(e,o)).av,i=await Kr(e,s),a=[];i.blockID&&a.push(i.blockID);try{const c=await jr(e,o);for(const u of c.refDefs??[]){const d=typeof(u==null?void 0:u.refID)=="string"&&u.refID.length>0?u.refID:void 0;d&&!a.includes(d)&&a.push(d)}}catch(c){if(!yt(c))throw c}for(const c of a)try{const{denied:u}=await v(e,t,c,n);return{denied:u,avData:s}}catch(u){if(yt(u))continue;throw u}throw a.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.`)}async function Sm(e,t,o){const n=await Kr(e,o??(await wo(e,t)).av),r=[];n.blockID&&r.push(n.blockID);try{const s=await jr(e,t);for(const i of s.refDefs??[]){const a=typeof(i==null?void 0:i.refID)=="string"&&i.refID.length>0?i.refID:void 0;a&&!r.includes(a)&&r.push(a)}}catch(s){if(!yt(s))throw s}return r[0]}async function Am(e,t,o){const n=rt();await t.reload();const r=[],s=[];let i=0,a=0,c=0;for(const u of o){const d=await Ue(e,u,n);if(!(d!=null&&d.notebook)){i+=1,a+=1,s.push(u);continue}if(!t.canRead(d.notebook)){i+=1,c+=1;continue}r.push(u)}return{results:r,unresolvedResults:s,rawResultCount:o.length,filteredOutCount:i,unresolvedCount:a,permissionFilteredOutCount:c,...i>0?{partial:!0,reason:c>0?"permission_filtered":"context_unresolved"}:{}}}async function Tm(e){const t=await e.request("/api/file/readDir",{path:hm});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=>mm.test(o))}function Pm(e){if(!e||typeof e!="object")return[];const t=e.values;return Array.isArray(t)?t.filter(o=>!!(o&&typeof o=="object")):[]}async function Cm(e,t,o){if(!t.trim())return[];if(typeof e.request!="function")return[];const n=new Set(o??[]),r=await Tm(e),s=[];for(const i of r)if(!n.has(i))try{const a=await Ur(e,{id:i,keyword:t,page:1,pageSize:3}),c=Pm(a.rows);if(c.length===0)continue;const u=Array.isArray(a.blockIDs)?a.blockIDs.filter(d=>typeof d=="string"&&d.length>0):[];if(u.length===0)continue;s.push({avID:i,avName:a.name,blockID:u[0],blockIDs:u,rows:a.rows,matchedRowCount:c.length,matchSource:"primary_key"})}catch{}return s}function nn(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 Om(e,t){return`<div class="av" data-node-id="${e}" data-av-id="${t}" data-type="NodeAttributeView" data-av-type="table"></div>`}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=nn(o.date,"date"),s=o.endDate===void 0?0:nn(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(i=>({type:i.type,name:i.name??"",content:i.content})),s=o.text??r.map(i=>i.type==="image"?`![](${i.content})`:`[${i.name||i.content}](${i.content})`).join(`
89
+ `);return{...n,type:"mAsset",text:{content:s},mAsset:r}}default:throw new Error(`Unsupported AV valueType: ${o.valueType}`)}}async function $m({client:e,permMgr:t,rawArgs:o}){const n=dp.parse(o),{denied:r,avData:s}=await K(e,t,n.id,"read");if(r)return r;const i=Pt(s);return y({id:n.id,av:s,...i.rows.length>0?{resolvedRows:i.rows.map(a=>({rowID:a.rowID,...a.sourceBlockID?{sourceBlockID:a.sourceBlockID}:{},...a.valueIDs.length>0?{valueIDs:a.valueIDs}:{}}))}:{}})}async function Em({client:e,permMgr:t,rawArgs:o}){const n=hp.parse(o),r=await Nf(e,n.keyword,n.excludes),s=Array.isArray(r.results)?r.results:[],i=await Cm(e,n.keyword,n.excludes),a=[...s],c=new Set(a.map(d=>d&&typeof d=="object"?d.avID:void 0).filter(d=>typeof d=="string"&&d.length>0));for(const d of i){const p=d.avID;typeof p=="string"&&c.has(p)||(typeof p=="string"&&c.add(p),a.push(d))}const u=await Am(e,t,a);return y({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 Nm({client:e,permMgr:t,rawArgs:o}){const n=lp.parse(o),{denied:r}=await K(e,t,n.id,"read");if(r)return r;const s=await Of(e,{id:n.id,blockID:n.blockID,viewID:n.viewID,page:n.page,pageSize:n.pageSize,query:n.query,groupPaging:n.groupPaging,createIfNotExist:n.createIfNotExist}),i=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=Array.isArray(i.rows)?i.rows:[],c=n.page??1,u=n.pageSize??(a.length||1),d=typeof i.pageCount=="number"?i.pageCount:1,p=typeof i.rowCount=="number"?i.rowCount:a.length,{rows:f,pageCount:k,rowCount:_,...w}=i;return ot(a,{total:p,page:c,pageSize:u,pageCount:d,hasNextPage:c<d},{avID:n.id,...w})}async function Rm({client:e,permMgr:t,rawArgs:o}){const n=pp.parse(o),{denied:r,avData:s}=await K(e,t,n.id,"read");if(r)return r;const i=await $f(e,n.id),a=i&&typeof i=="object"&&!Array.isArray(i)&&Array.isArray(i.keys)?i.keys:Array.isArray(i)&&i.length>0?i:gm(s);return y({avID:n.id,keys:a})}async function zm({client:e,permMgr:t,rawArgs:o}){const n=fp.parse(o),{denied:r}=await K(e,t,n.id,"read");if(r)return r;const s=await Ef(e,{id:n.id,...n.blockID?{blockID:n.blockID}:{}});return y({avID:n.id,...n.blockID?{blockID:n.blockID}:{},...s})}async function xm({client:e,permMgr:t,rawArgs:o}){const n=mp.parse(o),{denied:r}=await K(e,t,n.avID,"write");if(r)return r;if(n.blockIDs.length===0)return re({action:"add_rows",avID:n.avID,blockIDs:[],rows:[],added:0,skipped:!0,message:"No blockIDs were provided, so no rows were added."});await Rf(e,{avID:n.avID,blockID:n.blockID,viewID:n.viewID,groupID:n.groupID,previousID:n.previousID,ignoreDefaultFill:n.ignoreDefaultFill,srcs:n.blockIDs.map(i=>({id:i,isDetached:!1}))});const s=await Dm(e,n.avID,n.blockIDs);return s.unresolvedBlockIDs.length>0?wm(n.avID,n.blockIDs,s):S(e,re({action:"add_rows",avID:n.avID,blockIDs:n.blockIDs,rows:s.rows,added:n.blockIDs.length}),[{type:"reloadAttributeView",id:n.avID}])}async function Bm({client:e,permMgr:t,rawArgs:o}){const n=yp.parse(o),{denied:r}=await K(e,t,n.avID,"write");return r||(await zf(e,n.avID,n.srcIDs),S(e,re({action:"remove_rows",avID:n.avID,srcIDs:n.srcIDs,removed:n.srcIDs.length}),[{type:"reloadAttributeView",id:n.avID}]))}async function Fm({client:e,permMgr:t,rawArgs:o}){const n=gp.parse(o),{denied:r}=await K(e,t,n.avID,"write");if(r)return r;const s=n.keyID??pm();return await xf(e,{...n,keyID:s}),S(e,re({action:"add_column",avID:n.avID,keyID:s,keyName:n.keyName,keyType:n.keyType}),[{type:"reloadAttributeView",id:n.avID}])}async function qm({client:e,permMgr:t,rawArgs:o}){const n=bp.parse(o),{denied:r}=await K(e,t,n.avID,"write");if(r)return r;const s=n.keyID??n.columnID;return await Bf(e,n.avID,s,n.removeRelationDest),S(e,re({action:"remove_column",avID:n.avID,keyID:s,removeRelationDest:n.removeRelationDest??!1}),[{type:"reloadAttributeView",id:n.avID}])}async function jm({client:e,permMgr:t,rawArgs:o}){const n=kp.parse(o),{denied:r,avData:s}=await K(e,t,n.avID,"write");if(r)return r;const i=Jr(n.avID,"set_cell",Pt(s),n.rowID);if(!i.ok)return i.result;const a=Qr(n.columnID,i.rowID,n),c=await Ff(e,{avID:n.avID,keyID:n.columnID,itemID:i.rowID,value:a});return S(e,re({action:"set_cell",avID:n.avID,rowID:n.rowID,columnID:n.columnID,valueType:n.valueType},c),[{type:"reloadAttributeView",id:n.avID}])}async function Um({client:e,permMgr:t,rawArgs:o}){const n=_p.parse(o),{denied:r,avData:s}=await K(e,t,n.avID,"write");if(r)return r;const i=Pt(s),a=[];for(let c=0;c<n.items.length;c+=1){const u=n.items[c],d=Jr(n.avID,"batch_set_cells",i,u.rowID,c);if(!d.ok)return d.result;a.push(Qr(u.columnID,d.rowID,u))}return await qf(e,n.avID,a),S(e,re({action:"batch_set_cells",avID:n.avID,updated:n.items.length}),[{type:"reloadAttributeView",id:n.avID}])}async function Zm({client:e,permMgr:t,rawArgs:o}){const n=wp.parse(o),{denied:r,avData:s}=await K(e,t,n.avID,"write");if(r)return r;const i=await jf(e,n.avID);if(!i.avID||!i.blockID)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Pe,action:"duplicate_block",reason:"duplicate_identifiers_missing",message:`Duplicate AV returned incomplete identifiers for source "${n.avID}".`,sourceAvID:n.avID,duplicatedAvID:i.avID,duplicatedBlockID:i.blockID}},null,2)}],isError:!0};const a=n.previousID??await Sm(e,n.avID,s);if(!a)return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Pe,action:"duplicate_block",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:i.avID,duplicatedBlockID:i.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 v(e,t,a,"write");if(c.denied)return c.denied;const u=Om(i.blockID,i.avID);try{await ah(e,[{doOperations:[{action:"insert",id:i.blockID,data:u,previousID:a}],undoOperations:[{action:"delete",id:i.blockID,data:null}]}])}catch(k){const _=k instanceof Error?k:new Error(String(k));return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Pe,action:"duplicate_block",reason:"duplicate_insert_failed",message:_.message,sourceAvID:n.avID,duplicatedAvID:i.avID,duplicatedBlockID:i.blockID,insertedAfter:a,hint:"The duplicate AV definition was prepared, but MCP failed while inserting the duplicated database block into the document tree."}},null,2)}],isError:!0}}const d=await Lr(e,i.blockID);let p=!1,f;try{p=!(await K(e,t,i.avID,"read")).denied}catch(k){f=k instanceof Error?k.message:String(k)}return!d||!p?{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:Pe,action:"duplicate_block",reason:"duplicate_insert_verification_failed",message:`Duplicated AV insertion finished, but MCP could not verify the materialized result for block "${i.blockID}".`,sourceAvID:n.avID,duplicatedAvID:i.avID,duplicatedBlockID:i.blockID,insertedAfter:a,verification:{duplicatedBlockExists:d,duplicatedAvReadable:p,...f?{duplicatedAvReadableMessage:f}:{}},hint:"The duplicate AV definition was inserted, but the resulting AV/block could not be verified. Check the target document tree and duplicated AV state."}},null,2)}],isError:!0}:S(e,re({action:"duplicate_block",sourceAvID:n.avID,prepared:!0,materialized:!0,duplicatedAvReadable:!0,insertedAfter:a,semantics:n.previousID?"duplicated_and_inserted_with_override":"duplicated_and_inserted"},i),[{type:"reloadAttributeView",id:i.avID},{type:"reloadProtyle",id:c.context.documentId}])}async function Lm({client:e,permMgr:t,rawArgs:o}){const n=Ip.parse(o),{denied:r}=await K(e,t,n.avID,"read");if(r)return r;const s=await Ur(e,{id:n.avID,keyword:n.keyword,page:n.page,pageSize:n.pageSize}),i=s.blockIDs??[];if(i.length>0){const a=rt();await t.reload();const c=[],u=[];let d=0;for(let p=0;p<i.length;p+=1){const f=i[p],k=await Ue(e,{id:f},a)??await xe(e,f).catch(()=>null),_=k&&"notebook"in k?k.notebook:void 0;if(!_||!t.canRead(_)){d+=1;continue}c.push(f),u.push(s.rows[p])}return y({avID:n.avID,name:s.name,blockIDs:c,rows:u,...d>0?{filteredOutCount:d,partial:!0,reason:"permission_filtered"}:{}})}return y({avID:n.avID,...s})}const Mm={get:$m,render_attribute_view:Nm,get_attribute_view_keys:Rm,get_attribute_view_filter_sort:zm,search:Em,add_rows:xm,remove_rows:Bm,add_column:Fm,remove_column:qm,set_cell:jm,batch_set_cells:Um,duplicate_block:Zm,get_primary_key_values:Lm},Vm=[{action:"get",schema:g("get",{id:{type:"string",description:"Attribute view ID"}},["id"],"Get the full attribute view payload by AV ID.")},{action:"render_attribute_view",schema:g("render_attribute_view",{id:{type:"string",description:"Attribute view ID"},blockID:{type:"string",description:"Embedding block ID (required for view-specific rendering)"},viewID:{type:"string",description:"View ID to render (optional, defaults to the current active view)"},page:{type:"number",description:"Page number (1-based), default 1"},pageSize:{type:"number",description:"Rows per page, default 48"},query:{type:"string",description:"Filter keyword to narrow rows"},groupPaging:{type:"object",description:"Per-group pagination when the view uses group-by. Keys are group value strings; values are { pageSize: number }.",additionalProperties:{type:"object",properties:{pageSize:{type:"number"}},required:["pageSize"]}},createIfNotExist:{type:"boolean",description:"Whether to create the AV if it does not exist. Default false."}},["id"],"Render an attribute view with optional server-side paging, filtering, and view selection.")},{action:"get_attribute_view_keys",schema:g("get_attribute_view_keys",{id:{type:"string",description:"Attribute view ID"}},["id"],"Get the column (key) definitions of an attribute view.")},{action:"get_attribute_view_filter_sort",schema:g("get_attribute_view_filter_sort",{id:{type:"string",description:"Attribute view ID"},blockID:{type:"string",description:"Optional embedding block ID for view-specific filter/sort"}},["id"],"Get filter and sort settings for an attribute view.")},{action:"search",schema:g("search",{keyword:{type:"string",description:"Keyword to match AV name or primary-key values"},excludes:{type:"array",items:{type:"string"},description:"AV IDs to exclude from results"}},["keyword"],"Search attribute views by name or primary-key values.")},{action:"add_rows",schema:g("add_rows",{avID:{type:"string",description:"Attribute view ID"},blockID:{type:"string",description:"Owning database block ID (optional, inferred when possible)"},viewID:{type:"string",description:"Target view ID"},groupID:{type:"string",description:"Group ID for grouped views"},previousID:{type:"string",description:"Row ID after which to insert (optional)"},ignoreDefaultFill:{type:"boolean",description:"If true, skip default value fill for new rows"},blockIDs:{type:"array",items:{type:"string"},description:"IDs of content blocks to bind as new rows"}},["avID","blockIDs"],"Add rows (bound to content blocks) to a database.")},{action:"remove_rows",schema:g("remove_rows",{avID:{type:"string",description:"Attribute view ID"},srcIDs:{type:"array",items:{type:"string"},description:"Source block IDs of the rows to remove"}},["avID","srcIDs"],"Remove rows from a database.")},{action:"add_column",schema:g("add_column",{avID:{type:"string",description:"Attribute view ID"},keyID:{type:"string",description:"Column key ID (auto-generated if omitted)"},keyName:{type:"string",description:"Column display name"},keyType:{type:"string",description:"Column type (text, number, date, select, mSelect, url, email, phone, checkbox, relation, rollup, template, mAsset, lineNumber, created, updated)"},keyIcon:{type:"string",description:"Column icon"},previousKeyID:{type:"string",description:"Insert after this column"}},["avID","keyName","keyType"],"Add a column to a database.")},{action:"remove_column",schema:g("remove_column",{avID:{type:"string",description:"Attribute view ID"},keyID:{type:"string",description:"Column key ID to remove"},columnID:{type:"string",description:"Alias for keyID (deprecated, use keyID)"},removeRelationDest:{type:"boolean",description:"Also remove the paired relation column in the target AV (default false)"}},["avID"],"Remove a column from a database.")},{action:"set_cell",schema:g("set_cell",{avID:{type:"string",description:"Attribute view ID"},rowID:{type:"string",description:"Row item ID (value.blockID, NOT the source block ID or value.id)"},columnID:{type:"string",description:"Column key ID"},valueType:{type:"string",enum:["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"],description:"Cell value type"},text:{type:"string",description:"Text content (for text, url, email, phone, mAsset types)"},number:{type:"number",description:"Number value"},numberFormat:{type:"string",description:"Number format string"},date:{description:"ISO 8601 date string or epoch milliseconds"},endDate:{description:"End date (ISO 8601 or epoch ms), enables date range"},includeTime:{type:"boolean",description:"Include time in date display"},checked:{type:"boolean",description:"Checkbox state"},option:{type:"string",description:"Single select option content"},options:{type:"array",items:{type:"string"},description:"Multi-select option contents"},relationBlockIDs:{type:"array",items:{type:"string"},description:"Related block IDs"},url:{type:"string",description:"URL value"},email:{type:"string",description:"Email value"},phone:{type:"string",description:"Phone value"},assets:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["image","file"]},content:{type:"string",description:"Asset URL or path"},name:{type:"string",description:"Display name"}},required:["type","content"]},description:"Asset entries for mAsset type"}},["avID","rowID","columnID","valueType"],"Set a single cell value in a database.")},{action:"batch_set_cells",schema:g("batch_set_cells",{avID:{type:"string",description:"Attribute view ID"},items:{type:"array",items:{type:"object",properties:{rowID:{type:"string"},columnID:{type:"string"},valueType:{type:"string",enum:["text","number","date","checkbox","select","multi_select","relation","url","email","phone","mAsset"]},text:{type:"string"},number:{type:"number"},numberFormat:{type:"string"},date:{},endDate:{},includeTime:{type:"boolean"},checked:{type:"boolean"},option:{type:"string"},options:{type:"array",items:{type:"string"}},relationBlockIDs:{type:"array",items:{type:"string"}},url:{type:"string"},email:{type:"string"},phone:{type:"string"},assets:{type:"array",items:{type:"object",properties:{type:{type:"string"},content:{type:"string"},name:{type:"string"}},required:["type","content"]}}},required:["rowID","columnID","valueType"]},description:"Array of cell updates"}},["avID","items"],"Set multiple cell values in a single call.")},{action:"duplicate_block",schema:g("duplicate_block",{avID:{type:"string",description:"Source attribute view ID to duplicate"},previousID:{type:"string",description:"Block ID after which to insert the duplicate (optional, auto-resolved)"}},["avID"],"Duplicate an attribute view and insert it into the document tree.")},{action:"get_primary_key_values",schema:g("get_primary_key_values",{avID:{type:"string",description:"Attribute view ID"},keyword:{type:"string",description:"Filter by keyword in primary key values"},page:{type:"number",description:"Page number (1-based), default 1"},pageSize:{type:"number",description:"Rows per page, default all"}},["avID"],"Get primary key values for an attribute view.")}],Xr=se({name:"av",description:"🗃️ Grouped attribute-view (database) operations.",variants:Vm,actionSchema:Ud,aggregateOptions:{guidance:qn,actionHints:Yn},handlers:Mm});function Gm(e){return Xr.listTools(e)}async function Hm(e,t,o,n){return Xr.callTool(e,t,o,n)}async function Be(e,t,o){const n={id:t,attrs:o};return e.request("/api/attr/setBlockAttrs",n)}async function es(e,t){const o={id:t};return e.request("/api/attr/getBlockAttrs",o)}const Ym=/[\u200B\u200C\u200D\u2060\uFEFF]/g,Wm=/<[^>]+>/g;function Do(e){return e.replace(Ym,"")}function ts(e){return{...e,content:Do(e.content)}}function Jm(e){return{...e,kramdown:Do(e.kramdown)}}function os(e){return e.replace(Wm,"")}const ns={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"};function Km(e){const t={};for(const o of e){const n=ns[o];n&&(t[n]=!0)}return t}function Qm(e){const t={};for(const[o,n]of Object.entries(e)){const r=ns[o];r?t[r]=n:t[o]=n}return t}const rn={relevance:7,date:4,updated_desc:4,updated_asc:3,created_desc:2,created_asc:1,type:0};function Xm(e,t){return e&&e in rn?rn[e]:t}function ey(e,t){return!t||!Array.isArray(e.blocks)?e:{...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=os(s)),r})}}const ty=["id","type","box"],oy=["hPath","hpath"],ny=["content","plainContent","markdown","name","alias","memo","tag","subType","subtype","rootID","root_id"];function sn(e){return!(e==null||e===""||Array.isArray(e)&&e.length===0)}function ry(e){const t={};for(const o of ty)o in e&&(t[o]=e[o]);for(const o of oy)if(sn(e[o])){t.hPath=e[o];break}for(const o of ny)sn(e[o])&&(t[o]=e[o]);return t}const sy=/<mark>[^<]*<\/mark>/g,Ft=400,iy=150;function ay(e,t=iy){if(e.length<=Ft)return e;const o=[...e.matchAll(sy)];if(o.length===0)return e.length>Ft?e.slice(0,Ft)+"...":e;const n=[];for(const i of o){const a=Math.max(0,i.index-t),c=Math.min(e.length,i.index+i[0].length+t);n.push([a,c])}const r=[n[0]];for(let i=1;i<n.length;i++){const a=r[r.length-1],c=n[i];c[0]<=a[1]?a[1]=Math.max(a[1],c[1]):r.push(c)}const s=[];r[0][0]>0&&s.push("...");for(let i=0;i<r.length;i++)i>0&&s.push("..."),s.push(e.slice(r[i][0],r[i][1]));return r[r.length-1][1]<e.length&&s.push("..."),s.join("")}const an=400,cn=200;function rs(e){return e.map(t=>{if(!t||typeof t!="object")return t;const n=ry(t);if(n.type==="NodeDocument")return n;if(typeof n.content=="string"){const r=os(n.content).trim();r.length>0&&(n.excerpt=r.length>cn?r.slice(0,cn)+"...":r),n.content=ay(n.content)}return typeof n.markdown=="string"&&n.markdown.length>an&&(n.markdown=n.markdown.slice(0,an)+"..."),n})}function cy(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 Wt(e,t){const o=e.filter(n=>{const r=cy(n);return!r||t.canRead(r)});return{items:o,removedCount:e.length-o.length}}function Ct(e){return e>0?{partial:!0,filteredOutCount:e,reason:"permission_filtered"}:{}}function un(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 dt(e,t,o){const n=rt(),r=[];let s=0;for(const i of t){const a=await Ue(e,i,n);if(!(a!=null&&a.notebook)||!o.canRead(a.notebook)){s+=1;continue}r.push(i)}return{items:r,removedCount:s}}async function qt(e,t,o,n){const r=rt(),s=[];let i=0,a=0;const c=typeof n=="string"&&n.length>0?n.startsWith("/")?n:`/${n}`:void 0;for(const u of t){const d=await Ue(e,u,r);if(!(d!=null&&d.notebook)||!o.canRead(d.notebook)){i+=1;continue}if(c&&(!d.path||!(d.path===c||d.path.startsWith(`${c}/`)))){a+=1;continue}s.push(u)}return{items:s,permissionFilteredOutCount:i,pathFilteredOutCount:a}}function dn(e,t){if(!Array.isArray(e.blocks))return e;const{items:o,removedCount:n}=Wt(e.blocks,t),r=new Set;for(const s of o){if(!s||typeof s!="object")continue;const i=s,a=[i.rootID,i.rootId,i.root_id,i.id,i.path].find(c=>typeof c=="string"&&c.length>0);a&&r.add(a)}return{...e,blocks:o,matchedBlockCount:o.length,matchedRootCount:r.size,...n>0?{filteredOutBlockCount:n}:{}}}function Ge(e,t){const o=Array.isArray(e.backlinks)?Wt(e.backlinks,t):void 0,n=Array.isArray(e.backmentions)?Wt(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}:{},...Ct(r)}}function uy(e){return e.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_").replace(/'/g,"''")}function dy(e){return!!e&&typeof e=="object"}function ly(e){var n;const o=(n=e.trim().split(/\s+/)[0])==null?void 0:n.toUpperCase();if(o!=="SELECT"&&o!=="WITH")throw new Error("Only SELECT and WITH (CTE) statements are allowed. Mutation queries (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE) are forbidden.")}async function py(e,t){const o=await nt(e,`SELECT content, name FROM blocks WHERE id = '${de(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 fy(e,t,o,n){const s=["s.type = 'textmark block-ref'",`instr(s.markdown, '${de(t)}') > 0`];return n&&s.push(`s.root_id = '${de(n)}'`),o&&o.trim()&&s.push(`b.content LIKE '%${uy(o.trim())}%' ESCAPE '\\'`),nt(e,`
90
+ SELECT
91
+ s.block_id AS id,
92
+ s.root_id,
93
+ s.box,
94
+ s.path,
95
+ b.hpath,
96
+ b.type,
97
+ b.content,
98
+ b.markdown
99
+ FROM spans s
100
+ LEFT JOIN blocks b ON b.id = s.block_id
101
+ WHERE ${s.join(" AND ")}
102
+ ORDER BY b.updated DESC
103
+ LIMIT 200
104
+ `.trim())}async function ss(e,t,o,n){const r=await py(e,t);if(!r)return[];const s=[`id != '${de(t)}'`,`instr(content, '${de(r)}') > 0`];return n&&s.push(`root_id = '${de(n)}'`),o&&o.trim()&&s.push(`instr(content, '${de(o.trim())}') > 0`),nt(e,`
105
+ SELECT
106
+ id,
107
+ root_id,
108
+ box,
109
+ path,
110
+ hpath,
111
+ type,
112
+ content,
113
+ markdown
114
+ FROM blocks
115
+ WHERE ${s.join(" AND ")}
116
+ ORDER BY updated DESC
117
+ LIMIT 200
118
+ `.trim())}async function hy(e,t,o,n){const r=await zh(e,t,o,n);if(dy(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,i]=await Promise.all([fy(e,t,o,n),ss(e,t,o,n)]);return{backlinks:s,backmentions:i,fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}async function my(e,t,o,n){const r=await xh(e,t,o,n);return r&&typeof r=="object"&&Array.isArray(r.backmentions)?{backmentions:r.backmentions}:{backmentions:await ss(e,t,o,n),fallbackUsed:!0,sourcePayloadMissing:!0,fallbackQuery:"sql",resultConfidence:"fallback"}}const yy="search";function gy(e){let t=e.types?Qm(e.types):e.types;return e.typeShortcodes&&e.typeShortcodes.length>0&&(t={...Km(e.typeShortcodes),...t}),t}function by(e){return e.parentId?Math.min((e.pageSize??32)*3,128):e.pageSize}function ky(e){const t=e;return Array.isArray(t.blocks)&&(t.blocks=rs(t.blocks)),t}function _y(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 wy(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 Iy(e,t){const o=e,n=Array.isArray(o.blocks)?o.blocks:[],r=e,s=typeof r.pageCount=="number"?r.pageCount:1,i=t.page??1,a=t.pageSize??32,c=ko(n,20,`Use page/pageSize parameters to paginate. Current page: ${i}.`),u=typeof r.matchedBlockCount=="number"?r.matchedBlockCount:n.length,{blocks:d,pageCount:p,...f}=r;return ot(c.items,{total:u,page:i,pageSize:a,pageCount:s,hasNextPage:i<s},{...f,...c.meta?c.meta:{},...t.parentId&&n.length===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."}:{}})}function vy(e,t){const o=ko(e,50,"Add LIMIT and OFFSET to your SQL for pagination."),n=e.length;return ot(o.items,{total:n,page:1,pageSize:n,pageCount:1,hasNextPage:!1},{...Ct(t),...o.meta?o.meta:{}})}function Dy(e,t,o){const n=ko(t,20,"Use page/pageSize parameters to paginate asset content results.");return y({...e,assetContents:n.items,...Ct(o),...n.meta?n.meta:{}})}const Sy={fulltext:async({client:e,permMgr:t,rawArgs:o})=>{const n=xp.parse(o);if(n.parentId){const{denied:u}=await v(e,t,n.parentId,"read");if(u)return u}const r=Xm(n.sortBy,n.orderBy),s=await Nh(e,{query:n.query,method:n.method,types:gy(n),paths:n.paths,groupBy:n.groupBy,orderBy:r,page:n.page,pageSize:by(n)}),i=dn(s,t),a=ey(i,n.stripHtml??!1),c=ky(a);return n.parentId&&_y(c,n.parentId),n.hasTags!==void 0&&wy(c,n.hasTags),Iy(a,n)},query_sql:async({client:e,permMgr:t,rawArgs:o})=>{const n=Bp.parse(o);try{ly(n.stmt)}catch(a){return gt(a,{tool:yy,action:"query_sql",rawArgs:o})}const r=await nt(e,n.stmt),s=Array.isArray(r)?r:[],i=await dt(e,s,t);return vy(i.items,i.removedCount)},search_tag:async({client:e,rawArgs:t})=>{const o=Fp.parse(t),n=await Rh(e,o.k),r=n&&typeof n=="object"?n:{},s=Array.isArray(r.tags)?r.tags:[];return y({...r,...o.k.trim().length>0&&s.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."}:{}})},get_backlinks:async({client:e,permMgr:t,rawArgs:o})=>{const n=qp.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;try{const s=await hy(e,n.id,n.keyword,n.refTreeID),i=Ge(s,t);return y({...i,...s.sourcePayloadMissing?{sourcePayloadMissing:!0}:{},...s.fallbackQuery?{fallbackQuery:s.fallbackQuery}:{},...s.resultConfidence?{resultConfidence:s.resultConfidence}:{},...s.fallbackUsed?{warning:"SiYuan returned no backlink payload; SQL fallback results are shown."}:{}})}catch(s){if(un(s))return y({backlinks:[],backmentions:[],warning:"SiYuan rejected part of the backlink query due to restricted notebooks; restricted results were omitted.",partial:!0,reason:"permission_filtered"});throw s}},get_backmentions:async({client:e,permMgr:t,rawArgs:o})=>{const n=jp.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;try{const s=await my(e,n.id,n.keyword,n.refTreeID),i=Ge(s,t);return y({...i,...s.sourcePayloadMissing?{sourcePayloadMissing:!0}:{},...s.fallbackQuery?{fallbackQuery:s.fallbackQuery}:{},...s.resultConfidence?{resultConfidence:s.resultConfidence}:{},...s.fallbackUsed?{warning:"SiYuan returned no backmention payload; SQL fallback results are shown."}:{}})}catch(s){if(un(s))return y({backmentions:[],warning:"SiYuan rejected part of the backmention query due to restricted notebooks; restricted results were omitted.",partial:!0,reason:"permission_filtered"});throw s}},search_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=Up.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Bh(e,n),i=s&&typeof s=="object"?s:{},a=Array.isArray(i.blocks)?i.blocks:[],c=await dt(e,a,t);return y({...i,blocks:rs(c.items),...Ct(c.removedCount)})},find_replace:async({client:e,permMgr:t,rawArgs:o})=>{const n=Zp.parse(o);for(const r of n.ids){const{denied:s}=await v(e,t,r,"write");if(s)return s}if(Array.isArray(n.paths))for(const r of n.paths){const s=await Qe(e,r);if(!s)continue;const i=await x(t,s,"write");if(i)return i}return await Fh(e,n),y({success:!0,replaced:!0,ids:n.ids,k:n.k,r:n.r,...n.paths?{paths:n.paths}:{}})},search_assets:async({client:e,rawArgs:t})=>{const o=Lp.parse(t),n=await qh(e,o.k,o.exts);return y(n)},get_asset_content:async({client:e,rawArgs:t})=>{const o=Mp.parse(t),n=await jh(e,o.id,o.query,o.queryMethod??0);return y(n)},fulltext_asset_content:async({client:e,permMgr:t,rawArgs:o})=>{const n=Vp.parse(o),r=await Uh(e,n),s=r&&typeof r=="object"?r:{},i=Array.isArray(s.assetContents)?s.assetContents:[],a=await dt(e,i,t);return Dy(s,a.items,a.removedCount)},list_invalid_refs:async({client:e,permMgr:t,rawArgs:o})=>{const n=Gp.parse(o),r=await Zh(e,n.page,n.pageSize),s=dn(r??{},t);return y(s)}},Ay="search",Ty=[{action:"fulltext",schema:g("fulltext",{query:{type:"string",description:"Search query string"},method:{type:"number",description:"Search method: 0=keyword (default), 1=query syntax, 2=SQL, 3=regex"},types:{type:"object",additionalProperties:{type:"boolean"},description:'Block type filter. Accepts full names (e.g. {"heading": true}) or shortcodes (e.g. {"h": true, "p": true}). Shortcodes: 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, audio, widget.'},typeShortcodes:{type:"array",items:{type:"string"},description:'Alternative shorthand type filter as array: ["h","p"]. Merged with types if both provided.'},paths:{type:"array",items:{type:"string"},description:"Restrict search to specific notebook paths"},groupBy:{type:"number",description:"0=no grouping (default), 1=group by document"},orderBy:{type:"number",description:"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:{type:"string",description:'Named sort: "relevance", "date", "updated_desc", "updated_asc", "created_desc", "created_asc", "type". Overrides orderBy.'},page:{type:"number",description:"Page number (1-based), default 1"},pageSize:{type:"number",description:"Results per page, default 32, max 128"},parentId:{type:"string",description:"Post-filter: only return blocks within this document subtree (matches root_id or parent_id)"},hasTags:{type:"boolean",description:"When true, only blocks with tags; when false, only blocks without tags"},stripHtml:{type:"boolean",description:"When true, add plain-text fields while keeping highlighted HTML content unchanged"}},["query"],"Full-text search across all blocks.")},{action:"query_sql",schema:g("query_sql",{stmt:{type:"string",description:"SQL SELECT statement to execute against the blocks/spans/assets tables"}},["stmt"],"Execute a read-only SQL query against the database.")},{action:"search_tag",schema:g("search_tag",{k:{type:"string",description:"Tag keyword to search for"}},["k"],"Search for tags matching a keyword.")},{action:"get_backlinks",schema:g("get_backlinks",{id:{type:"string",description:"Block or document ID to find backlinks for"},keyword:{type:"string",description:"Filter backlinks by keyword"},refTreeID:{type:"string",description:"Optional document tree ID to narrow backlink scope"}},["id"],"Find documents/blocks that link to the given block.")},{action:"get_backmentions",schema:g("get_backmentions",{id:{type:"string",description:"Block or document ID to find backmentions for"},keyword:{type:"string",description:"Filter backmentions by keyword"},refTreeID:{type:"string",description:"Optional document tree ID to narrow backmention scope"}},["id"],"Find documents/blocks that mention the given block name.")},{action:"search_refs",schema:g("search_refs",{id:{type:"string",description:"Referenced block or document ID"},rootID:{type:"string",description:"Optional current root document ID"},k:{type:"string",description:"Keyword filter"},beforeLen:{type:"number",description:"Context length before the reference, default 512"},isSquareBrackets:{type:"boolean",description:"Search in square-bracket reference mode"},isDatabase:{type:"boolean",description:"Whether the reference target is a database"},reqId:{type:"string",description:"Optional passthrough request ID"}},["id"],"Search blocks that reference a given block or document.")},{action:"find_replace",schema:g("find_replace",{k:{type:"string",description:"Find keyword"},r:{type:"string",description:"Replacement text; use empty string to delete matches"},ids:{type:"array",items:{type:"string"},description:"Document or block IDs to mutate"},paths:{type:"array",items:{type:"string"},description:"Optional path scope list"},types:{type:"object",additionalProperties:{type:"boolean"},description:"Optional block type filter"},method:{type:"number",description:"Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"},orderBy:{type:"number",description:"Sort order"},groupBy:{type:"number",description:"Grouping mode"},replaceTypes:{type:"object",additionalProperties:{type:"boolean"},description:"Replace target kinds such as text, code, docTitle, blockRef"}},["k","r","ids"],"Find and replace text in documents or blocks.")},{action:"search_assets",schema:g("search_assets",{k:{type:"string",description:"Asset filename keyword"},exts:{type:"array",items:{type:"string"},description:"Optional extension filters"}},["k"],"Search asset files by filename.")},{action:"get_asset_content",schema:g("get_asset_content",{id:{type:"string",description:"Asset content ID"},query:{type:"string",description:"Matched query text"},queryMethod:{type:"number",description:"Query method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"}},["id","query"],"Get a specific asset-content record.")},{action:"fulltext_asset_content",schema:g("fulltext_asset_content",{query:{type:"string",description:"Search query string"},types:{type:"object",additionalProperties:{type:"boolean"},description:"Asset type filter"},method:{type:"number",description:"Search method: 0=keyword, 1=query syntax, 2=SQL, 3=regex"},orderBy:{type:"number",description:"Sort order: 0=relevance DESC, 1=relevance ASC, 2=updated ASC, 3=updated DESC"},page:{type:"number",description:"Page number (1-based)"},pageSize:{type:"number",description:"Results per page"}},["query"],"Full-text search indexed asset contents.")},{action:"list_invalid_refs",schema:g("list_invalid_refs",{page:{type:"number",description:"Page number (1-based)"},pageSize:{type:"number",description:"Results per page"}},[],"List invalid block references.")}],is=se({name:Ay,description:"🔍 Grouped search and query operations.",variants:Ty,actionSchema:zp,aggregateOptions:{guidance:Jn,actionHints:Kn},handlers:Sy});function Py(e){return is.listTools(e)}async function Cy(e,t,o,n){return is.callTool(e,t,o,n)}function Oy(e){return typeof e!="string"?!1:e!=="d"}function $y(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 Ey(e,t){const o=rt(),n=new Map;let r=!1;for(const s of t){s&&typeof s=="object"&&Oy(s.type)&&(r=!0);const i=await Ue(e,s,o);if(!(i!=null&&i.documentId)||!i.notebook||!i.path)continue;let a=n.get(i.documentId);if(!a){let c,u;try{const d=await xe(e,i.documentId);c=d.name,u=d.hPath}catch{c=void 0,u=void 0}a={documentId:i.documentId,notebook:i.notebook,path:i.path,...u?{hPath:u}:{},...c?{name:c}:{},updatedBlockCount:0,sampleBlocks:[]},n.set(i.documentId,a)}a.updatedBlockCount+=1,a.sampleBlocks.length<3&&a.sampleBlocks.push($y(s))}return{documents:[...n.values()],containsLowLevelBlocks:r}}function So(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,i=typeof(n==null?void 0:n.previousID)=="string"?n.previousID:t.previousID,a=typeof(n==null?void 0:n.nextID)=="string"?n.nextID:t.nextID;return re({action:t.action,...r?{id:r}:{},...s?{parentID:s}:{},...i?{previousID:i}:{},...a?{nextID:a}:{},dataType:t.dataType})}function Ny(e,t){const o={success:!0,id:t.id,dataType:t.dataType};if(t.dataType==="markdown"&&(o.markdown=Do(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."),y(o)}const Ry=async({client:e,permMgr:t,rawArgs:o})=>{const n=zl.parse(o),r=n.nextID||n.previousID||n.parentID;let s;if(r){const{denied:a,context:c}=await v(e,t,r,"write");if(a)return a;s=c.documentId}const i=await Uf(e,n.dataType,n.data,n.nextID,n.previousID,n.parentID);return S(e,So(i,{action:"insert",dataType:n.dataType,parentID:n.parentID,previousID:n.previousID,nextID:n.nextID}),s?[{type:"reloadProtyle",id:s}]:[])},zy=async({client:e,permMgr:t,rawArgs:o})=>{const n=xl.parse(o),{denied:r,context:s}=await v(e,t,n.parentID,"write");if(r)return r;const i=await Zf(e,n.dataType,n.data,n.parentID);return S(e,So(i,{action:"prepend",dataType:n.dataType,parentID:n.parentID}),[{type:"reloadProtyle",id:s.documentId}])},xy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Bl.parse(o),{denied:r,context:s}=await v(e,t,n.parentID,"write");if(r)return r;const i=await Lf(e,n.dataType,n.data,n.parentID);return S(e,So(i,{action:"append",dataType:n.dataType,parentID:n.parentID}),[{type:"reloadProtyle",id:s.documentId}])},By=async({client:e,permMgr:t,rawArgs:o})=>{const n=Fl.parse(o),{denied:r,context:s}=await v(e,t,n.id,"write");if(r)return r;const i=await Mf(e,n.dataType,n.data,n.id);return S(e,Ny(i,{id:n.id,dataType:n.dataType,data:n.data}),[{type:"reloadProtyle",id:s.documentId}])},Fy=async({client:e,permMgr:t,rawArgs:o})=>{const n=ql.parse(o),{denied:r,context:s}=await v(e,t,n.id,"delete");return r||(await Vf(e,n.id),S(e,y({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId}]))},qy=async({client:e,permMgr:t,rawArgs:o})=>{const n=jl.parse(o),r=await v(e,t,n.id,"write");if(r.denied)return r.denied;if(n.parentID){const a=await v(e,t,n.parentID,"write");if(a.denied)return a.denied}if(n.previousID){const a=await v(e,t,n.previousID,"write");if(a.denied)return a.denied}const s=await Gf(e,n.id,n.previousID,n.parentID),i=[{type:"reloadProtyle",id:r.context.documentId}];if(n.parentID){const a=await v(e,t,n.parentID,"write");if(a.denied)return a.denied;i.push({type:"reloadProtyle",id:a.context.documentId})}if(n.previousID){const a=await v(e,t,n.previousID,"write");if(a.denied)return a.denied;i.push({type:"reloadProtyle",id:a.context.documentId})}return S(e,re({id:n.id,...n.previousID?{previousID:n.previousID}:{},...n.parentID?{parentID:n.parentID}:{}},s),i)},jy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ul.parse(o),{denied:r,context:s}=await v(e,t,n.id,"write");return r||(n.folded?await Hf(e,n.id):await Yf(e,n.id),S(e,y({success:!0,id:n.id,folded:n.folded}),[{type:"reloadProtyle",id:s.documentId}]))},Uy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Zl.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=Jm(await Wf(e,n.id));return y(s)},Zy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ll.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Zr(e,n.id),i=Array.isArray(s)?s:[],a=qr(i,n.page??1,n.pageSize??50);return ot(a.items,a,{...a.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.'}:{}})},Ly=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ml.parse(o),r=await v(e,t,n.fromID,"write");if(r.denied)return r.denied;const s=await v(e,t,n.toID,"write");return s.denied?s.denied:(await Jf(e,n.fromID,n.toID,n.refIDs),S(e,y({success:!0,fromID:n.fromID,toID:n.toID}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId}]))},My=async({client:e,permMgr:t,rawArgs:o})=>{const n=Vl.parse(o),{denied:r,context:s}=await v(e,t,n.id,"write");return r||(await Be(e,n.id,n.attrs),S(e,y({success:!0,id:n.id,attrs:n.attrs}),[{type:"reloadProtyle",id:s.documentId}]))},Vy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Gl.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await es(e,n.id);return y(s)},Gy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Hl.parse(o);try{const{denied:s}=await v(e,t,n.id,"read");if(s)return s}catch(s){if(yt(s))return y({id:n.id,exists:!1});throw s}const r=await Lr(e,n.id);return y({id:n.id,exists:r})},Hy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Yl.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Kf(e,n.id);return y(s)},Yy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Wl.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Qf(e,n.id,n.excludeTypes);return y(s)},Wy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Jl.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Xf(e,n.id);return y(s)},Jy=async({client:e,permMgr:t,rawArgs:o})=>{const n=Kl.parse(o),r=await eh(e),s=Array.isArray(r)?r:[],i=await dt(e,s,t),a=typeof n.count=="number"?n.count:void 0,c=typeof a=="number"?i.items.slice(0,a):i.items,u=await Ey(e,c);return y({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.",...i.removedCount>0?{partial:!0,filteredOutCount:i.removedCount,reason:"permission_filtered"}:{}})},Ky=async({client:e,permMgr:t,rawArgs:o})=>{const n=Ql.parse(o);for(const s of n.ids){const{denied:i}=await v(e,t,s,"read");if(i)return i}const r=await th(e,n.ids);return y(r)},Qy=async({client:e,permMgr:t,rawArgs:o})=>{const n=tp.parse(o),r=new Set;for(const i of n.blocks){const a=i.nextID||i.previousID||i.parentID;if(!a)continue;const{denied:c,context:u}=await v(e,t,a,"write");if(c)return c;r.add(u.documentId)}const s=await oh(e,n.blocks);return S(e,y({success:!0,action:"batch_insert",count:n.blocks.length,transactions:s}),[...r].map(i=>({type:"reloadProtyle",id:i})))},Xy=async({client:e,permMgr:t,rawArgs:o})=>{const n=op.parse(o),r=new Set;for(const i of n.blocks){const{denied:a,context:c}=await v(e,t,i.id,"write");if(a)return a;r.add(c.documentId)}const s=await nh(e,n.blocks);return S(e,y({success:!0,action:"batch_update",count:n.blocks.length,transactions:s}),[...r].map(i=>({type:"reloadProtyle",id:i})))},eg=async({client:e,permMgr:t,rawArgs:o})=>{const n=np.parse(o),r=await x(t,n.notebook,"write");if(r)return r;const s=await rh(e,n.notebook,n.dataType,n.data);return S(e,y({success:!0,action:"append_daily_note",notebook:n.notebook,dataType:n.dataType,transactions:s}),[{type:"reloadFiletree"}])},tg=async({client:e,permMgr:t,rawArgs:o})=>{const n=rp.parse(o),r=await x(t,n.notebook,"write");if(r)return r;const s=await sh(e,n.notebook,n.dataType,n.data);return S(e,y({success:!0,action:"prepend_daily_note",notebook:n.notebook,dataType:n.dataType,transactions:s}),[{type:"reloadFiletree"}])},og=async({client:e,permMgr:t,rawArgs:o})=>{const n=sp.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Io(e,n.id);return y(s)},ng=async({client:e,permMgr:t,rawArgs:o})=>{const n=ip.parse(o);for(const s of n.ids){const{denied:i}=await v(e,t,s,"read");if(i)return i}const r=await ih(e,n.ids,n.refCount??!1,n.av??!1);return y(r)},rg={insert:Ry,prepend:zy,append:xy,update:By,delete:Fy,move:qy,set_fold_state:jy,get_kramdown:Uy,get_children:Zy,transfer_ref:Ly,set_attrs:My,get_attrs:Vy,exists:Gy,info:Hy,breadcrumb:Yy,dom:Wy,recent_updated:Jy,word_count:Ky,batch_insert:Qy,batch_update:Xy,append_daily_note:eg,prepend_daily_note:tg,doc_info:og,docs_info:ng},sg=[{action:"insert",schema:g("insert",{dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Block content"},nextID:{type:"string",description:"Next block ID"},previousID:{type:"string",description:"Previous block ID"},parentID:{type:"string",description:"Parent block or document ID"}},["dataType","data"],"Insert a new block at the specified position.")},{action:"prepend",schema:g("prepend",{dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Block content"},parentID:{type:"string",description:"Parent block or document ID"}},["dataType","data","parentID"],"Insert a block at the beginning of a parent.")},{action:"append",schema:g("append",{dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Block content"},parentID:{type:"string",description:"Parent block or document ID"}},["dataType","data","parentID"],"Insert a block at the end of a parent.")},{action:"update",schema:g("update",{dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"New block content"},id:{type:"string",description:"Block ID"}},["dataType","data","id"],"Update block content.")},{action:"delete",schema:g("delete",{id:{type:"string",description:"Block ID"}},["id"],"Delete a block by ID.")},{action:"move",schema:g("move",{id:{type:"string",description:"Block ID"},previousID:{type:"string",description:"Previous block ID"},parentID:{type:"string",description:"New parent block ID"}},["id"],"Move a block to a new position.")},{action:"set_fold_state",schema:g("set_fold_state",{id:{type:"string",description:"Foldable block ID"},folded:{type:"boolean",description:"true to fold, false to unfold"}},["id","folded"],"Set the fold state of a foldable block.")},{action:"get_kramdown",schema:g("get_kramdown",{id:{type:"string",description:"Block ID or document ID"}},["id"],"Get block content in kramdown format.")},{action:"get_children",schema:g("get_children",{id:{type:"string",description:"Block ID or document ID"},page:{type:"number",description:"Page number (1-based), default 1"},pageSize:{type:"number",description:"Items per page, default 50"}},["id"],"Get child blocks of a parent with pagination support.")},{action:"transfer_ref",schema:g("transfer_ref",{fromID:{type:"string",description:"Source block ID"},toID:{type:"string",description:"Target block ID"},refIDs:{type:"array",items:{type:"string"},description:"Reference block IDs"}},["fromID","toID"],"Transfer block references from one block to another.")},{action:"set_attrs",schema:g("set_attrs",{id:{type:"string",description:"Block ID"},attrs:{type:"object",description:"Block attributes",additionalProperties:{type:"string"}}},["id","attrs"],"Set block attributes.")},{action:"get_attrs",schema:g("get_attrs",{id:{type:"string",description:"Block ID"}},["id"],"Get block attributes.")},{action:"exists",schema:g("exists",{id:{type:"string",description:"Block ID"}},["id"],"Check whether a block exists.")},{action:"info",schema:g("info",{id:{type:"string",description:"Block ID"}},["id"],"Get block position and root document metadata.")},{action:"breadcrumb",schema:g("breadcrumb",{id:{type:"string",description:"Block ID"},excludeTypes:{type:"array",items:{type:"string"},description:"Optional block types to exclude"}},["id"],"Get the breadcrumb path for a block.")},{action:"dom",schema:g("dom",{id:{type:"string",description:"Block ID"}},["id"],"Get rendered DOM for a block.")},{action:"recent_updated",schema:g("recent_updated",{count:{type:"number",description:"Maximum number of recent blocks to return"}},[],"Get recently updated blocks.")},{action:"word_count",schema:g("word_count",{ids:{type:"array",items:{type:"string"},description:"One or more block IDs"}},["ids"],"Get word-count statistics for blocks.")},{action:"batch_insert",schema:g("batch_insert",{blocks:{type:"array",description:"Blocks to insert",items:{type:"object",additionalProperties:!1,properties:{dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Block content"},nextID:{type:"string",description:"Next block ID"},previousID:{type:"string",description:"Previous block ID"},parentID:{type:"string",description:"Parent block or document ID"}},required:["dataType","data"]}}},["blocks"],"Insert multiple blocks in one request.")},{action:"batch_update",schema:g("batch_update",{blocks:{type:"array",description:"Blocks to update",items:{type:"object",additionalProperties:!1,properties:{id:{type:"string",description:"Block ID"},dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Replacement block content"}},required:["id","dataType","data"]}}},["blocks"],"Update multiple blocks in one request.")},{action:"append_daily_note",schema:g("append_daily_note",{notebook:{type:"string",description:"Notebook ID"},dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Block content"}},["notebook","dataType","data"],"Append a block to today’s daily note, creating the note if needed.")},{action:"prepend_daily_note",schema:g("prepend_daily_note",{notebook:{type:"string",description:"Notebook ID"},dataType:{type:"string",enum:["markdown","dom"],description:"Data format"},data:{type:"string",description:"Block content"}},["notebook","dataType","data"],"Prepend a block to today’s daily note, creating the note if needed.")},{action:"doc_info",schema:g("doc_info",{id:{type:"string",description:"Block ID or document ID"}},["id"],"Get owning document info for a block or document ID.")},{action:"docs_info",schema:g("docs_info",{ids:{type:"array",items:{type:"string"},description:"Document IDs"},refCount:{type:"boolean",description:"When true, include reference counts"},av:{type:"boolean",description:"When true, include AV metadata"}},["ids"],"Get document info for multiple documents.")}],as=se({name:"block",description:"🧱 Grouped block operations.",variants:sg,actionSchema:jd,aggregateOptions:{guidance:Fn,actionHints:Hn,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:rg}),ig=as.listTools,ag=as.callTool;async function cg(e,t,o,n){const r=new FormData,s=new File([o],n);r.append("assetsDirPath",t),r.append("file[]",s,n);const i=`${e.getBaseUrl()}/api/asset/upload`,a=e.getAuthHeaders(),c=await fetch(i,{method:"POST",headers:a,body:r});if(!c.ok)throw new Error(`HTTP error: ${c.status} ${c.statusText}`);const u=await c.json();if(u.code!==0)throw new Error(`SiYuan API error: ${u.code} - ${u.msg}`);return u.data}async function ug(e,t,o){const n={id:t,path:o};return e.request("/api/template/render",n)}async function dg(e,t){const o={template:t};return e.request("/api/template/renderSprig",o)}async function cs(e,t){const o={id:t};return e.request("/api/export/exportMdContent",o)}async function lg(e,t,o){const n={paths:t,name:o};return e.request("/api/export/exportResources",n)}async function pg(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushMsg",n)}async function fg(e,t,o){const n={msg:t,timeout:o};return e.request("/api/notification/pushErrMsg",n)}async function hg(e){return e.request("/api/system/version")}async function mg(e){return e.request("/api/system/currentTime")}async function yg(e){return e.request("/api/asset/getUnusedAssets",{})}async function gg(e,t){return e.request("/api/asset/getDocAssets",{id:t})}async function bg(e,t){return e.request("/api/asset/getDocImageAssets",{id:t})}async function kg(e,t){return e.request("/api/asset/getImageOCRText",t?{path:t}:{})}async function _g(e){return e.request("/api/asset/removeUnusedAssets",{})}async function wg(e,t,o){return e.request("/api/asset/renameAsset",{oldPath:t,newName:o})}async function Ig(e,t){return e.request("/api/asset/deleteAsset",{path:t})}async function vg(e,t,o){return e.request("/api/asset/setImageAlpha",{path:t,alpha:o})}const jt=[120,240];function Dg(e){return e instanceof Error&&/SiYuan API error:\s*-1\s*-\s*indexing/i.test(e.message)}async function Sg(e){await new Promise(t=>setTimeout(t,e))}async function Ag(e,t){let o;for(let r=0;r<=jt.length;r+=1)try{return await Vr(e,t)}catch(s){if(!Dg(s)||r===jt.length){o=s;break}o=s,await Sg(jt[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 Tg(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 Jt(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,...i}=r;return{...i,childCount:s.length,childrenTruncated:!0}}return Array.isArray(r.children)?{...r,children:Jt(r.children,t,o+1)}:r}):e}async function Kt(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},i=typeof r.id=="string"?r.id:void 0;if(i&&(r.name===void 0||r.icon===void 0))try{let a=o.get(i);a||(a=Io(e,i),o.set(i,a));const c=await a;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 Kt(e,r.children,o)),s})):t}function Pg(e,t){if(Array.isArray(e))return Ge({backmentions:e},t).backmentions;if(!e||typeof e!="object")return e;const o=e;return Array.isArray(o.files)?{...o,files:Ge({backmentions:o.files},t).backmentions}:Array.isArray(o.docs)?{...o,docs:Ge({backmentions:o.docs},t).backmentions}:e}async function Cg(e,t,o,n){if(Array.isArray(t)){const s=await qt(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 qt(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 qt(e,r.docs,o,n);return{data:{...r,docs:s.items},permissionFilteredOutCount:s.permissionFilteredOutCount,pathFilteredOutCount:s.pathFilteredOutCount}}return{data:Pg(t,o),permissionFilteredOutCount:0,pathFilteredOutCount:0}}const Og=async({client:e,permMgr:t,rawArgs:o})=>{const n=ol.parse(o);if(await t.reload(),!t.canWrite(n.notebook))return _o(n.notebook,t.get(n.notebook),"write");const r=await ch(e,n.notebook,n.path,n.markdown);return n.icon&&await Be(e,r,{icon:n.icon}),S(e,y({success:!0,notebook:n.notebook,path:n.path,id:r,iconHint:Tt("document",!!n.icon)}),n.icon?[{type:"reloadIcon"}]:[{type:"reloadProtyle",id:r},{type:"reloadFiletree"}])},$g=async({client:e,permMgr:t,rawArgs:o})=>{const n=nl.parse(o);if(n.id){const{denied:r,context:s}=await v(e,t,n.id,"write");return r||(await dh(e,n.id,n.title),S(e,y({success:!0,id:n.id,title:n.title}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await x(t,n.notebook,"write");if(r)return r}return await uh(e,n.notebook,n.path,n.title),S(e,y({success:!0,notebook:n.notebook,path:n.path,title:n.title}),[{type:"reloadFiletree"}])},Eg=async({client:e,permMgr:t,rawArgs:o})=>{const n=rl.parse(o);if(n.id){const{denied:r,context:s}=await v(e,t,n.id,"delete");return r||(await ph(e,n.id),S(e,y({success:!0,id:n.id}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}]))}if(n.notebook){const r=await x(t,n.notebook,"delete");if(r)return r}return await lh(e,n.notebook,n.path),S(e,y({success:!0,notebook:n.notebook,path:n.path}),[{type:"reloadFiletree"}])},Ng=async({client:e,permMgr:t,rawArgs:o})=>{const n=sl.parse(o);if(n.toNotebook){const r=await x(t,n.toNotebook,"write");if(r)return r}if(n.toID){const r=await Jh(e,n.toID),s=await x(t,r,"write");if(s)return s}if(n.fromIDs){const r=[];for(const s of n.fromIDs){const{denied:i,context:a}=await v(e,t,s,"write");if(i)return i;r.push(a.documentId)}return await hh(e,n.fromIDs,n.toID),S(e,y({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 Qe(e,r);if(!s)throw new Error(`Unable to resolve source notebook for storage path "${r}" while checking permissions.`);const i=await x(t,s,"write");if(i)return i}return await fh(e,n.fromPaths,n.toNotebook,n.toPath),S(e,y({success:!0,fromPaths:n.fromPaths,toNotebook:n.toNotebook,toPath:n.toPath}),[{type:"reloadFiletree"}])},Rg=async({client:e,permMgr:t,rawArgs:o})=>{const n=il.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;const s=await Gr(e,n.id);return y(s)},zg=async({client:e,permMgr:t,rawArgs:o})=>{const n=al.parse(o);if(n.notebook){const s=await x(t,n.notebook,"read");if(s)return s}if(n.id){const{denied:s}=await v(e,t,n.id,"read");if(s)return s;const i=await Ag(e,n.id);return y(i)}const r=await Mr(e,n.notebook,n.path);return y(r)},xg=async({client:e,permMgr:t,rawArgs:o})=>{const n=cl.parse(o),r=await x(t,n.notebook,"read");if(r)return r;const s=await mh(e,n.path,n.notebook);return y(s)},Bg=async({client:e,permMgr:t,rawArgs:o})=>{const n=ul.parse(o),{denied:r,context:s}=await v(e,t,n.id,"read");if(r)return r;const i=await Zr(e,s.documentId);return y(i)},Fg=async({client:e,permMgr:t,rawArgs:o})=>{const n=dl.parse(o),{denied:r,context:s}=await v(e,t,n.id,"read");if(r)return r;const i=await Yr(e,s.notebook,s.path);return y(i)},qg=async({client:e,permMgr:t,rawArgs:o})=>{const n=ll.parse(o),{denied:r}=await v(e,t,n.id,"write");return r||(await Be(e,n.id,{icon:n.icon}),S(e,y({success:!0,id:n.id,icon:n.icon}),[{type:"reloadIcon"}]))},jg=async({client:e,permMgr:t,rawArgs:o})=>{const n=pl.parse(o),{denied:r,context:s}=await v(e,t,n.id,"write");if(r)return r;const i=n.source;if(!i)return await Be(e,n.id,{"title-img":""}),S(e,y({success:!0,id:n.id,cleared:!0}),[{type:"reloadProtyle",id:s.documentId}]);const a=Tg(i);return await Be(e,n.id,{"title-img":a.titleImg}),S(e,y({success:!0,id:n.id,source:a.source,titleImg:a.titleImg}),[{type:"reloadProtyle",id:s.documentId}])},Ug=async({client:e,permMgr:t,rawArgs:o})=>{const n=fl.parse(o),r=await x(t,n.notebook,"read");if(r)return r;const s=n.maxDepth??3,i=await gh(e,n.notebook,n.path),a='Use maxDepth to control tree depth. Use document(action="list_tree") with a deeper path to expand specific subtrees.';if(i&&typeof i=="object"&&Array.isArray(i.tree)){const u=await Kt(e,i.tree);return y({...i,tree:Jt(u,s),maxDepth:s,depthHint:a})}const c=await Kt(e,i);return y({tree:Jt(c,s),maxDepth:s,depthHint:a})},Zg=async({client:e,permMgr:t,rawArgs:o})=>{const n=hl.parse(o),r=await x(t,n.notebook,"read");if(r)return r;const s=await bh(e,n.query),i=await Cg(e,s,t,n.path),a=i.permissionFilteredOutCount+i.pathFilteredOutCount;return y({...i.data&&typeof i.data=="object"&&!Array.isArray(i.data)?i.data:{docs:i.data},...n.path?{path:n.path,pathApplied:!0}:{},...i.permissionFilteredOutCount>0?{partial:!0,reason:"permission_filtered"}:{},...a>0?{filteredOutCount:a}:{},...i.pathFilteredOutCount>0?{pathFilteredOutCount:i.pathFilteredOutCount}:{}})},Lg=async({client:e,permMgr:t,rawArgs:o})=>{const n=ml.parse(o),{denied:r}=await v(e,t,n.id,"read");if(r)return r;if(n.mode==="html"){const _=await kh(e,n.id,0,n.size);return y({id:n.id,mode:"html",..._&&typeof _=="object"?_:{content:_}})}const s=ts(await cs(e,n.id)),i=typeof s.content=="string"?s.content:"",a=n.page??1,c=n.pageSize??8e3,u=Math.max(1,Math.ceil(i.length/c)),d=Math.min(a,u),p=(d-1)*c,f=i.slice(p,p+c),k=i.length>c;return y({id:n.id,mode:"markdown",hPath:s.hPath,content:f,...k?{truncated:!0,contentLength:i.length,showing:f.length,page:d,pageSize:c,pageCount:u,hasNextPage:d<u,hint:'Use page/pageSize to read the next markdown chunk. For structured reads, use document(action="get_child_blocks") or block(action="get_kramdown").'}:{}})},Mg=async({client:e,permMgr:t,rawArgs:o})=>{const n=yl.parse(o),r=await x(t,n.notebook,"write");if(r)return r;const s=await _h(e,n.notebook,n.app);let i;try{i=await Vr(e,s.id)}catch{i=void 0}return S(e,y({success:!0,notebook:n.notebook,...s,...i?{hPath:i}:{},iconHint:Tt("document")}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}])},Vg=async({client:e,permMgr:t,rawArgs:o})=>{const n=gl.parse(o),{denied:r,context:s}=await v(e,t,n.id,"write");if(r)return r;const i=await wh(e,n.id);return S(e,y({success:!0,sourceID:n.id,...i}),[{type:"reloadProtyle",id:s.documentId},{type:"reloadFiletree"}])},Gg=async({client:e,permMgr:t,rawArgs:o})=>{const n=bl.parse(o);for(const r of n.paths){const s=await Qe(e,r);if(!s)throw new Error(`Unable to resolve notebook for storage path "${r}" while checking permissions.`);const i=await x(t,s,"delete");if(i)return i}return await Ih(e,n.paths),S(e,y({success:!0,paths:n.paths,count:n.paths.length}),[{type:"reloadFiletree"}])},Hg=async({client:e,permMgr:t,rawArgs:o})=>{const n=kl.parse(o),r=await x(t,n.notebook,"write");if(r)return r;const s=await vh(e,n.notebook,n.path,n.title,n.markdown??"",n.sorts);return S(e,y({success:!0,notebook:n.notebook,path:n.path,title:n.title,...s,iconHint:Tt("document")}),[{type:"reloadProtyle",id:s.id},{type:"reloadFiletree"}])},Yg=async({client:e,permMgr:t,rawArgs:o})=>{const n=_l.parse(o),r=await v(e,t,n.headingID,"write");if(r.denied)return r.denied;const s=await x(t,n.targetNotebook,"write");return s||(await Dh(e,n.headingID,n.targetNotebook,n.targetPath,n.previousPath),S(e,y({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"}]))},Wg=async({client:e,permMgr:t,rawArgs:o})=>{const n=wl.parse(o),r=await v(e,t,n.srcID,"write");if(r.denied)return r.denied;const s=await v(e,t,n.targetID,"write");if(s.denied)return s.denied;const i=await Sh(e,n.srcID,n.targetID,n.after??!1);return S(e,y({success:!0,srcID:n.srcID,targetID:n.targetID,after:n.after??!1,...i}),[{type:"reloadProtyle",id:r.context.documentId},{type:"reloadProtyle",id:s.context.documentId},{type:"reloadFiletree"}])},Jg={create:Og,rename:$g,remove:Eg,move:Ng,get_path:Rg,get_hpath:zg,get_ids:xg,get_child_blocks:Bg,get_child_docs:Fg,set_icon:qg,set_cover:jg,list_tree:Ug,search_docs:Zg,get_doc:Lg,create_daily_note:Mg,duplicate:Vg,remove_batch:Gg,create_empty:Hg,heading_to_doc:Yg,doc_to_heading:Wg},Kg=[{action:"create",schema:g("create",{notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Document path like /Inbox/Weekly Note"},markdown:{type:"string",description:"Initial markdown content (optional)"},icon:{type:"string",description:"Document icon (optional)"}},["notebook","path"],"Create a new document")},{action:"rename",schema:g("rename",{notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Storage path (from get_path)"},title:{type:"string",description:"New document title"}},["notebook","path","title"],"Rename a document")},{action:"remove",schema:g("remove",{notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Storage path (from get_path)"}},["notebook","path"],"Delete a document")},{action:"move",schema:g("move",{notebook:{type:"string",description:"Source notebook ID"},path:{type:"string",description:"Source storage path"},toNotebook:{type:"string",description:"Target notebook ID (optional, defaults to source)"},toPath:{type:"string",description:"Target storage path (optional, defaults to source)"},fromIDs:{type:"array",items:{type:"string"},description:"Source document IDs (alternative to notebook+path)"},fromPaths:{type:"array",items:{type:"string"},description:"Source storage paths (alternative to notebook+path)"},toID:{type:"string",description:"Target document or notebook ID (alternative)"}},["notebook","path"],"Move a document to another location")},{action:"get_path",schema:g("get_path",{id:{type:"string",description:"Document ID"}},["id"],"Get the storage path of a document by its ID")},{action:"get_hpath",schema:g("get_hpath",{id:{type:"string",description:"Document ID"},notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Storage path"}},[],"Get the human-readable path of a document")},{action:"get_ids",schema:g("get_ids",{notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Human-readable path like /Inbox/Week"}},["notebook","path"],"Get document IDs matching a path pattern")},{action:"get_child_blocks",schema:g("get_child_blocks",{id:{type:"string",description:"Document ID"}},["id"],"Get top-level blocks of a document")},{action:"get_child_docs",schema:g("get_child_docs",{id:{type:"string",description:"Document ID"}},["id"],"Get child documents")},{action:"set_icon",schema:g("set_icon",{id:{type:"string",description:"Document ID"},icon:{type:"string",description:"Icon (Unicode hex or emoji)"}},["id","icon"],"Set document icon")},{action:"set_cover",schema:g("set_cover",{id:{type:"string",description:"Document ID"},source:{type:"string",description:"Image URL or asset path"}},["id"],"Set document cover image")},{action:"list_tree",schema:g("list_tree",{notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Root path"},maxDepth:{type:"number",description:"Max depth (default 3)"}},["notebook"],"Get document tree")},{action:"search_docs",schema:g("search_docs",{notebook:{type:"string",description:"Notebook ID"},query:{type:"string",description:"Search keyword"}},["notebook","query"],"Search documents by title")},{action:"get_doc",schema:g("get_doc",{id:{type:"string",description:"Document ID"},mode:{type:"string",enum:["markdown","html"],description:"Return format (default markdown)"},size:{type:"number",description:"Max content size hint"},page:{type:"number",description:"Page number for markdown pagination (1-based)"},pageSize:{type:"number",description:"Characters per page for pagination (default 8000)"}},["id"],"Get full document content")},{action:"create_daily_note",schema:g("create_daily_note",{notebook:{type:"string",description:"Notebook ID"}},["notebook"],"Create or open today's daily note")},{action:"duplicate",schema:g("duplicate",{id:{type:"string",description:"Source document ID"}},["id"],"Duplicate a document")},{action:"remove_batch",schema:g("remove_batch",{paths:{type:"array",items:{type:"string"},description:"Storage paths to remove"}},["paths"],"Delete multiple documents")},{action:"create_empty",schema:g("create_empty",{notebook:{type:"string",description:"Notebook ID"},path:{type:"string",description:"Human-readable path"}},["notebook","path"],"Create an empty document")},{action:"heading_to_doc",schema:g("heading_to_doc",{headingID:{type:"string",description:"Heading block ID to convert"}},["headingID"],"Convert a heading to a separate document")},{action:"doc_to_heading",schema:g("doc_to_heading",{srcID:{type:"string",description:"Source document ID"},targetID:{type:"string",description:"Target document ID"},after:{type:"boolean",description:"Insert after (default before)"}},["srcID","targetID"],"Merge a document into another as a heading")}],us=se({name:"document",description:"📝 Grouped document operations.",variants:Kg,actionSchema:qd,aggregateOptions:{guidance:Bn,actionHints:Gn,propertyDescriptionOverrides:{path:'Path value. For action="create", use a human-readable target path such as /Inbox/Weekly Note. For other document actions that use notebook + path, use a storage path returned by document(action="get_path").',fromPaths:'Source storage paths returned by document(action="get_path").',toPath:'Target storage path. Use the storage path of an existing destination document returned by document(action="get_path").'}},handlers:Jg});function Qg(e){return us.listTools(e)}async function Xg(e,t,o,n){return us.callTool(e,t,o,n)}const eb="file",Qt=10,tb=[{action:"upload_asset",schema:g("upload_asset",{assetsDirPath:{type:"string",description:"Asset directory path (e.g., /assets/)"},localFilePath:{type:"string",description:"Local file path to read and upload into the assets directory"},confirmLargeFile:{type:"boolean",description:"Set to true only after the user explicitly confirms uploading a file larger than the configured safety threshold."}},["assetsDirPath","localFilePath"],"Read a local file and upload it to the specified assets directory.")},{action:"render_template",schema:g("render_template",{id:{type:"string",description:"Document ID for template context"},path:{type:"string",description:"Template file path inside the SiYuan workspace (not an arbitrary local filesystem path)"}},["id","path"],"Render a template with document context.")},{action:"render_sprig",schema:g("render_sprig",{template:{type:"string",description:"Sprig template content"}},["template"],"Render a Sprig template.")},{action:"export_md",schema:g("export_md",{id:{type:"string",description:"Document ID to export"}},["id"],"Export document content as Markdown.")},{action:"export_resources",schema:g("export_resources",{paths:{type:"array",items:{type:"string"},description:"Paths to export"},name:{type:"string",description:"Export file name"},outputPath:{type:"string",description:"Optional local absolute or relative filesystem path to save the exported ZIP"}},["paths"],"Export resources as a ZIP archive.")},{action:"list_unused_assets",schema:g("list_unused_assets",{},[],"List unused asset files.")},{action:"get_doc_assets",schema:g("get_doc_assets",{id:{type:"string",description:"Document ID"},assetType:{type:"string",enum:["all","image"],description:"Filter: 'all' (default) returns all assets, 'image' returns only image assets."}},["id"],"List assets referenced by a document. Use assetType to filter.")},{action:"get_image_ocr_text",schema:g("get_image_ocr_text",{path:{type:"string",description:"Optional asset path; omit to receive an empty OCR text payload"}},[],"Get stored OCR text for an image asset.")},{action:"remove_unused_assets",schema:g("remove_unused_assets",{},[],"Remove all unused asset files.")},{action:"rename_asset",schema:g("rename_asset",{oldPath:{type:"string",description:"Existing asset path"},newName:{type:"string",description:"New asset file name"}},["oldPath","newName"],"Rename an asset file.")},{action:"delete_asset",schema:g("delete_asset",{path:{type:"string",description:"Asset path to delete"}},["path"],"Delete an asset file.")},{action:"set_image_alpha",schema:g("set_image_alpha",{path:{type:"string",description:"Asset path to update"},alpha:{type:"number",description:"Alpha value passed through to SiYuan"}},["path","alpha"],"Set image alpha for an asset.")}];function ob(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 nb(e){return[...new Set(e.map(ob).filter(Boolean))]}function rb(e){return $e.isAbsolute(e)?e:$e.resolve(process.cwd(),e)}function sb(e){return $e.isAbsolute(e)?e:$e.resolve(process.cwd(),e)}function ib(e){return e instanceof Error&&/is not in workspace/i.test(e.message)}function ds(e,t){return se({name:"file",description:"📁 Grouped file and asset operations.",variants:tb,actionSchema:Zd,aggregateOptions:{guidance:jn,actionHints:Wn},handlers:{upload_asset:async({client:o,rawArgs:n})=>{const r=vp.parse(n),s=sb(r.localFilePath);if(!Ze.existsSync(s))throw new Error(`Local file does not exist: ${s}`);const i=Ze.statSync(s);if(!i.isFile())throw new Error(`Local file path must point to a regular file: ${s}`);if(i.size>t&&r.confirmLargeFile!==!0)return y({success:!1,requiresConfirmation:!0,reason:"file_too_large",localFilePath:s,fileSizeBytes:i.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 a=$e.basename(s),c=Ze.readFileSync(s),u=await cg(o,r.assetsDirPath,c,a);return y({...u,localFilePath:s,uploadedFileName:a,...i.size>t?{largeFileConfirmed:!0}:{}})},render_template:async({client:o,permMgr:n,rawArgs:r})=>{const s=Dp.parse(r),{denied:i}=await v(o,n,s.id,"read");if(i)return i;try{const a=await ug(o,s.id,s.path);return y(a)}catch(a){if(ib(a))return{content:[{type:"text",text:JSON.stringify({error:{type:"api_error",tool:eb,action:"render_template",message:a.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 a}},render_sprig:async({client:o,rawArgs:n})=>{const r=Sp.parse(n),s=await dg(o,r.template);return y(s)},export_md:async({client:o,permMgr:n,rawArgs:r})=>{const s=Ap.parse(r),{denied:i}=await v(o,n,s.id,"read");if(i)return i;const a=ts(await cs(o,s.id));return y(a)},export_resources:async({client:o,rawArgs:n})=>{const r=Tp.parse(n),s=nb(r.paths);if(s.length===0)throw new Error("export_resources requires at least one non-empty resource path.");let i;try{i=await lg(o,s,r.name)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(`Failed to export resources. original_paths=${JSON.stringify(r.paths)} normalized_paths=${JSON.stringify(s)} cause=${c}`)}if(r.outputPath){const a=rb(r.outputPath),c=await o.readFileBinary(i.path);return Ze.mkdirSync($e.dirname(a),{recursive:!0}),Ze.writeFileSync(a,c),y({...i,outputPath:a,bytes:c.byteLength})}return y(i)},list_unused_assets:async({client:o,rawArgs:n})=>{Pp.parse(n);const r=await yg(o);return y({assets:r,count:Array.isArray(r)?r.length:void 0})},get_doc_assets:async({client:o,permMgr:n,rawArgs:r})=>{const s=Cp.parse(r),{denied:i}=await v(o,n,s.id,"read");if(i)return i;const a=s.assetType==="image"?await bg(o,s.id):await gg(o,s.id);return y({id:s.id,assetType:s.assetType??"all",assets:a,count:Array.isArray(a)?a.length:void 0})},get_image_ocr_text:async({client:o,rawArgs:n})=>{const r=Op.parse(n),s=await kg(o,r.path);return y({path:r.path??null,...s})},remove_unused_assets:async({client:o,rawArgs:n})=>{$p.parse(n);const r=await _g(o);return y({success:!0,...r&&typeof r=="object"&&!Array.isArray(r)?r:{result:r}})},rename_asset:async({client:o,rawArgs:n})=>{const r=Ep.parse(n),s=await wg(o,r.oldPath,r.newName);return y({success:!0,oldPath:r.oldPath,newName:r.newName,...s})},delete_asset:async({client:o,rawArgs:n})=>{const r=Np.parse(n),s=await Ig(o,r.path);return y({success:!0,path:r.path,...s&&typeof s=="object"&&!Array.isArray(s)?s:{}})},set_image_alpha:async({client:o,rawArgs:n})=>{const r=Rp.parse(n),s=await vg(o,r.path,r.alpha);return y({success:!0,path:r.path,alpha:r.alpha,...s&&typeof s=="object"&&!Array.isArray(s)?s:{}})}}})}const ab=ds(Qt,Qt*1024*1024);function cb(e){return ab.listTools(e)}async function ub(e,t,o,n){const r="uploadLargeFileThresholdMB"in o&&typeof o.uploadLargeFileThresholdMB=="number"?o.uploadLargeFileThresholdMB:Qt,s=r*1024*1024;return ds(r,s).callTool(e,t,o,n)}async function db(e){return e.request("/api/riff/getRiffDecks",{})}async function ln(e,t){return e.request("/api/riff/getRiffDueCards",{deckID:t??""})}async function lb(e,t){return e.request("/api/riff/getNotebookRiffDueCards",{notebook:t})}async function pb(e,t){return e.request("/api/riff/getTreeRiffDueCards",{rootID:t})}async function fb(e,t,o,n,r){return e.request("/api/riff/reviewRiffCard",{deckID:t,cardID:o,rating:n,...r!==void 0?{reviewedCards:r}:{}})}async function hb(e,t,o){return e.request("/api/riff/skipReviewRiffCard",{deckID:t,cardID:o})}async function pn(e,t,o){return e.request("/api/riff/addRiffCards",{deckID:t,blockIDs:o})}async function mb(e,t,o){return e.request("/api/riff/removeRiffCards",{deckID:t,blockIDs:o})}async function fn(e,t,o,n){return e.request("/api/riff/getRiffCards",{id:t,page:o,...n!==void 0?{pageSize:n}:{}})}async function yb(e,t){return e.request("/api/riff/getRiffCardsByBlockIDs",{blockIDs:t})}const ke="20230218211946-2kw8jgx",bt="custom-riff-decks",gb="Built-in Deck",bb=5,kb=300,hn=6,_b=300,wb=[{action:"list_cards",schema:g("list_cards",{scope:{type:"string",enum:["all","deck","notebook","tree"],description:"Query scope"},filter:{type:"string",enum:["due","new","old"],description:"Card filter by review state"},deckID:{type:"string",description:"Deck ID, required when scope=deck"},notebook:{type:"string",description:"Notebook ID, required when scope=notebook"},rootID:{type:"string",description:"Root document/block ID, required when scope=tree"}},["scope","filter"],"List due flashcards and optionally filter to new/old cards.")},{action:"get_decks",schema:g("get_decks",{},[],"Get flashcard deck definitions.")},{action:"get_cards",schema:g("get_cards",{deckID:{type:"string",description:"Deck ID (use empty string to query across all decks)"},page:{type:"number",description:"Page number (1-based), default 1"},pageSize:{type:"number",description:"Cards per page, default 32, max 512"}},["deckID"],"List all cards in a deck with pagination (not limited to due cards).")},{action:"review_card",schema:g("review_card",{deckID:{type:"string",description:"Deck ID"},cardID:{type:"string",description:"Card ID"},rating:{type:"number",description:"Review rating passed through to the kernel"},reviewedCards:{type:"array",items:{type:"object"},description:"Optional reviewedCards payload passed through to the kernel"}},["deckID","cardID","rating"],"Submit a review result for one flashcard.")},{action:"skip_review_card",schema:g("skip_review_card",{deckID:{type:"string",description:"Deck ID"},cardID:{type:"string",description:"Card ID"}},["deckID","cardID"],"Skip the current flashcard in a review flow.")},{action:"create_card",schema:g("create_card",{deckID:{type:"string",description:"Deck ID"},blockIDs:{type:"array",items:{type:"string"},description:"Existing block IDs to turn into flashcards"}},["deckID","blockIDs"],"Turn existing blocks into flashcards by writing deck attrs and registering riff cards.")},{action:"add_card",schema:g("add_card",{deckID:{type:"string",description:"Deck ID"},blockIDs:{type:"array",items:{type:"string"},description:"Existing block IDs to add as flashcards"}},["deckID","blockIDs"],"Add existing blocks to a flashcard deck.")},{action:"remove_card",schema:g("remove_card",{deckID:{type:"string",description:"Deck ID"},blockIDs:{type:"array",items:{type:"string"},description:"Existing block IDs to remove from a flashcard deck"}},["deckID","blockIDs"],"Remove existing blocks from a flashcard deck.")}];function Ib(e){return typeof e=="string"?["new","0"].includes(e.toLowerCase()):e===0}function vb(e){return typeof e=="string"?["old","1","review"].includes(e.toLowerCase()):e===1}function Db(e,t){return t==="due"?e:t==="new"?e.filter(o=>Ib(o.state)):e.filter(o=>vb(o.state))}function Ut(e){return e===""?ke:e}function ls(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}async function Ao(e,t){const o=await es(e,t);return o&&typeof o=="object"?o:{}}async function mn(e,t){for(const o of t)if((await Ao(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.`)}function Sb(e,t){const o=ls(e);return o.includes(t)||o.push(t),o.join(",")}async function Ab(e,t,o){for(const n of t){const r=await Ao(e,n);await Be(e,n,{[bt]:Sb(r[bt],o)})}}async function yn(e,t,o,n){for(const r of t){const s=await Ao(e,r);if(!ls(s[bt]).includes(o))throw new Error(`flashcard/${n} did not persist a valid deck binding for block "${r}". Expected ${bt} to include "${o}".`)}}function Tb(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:[]}function Pb(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 gn(e){return!e||typeof e!="object"?!1:typeof e.riffCardID=="string"&&e.riffCardID.length>0?!0:!!e.riffCard}async function Zt(e,t,o,n){const r=new Set(t);for(let s=0;s<hn;s+=1){const i=await yb(e,t),a=new Map;for(const u of Tb(i)){const d=Pb(u);d&&a.set(d,u)}if([...r].every(u=>{const d=a.get(u);return o==="present"?gn(d):!gn(d)}))return;s<hn-1&&await fs(_b)}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 ps(e){return Array.isArray(e==null?void 0:e.blocks)?e.blocks:Array.isArray(e==null?void 0:e.cards)?e.cards:[]}function Cb(e){return(!e.type||e.type==="")&&typeof e.content=="string"&&e.content.includes("不存在符合条件的内容块")}function Ob(e){return e.length>0&&e.some(Cb)}function fs(e){return new Promise(t=>{setTimeout(t,e)})}async function $b(e,t,o,n){let r=await fn(e,t,o,n);for(let s=1;s<bb;s+=1){if(!Ob(ps(r)))return r;await fs(kb),r=await fn(e,t,o,n)}return r}const hs=se({name:"flashcard",description:"🃏 Grouped flashcard review and deck operations.",variants:wb,actionSchema:Ld,aggregateOptions:{guidance:Ln,actionHints:er},handlers:{list_cards:async({client:e,rawArgs:t})=>{const o=Tl.parse(t),r=(o.scope==="all"?await ln(e,""):o.scope==="deck"?await ln(e,o.deckID):o.scope==="notebook"?await lb(e,o.notebook):await pb(e,o.rootID))??{};return y({...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}:{},cards:Db(Array.isArray(r.cards)?r.cards:[],o.filter)})},get_decks:async({client:e,rawArgs:t})=>{Pl.parse(t);const o=await db(e),n=Array.isArray(o)?[...o]:[];return n.some(s=>{if(!s||typeof s!="object")return!1;const i=s;return i.id===ke||i.deckID===ke})||n.unshift({id:ke,deckID:ke,name:gb,builtin:!0}),y({action:"get_decks",decks:n})},get_cards:async({client:e,rawArgs:t})=>{const o=Rl.parse(t),n=await $b(e,o.deckID,o.page??1,o.pageSize);return y({action:"get_cards",deckID:o.deckID,page:o.page??1,...o.pageSize!==void 0?{pageSize:o.pageSize}:{},cards:ps(n),total:n==null?void 0:n.total,pageCount:n==null?void 0:n.pageCount})},review_card:async({client:e,rawArgs:t})=>{const o=Cl.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.");const n=await fb(e,o.deckID,o.cardID,o.rating,o.reviewedCards);return y({action:"review_card",deckID:o.deckID,cardID:o.cardID,rating:o.rating,...o.reviewedCards!==void 0?{reviewedCards:o.reviewedCards}:{},result:n})},skip_review_card:async({client:e,rawArgs:t})=>{const o=Ol.parse(t);if(o.deckID==="")throw new Error("flashcard/skip_review_card requires a concrete deckID. Use flashcard/get_cards first to resolve the card deck, then retry.");const n=await hb(e,o.deckID,o.cardID);return y({action:"skip_review_card",deckID:o.deckID,cardID:o.cardID,result:n})},create_card:async({client:e,rawArgs:t})=>{const o=$l.parse(t),n=Ut(o.deckID);await mn(e,o.blockIDs),await Ab(e,o.blockIDs,n);const r=await pn(e,n,o.blockIDs);return await yn(e,o.blockIDs,n,"create_card"),await Zt(e,o.blockIDs,"present","create_card"),y({action:"create_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})},add_card:async({client:e,rawArgs:t})=>{const o=El.parse(t),n=Ut(o.deckID);await mn(e,o.blockIDs);const r=await pn(e,n,o.blockIDs);return await yn(e,o.blockIDs,n,"add_card"),n===ke&&await Zt(e,o.blockIDs,"present","add_card"),y({action:"add_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})},remove_card:async({client:e,rawArgs:t})=>{const o=Nl.parse(t),n=Ut(o.deckID),r=await mb(e,n,o.blockIDs);return n===ke&&await Zt(e,o.blockIDs,"absent","remove_card"),y({action:"remove_card",deckID:o.deckID,effectiveDeckID:n,blockIDs:o.blockIDs,result:r})}}}),Eb=hs.listTools,Nb=hs.callTool,ms="/data/storage/petal/siyuan-plugins-mcp-sisyphus/puppyStats.json";function Xe(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Rb(e){if(!e)return{totalCalls:0,balance:0,updatedAt:0};try{const t=JSON.parse(e),o=Xe(t.totalCalls),n=t.balance===void 0?o:Xe(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 ys(e){try{return Rb(await e.readFile(ms))}catch{return{totalCalls:0,balance:0,updatedAt:0}}}async function zb(e,t){const o={totalCalls:Xe(t.totalCalls),balance:Xe(t.balance),updatedAt:typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?t.updatedAt:Date.now(),...t.lastAction?{lastAction:t.lastAction}:{}};return await e.writeFile(ms,JSON.stringify(o)),o}async function xb(e,t,o){const n=await ys(e),r=Xe(t);if(n.balance<r)throw new Error(`Insufficient mascot balance. Need ${r}, have ${n.balance}.`);return zb(e,{totalCalls:n.totalCalls,balance:n.balance-r,updatedAt:Date.now(),lastAction:o})}const Ot=[{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:"🧀"}];Ot[0];Ot[1];function Bb(e){return Ot.find(t=>t.id===e)??null}const Fb=[{action:"get_balance",schema:g("get_balance",{},[],"Get the mascot balance. Every successful MCP tool call earns 1 coin.")},{action:"shop",schema:g("shop",{},[],"List the mascot shop inventory.")},{action:"buy",schema:g("buy",{item_id:{type:"string",description:'Stable shop item ID returned by mascot(action="shop")'}},["item_id"],"Buy one item from the mascot shop.")}],gs=se({name:"mascot",description:"🐾 Grouped mascot balance and care operations. Every successful MCP tool call earns 1 coin for the mascot.",variants:Fb,actionSchema:Md,aggregateOptions:{guidance:Mn,actionHints:tr},handlers:{get_balance:async({client:e,rawArgs:t})=>{Il.parse(t);const o=await ys(e);return y({action:"get_balance",balance:o.balance,totalEarned:o.totalCalls})},shop:async({rawArgs:e})=>(vl.parse(e),y({action:"shop",items:Ot})),buy:async({client:e,rawArgs:t})=>{const o=Dl.parse(t),n=Bb(o.item_id);if(!n)throw new Error(`Unknown mascot shop item: ${o.item_id}.`);const r=await xb(e,n.cost,`buy:${n.id}`);return y({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 qb(e){return gs.listTools(e)}async function jb(e,t,o,n){return gs.callTool(e,t,o,n)}const bs="notebook",Ub=[{action:"list",schema:g("list",{},[],"List all notebooks in the workspace.")},{action:"create",schema:g("create",{name:{type:"string",description:"Notebook name"},icon:{type:"string",description:'Optional notebook icon. Prefer a Unicode hex code string such as "1f4d4" for 📔 instead of a raw emoji character.'}},["name"],"Create a new notebook.")},{action:"set_open_state",schema:g("set_open_state",{notebook:{type:"string",description:"Notebook ID"},opened:{type:"boolean",description:"true to open, false to close"}},["notebook","opened"],"Set notebook open state (open or close).")},{action:"remove",schema:g("remove",{notebook:{type:"string",description:"Notebook ID"}},["notebook"],"Remove a notebook.")},{action:"rename",schema:g("rename",{notebook:{type:"string",description:"Notebook ID"},name:{type:"string",description:"New notebook name"}},["notebook","name"],"Rename a notebook.")},{action:"get_conf",schema:g("get_conf",{notebook:{type:"string",description:"Notebook ID"}},["notebook"],"Get notebook configuration.")},{action:"set_conf",schema:g("set_conf",{notebook:{type:"string",description:"Notebook ID"},conf:{type:"object",description:"Notebook configuration",properties:{name:{type:"string"},closed:{type:"boolean"},refCreateSavePath:{type:"string"},createDocNameTemplate:{type:"string"},dailyNoteSavePath:{type:"string"},dailyNoteTemplatePath:{type:"string"}}}},["notebook","conf"],"Set notebook configuration.")},{action:"set_icon",schema:g("set_icon",{notebook:{type:"string",description:"Notebook ID"},icon:{type:"string",description:'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.'}},["notebook","icon"],"Set the icon for a notebook.")},{action:"get_permissions",schema:g("get_permissions",{notebook:{type:"string",description:'Notebook ID, or "all" to return every notebook permission entry. Omit to return all notebooks.'}},[],'Get permission levels for notebooks. Omit notebook or pass "all" to return every notebook; pass a specific notebook ID to return only that notebook.')},{action:"set_permission",schema:g("set_permission",{notebook:{type:"string",description:"Notebook ID"},permission:{type:"string",enum:["none","r","rw","rwd"],description:'Permission level: "none" blocks all access, "r" allows read only, "rw" allows read/write without delete, "rwd" allows read/write/delete (default)'}},["notebook","permission"],"Set the permission level for a notebook.")},{action:"get_child_docs",schema:g("get_child_docs",{notebook:{type:"string",description:"Notebook ID"},page:{type:"number",description:"Page number (1-based), default 1"},pageSize:{type:"number",description:"Rows per page, default 50"}},["notebook"],"Get direct child documents at the notebook root. Returns a paginated { data, total, page, pageSize, pageCount, hasNextPage } payload.")}];function bn(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 Zb(e){const t=e instanceof Error?e.message:String(e);return/initializing|kernel still initializing|notebook is currently closed/i.test(t)}async function Lb(e,t,o,n){let r=0;for(;r<=o;){r+=1;try{return{children:await Yr(e,t,"/"),attempts:r}}catch(s){if(r>o||!Zb(s))return{error:s,attempts:r};await new Promise(i=>setTimeout(i,n))}}return{error:new Error(`Failed to get child documents for notebook "${t}".`),attempts:r}}function Mb(e,t,o,n){return{content:[{type:"text",text:JSON.stringify({error:{type:"internal_error",tool:bs,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 ks=se({name:"notebook",description:"📚 Grouped notebook operations.",variants:Ub,actionSchema:Fd,aggregateOptions:{guidance:xn,actionHints:Vn},handlers:{list:async({client:e,rawArgs:t})=>{Vd.parse(t);const o=await Ve(e);return y(o.notebooks)},create:async({client:e,rawArgs:t})=>{const o=Gd.parse(t),n=await Ph(e,o.name);return o.icon&&(await tn(e,n.notebook.id,o.icon),n.notebook.icon=o.icon),S(e,y({...n.notebook,iconHint:Tt("notebook",!!o.icon)}),o.icon?[{type:"reloadIcon"}]:[{type:"reloadFiletree"}])},set_open_state:async({client:e,permMgr:t,rawArgs:o})=>{const n=Hd.parse(o),r=await x(t,n.notebook,"read");return r||(n.opened?await Ah(e,n.notebook):await Th(e,n.notebook),S(e,y({success:!0,notebook:n.notebook,opened:n.opened}),[{type:"reloadFiletree"}]))},remove:async({client:e,permMgr:t,rawArgs:o})=>{const n=Yd.parse(o),r=await x(t,n.notebook,"delete");return r||(await Ch(e,n.notebook),S(e,y({success:!0,notebook:n.notebook}),[{type:"reloadFiletree"}]))},rename:async({client:e,permMgr:t,rawArgs:o})=>{const n=Wd.parse(o),r=await x(t,n.notebook,"write");return r||(await Oh(e,n.notebook,n.name),S(e,y({success:!0,notebook:n.notebook,name:n.name}),[{type:"reloadFiletree"}]))},get_conf:async({client:e,permMgr:t,rawArgs:o})=>{const n=Jd.parse(o),r=await x(t,n.notebook,"read");if(r)return r;const s=await $h(e,n.notebook);return y(s)},set_conf:async({client:e,permMgr:t,rawArgs:o})=>{const n=Kd.parse(o),r=await x(t,n.notebook,"write");if(r)return r;const s=await Eh(e,n.notebook,n.conf);return S(e,y(s),[{type:"reloadFiletree"}])},set_icon:async({client:e,permMgr:t,rawArgs:o})=>{const n=Qd.parse(o),r=await x(t,n.notebook,"write");return r||(await tn(e,n.notebook,n.icon),S(e,y({success:!0,notebook:n.notebook,icon:n.icon}),[{type:"reloadIcon"}]))},get_permissions:async({client:e,permMgr:t,rawArgs:o})=>{const n=Xd.parse(o);await t.reload();const s=(await Ve(e)).notebooks.map(a=>({id:a.id,name:a.name,permission:t.get(a.id)}));if(!n.notebook||n.notebook==="all")return y({notebooks:s});const i=s.find(a=>a.id===n.notebook);return i?y({notebook:i}):gt(new Error(`Notebook "${n.notebook}" not found.`),{tool:bs,action:"get_permissions",rawArgs:o})},set_permission:async({client:e,permMgr:t,rawArgs:o})=>{const n=el.parse(o);return await t.set(n.notebook,n.permission),S(e,y({success:!0,notebook:n.notebook,permission:n.permission}),[{type:"reloadFiletree"}])},get_child_docs:async({client:e,permMgr:t,rawArgs:o})=>{const n=tl.parse(o),r=2,s=150,i=await x(t,n.notebook,"read");if(i)return i;const c=(await Ve(e)).notebooks.find(f=>f.id===n.notebook);if(!c)throw bn(new Error("Notebook not found in lsNotebooks result."),n.notebook,!1,!1);const u=await Lb(e,n.notebook,r,s);if(u.error){const f=bn(u.error,n.notebook,!0,!!c.closed);if(c.closed)return Mb(n.notebook,f.message,u.attempts,r*s);throw f}const d=u.children??[],p=qr(d,n.page??1,n.pageSize??50);return ot(p.items,p,{notebook:n.notebook})}}});function Vb(e){return ks.listTools(e)}function Gb(e,t,o,n){return ks.callTool(e,t,o,n)}const Hb=[{action:"workspace_info",schema:g("workspace_info",{},[],"Get SiYuan workspace metadata. High-risk: exposes the absolute workspace path.")},{action:"network",schema:g("network",{},[],"Get current network proxy information.")},{action:"changelog",schema:g("changelog",{},[],"Get the current version changelog HTML when available.")},{action:"conf",schema:g("conf",{mode:{type:"string",enum:["summary","get"],description:'Read mode: "summary" returns a navigable overview, "get" reads a specific key path'},keyPath:{type:"string",description:'Dot/bracket path to a specific config field, e.g. "conf.appearance.mode" or "conf.langs[0]"'},maxDepth:{type:"number",description:"Maximum object traversal depth for summary/get responses"},maxItems:{type:"number",description:"Maximum keys/items to include per level"}},[],"Get masked system configuration with summary-first progressive reading.")},{action:"sys_fonts",schema:g("sys_fonts",{mode:{type:"string",enum:["summary","list"],description:'Read mode: "summary" returns counts and samples, "list" returns paginated items'},offset:{type:"number",description:"Pagination offset for list mode"},limit:{type:"number",description:"Pagination size for list mode"},query:{type:"string",description:"Optional keyword filter for font names"}},[],"List available system fonts with summary-first paginated reading.")},{action:"boot_progress",schema:g("boot_progress",{},[],"Get boot progress details.")},{action:"push_msg",schema:g("push_msg",{msg:{type:"string",description:"Message content"},timeout:{type:"number",description:"Display timeout in milliseconds"}},["msg"],"Push a notification message.")},{action:"push_err_msg",schema:g("push_err_msg",{msg:{type:"string",description:"Error message content"},timeout:{type:"number",description:"Display timeout in milliseconds"}},["msg"],"Push an error notification message.")},{action:"get_version",schema:g("get_version",{},[],"Get the SiYuan system version.")},{action:"get_current_time",schema:g("get_current_time",{},[],"Get the current system time.")}],Yb=1,Wb=12,kn=20,_s=50,Jb=200;function ut(e,t,o,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(o,Math.min(n,Math.trunc(e)))}function Kb(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 Qb(e,t){const o=Kb(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 kt(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=>kt(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,i])=>[s,kt(i,t+1,o,n)])),truncated:r.length>n,omittedKeys:Math.max(0,r.length-n)}}return{type:"primitive",value:String(e),truncated:!1}}function Xb(e,t,o,n,r){if(t==="get"){if(!o)throw new Error('keyPath is required when mode="get".');const a=Qb(e,o);return{mode:t,keyPath:o,value:kt(a,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},i=Object.keys(s);return{mode:t,totalTopLevelKeys:i.length,topLevelKeys:i.slice(0,r),truncatedTopLevelKeys:Math.max(0,i.length-r),summary:kt(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]".']}}function ek(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):e&&typeof e=="object"&&Array.isArray(e.fonts)?e.fonts.filter(t=>typeof t=="string"):[]}function tk(e,t,o,n,r){const s=ek(e),i=r?s.filter(c=>c.toLowerCase().includes(r.toLowerCase())):s;if(t==="list"){const c=i.slice(o,o+n);return{mode:t,query:r??"",total:i.length,offset:o,limit:n,hasMore:o+c.length<i.length,items:c}}const a=i.slice(0,kn);return{mode:t,query:r??"",total:i.length,sample:a,sampleLimit:kn,hasMore:i.length>a.length,next:{action:"sys_fonts",mode:"list",offset:0,limit:_s,...r?{query:r}:{}},hints:['Use system(action="sys_fonts", mode="list", offset=0, limit=50) to page through fonts.',"Add query to narrow results before paging when you know part of the font name."]}}const ws=se({name:"system",description:"🖥️ Grouped system and notification operations.",variants:Hb,actionSchema:Kp,aggregateOptions:{guidance:Zn,actionHints:Xn},handlers:{workspace_info:async({client:e,rawArgs:t})=>(Qp.parse(t),y(await Kh(e))),network:async({client:e,rawArgs:t})=>(Xp.parse(t),y(await Qh(e))),changelog:async({client:e,rawArgs:t})=>(ef.parse(t),y(await Xh(e))),conf:async({client:e,rawArgs:t})=>{const o=tf.parse(t),n=await em(e),r=o.mode??"summary",s=ut(o.maxDepth,Yb,0,5),i=ut(o.maxItems,Wb,1,100);return y(Xb(n,r,o.keyPath,s,i))},sys_fonts:async({client:e,rawArgs:t})=>{const o=of.parse(t),n=await tm(e),r=o.mode??"summary",s=ut(o.offset,0,0,Number.MAX_SAFE_INTEGER),i=ut(o.limit,_s,1,Jb);return y(tk(n,r,s,i,o.query))},boot_progress:async({client:e,rawArgs:t})=>(nf.parse(t),y(await om(e))),push_msg:async({client:e,rawArgs:t})=>{const o=rf.parse(t);return y(await pg(e,o.msg,o.timeout))},push_err_msg:async({client:e,rawArgs:t})=>{const o=sf.parse(t);return y(await fg(e,o.msg,o.timeout))},get_version:async({client:e,rawArgs:t})=>(af.parse(t),y({version:await hg(e)})),get_current_time:async({client:e,rawArgs:t})=>{cf.parse(t);const o=await mg(e);return y({currentTime:o,iso:new Date(o).toISOString()})}}});function ok(e){return ws.listTools(e)}function nk(e,t,o,n){return ws.callTool(e,t,o,n)}async function rk(e,t={}){const o={...t,app:t.app||"siyuan-mcp-sisyphus"};return e.request("/api/tag/getTag",o)}async function sk(e,t,o){return e.request("/api/tag/renameTag",{oldLabel:t,newLabel:o})}async function ik(e,t){return e.request("/api/tag/removeTag",{label:t})}const ak=[{action:"list",schema:g("list",{sort:{type:"number",description:"Optional tag sort mode"},ignoreMaxListHint:{type:"boolean",description:"Ignore SiYuan max list hint"},app:{type:"string",description:"Optional app identifier passed through to SiYuan"}},[],"List tags in the workspace.")},{action:"rename",schema:g("rename",{oldLabel:{type:"string",description:"Existing tag label"},newLabel:{type:"string",description:"New tag label"}},["oldLabel","newLabel"],"Rename a tag.")},{action:"remove",schema:g("remove",{label:{type:"string",description:"Tag label to remove"}},["label"],"Remove a tag.")}],Is=se({name:"tag",description:"🏷️ Grouped tag operations.",variants:ak,actionSchema:Hp,aggregateOptions:{guidance:Un,actionHints:Qn},handlers:{list:async({client:e,rawArgs:t})=>{const o=Yp.parse(t),n=await rk(e,o);return y(n)},rename:async({client:e,rawArgs:t})=>{const o=Wp.parse(t);return await sk(e,o.oldLabel,o.newLabel),S(e,y({success:!0,oldLabel:o.oldLabel,newLabel:o.newLabel}),[{type:"reloadTag"}])},remove:async({client:e,rawArgs:t})=>{const o=Jp.parse(t);return await ik(e,o.label),S(e,y({success:!0,label:o.label}),[{type:"reloadTag"}])}}}),ck=Is.listTools,uk=Is.callTool,To={notebook:{category:"notebook",listTools:Vb,callTool:Gb},document:{category:"document",listTools:Qg,callTool:Xg},block:{category:"block",listTools:ig,callTool:ag},av:{category:"av",listTools:Gm,callTool:Hm},file:{category:"file",listTools:cb,callTool:ub},search:{category:"search",listTools:Py,callTool:Cy},tag:{category:"tag",listTools:ck,callTool:uk},system:{category:"system",listTools:ok,callTool:nk},flashcard:{category:"flashcard",listTools:Eb,callTool:Nb},mascot:{category:"mascot",listTools:qb,callTool:jb}};function Po(e){return qe.includes(e)?e:null}function vs(){return Xt.join(Tn.homedir(),".siyuan-sisyphus","config.json")}function dk(){return Xt.join(Tn.homedir(),".siyuan-mcp","config.json")}function Ds(e){const t=lk(e);if(!ue.existsSync(t))return{};try{const o=ue.readFileSync(t,"utf8"),n=JSON.parse(o);return n&&typeof n=="object"?{apiUrl:typeof n.apiUrl=="string"?n.apiUrl:void 0,token:typeof n.token=="string"?n.token:void 0}:{}}catch(o){const n=o instanceof Error?o.message:String(o);throw new Error(`[siyuan-sisyphus] Failed to load config at ${t}: ${n}`)}}function lk(e){if(e)return e;const t=vs();if(ue.existsSync(t))return t;const o=dk();return ue.existsSync(o)?o:t}function Ss(e,t,o){const n=t||process.env.SIYUAN_API_URL||e.apiUrl||"http://127.0.0.1:6806",r=o||process.env.SIYUAN_TOKEN||e.token||"";return{apiUrl:n,token:r}}function As(e){process.env.SIYUAN_API_URL=e.apiUrl,e.token&&(process.env.SIYUAN_TOKEN=e.token)}function pk(e,t){const o=t.properties??{},n=new Map,r=new Set,s=new Set;for(const[f,k]of Object.entries(o)){if(f==="action"||f==="topic")continue;const _=wn(f);for(const T of _)n.set(T.toLowerCase(),f);if(_t(k)==="boolean")for(const T of _)r.add(T);else for(const T of _)s.add(T)}const i=[];for(const f of Object.keys(o))if(!(f==="action"||f==="topic"))for(const k of wn(f))i.push(`${k}-json`);const a=Pn(e,{boolean:[...r],string:[...s,...i]}),c=mk(e),u={},d=[],p={};for(const[f,k]of Object.entries(a))if(f!=="_"&&f.endsWith("-json")){const _=f.slice(0,-5),w=n.get(_.toLowerCase());if(!w){d.push(`Unknown flag --${f}.`);continue}if(typeof k!="string"||k.length===0)continue;try{p[w]=JSON.parse(k)}catch(T){throw new Error(`--${f} must be valid JSON: ${T instanceof Error?T.message:String(T)}`)}}for(const[f,k]of Object.entries(a)){if(f==="_"||f.endsWith("-json"))continue;const _=n.get(f.toLowerCase());if(!_){d.push(`Unknown flag --${f}; ignored.`);continue}if(_ in p||_ in u)continue;const w=o[_];_t(w)==="boolean"&&k===!1&&!c.has(f.toLowerCase())||(u[_]=fk(_,k,w))}return a._.length>0&&d.push(`Extra positional arguments ignored: ${a._.join(" ")}`),{args:{...u,...p},warnings:d}}function fk(e,t,o){const n=_t(o);if(n==="array")return Array.isArray(t)?t.map(r=>_n(r,o.items)):typeof t=="string"?t.split(",").map(r=>_n(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(`--${Lt(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(`--${Lt(e)} expects JSON for an object field. Use --${Lt(e)}-json '{"..."}'.`)}return t}return typeof t=="string"?t:String(t)}function _n(e,t){if(!t)return e;const o=_t(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 _t(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 wn(e){const t=Ts(e),o=new Set([e]);return t.length===0?[...o]:(o.add(t.join("-")),o.add(t.join("_")),o.add(hk(t)),[...o])}function Ts(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 hk(e){return e.length===0?"":e[0]+e.slice(1).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Lt(e){const t=Ts(e);return t.length>0?t.join("-"):e.toLowerCase()}function mk(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}const yk=new Set(["action","only","optional","required","requires","mode"]);function Fe(e,t){return t==="cli"?`--${et(e)}`:e}function Ps(e,t,o={},n){{const r=Object.entries(o).filter(([,s])=>s!==void 0).map(([s,i])=>vk(s,i));return[N,e,et(t),...r].join(" ").trim()}}function W(e,t){if(!e)return e;let o=e;return o=o.replace(/siyuan:\/\/help\/action\/([a-z_]+)\/([a-z_]+)/g,(n,r,s)=>`${N} ${r} ${et(s)}`),o=o.replace(/siyuan:\/\/help\/tool-overview/g,`${N} list`),o=o.replace(/siyuan:\/\/help\/examples/g,`${N} help <tool> <action>`),o=o.replace(/siyuan:\/\/help\/ai-layout-guide/g,`${N} help document create`),o=o.replace(/\b([a-z]+)\(action=["”“]([a-z_]+)["”“](?:,\s*([^)]*))?\)/g,(n,r,s,i)=>{const a=wk(i);if(s==="help"){const c=typeof a.topic=="string"?Os(a.topic).trim():"";return c?`${N} help ${r} ${et(c)}`:`${N} help ${r}`}return Ps(r,s,a)}),o=o.replace(/\b([A-Za-z][A-Za-z0-9_]*)(\s*\+\s*[A-Za-z][A-Za-z0-9_]*)+\b/g,n=>In(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=>In(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=>Fe(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=>Fe(n,"cli")).join(", "):o==="action only"?"command only":o}function gk(e,t){if(!_e(e))return e;if(Ak(e)){const o={...e};return typeof o.hint=="string"&&(o.hint=W(o.hint)),Array.isArray(o.shapes)&&(o.shapes=o.shapes.map(n=>typeof n=="string"?W(n):n)),o.requiredFields=kk(o.requiredFields,t),o.example=Cs(o.tool,o.action,o.example),Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?W(n):n)),typeof o.fullDocResource=="string"&&(o.fullDocResource=`${N} help ${o.tool} ${et(String(o.action))}`),o}if(Sk(e)){const o={...e};return Array.isArray(o.guidance)&&(o.guidance=o.guidance.map(n=>typeof n=="string"?W(n):n)),_e(o.actionSummaries)&&(o.actionSummaries=Object.fromEntries(Object.entries(o.actionSummaries).map(([n,r])=>[n,typeof r=="string"?W(r):r]))),_e(o.actions)&&(o.actions=Object.fromEntries(Object.entries(o.actions).map(([n,r])=>!_e(r)||typeof r.hint!="string"?[n,r]:[n,{...r,hint:W(r.hint)}]))),typeof o.detailsHint=="string"&&(o.detailsHint=W(o.detailsHint)),Array.isArray(o.helpResources)&&(o.helpResources=o.helpResources.map(n=>typeof n=="string"?W(n):n)),o}if(_e(e.error)){const o=e.error;return{...e,error:{...o,...typeof o.hint=="string"?{hint:W(o.hint)}:{},...typeof o.details=="string"?{details:W(o.details)}:{}}}}return bk(e)}function bk(e,t){const o={...e};for(const n of["hint","detailsHint"])typeof o[n]=="string"&&(o[n]=W(o[n]));for(const n of["guidance","hints"])Array.isArray(o[n])&&(o[n]=o[n].map(r=>typeof r=="string"?W(r):r));return o}function Cs(e,t,o,n){if(typeof e!="string"||typeof t!="string")return o;if(Array.isArray(o))return o.map(s=>Cs(e,t,s));if(!_e(o))return typeof o=="string"?W(o):o;const r={...o};return delete r.action,Ps(e,t,r)}function kk(e,t){return Array.isArray(e)&&e.every(o=>typeof o=="string")?e.map(o=>Fe(o,t)):Array.isArray(e)?e.map(o=>Array.isArray(o)?o.map(n=>typeof n=="string"?Fe(n,t):n):o):e}function In(e,t){const o=t==="+"?/\s*\+\s*/:/\s*\/\s*/,n=e.split(o);return n.some(r=>!_k(r))?e:n.map(r=>Fe(r,"cli")).join(` ${t} `)}function _k(e){const t=e.trim();return!t||yk.has(t.toLowerCase())?!1:/^[A-Za-z][A-Za-z0-9_]*$/.test(t)}function wk(e){if(!e)return{};const t={};for(const o of Ik(e,",")){const n=o.trim();if(!n)continue;const r=n.indexOf("=");if(r<=0)continue;const s=n.slice(0,r).trim(),i=n.slice(r+1).trim();s&&(t[s]=Os(i))}return t}function Ik(e,t){const o=[];let n="",r=!1,s=!1,i=!1,a=0,c=0,u=0;for(const d of e){if(d==="'"&&!s&&!i){r=!r,n+=d;continue}if(d==='"'&&!r&&!i){s=!s,n+=d;continue}if((d==="“"||d==="”")&&!r&&!s){i=!i,n+=d;continue}if(!r&&!s&&!i&&(d==="["&&a++,d==="]"&&(a=Math.max(0,a-1)),d==="{"&&c++,d==="}"&&(c=Math.max(0,c-1)),d==="("&&u++,d===")"&&(u=Math.max(0,u-1)),d===t&&a===0&&c===0&&u===0)){o.push(n),n="";continue}n+=d}return n&&o.push(n),o}function vk(e,t){const o=Fe(e,"cli");return Array.isArray(t)||_e(t)?`${o}-json '${JSON.stringify(t)}'`:typeof t=="boolean"?`${o} ${t?"true":"false"}`:typeof t=="number"?`${o} ${t}`:`${o} ${Dk(String(t))}`}function Dk(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 _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sk(e){return typeof e.tool=="string"&&(Array.isArray(e.commonActions)||Array.isArray(e.advancedActions))&&e.action===void 0}function Ak(e){return typeof e.tool=="string"&&typeof e.action=="string"&&(e.example!==void 0||Array.isArray(e.shapes))}const V={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m",bold:"\x1B[1m"},$s=["id","name","title","path","hpath","notebook","box","rootID","blockID","docID","avID","deckID","cardID","status","version","count","total","page","pageCount"],Tk=new Map($s.map((e,t)=>[e,t]));function Pk(e){return!!e.isTTY}function ye(e,t,o){return Pk(e)?`${t}${o}${V.reset}`:o}function Es(e){switch(e){case"success":return V.green+V.bold;case"warning":return V.yellow+V.bold;case"error":return V.red+V.bold;case"muted":return V.dim;case"info":default:return V.cyan+V.bold}}function H(e,t=""){e.write(t.endsWith(`
119
+ `)?t:`${t}
120
+ `)}function tt(e,t=process.stdout){H(t,ye(t,V.bold,e))}function te(e,t,o=process.stdout){const n=e==="success"?"✓":e==="warning"?"!":e==="error"?"✗":"•";H(o,ye(o,Es(e),`${n} ${t}`))}function vn(e,t=process.stdout){H(t,ye(t,V.dim,e))}function G(e,t=process.stdout){H(t),H(t,ye(t,V.cyan+V.bold,e))}function ee(e,t=process.stdout,o="info"){for(const n of e)H(t,`${ye(t,Es(o)," •")} ${n}`)}function $t(e,t=process.stdout){if(e.length===0)return;const o=e.map(r=>wt(r.key)),n=Math.max(...o.map(r=>r.length));for(let r=0;r<e.length;r++){const s=o[r].padEnd(n);H(t,` ${ye(t,V.bold,`${s}:`)} ${It(e[r].value)}`)}}function ce(e,t,o=process.stdout){H(o,`${ye(o,V.dim+V.bold,`${e}:`)} ${t}`)}function we(e,t={}){const o=process.stderr,n=W(e instanceof Error?e.message:String(e));te("error",n,o),t.exitHint&&ce("Hint",W(t.exitHint),o),t.debug&&e instanceof Error&&e.stack&&H(o,e.stack)}function Ns(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(`
121
+ `)||process.stdout.write(`
122
+ `),e.isError?1:0}return n=gk(n,"cli"),t.json?Ck(n,e.isError):e.isError?(Ok(n),1):($k(n),0)}function Ck(e,t){return process.stdout.write(JSON.stringify(e)+`
123
+ `),t?1:0}function Ok(e){const t=process.stderr;if(Ie(e)&&Ie(e.error)){const o=e.error,n=typeof o.type=="string"?o.type:"error",r=typeof o.message=="string"?o.message:"Unknown error";if(te("error",`[${n}] ${r}`,t),Array.isArray(o.fields)){const s=o.fields.filter(Ie).map(i=>{const a=typeof i.path=="string"&&i.path?i.path:"(field)",c=typeof i.message=="string"?i.message:"Invalid value";return`${ye(t,V.yellow+V.bold,a)} — ${c}`});s.length>0&&(G("Fields",t),ee(s,t,"warning"))}typeof o.hint=="string"&&o.hint&&(G("Hint",t),H(t,` ${o.hint}`)),typeof o.details=="string"&&o.details&&(G("Details",t),H(t,Et(o.details,2)));return}te("error",`Error: ${Se(e)}`,t)}function $k(e){const t=process.stdout;if(typeof e=="string"){t.write(e),e.endsWith(`
124
+ `)||t.write(`
125
+ `);return}if(e==null){te("success","Done",t);return}if(Array.isArray(e)){te("info",`${e.length} item${e.length===1?"":"s"}`,t),Co(e,"Items",t);return}if(!Ie(e)){H(t,Se(e));return}const o=e;if(Zk(o)){zk(o,t);return}if(Lk(o)){xk(o,t);return}if(Array.isArray(o.data)&&typeof o.total=="number"&&typeof o.page=="number"){Ek(o,t);return}Nk(o,t)}function Ek(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:"?",i=typeof e.pageSize=="number"?e.pageSize:void 0;te("success",`${o.length} of ${n} items · page ${r}/${s}`,t),$t([...i!==void 0?[{key:"pageSize",value:i}]:[],...typeof e.hasNextPage=="boolean"?[{key:"hasNextPage",value:e.hasNextPage}]:[]],t),Co(o,"Items",t),e.hasNextPage&&(G("Next Step",t),ce("Tip","More pages are available. Re-run with `--page <n>`.",t))}function Nk(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?te("success",n??"Success",t):n&&te("info",n,t);const s=Rs(r,new Set(n?["message"]:[]));s.length>0&&$t(s,t);const i=new Set(s.map(c=>c.key));n&&i.add("message");const a=r.filter(([c])=>!i.has(c));if(a.length===0){!o&&!n&&s.length===0&&H(t,Se(e));return}for(const[c,u]of a)Rk(c,u,t)}function Rk(e,t,o){if(t!==void 0){if(Array.isArray(t)){Co(t,wt(e),o);return}if(G(wt(e),o),Ie(t)){const n=Fk(t);if(n.length>0&&n.length===Object.keys(t).length){$t(n,o);return}H(o,Et(Se(t),2));return}H(o,` ${It(t)}`)}}function Co(e,t,o){if(e.length===0){G(t,o),vn(" No items.",o);return}G(t,o);const n=e.slice(0,10);for(const r of n){const s=qk(r);if(s){H(o,` • ${s}`);continue}H(o,Et(Se(r),2))}e.length>n.length&&vn(` … ${e.length-n.length} more item(s) not shown. Use --json for full output.`,o)}function zk(e,t){const o=typeof e.tool=="string"?e.tool:"tool";tt(`${o} tool`,t);const n=Ce(e.guidance);n.length>0&&(G("Guidance",t),ee(n,t)),Dn("Common Actions",Ce(e.commonActions),e.actionSummaries,t),Dn("Advanced Actions",Ce(e.advancedActions),e.actionSummaries,t);const r=Ce(e.requiresConfirmation);r.length>0&&(G("Confirmation",t),ee(r.map(s=>`${s} requires explicit confirmation.`),t,"warning")),typeof e.detailsHint=="string"&&e.detailsHint&&(G("Next Step",t),ce("Tip",e.detailsHint,t))}function xk(e,t){const o=typeof e.tool=="string"?e.tool:"tool",n=typeof e.action=="string"?e.action:"help";tt(`${o} ${n}`,t),typeof e.hint=="string"&&e.hint&&te("info",e.hint,t);const r=Ce(e.shapes);r.length>0&&(G("Accepted Shapes",t),ee(r,t));const s=jk(e.requiredFields);s.length>0&&(G("Required Fields",t),ee(s,t)),e.example!==void 0&&(G("Example",t),Bk(e.example,t));const i=Ce(e.guidance);i.length>0&&(G("Guidance",t),ee(i,t)),e.requiresConfirmation===!0&&(G("Safety",t),ee(["This action requires explicit confirmation."],t,"warning")),typeof e.fullDocResource=="string"&&e.fullDocResource&&(G("Reference",t),ce("Resource",e.fullDocResource,t))}function Dn(e,t,o,n){if(t.length===0)return;const r=Ie(o)?o:{};G(e,n),ee(t.map(s=>{const i=typeof r[s]=="string"?String(r[s]):"";return i?`${s} — ${i}`:s}),n)}function Bk(e,t){if(typeof e=="string"){H(t,` ${e}`);return}if(Array.isArray(e)&&e.every(o=>typeof o=="string")){ee(e,t);return}H(t,Et(Se(e),2))}function Rs(e,t=new Set){return e.filter(([n,r])=>!t.has(n)&&Oo(r)).map(([n,r])=>({key:n,value:r})).sort((n,r)=>Sn(n.key)-Sn(r.key)||n.key.localeCompare(r.key)).slice(0,8)}function Sn(e){return Tk.get(e)??$s.length+100}function Fk(e){return Object.entries(e).filter(([,t])=>Oo(t)).map(([t,o])=>({key:t,value:o}))}function qk(e){if(Oo(e))return It(e);if(!Ie(e))return null;const t=Rs(Object.entries(e));return t.length===0?null:t.slice(0,4).map(o=>`${wt(o.key)}: ${It(o.value)}`).join(" · ")}function jk(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 Ce(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Se(e){return JSON.stringify(e,null,2)}function wt(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 It(e){return typeof e=="string"?Uk(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":Se(e)}function Uk(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Et(e,t){const o=" ".repeat(t);return e.split(`
126
+ `).map(n=>`${o}${n}`).join(`
127
+ `)}function Oo(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zk(e){return typeof e.tool=="string"&&(Array.isArray(e.commonActions)||Array.isArray(e.advancedActions))&&e.action===void 0}function Lk(e){return typeof e.tool=="string"&&typeof e.action=="string"&&(e.example!==void 0||Array.isArray(e.shapes))}async function Mk(e){const{tool:t,action:o,rest:n}=e;if(!t||!o)throw new Error("runDispatch requires both tool and action.");const r=Po(t);if(!r)throw Hk(t);const s=o.replace(/-/g,"_");if(!Ee[r].includes(s)&&s!=="help")throw Yk(r,s);const a=Ds(e.configPath),c=Ss(a,e.url,e.token);As(c);const u=new $n({baseUrl:c.apiUrl});c.token&&u.setToken(c.token);const d=new zn(u);try{await d.load()}catch{}const p=Gk(),f=To[r],k=Vk(r,p),{args:_,warnings:w}=pk(n,k);if(w.length>0&&e.debug)for(const z of w)process.stderr.write(`[warn] ${z}
128
+ `);const T={action:s,..._};try{const z=await f.callTool(u,T,p[r],d);return Ns(z,{json:e.json,debug:e.debug})}catch(z){return we(z,{debug:e.debug}),1}}function Vk(e,t){const n=To[e].listTools(t[e])[0];if(!n)throw new Error(`Tool "${e}" has no aggregated descriptor — this is a bug.`);return n.inputSchema}function Gk(){const e=En();for(const t of qe){const o=Ee[t],n=e[t].actions;for(const r of o)n[r]=!0}return e}function Hk(e){const t=qe.join(", ");return new Error(`Unknown tool "${e}". Available tools: ${t}. Try "${N} list".`)}function Yk(e,t){const o=Ee[e].join(", ");return new Error(`Unknown action "${t}" for tool "${e}". Available actions: ${o}. Try "${N} help ${e}".`)}class An{constructor(){ae(this,"rl");ae(this,"closed",!1);this.rl=Bs.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 Wk(e){const t=e??vs();if(ue.existsSync(t)){const n=new An,r=(await n.ask(`Config already exists at ${t}. Overwrite? [y/N] `)).toLowerCase();if(n.close(),r!=="y"&&r!=="yes"){te("warning","Aborted. Existing config was kept.");return}}const o=new An;try{tt("SiYuan CLI setup"),ce("Path",t),ce("Tip","Press Enter to accept the default shown in brackets."),process.stdout.write(`
129
+ `);const n=await o.ask("SiYuan API URL [http://127.0.0.1:6806]: ")||"http://127.0.0.1:6806",r=await o.ask("SiYuan API token (find it in SiYuan > Settings > About): "),s={apiUrl:n,token:r},i=Xt.dirname(t);ue.existsSync(i)||ue.mkdirSync(i,{recursive:!0,mode:448}),ue.writeFileSync(t,JSON.stringify(s,null,2)+`
130
+ `,{mode:384}),process.stdout.write(`
131
+ `),te("success","Config written."),$t([{key:"path",value:t},{key:"apiUrl",value:n},{key:"token",value:r?"configured":"empty"}]),process.stdout.write(`
132
+ `),ce("Next","Run `siyuan-sisyphus notebook list` to verify the connection. (`siyuan` also works.)")}finally{o.close()}}function Jk(e){const t=process.stdout,o=e.tool?Po(e.tool):null;return o?(tt(`${o} actions`,t),ee(Ee[o].map(n=>{const r=He(o,n)==="basic"?"common":"advanced",s=Ne(o,n)?" · confirmation required":"";return`${n} — ${r}${s}`}),t),G("Next Step",t),ce("Tip",`Run \`${N} help ${o} <action>\` for fields and examples.`,t),0):(e.tool&&we(`Unknown tool "${e.tool}". Showing all tools instead.`),tt("SiYuan tools",t),ee(qe.map(n=>{const r=Ee[n],s=r.filter(a=>He(n,a)==="basic").length,i=r.length-s;return`${n} — ${r.length} actions (${s} common, ${i} advanced)`}),t),G("Next Step",t),ce("Tip",`Run \`${N} list <tool>\` to see a tool’s actions.`,t),0)}async function Kk(e){const t=e.tool;if(!t)return we(`Missing tool. Usage: ${N} help <tool> [action]`),2;const o=Po(t);if(!o)return we(`Unknown tool "${t}". Available: ${qe.join(", ")}.`),2;const n=Ds(e.configPath),r=Ss(n,e.url,e.token);As(r);const s=new $n({baseUrl:r.apiUrl});r.token&&s.setToken(r.token);const i=new zn(s),a=Qk(),c=To[o],u={action:"help"};e.action&&(u.topic=e.action);try{const d=await c.callTool(s,u,a[o],i);return Ns(d,{json:e.json,debug:e.debug})}catch(d){return we(d,{debug:e.debug}),1}}function Qk(){const e=En();for(const t of qe){const o=Ee[t],n=e[t].actions;for(const r of o)n[r]=!0}return e}async function Xk(){let e;try{e=Ls(process.argv.slice(2))}catch(t){return we(t),2}switch(e.command){case"show-help":return process.stdout.write(Vs()),0;case"version":return process.stdout.write(`0.1.0
133
+ `),0;case"init":return await Wk(e.configPath),0;case"list":return Jk(e);case"help":return await Kk(e);case"dispatch":return await Mk(e);default:throw new Error(`Unknown command: ${String(e.command)}`)}}Xk().then(e=>process.exit(e)).catch(e=>{we(e,{debug:process.env.SIYUAN_MCP_DEBUG==="1"}),process.exit(1)});
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "siyuan-sisyphus",
3
+ "version": "0.1.0",
4
+ "description": "Direct command-line control for SiYuan Note. Call any SiYuan MCP tool as a subcommand: `siyuan-sisyphus block append --parent-id ... --data \"...\"`.",
5
+ "bin": {
6
+ "siyuan-sisyphus": "./dist/cli.cjs",
7
+ "siyuan": "./dist/cli.cjs"
8
+ },
9
+ "files": [
10
+ "dist/cli.cjs",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "keywords": [
17
+ "siyuan",
18
+ "siyuan-cli",
19
+ "mcp",
20
+ "cli",
21
+ "note-taking",
22
+ "obsidian-cli-alternative"
23
+ ],
24
+ "license": "MIT",
25
+ "author": "Taihong Yang",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/yangtaihong59/siyuan-plugins-mcp-sisyphus.git"
29
+ },
30
+ "homepage": "https://github.com/yangtaihong59/siyuan-plugins-mcp-sisyphus#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/yangtaihong59/siyuan-plugins-mcp-sisyphus/issues"
33
+ }
34
+ }