agent-remnote 1.5.1 → 1.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-remnote",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "license": "MIT",
5
5
  "bin": {
6
6
  "agent-remnote": "./cli.js"
Binary file
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@remnote/plugin",
3
3
  "version": "0.0.2",
4
- "build_id": "0.0.2:1774461211291",
5
- "built_at": 1774461226265,
6
- "source_stamp": 1774461211291,
4
+ "build_id": "0.0.2:1774922238299",
5
+ "built_at": 1774923294946,
6
+ "source_stamp": 1774922238299,
7
7
  "mode": "dist"
8
8
  }
@@ -1 +1 @@
1
- import{d as a}from"./index-CTg2hlbS.js";import{o,a as t}from"./indexPlugin-Cx5F4LoS.js";a.declareIndexPlugin(o,t);
1
+ import{d as a}from"./index-CTg2hlbS.js";import{o,a as t}from"./indexPlugin-BEtBEAsb.js";a.declareIndexPlugin(o,t);
@@ -1 +1 @@
1
- import{d as t}from"./index-CTg2hlbS.js";import{o,a}from"./indexPlugin-Cx5F4LoS.js";t.declareIndexPlugin(o,a);
1
+ import{d as t}from"./index-CTg2hlbS.js";import{o,a}from"./indexPlugin-BEtBEAsb.js";t.declareIndexPlugin(o,a);
@@ -1,12 +1,12 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-OYpYHp3Y.js","./index-CTg2hlbS.js","./index-Ch_qCilz.js","./index-4b5IDxii.js","./index-CMP2i-HY.js","./blank-line-B2rM3oxN.js","./index-dJjNfQvw.js","./index-XfOTAlvl.js","./index-BnR23rlw.js","./index-BpbrUbge.js"])))=>i.map(i=>d[i]);
2
- var Vt=Object.defineProperty;var zt=(e,t,n)=>t in e?Vt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ue=(e,t,n)=>zt(e,typeof t!="symbol"?t+"":t,n);import{d as S}from"./index-CTg2hlbS.js";const fe={name:"agent-remnote backup",code:"agent_remnote_backup",description:"Internal backup marker for replace-style write operations."},Gt={slots:[{code:"backup_kind",name:"Kind",propertyType:S.PropertyType.SINGLE_SELECT,enumValues:{children_replace:"Children Replace",selection_replace:"Selection Replace"},propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"cleanup_policy",name:"Cleanup Policy",propertyType:S.PropertyType.SINGLE_SELECT,enumValues:{auto:"Auto",visible:"Visible"},propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"cleanup_state",name:"Cleanup State",propertyType:S.PropertyType.SINGLE_SELECT,enumValues:{pending:"Pending",orphan:"Orphan",retained:"Retained",cleaned:"Cleaned"},propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_txn",name:"Source Txn",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_op",name:"Source Op",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_parent",name:"Source Parent",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_anchor",name:"Source Anchor",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"created_at",name:"Created At",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0}]};async function Yt(e){await e.app.registerPowerup({name:fe.name,code:fe.code,description:fe.description,options:Gt})}function gt(e,t=8e3){return new Promise((n,o)=>{const r=new WebSocket(e);let i=!1;const s=()=>{try{r.onopen=null}catch{}try{r.onerror=null}catch{}try{r.onclose=null}catch{}clearTimeout(a)},c=d=>{i||(i=!0,s(),o(d))};r.onopen=()=>{i||(i=!0,s(),n(r))},r.onerror=()=>c(new Error("WebSocket connection failed")),r.onclose=()=>c(new Error("WebSocket closed"));const a=setTimeout(()=>c(new Error("WebSocket connection timeout")),t)})}function jt(e,t=15e3){return new Promise((n,o)=>{const r=d=>{try{n(JSON.parse(String(d.data)))}catch{n(null)}c()},i=()=>{c(),o(new Error("WebSocket closed"))},s=()=>{c(),o(new Error("WebSocket error"))},c=()=>{e.removeEventListener("message",r),e.removeEventListener("close",i),e.removeEventListener("error",s),clearTimeout(a)};e.addEventListener("message",r),e.addEventListener("close",i),e.addEventListener("error",s);const a=setTimeout(()=>{c(),o(new Error("WebSocket timeout"))},t)})}function Kt(e,t=15e3){return new Promise((n,o)=>{const r=l=>{try{const u=JSON.parse(String(l.data));(u?.type==="OpDispatchBatch"||u?.type==="OpDispatch"||u?.type==="NoWork"||u?.type==="Error")&&(a(),n(u))}catch{}},i=()=>{a(),o(new Error("WebSocket closed"))},s=()=>{a(),o(new Error("WebSocket error"))},c=()=>{a(),o(new Error("WebSocket timeout"))},a=()=>{e.removeEventListener("message",r),e.removeEventListener("close",i),e.removeEventListener("error",s),clearTimeout(d)};e.addEventListener("message",r),e.addEventListener("close",i),e.addEventListener("error",s);const d=setTimeout(c,t)})}function le(e,t){e.send(JSON.stringify(t))}async function Xt(e){const t=await gt(e);le(t,{type:"QueryStats"});const n=await jt(t);if(t.close(),n?.type!=="Stats")throw new Error("Invalid Stats response");return n}const j={wsPort:"ws-port",autoConnectControl:"auto-connect-control",autoSyncOnConnect:"auto-sync-on-connect",syncConcurrency:"sync-concurrency"},bt=6789;function Ht(e){if(typeof e!="number"||!Number.isFinite(e))return null;const t=Math.trunc(e);return t<1||t>65535?null:t}function Qt(e){return`ws://localhost:${e}/ws`}async function Ae(e){let t=null;try{t=await e.settings.getSetting(j.wsPort)}catch{}const n=Ht(t)??bt;return Qt(n)}const ft="agent-remnote.client-instance-id";function Jt(){try{const n=globalThis.crypto;if(n&&typeof n.randomUUID=="function")return n.randomUUID()}catch{}const e=Math.random().toString(36).slice(2,12);return`client-${Date.now().toString(36)}-${e}`}async function He(e){try{const n=await e.storage.getLocal(ft);if(typeof n=="string"&&n.trim())return n.trim()}catch{}const t=Jt();try{await e.storage.setLocal(ft,t)}catch{}return t}async function Zt(e){try{await e.settings.registerNumberSetting({id:j.wsPort,title:"WebSocket Port",defaultValue:bt})}catch{}try{await e.settings.registerBooleanSetting({id:j.autoConnectControl,title:"Auto-connect control channel",defaultValue:!0})}catch{}try{await e.settings.registerBooleanSetting({id:j.autoSyncOnConnect,title:"Auto-sync on connect",defaultValue:!0})}catch{}try{await e.settings.registerNumberSetting({id:j.syncConcurrency,title:"Sync concurrency",defaultValue:4})}catch{}}function kt(e){const t=String(e||""),n={"rem.create":"create_rem","rem.createPortal":"create_portal","portal.createMany":"create_portal_bulk","rem.createSingleWithMarkdown":"create_single_rem_with_markdown","rem.createTreeWithMarkdown":"create_tree_with_markdown","rem.replaceChildrenWithMarkdown":"replace_children_with_markdown","rem.createLink":"create_link_rem","rem.updateText":"update_text","rem.move":"move_rem","rem.moveMany":"move_rem_bulk","rem.delete":"delete_rem","backup.deleteArtifact":"delete_backup_artifact","portal.create":"create_portal","tag.add":"add_tag","tag.remove":"remove_tag","tag.addMany":"add_tag_bulk","tag.removeMany":"remove_tag_bulk","attribute.set":"set_attribute","table.create":"create_table","property.add":"add_property","property.setType":"set_property_type","table.setFilter":"set_table_filter","option.add":"add_option","option.remove":"remove_option","table.addRow":"table_add_row","table.removeRow":"table_remove_row","cell.setSelect":"set_cell_select","cell.setCheckbox":"set_cell_checkbox","cell.setNumber":"set_cell_number","cell.setDate":"set_cell_date","table.cellWrite":"table_cell_write","source.add":"add_source","source.remove":"remove_source","source.addMany":"add_source_bulk","source.removeMany":"remove_source_bulk","todo.setStatus":"set_todo_status","todo.setStatusMany":"set_todo_status_bulk"};return n[t]?n[t]:t}const er="modulepreload",tr=function(e,t){return new URL(e,t).href},mt={},be=function(t,n,o){let r=Promise.resolve();if(n&&n.length>0){const s=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),a=c?.nonce||c?.getAttribute("nonce");r=Promise.allSettled(n.map(d=>{if(d=tr(d,o),d in mt)return;mt[d]=!0;const l=d.endsWith(".css"),u=l?'[rel="stylesheet"]':"";if(!!o)for(let m=s.length-1;m>=0;m--){const v=s[m];if(v.href===d&&(!l||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=l?"stylesheet":er,l||(f.as="script"),f.crossOrigin="",f.href=d,a&&f.setAttribute("nonce",a),document.head.appendChild(f),l)return new Promise((m,v)=>{f.addEventListener("load",m),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return r.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};function ne(e){return new Promise(t=>setTimeout(t,e))}async function we(e,t,n,o=0){const r=typeof n=="string"?n.trim():"";if(!r)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");try{typeof t.setParent=="function"?await t.setParent(r):await e.rem.moveRems([t._id],r,o)}catch(i){try{await t.remove()}catch{}throw i}}function rr(e){const t=[],n=/\(\(([^\s()|]+)(?:\|[^()]+)?\)\)|\{ref:([A-Za-z0-9]+)\}/g;let o=0;for(const i of e.matchAll(n)){const s=e.slice(o,i.index??0);s&&t.push({i:"m",text:s});const c=(i[1]??i[2]??"").trim();c&&t.push({i:"q",_id:c}),o=(i.index??0)+i[0].length}const r=e.slice(o);return r&&t.push({i:"m",text:r}),t.length>0?t:[{i:"m",text:e}]}function q(e){return e==null?[]:Array.isArray(e)?e:typeof e=="string"?rr(e):typeof e=="object"?[e]:[{i:"m",text:String(e)}]}async function nr(e){const{unified:t}=await be(async()=>{const{unified:u}=await import("./index-OYpYHp3Y.js");return{unified:u}},__vite__mapDeps([0,1,2]),import.meta.url),{default:n}=await be(async()=>{const{default:u}=await import("./index-4b5IDxii.js");return{default:u}},__vite__mapDeps([3,4,5,6,2]),import.meta.url),{default:o}=await be(async()=>{const{default:u}=await import("./index-XfOTAlvl.js");return{default:u}},__vite__mapDeps([7,5,6,8]),import.meta.url),{default:r}=await be(async()=>{const{default:u}=await import("./index-BpbrUbge.js");return{default:u}},__vite__mapDeps([9,8,6,4]),import.meta.url),s=t().use(n).use(o).parse(e);s.children=or(s.children);const c=[],a=[];let d=[];for(const u of s.children)if(u.type==="heading"){if(a.length>0&&c.length>0){const f=t().use(r).stringify({type:"root",children:a});c[c.length-1].body=qe(f),a.length=0}const p=t().use(r).stringify({type:"root",children:[u]});c.push({heading:p.trim(),body:""})}else c.length===0?d.push(u):a.push(u);if(a.length>0&&c.length>0){const u=t().use(r).stringify({type:"root",children:a});c[c.length-1].body=qe(u)}return{preface:d.length>0?qe(t().use(r).stringify({type:"root",children:d})):void 0,items:c}}function or(e){const t=[];for(const n of e)if(n.type==="list"&&Array.isArray(n.children))for(const o of n.children){if(!o||!Array.isArray(o.children)||o.children.length===0)continue;const r=o.children[0];if(r&&r.type==="heading"){t.push(r);const i=o.children.slice(1);i.length>0&&t.push(...i)}else t.push(o)}else t.push(n);return t}function qe(e){return e=at(e),e=Rt(e),e=Et(e),e=it(e),e}const ar=/^[A-Za-z0-9]{17}$/,ir=/\(\(([^\s()|]+)(?:\|[^()]+)?\)\)|\{ref:([A-Za-z0-9]+)\}/g;function vt(e){const t=e.includes("((")&&e.includes("))"),n=e.includes("{ref:")&&e.includes("}");if(!t&&!n)return{markdown:e,refs:[]};const o=[];return{markdown:e.replace(ir,(i,s,c)=>{const a=typeof s=="string"&&s.trim()?s:c,d=typeof a=="string"?a.trim():"";if(!ar.test(d))return i;const l=`AGENT_REMNOTE_REF_PLACEHOLDER_${o.length}`;return o.push({placeholder:l,remId:d,original:i}),l}),refs:o}}async function St(e,t){const n=new Map;for(const o of t)if(!n.has(o.remId))try{n.set(o.remId,!!await e.rem.findOne(o.remId))}catch{n.set(o.remId,!1)}return n}function ke(e,t,n,o){if(!Array.isArray(e)||t.length===0)return{richText:e,changed:!1};const r=(a,d)=>{let l=0,u=!1;const p=[],f=v=>{v&&(d&&typeof d=="object"?p.push({...d,text:v}):p.push(v))};for(;l<a.length;){let v=-1,I;for(const T of t){const k=a.indexOf(T.placeholder,l);k>=0&&(v<0||k<v)&&(v=k,I=T)}if(v<0||!I)break;const y=a.slice(l,v);f(y),o==="resolve"&&n.get(I.remId)===!0?p.push({i:"q",_id:I.remId}):f(I.original),l=v+I.placeholder.length,u=!0}const m=a.slice(l);return f(m),u?p.length===0?{items:d?[d]:[a],changed:!1}:{items:p,changed:!0}:{items:d?[d]:[a],changed:!1}},i=a=>{if(typeof a=="string")return r(a);if(a&&typeof a=="object"){if(a.i==="m"&&typeof a.text=="string")return r(a.text,a);const d=a.children;if(Array.isArray(d)){const l=ke(d,t,n,o);return l.changed?{items:[{...a,children:l.richText}],changed:!0}:{items:[a],changed:!1}}}return{items:[a],changed:!1}};let s=!1;const c=[];for(const a of e){const d=i(a);d.changed&&(s=!0),c.push(...d.items)}return s?{richText:c,changed:!0}:{richText:e,changed:!1}}function sr(e){if(!Array.isArray(e)||e.length===0||!e.every(n=>typeof n=="string"))return!1;const t=e.join("");return t.trim()?!!(/\[[^\]]+\]\([^)]+\)/.test(t)||t.includes("**")||t.includes("`")||t.includes("~~")):!1}async function K(e,t,n){const o=Tt(t),{markdown:r,refs:i}=vt(o),s=await e.rem.createSingleRemWithMarkdown(r,n);if(!s)return;if(i.length===0)return s;const c=await St(e,i),a=ke(s.text,i,c,"resolve");if(!a.changed)return s;try{await s.setText(a.richText)}catch{const d=ke(s.text,i,c,"plain");try{await s.setText(d.richText)}catch{}}return s}async function Q(e,t,n){const o=Tt(t),{markdown:r,refs:i}=vt(o),s=await e.rem.createTreeWithMarkdown(r,n);if(!Array.isArray(s)||s.length===0)return s;const c=i.length>0?await St(e,i):null;for(const a of s){if(!a)continue;const d=a.text;let l=d,u=!1;if(sr(d))try{l=await e.richText.parseFromMarkdown(d.join("")),u=!0}catch{}let p=u,f=l;if(c){const m=ke(l,i,c,"resolve");m.changed&&(f=m.richText,p=!0)}if(p)try{await a.setText(f)}catch{if(!c)continue;const m=ke(l,i,c,"plain");if(!m.changed&&!u)continue;try{await a.setText(m.richText)}catch{}}}return s}async function cr(e,t,n,o=2){const r=[],i=[{level:-1,id:n??null}],s=t.replace(/\r\n?/g,`
2
+ var zt=Object.defineProperty;var Gt=(e,t,n)=>t in e?zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ue=(e,t,n)=>Gt(e,typeof t!="symbol"?t+"":t,n);import{d as S}from"./index-CTg2hlbS.js";const fe={name:"agent-remnote backup",code:"agent_remnote_backup",description:"Internal backup marker for replace-style write operations."},Yt={slots:[{code:"backup_kind",name:"Kind",propertyType:S.PropertyType.SINGLE_SELECT,enumValues:{children_replace:"Children Replace",selection_replace:"Selection Replace"},propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"cleanup_policy",name:"Cleanup Policy",propertyType:S.PropertyType.SINGLE_SELECT,enumValues:{auto:"Auto",visible:"Visible"},propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"cleanup_state",name:"Cleanup State",propertyType:S.PropertyType.SINGLE_SELECT,enumValues:{pending:"Pending",orphan:"Orphan",retained:"Retained",cleaned:"Cleaned"},propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_txn",name:"Source Txn",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_op",name:"Source Op",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_parent",name:"Source Parent",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"source_anchor",name:"Source Anchor",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0},{code:"created_at",name:"Created At",propertyType:S.PropertyType.TEXT,propertyLocation:S.PropertyLocation.ONLY_DOCUMENT,onlyProgrammaticModifying:!0}]};async function jt(e){await e.app.registerPowerup({name:fe.name,code:fe.code,description:fe.description,options:Yt})}function bt(e,t=8e3){return new Promise((n,o)=>{const r=new WebSocket(e);let i=!1;const s=()=>{try{r.onopen=null}catch{}try{r.onerror=null}catch{}try{r.onclose=null}catch{}clearTimeout(a)},c=d=>{i||(i=!0,s(),o(d))};r.onopen=()=>{i||(i=!0,s(),n(r))},r.onerror=()=>c(new Error("WebSocket connection failed")),r.onclose=()=>c(new Error("WebSocket closed"));const a=setTimeout(()=>c(new Error("WebSocket connection timeout")),t)})}function Kt(e,t=15e3){return new Promise((n,o)=>{const r=d=>{try{n(JSON.parse(String(d.data)))}catch{n(null)}c()},i=()=>{c(),o(new Error("WebSocket closed"))},s=()=>{c(),o(new Error("WebSocket error"))},c=()=>{e.removeEventListener("message",r),e.removeEventListener("close",i),e.removeEventListener("error",s),clearTimeout(a)};e.addEventListener("message",r),e.addEventListener("close",i),e.addEventListener("error",s);const a=setTimeout(()=>{c(),o(new Error("WebSocket timeout"))},t)})}function Xt(e,t=15e3){return new Promise((n,o)=>{const r=l=>{try{const u=JSON.parse(String(l.data));(u?.type==="OpDispatchBatch"||u?.type==="OpDispatch"||u?.type==="NoWork"||u?.type==="Error")&&(a(),n(u))}catch{}},i=()=>{a(),o(new Error("WebSocket closed"))},s=()=>{a(),o(new Error("WebSocket error"))},c=()=>{a(),o(new Error("WebSocket timeout"))},a=()=>{e.removeEventListener("message",r),e.removeEventListener("close",i),e.removeEventListener("error",s),clearTimeout(d)};e.addEventListener("message",r),e.addEventListener("close",i),e.addEventListener("error",s);const d=setTimeout(c,t)})}function le(e,t){e.send(JSON.stringify(t))}async function Ht(e){const t=await bt(e);le(t,{type:"QueryStats"});const n=await Kt(t);if(t.close(),n?.type!=="Stats")throw new Error("Invalid Stats response");return n}const K={wsPort:"ws-port",autoConnectControl:"auto-connect-control",autoSyncOnConnect:"auto-sync-on-connect",syncConcurrency:"sync-concurrency"},kt=6789;function Qt(e){if(typeof e!="number"||!Number.isFinite(e))return null;const t=Math.trunc(e);return t<1||t>65535?null:t}function Jt(e){return`ws://localhost:${e}/ws`}async function Ae(e){let t=null;try{t=await e.settings.getSetting(K.wsPort)}catch{}const n=Qt(t)??kt;return Jt(n)}const ft="agent-remnote.client-instance-id";function Zt(){try{const n=globalThis.crypto;if(n&&typeof n.randomUUID=="function")return n.randomUUID()}catch{}const e=Math.random().toString(36).slice(2,12);return`client-${Date.now().toString(36)}-${e}`}async function He(e){try{const n=await e.storage.getLocal(ft);if(typeof n=="string"&&n.trim())return n.trim()}catch{}const t=Zt();try{await e.storage.setLocal(ft,t)}catch{}return t}async function er(e){try{await e.settings.registerNumberSetting({id:K.wsPort,title:"WebSocket Port",defaultValue:kt})}catch{}try{await e.settings.registerBooleanSetting({id:K.autoConnectControl,title:"Auto-connect control channel",defaultValue:!0})}catch{}try{await e.settings.registerBooleanSetting({id:K.autoSyncOnConnect,title:"Auto-sync on connect",defaultValue:!0})}catch{}try{await e.settings.registerNumberSetting({id:K.syncConcurrency,title:"Sync concurrency",defaultValue:4})}catch{}}function vt(e){const t=String(e||""),n={"rem.create":"create_rem","rem.createPortal":"create_portal","portal.createMany":"create_portal_bulk","rem.createSingleWithMarkdown":"create_single_rem_with_markdown","rem.createTreeWithMarkdown":"create_tree_with_markdown","rem.replaceChildrenWithMarkdown":"replace_children_with_markdown","rem.createLink":"create_link_rem","rem.updateText":"update_text","rem.move":"move_rem","rem.moveMany":"move_rem_bulk","rem.delete":"delete_rem","backup.deleteArtifact":"delete_backup_artifact","portal.create":"create_portal","tag.add":"add_tag","tag.remove":"remove_tag","tag.addMany":"add_tag_bulk","tag.removeMany":"remove_tag_bulk","attribute.set":"set_attribute","table.create":"create_table","property.add":"add_property","property.setType":"set_property_type","table.setFilter":"set_table_filter","option.add":"add_option","option.remove":"remove_option","table.addRow":"table_add_row","table.removeRow":"table_remove_row","cell.setSelect":"set_cell_select","cell.setCheckbox":"set_cell_checkbox","cell.setNumber":"set_cell_number","cell.setDate":"set_cell_date","table.cellWrite":"table_cell_write","source.add":"add_source","source.remove":"remove_source","source.addMany":"add_source_bulk","source.removeMany":"remove_source_bulk","todo.setStatus":"set_todo_status","todo.setStatusMany":"set_todo_status_bulk"};return n[t]?n[t]:t}const tr="modulepreload",rr=function(e,t){return new URL(e,t).href},mt={},be=function(t,n,o){let r=Promise.resolve();if(n&&n.length>0){const s=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),a=c?.nonce||c?.getAttribute("nonce");r=Promise.allSettled(n.map(d=>{if(d=rr(d,o),d in mt)return;mt[d]=!0;const l=d.endsWith(".css"),u=l?'[rel="stylesheet"]':"";if(!!o)for(let m=s.length-1;m>=0;m--){const v=s[m];if(v.href===d&&(!l||v.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=l?"stylesheet":tr,l||(f.as="script"),f.crossOrigin="",f.href=d,a&&f.setAttribute("nonce",a),document.head.appendChild(f),l)return new Promise((m,v)=>{f.addEventListener("load",m),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return r.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};function ne(e){return new Promise(t=>setTimeout(t,e))}async function we(e,t,n,o=0){const r=typeof n=="string"?n.trim():"";if(!r)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");try{typeof t.setParent=="function"?await t.setParent(r):await e.rem.moveRems([t._id],r,o)}catch(i){try{await t.remove()}catch{}throw i}}function nr(e){const t=[],n=/\(\(([^\s()|]+)(?:\|[^()]+)?\)\)|\{ref:([A-Za-z0-9]+)\}/g;let o=0;for(const i of e.matchAll(n)){const s=e.slice(o,i.index??0);s&&t.push({i:"m",text:s});const c=(i[1]??i[2]??"").trim();c&&t.push({i:"q",_id:c}),o=(i.index??0)+i[0].length}const r=e.slice(o);return r&&t.push({i:"m",text:r}),t.length>0?t:[{i:"m",text:e}]}function q(e){return e==null?[]:Array.isArray(e)?e:typeof e=="string"?nr(e):typeof e=="object"?[e]:[{i:"m",text:String(e)}]}async function or(e){const{unified:t}=await be(async()=>{const{unified:u}=await import("./index-OYpYHp3Y.js");return{unified:u}},__vite__mapDeps([0,1,2]),import.meta.url),{default:n}=await be(async()=>{const{default:u}=await import("./index-4b5IDxii.js");return{default:u}},__vite__mapDeps([3,4,5,6,2]),import.meta.url),{default:o}=await be(async()=>{const{default:u}=await import("./index-XfOTAlvl.js");return{default:u}},__vite__mapDeps([7,5,6,8]),import.meta.url),{default:r}=await be(async()=>{const{default:u}=await import("./index-BpbrUbge.js");return{default:u}},__vite__mapDeps([9,8,6,4]),import.meta.url),s=t().use(n).use(o).parse(e);s.children=ar(s.children);const c=[],a=[];let d=[];for(const u of s.children)if(u.type==="heading"){if(a.length>0&&c.length>0){const f=t().use(r).stringify({type:"root",children:a});c[c.length-1].body=qe(f),a.length=0}const p=t().use(r).stringify({type:"root",children:[u]});c.push({heading:p.trim(),body:""})}else c.length===0?d.push(u):a.push(u);if(a.length>0&&c.length>0){const u=t().use(r).stringify({type:"root",children:a});c[c.length-1].body=qe(u)}return{preface:d.length>0?qe(t().use(r).stringify({type:"root",children:d})):void 0,items:c}}function ar(e){const t=[];for(const n of e)if(n.type==="list"&&Array.isArray(n.children))for(const o of n.children){if(!o||!Array.isArray(o.children)||o.children.length===0)continue;const r=o.children[0];if(r&&r.type==="heading"){t.push(r);const i=o.children.slice(1);i.length>0&&t.push(...i)}else t.push(o)}else t.push(n);return t}function qe(e){return e=at(e),e=Et(e),e=Tt(e),e=it(e),e}const ir=/^[A-Za-z0-9]{17}$/,sr=/\(\(([^\s()|]+)(?:\|[^()]+)?\)\)|\{ref:([A-Za-z0-9]+)\}/g;function St(e){const t=e.includes("((")&&e.includes("))"),n=e.includes("{ref:")&&e.includes("}");if(!t&&!n)return{markdown:e,refs:[]};const o=[];return{markdown:e.replace(sr,(i,s,c)=>{const a=typeof s=="string"&&s.trim()?s:c,d=typeof a=="string"?a.trim():"";if(!ir.test(d))return i;const l=`AGENT_REMNOTE_REF_PLACEHOLDER_${o.length}`;return o.push({placeholder:l,remId:d,original:i}),l}),refs:o}}async function Rt(e,t){const n=new Map;for(const o of t)if(!n.has(o.remId))try{n.set(o.remId,!!await e.rem.findOne(o.remId))}catch{n.set(o.remId,!1)}return n}function ke(e,t,n,o){if(!Array.isArray(e)||t.length===0)return{richText:e,changed:!1};const r=(a,d)=>{let l=0,u=!1;const p=[],f=v=>{v&&(d&&typeof d=="object"?p.push({...d,text:v}):p.push(v))};for(;l<a.length;){let v=-1,I;for(const E of t){const k=a.indexOf(E.placeholder,l);k>=0&&(v<0||k<v)&&(v=k,I=E)}if(v<0||!I)break;const y=a.slice(l,v);f(y),o==="resolve"&&n.get(I.remId)===!0?p.push({i:"q",_id:I.remId}):f(I.original),l=v+I.placeholder.length,u=!0}const m=a.slice(l);return f(m),u?p.length===0?{items:d?[d]:[a],changed:!1}:{items:p,changed:!0}:{items:d?[d]:[a],changed:!1}},i=a=>{if(typeof a=="string")return r(a);if(a&&typeof a=="object"){if(a.i==="m"&&typeof a.text=="string")return r(a.text,a);const d=a.children;if(Array.isArray(d)){const l=ke(d,t,n,o);return l.changed?{items:[{...a,children:l.richText}],changed:!0}:{items:[a],changed:!1}}}return{items:[a],changed:!1}};let s=!1;const c=[];for(const a of e){const d=i(a);d.changed&&(s=!0),c.push(...d.items)}return s?{richText:c,changed:!0}:{richText:e,changed:!1}}function cr(e){if(!Array.isArray(e)||e.length===0||!e.every(n=>typeof n=="string"))return!1;const t=e.join("");return t.trim()?!!(/\[[^\]]+\]\([^)]+\)/.test(t)||t.includes("**")||t.includes("`")||t.includes("~~")):!1}async function X(e,t,n){const o=It(t),{markdown:r,refs:i}=St(o),s=await e.rem.createSingleRemWithMarkdown(r,n);if(!s)return;if(i.length===0)return s;const c=await Rt(e,i),a=ke(s.text,i,c,"resolve");if(!a.changed)return s;try{await s.setText(a.richText)}catch{const d=ke(s.text,i,c,"plain");try{await s.setText(d.richText)}catch{}}return s}async function J(e,t,n){const o=It(t),{markdown:r,refs:i}=St(o),s=await e.rem.createTreeWithMarkdown(r,n);if(!Array.isArray(s)||s.length===0)return s;const c=i.length>0?await Rt(e,i):null;for(const a of s){if(!a)continue;const d=a.text;let l=d,u=!1;if(cr(d))try{l=await e.richText.parseFromMarkdown(d.join("")),u=!0}catch{}let p=u,f=l;if(c){const m=ke(l,i,c,"resolve");m.changed&&(f=m.richText,p=!0)}if(p)try{await a.setText(f)}catch{if(!c)continue;const m=ke(l,i,c,"plain");if(!m.changed&&!u)continue;try{await a.setText(m.richText)}catch{}}}return s}async function dr(e,t,n,o=2){const r=[],i=[{level:-1,id:n??null,syntax:"base"}],s=t.replace(/\r\n?/g,`
3
3
  `).replace(/\t/g," ").split(`
4
- `),c=s.some(y=>(y.match(/^\s*/)?.[0]??"").length>=o),a=s.some(y=>/^(?:\s*[-*+]\s+)?\s*#{1,6}\s+/.test(y));let d=0;const l=async(y,h)=>{const T=typeof h=="string"?h.trim():"";if(!T)return null;const k=await e.rem.createRem();if(!k)return null;await we(e,k,T,999999);try{await k.setText(q(y))}catch{}return k},u=async(y,h)=>{const T=typeof h=="string"?h.trim():"";if(!T)return null;const k=await e.rem.createRem();if(!k)return null;await we(e,k,T,999999);try{await k.setText(q(y))}catch{}return k},p=y=>{const h=y.match(/^\[([ xX])\]\s+(.*)$/);if(!h)return null;const T=(h[1]??" ").toLowerCase(),k=String(h[2]??"").trim();return k?{status:T==="x"?"Finished":"Unfinished",body:k}:null},f=async(y,h,T)=>{const k={i:"m",code:!0,text:y},A=h.trim();A&&(k.language=A);const b=await u([k],T);if(b)try{typeof b.setIsCode=="function"&&await b.setIsCode(!0)}catch{}return b},m=async(y,h,T)=>{const k=typeof T=="string"?T.trim():"";if(!k)return null;try{const A=await K(e,y,k);if(A)return A}catch{}return await l(h,k)},v=async()=>{const y=i.slice();for(;d<s.length;){let h=s[d];if(!h||/^\s*$/.test(h)){d+=1;continue}const T=h.match(/^(\s*)```(.*)$/);if(T){const w=(T[1]??"").length,_=Math.max(0,Math.floor(w/Math.max(1,o))),R=[],C=String(T[2]??"").trimEnd();for(d+=1;d<s.length;){const Z=s[d];if(/^\s*```\s*$/.test(Z)){d+=1;break}R.push(Z),d+=1}const B=R.join(`
5
- `),V=Ve(y,_),z=await f(B,C,V);z&&(r.push(z),yt(y,_,z._id));continue}const k=(h.match(/^\s*/)?.[0]??"").length;let A=Math.max(0,Math.floor(k/Math.max(1,o))),b=h.slice(k),x=b,M=null;const L=b.match(/^([*+-])\s+(.*)$/);if(L){b=L[2];const O=p(b);O?(M=O.status,b=O.body,x=O.body):x=b;const w=y[y.length-1];A===0&&w&&w.level>=0&&w.id&&(A=w.level+1)}else{const O=b.match(/^(\d+\.)\s+(.*)$/);if(O){b=O[2],x=b;const w=y[y.length-1];A===0&&w&&w.level>=0&&w.id&&(A=w.level+1)}}const F=Ve(y,A),E=await m(x,b,F);if(E){if(M){try{typeof E.setIsTodo=="function"&&await E.setIsTodo(!0)}catch{}try{typeof E.setTodoStatus=="function"&&await E.setTodoStatus(M)}catch{}}r.push(E),yt(y,A,E._id)}d+=1,r.length%20===0&&await ne(15)}},I=async()=>{const y=Ve(i,0);let h=null,T=[];const k=async()=>{const x=T.join(`
6
- `);T=[];let M=x.replace(/\r\n?/g,`
7
- `);if(M=M.replace(/^\s*\n+/g,"").replace(/\n+\s*$/g,""),!M.trim())return;M=at(M),M=Rt(M),M=Et(M),M=it(M);const L=h??y;if(L){try{await Q(e,M,L)}catch{}await ne(10)}},A=async x=>{await k();const M=y??"";if(!M)return;const L=await K(e,x.trim(),M);L&&(r.push(L),h=L._id)};let b=!1;for(;d<s.length;){const M=s[d]??"";if(d+=1,M.trim().length===0){T.push(M);continue}if(/^\s*```/.test(M)){b=!b,T.push(M);continue}if(b){T.push(M);continue}const L=M.match(/^\s*(?:[-*+]\s+)?(#{1,6})\s+(.*)$/);if(L){await k();const F=L[1],E=L[2];await A(`${F} ${E}`);continue}T.push(M)}await k()};if(a)await I();else if(c)await v();else for(;d<s.length;){const y=s[d];if(d+=1,!y||/^\s*$/.test(y))continue;let h=y.trimEnd();const T=h.match(/^([*+-])\s+(.*)$/);let k=h;if(T){h=T[2];const b=p(h);if(b){k=b.body,h=b.body;const x=await m(k.replace(/^\s+/,""),h.replace(/^\s+/,""),n??null);if(x){try{typeof x.setIsTodo=="function"&&await x.setIsTodo(!0)}catch{}try{typeof x.setTodoStatus=="function"&&await x.setTodoStatus(b.status)}catch{}r.push(x)}r.length%20===0&&await ne(15);continue}k=h}else{const b=h.match(/^(\d+\.)\s+(.*)$/);b&&(h=b[2],k=h)}const A=await m(k.replace(/^\s+/,""),h.replace(/^\s+/,""),n??null);A&&r.push(A),r.length%20===0&&await ne(15)}return r}function Ve(e,t){for(;e.length>0&&e[e.length-1].level>=t;)e.pop();return e.length>0?e[e.length-1].id:null}function yt(e,t,n){e.push({level:t,id:n})}function Rt(e){const t=e.split(`
4
+ `),c=s.some(y=>(y.match(/^\s*/)?.[0]??"").length>=o),a=s.some(y=>/^(?:\s*[-*+]\s+)?\s*#{1,6}\s+/.test(y));let d=0;const l=async(y,h)=>{const E=typeof h=="string"?h.trim():"";if(!E)return null;const k=await e.rem.createRem();if(!k)return null;await we(e,k,E,999999);try{await k.setText(q(y))}catch{}return k},u=async(y,h)=>{const E=typeof h=="string"?h.trim():"";if(!E)return null;const k=await e.rem.createRem();if(!k)return null;await we(e,k,E,999999);try{await k.setText(q(y))}catch{}return k},p=y=>{const h=y.match(/^\[([ xX])\]\s+(.*)$/);if(!h)return null;const E=(h[1]??" ").toLowerCase(),k=String(h[2]??"").trim();return k?{status:E==="x"?"Finished":"Unfinished",body:k}:null},f=async(y,h,E)=>{const k={i:"m",code:!0,text:y},A=h.trim();A&&(k.language=A);const b=await u([k],E);if(b)try{typeof b.setIsCode=="function"&&await b.setIsCode(!0)}catch{}return b},m=async(y,h,E)=>{const k=typeof E=="string"?E.trim():"";if(!k)return null;try{const A=await X(e,y,k);if(A)return A}catch{}return await l(h,k)},v=async()=>{const y=i.slice();for(;d<s.length;){let h=s[d];if(!h||/^\s*$/.test(h)){d+=1;continue}const E=h.match(/^(\s*)```(.*)$/);if(E){const _=(E[1]??"").length,R=Math.max(0,Math.floor(_/Math.max(1,o))),P=[],B=String(E[2]??"").trimEnd();for(d+=1;d<s.length;){const z=s[d];if(/^\s*```\s*$/.test(z)){d+=1;break}P.push(z),d+=1}const V=P.join(`
5
+ `),j=Ve(y,R),H=await f(V,B,j);H&&(r.push(H),ht(y,R,H._id,"code"));continue}const k=(h.match(/^\s*/)?.[0]??"").length;let A=Math.max(0,Math.floor(k/Math.max(1,o))),b=h.slice(k),C=b,M=null,L="plain";const F=b.match(/^([*+-])\s+(.*)$/);if(F){b=F[2];const w=p(b);w?(M=w.status,b=w.body,C=w.body):C=b,A===0&&(A=yt(y)),L="unordered_list_item"}else{const w=b.match(/^(\d+\.)\s+(.*)$/);w&&(b=w[2],C=b,A===0&&(A=yt(y)),L="ordered_list_item")}const T=Ve(y,A),O=await m(C,b,T);if(O){if(M){try{typeof O.setIsTodo=="function"&&await O.setIsTodo(!0)}catch{}try{typeof O.setTodoStatus=="function"&&await O.setTodoStatus(M)}catch{}}r.push(O),ht(y,A,O._id,L)}d+=1,r.length%20===0&&await ne(15)}},I=async()=>{const y=Ve(i,0);let h=null,E=[];const k=async()=>{const C=E.join(`
6
+ `);E=[];let M=C.replace(/\r\n?/g,`
7
+ `);if(M=M.replace(/^\s*\n+/g,"").replace(/\n+\s*$/g,""),!M.trim())return;M=at(M),M=Et(M),M=Tt(M),M=it(M);const L=h??y;if(L){try{await J(e,M,L)}catch{}await ne(10)}},A=async C=>{await k();const M=y??"";if(!M)return;const L=await X(e,C.trim(),M);L&&(r.push(L),h=L._id)};let b=!1;for(;d<s.length;){const M=s[d]??"";if(d+=1,M.trim().length===0){E.push(M);continue}if(/^\s*```/.test(M)){b=!b,E.push(M);continue}if(b){E.push(M);continue}const L=M.match(/^\s*(?:[-*+]\s+)?(#{1,6})\s+(.*)$/);if(L){await k();const F=L[1],T=L[2];await A(`${F} ${T}`);continue}E.push(M)}await k()};if(a)await I();else if(c)await v();else for(;d<s.length;){const y=s[d];if(d+=1,!y||/^\s*$/.test(y))continue;let h=y.trimEnd();const E=h.match(/^([*+-])\s+(.*)$/);let k=h;if(E){h=E[2];const b=p(h);if(b){k=b.body,h=b.body;const C=await m(k.replace(/^\s+/,""),h.replace(/^\s+/,""),n??null);if(C){try{typeof C.setIsTodo=="function"&&await C.setIsTodo(!0)}catch{}try{typeof C.setTodoStatus=="function"&&await C.setTodoStatus(b.status)}catch{}r.push(C)}r.length%20===0&&await ne(15);continue}k=h}else{const b=h.match(/^(\d+\.)\s+(.*)$/);b&&(h=b[2],k=h)}const A=await m(k.replace(/^\s+/,""),h.replace(/^\s+/,""),n??null);A&&r.push(A),r.length%20===0&&await ne(15)}return r}function lr(e){return e==="unordered_list_item"||e==="ordered_list_item"}function yt(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(!lr(n.syntax))return Math.max(0,n.level+1)}return 0}function Ve(e,t){for(;e.length>0&&e[e.length-1].level>=t;)e.pop();return e.length>0?e[e.length-1].id:null}function ht(e,t,n,o){e.push({level:t,id:n,syntax:o})}function Et(e){const t=e.split(`
8
8
  `);let n=!1;for(let o=0;o<t.length;o+=1){const r=t[o];if(/^\s*```/.test(r)){n=!n;continue}if(!n){if(/^\s{1,3}[-*+]\s+/.test(r)){t[o]=r.replace(/^\s{1,3}([-*+])\s+/,"$1 ");continue}if(/^\s{1,3}\d+\.\s+/.test(r)){t[o]=r.replace(/^\s{1,3}(\d+\.)\s+/,"$1 ");continue}}}return t.join(`
9
- `)}function Et(e){const t=e.split(`
9
+ `)}function Tt(e){const t=e.split(`
10
10
  `),n=[];let o=!1;for(let r=0;r<t.length;r+=1){const i=t[r];if(/^\s*```/.test(i)){o=!o,n.push(i);continue}if(o)n.push(i);else{if(i.trim().length===0)continue;n.push(i)}}return n.join(`
11
11
  `)}function at(e){return e.replace(/[\u00A0\u2007\u202F\u2002-\u2006\u2008-\u200A\u3000]/g," ").replace(/[\u200B\u200C\u200D\u2060]/g,"")}function it(e){const t=e.split(`
12
- `).filter(r=>r.trim().length>0);if(t.length!==1)return e;const n=t[0].match(/^\s*[-*+]\s+(.*)$/),o=t[0].match(/^\s*\d+\.\s+(.*)$/);return n?n[1]:o?o[1]:e}function Tt(e){return it(at(e))}function Qe(e){return typeof e=="string"?e.trim():""}function dr(e){return Qe(e.title)||"Imported (bundle)"}function lr(e){const t=e?.bundle;if(!t||typeof t!="object")return null;const n=t.enabled===!0,o=Qe(t.title)||Qe(e?.bundle_title);return!n&&!o?null:{title:o||"Imported (bundle)"}}async function ur(e,t){const{text:n,markdown:o,date:r,offset_days:i,prepend:s,position:c}=t.payload||{};let a=null;if(typeof r=="string"||typeof r=="number"){const f=new Date(r);isNaN(f.getTime())||(a=f)}if(!a){const f=typeof i=="number"?i:0,m=new Date;a=new Date(m.getFullYear(),m.getMonth(),m.getDate()+f)}const d=await e.date.getDailyDoc(a);if(!d?._id)throw new Error("Daily document not found for that date. Please open it in RemNote first.");const l=typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):void 0,u=lr(t.payload||{});if(u){const f=[];let m=null;try{const v=dr(u);try{if(m=await K(e,v,d._id),!m?._id)throw new Error("createSingleRemWithMarkdown returned null for bundle title")}catch{if(m=await e.rem.createRem(),!m?._id)throw new Error("createRem failed for bundle title");await m.setText(q(v))}const I=l!==void 0?l:typeof s=="boolean"&&s?0:999999;try{await e.rem.moveRems([m._id],d._id,I)}catch(y){try{await m.remove()}catch{}throw y}if(typeof o=="string"&&o.trim())try{const y=await Q(e,o,m._id);if(Array.isArray(y))for(const h of y)h?._id&&f.push(h._id)}catch{const y=await K(e,o,m._id);y?._id&&f.push(y._id)}else if(n!=null){const y=await e.rem.createRem();if(!y)throw new Error("createRem failed");try{await y.setText(q(n))}catch(h){try{await y.remove()}catch{}throw h}try{await e.rem.moveRems([y._id],m._id,999999)}catch(h){try{await y.remove()}catch{}throw h}y?._id&&f.push(y._id)}else throw new Error("Missing content (text/markdown)");return{ok:!0,daily_id:d._id,created_ids:[m._id],bundle:{rem_id:m._id},bundle_inner_created_ids:f.length?f:void 0}}catch(v){if(m?._id)try{await m.remove()}catch{}throw v}}const p=[];if(typeof o=="string"&&o.trim())try{const f=await Q(e,o,d._id);if(Array.isArray(f))for(const m of f)m?._id&&p.push(m._id)}catch{const f=await K(e,o,d._id);f?._id&&p.push(f._id)}else if(n!=null){const f=await e.rem.createRem();if(!f)throw new Error("createRem failed");try{await f.setText(q(n))}catch(m){try{await f.remove()}catch{}throw m}try{await e.rem.moveRems([f._id],d._id,typeof s=="boolean"&&s?0:999999)}catch(m){try{await f.remove()}catch{}throw m}f?._id&&p.push(f._id)}else throw new Error("Missing content (text/markdown)");return{ok:!0,daily_id:d._id,created_ids:p}}function Je(e){return typeof e=="string"?e.trim():""}function ve(e){return typeof e=="string"?e.trim():""}function ie(e){const t=e?.parent;if(typeof t=="string")return t.trim();const n=t?._id;return typeof n=="string"?n.trim():""}function st(e){const t=e?.text;return typeof t=="string"?ve(t):Array.isArray(t)&&t.every(n=>typeof n=="string")?ve(t.join("")):""}const fr=["agent-remnote: children replace backup (auto)","agent-remnote: replace backup (auto)"],ht=50;async function mr(e){if(!e)return!1;try{if(typeof e.hasPowerup=="function"&&await e.hasPowerup(fe.code)===!0)return!0}catch{}const t=st(e);return fr.some(n=>t===n||t.startsWith(n))}async function yr(e,t){const n=[],o=[];for(const r of t)try{const i=await e.rem.findOne(r);await mr(i)?o.push(r):n.push(r)}catch{n.push(r)}return{contentChildIds:n,backupChildIds:o}}async function hr(e,t,n){const o=[...t];let r=0;for(;o.length>0;){const i=o.shift();if(i){if(r+=1,r>n)return r;try{const s=await e.rem.findOne(i),c=Me(s);for(const a of c)o.push(a)}catch{}}}return r}async function pr(e){try{if(typeof e.rem?.setHiddenExplicitlyIncludedState=="function")return await e.rem.setHiddenExplicitlyIncludedState("hidden",e.portalId),!0}catch{}return!1}async function It(e){const t=e.rem;if(!t)return;try{typeof t.addPowerup=="function"&&await t.addPowerup(fe.code)}catch{}const n=async(r,i)=>{try{typeof t.setPowerupProperty=="function"&&await t.setPowerupProperty(fe.code,r,[i])}catch{}},o=new Date().toISOString();await n("backup_kind",e.backupKind),await n("cleanup_policy",e.cleanupPolicy),await n("cleanup_state",e.cleanupState),await n("source_txn",e.op.txn_id),await n("source_op",e.op.op_id),await n("source_parent",e.sourceParentId),await n("source_anchor",e.sourceAnchorId),await n("created_at",o)}function Me(e){return Array.isArray(e?.children)?e.children.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim()):[]}async function Ze(e,t,n,o,r){const i=[];if(Array.isArray(t))for(let c=0;c<t.length;c+=1){const a=t[c],d=Je(a?._id);d&&ie(a)===o&&i.push({id:d,rem:a,index:c})}if(i.length===0)for(let c=0;c<n.length;c+=1){const a=Je(n[c]);if(a)try{const d=await e.rem.findOne(a);if(!d)continue;ie(d)===o&&i.push({id:a,rem:d,index:c})}catch{}}if(i.length===0)return[];const s=[];for(const c of i){let a;try{typeof c.rem?.positionAmongstVisibleSiblings=="function"&&(a=await c.rem.positionAmongstVisibleSiblings(r))}catch{}if(a===void 0)try{typeof c.rem?.positionAmongstSiblings=="function"&&(a=await c.rem.positionAmongstSiblings(r))}catch{}typeof a=="number"&&Number.isFinite(a)&&a>=0&&s.push({id:c.id,pos:Math.floor(a),index:c.index})}if(s.length!==i.length){const c=new Set,a=[];for(const d of i)c.has(d.id)||(c.add(d.id),a.push(d.id));return a}return s.sort((c,a)=>c.pos!==a.pos?c.pos-a.pos:c.index-a.index),s.map(c=>c.id)}function _r(e){return ve(e.title)||"Imported (bundle)"}function wr(e){const t=e?.bundle;if(!t||typeof t!="object")return null;const n=t.enabled===!0,o=ve(t.title)||ve(e?.bundle_title);return!n&&!o?null:{title:o||"Imported (bundle)"}}function gr(e){if(!e||typeof e!="object")return!1;if(e.staged===!0)return!0;const t=e.staging;return!!(t===!0||t&&typeof t=="object"&&t.enabled===!0)}async function br(e,t){const{markdown:n,parent_id:o,client_temp_id:r}=t.payload||{},i=typeof o=="string"?o.trim():"";if(!i)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const s=await K(e,String(n??""),i);if(!s)throw new Error("createSingleRemWithMarkdown returned null");const c={ok:!0};return r&&s._id&&(c.created={client_temp_id:r,remote_id:s._id,remote_type:"rem"}),c}async function At(e,t){const{markdown:n,parent_id:o,client_temp_ids:r,indent_mode:i,parse_mode:s,indent_size:c,prepared:a,position:d}=t.payload||{},l=typeof o=="string"?o.trim():"";if(!l)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const u=gr(t.payload||{});let p=u;const f=typeof d=="number"&&Number.isFinite(d)&&d>=0?Math.floor(d):void 0,m=typeof s=="string"?s:void 0,v=m==="ast"||m==="prepared",I={ok:!0},y=String(n??""),h=wr(t.payload||{}),T=h?_r(h):"";let k=null,A=l,b=null;if(u)try{const E=await K(e,"agent-remnote: staged import (auto)",l);if(!E?._id)throw new Error("createSingleRemWithMarkdown returned null for staged import container");k=String(E._id);try{await e.rem.moveRems([k],l,1e9)}catch{}A=k}catch{if(k)try{const E=await e.rem.findOne(k);E&&await E.remove()}catch{}p=!1,k=null,A=l}const x=async()=>{if(!p||!k)return;const E=f??999999,O=await e.rem.findOne(k),w=Array.isArray(O?.children)?O.children.filter(_=>typeof _=="string"&&_.trim()).map(_=>_.trim()):[];if(w.length===0)throw new Error(`Staged import produced no root Rems (staging_rem_id=${k})`);try{await e.rem.moveRems(w,l,E)}catch(_){try{for(const R of w)try{const C=await e.rem.findOne(R);if(!C)continue;ie(C)===l&&await C.remove()}catch{}}catch{}try{const R=await e.rem.findOne(k);R&&await R.remove()}catch{}throw new Error(`Failed to move staged content to target parent: ${String(_?.message||_)} (rolled_back=true, staging_rem_id=${k})`)}try{const _=await e.rem.findOne(k);_&&await _.remove()}catch{}};if(h){try{if(b=await K(e,T,A),!b?._id)throw new Error("createSingleRemWithMarkdown returned null for bundle title");!p&&f!==void 0&&await e.rem.moveRems([b._id],l,f)}catch{if(b?._id)try{await b.remove()}catch{}if(b=await e.rem.createRem(),!b?._id)throw new Error("createRem failed for bundle title");await b.setText(q(T));try{p?await e.rem.moveRems([b._id],A,999999):await e.rem.moveRems([b._id],l,f??999999)}catch(E){try{await b.remove()}catch{}throw E}}A=String(b._id)}const M=p||h?void 0:f,L=M===void 0&&i!==!1&&!v&&m!=="raw",F=async()=>{b?._id&&(Array.isArray(I.created_ids)&&(I.bundle_inner_created_ids=I.created_ids),I.bundle={rem_id:b._id},I.created_ids=[b._id])};try{if(v&&a&&Array.isArray(a.items)){const w=a;if(w.preface&&w.preface.trim())try{await Q(e,w.preface,A)}catch{}const _=[];for(const R of w.items){const C=await K(e,R.heading,A);if(C){if(Array.isArray(r)&&_.length<r.length){const B=r[_.length];B&&_.push({client_temp_id:B,remote_id:C._id,remote_type:"rem"})}if(R.body&&R.body.trim())try{await Q(e,R.body,C._id)}catch{}}await ne(10)}return _.length&&(I.id_map=_),await F(),await x(),I}if(v){const w=await nr(y);if(w.preface&&w.preface.trim())try{await Q(e,w.preface,A)}catch{}const _=[];for(const R of w.items){const C=await K(e,R.heading,A);if(C){if(Array.isArray(r)&&_.length<r.length){const B=r[_.length];B&&_.push({client_temp_id:B,remote_id:C._id,remote_type:"rem"})}if(R.body&&R.body.trim())try{await Q(e,R.body,C._id)}catch{}}await ne(10)}return _.length&&(I.id_map=_),await F(),await x(),I}if(L){const w=await cr(e,y,A,typeof c=="number"?c:2),_=Array.isArray(w)?w.filter(R=>R?._id).map(R=>String(R._id)):[];if(_.length>0){const R=await Ze(e,w,_,A);I.created_ids=R.length>0?R:_}if(Array.isArray(w)&&Array.isArray(r)){const R=[];for(let C=0;C<Math.min(w.length,r.length);C+=1){const B=w[C],V=r[C];B&&B._id&&V&&R.push({client_temp_id:V,remote_id:B._id,remote_type:"rem"})}R.length&&(I.id_map=R)}return await F(),await x(),I}const E=await Q(e,y,A),O=[];if(Array.isArray(E))for(const w of E)w?._id&&O.push(w._id);if(O.length&&(I.created_ids=O),M!==void 0&&O.length>0){const w=await Ze(e,E,O,A);if(w.length===0)throw new Error("Failed to determine root Rems for moveRems");try{await e.rem.moveRems(w,A,M)}catch(_){for(const R of O)try{const C=await e.rem.findOne(R);C&&await C.remove()}catch{}throw _}}if(Array.isArray(E)&&Array.isArray(r)){const w=[];for(let _=0;_<Math.min(E.length,r.length);_+=1){const R=E[_],C=r[_];R?._id&&C&&w.push({client_temp_id:C,remote_id:R._id,remote_type:"rem"})}w.length&&(I.id_map=w)}return await F(),await x(),I}catch(E){if(b?._id&&!p)try{await b.remove()}catch{}if(p&&k)try{const O=await e.rem.findOne(k);O&&await O.remove()}catch{}throw E}}async function kr(e,t){const{markdown:n,target:o,require_same_parent:r,require_contiguous:i,portal_id:s,assertions:c}=t.payload||{},a="none",d=String(n??""),l=d.trim().length>0,u=r!==!1,p=i!==!1,f=c===void 0?[]:Array.isArray(c)?c:null;if(f===null)return{ok:!1,fatal:!0,error:"replace_selection_with_markdown assertions must be an array of strings"};const m=f.map(g=>typeof g=="string"?g.trim():"").filter(Boolean);if(f.some(g=>typeof g!="string"||!["single-root","no-literal-bullet"].includes(g.trim())))return{ok:!1,fatal:!0,error:"replace_selection_with_markdown assertions must only include: single-root, no-literal-bullet"};const I=m.includes("single-root"),y=m.includes("no-literal-bullet"),h=typeof o?.mode=="string"?o.mode:"",T=h==="current"?"current":h==="explicit"?"explicit":"expected",k=Array.isArray(o?.rem_ids)?o.rem_ids.map(g=>typeof g=="string"?g.trim():"").filter(Boolean):[];if(T!=="current"&&k.length===0)return{ok:!1,fatal:!0,error:`${T} mode requires target.rem_ids`};let b=(typeof s=="string"?s.trim():"")||void 0;if(!b)try{const g=await e.focus.getFocusedPortal();g?._id&&(b=String(g._id))}catch{}let x=[];if(T!=="explicit")try{const g=await e.editor.getSelection();if(!g?.type||g.type!==S.SelectionType.Rem)return{ok:!1,fatal:!0,error:`Current selectionType=${g?.type??"None"}; only Rem selection is supported`};x=Array.isArray(g.remIds)?g.remIds.filter(P=>typeof P=="string"&&P.trim()).map(P=>P.trim()):[]}catch{return{ok:!1,fatal:!0,error:"Failed to read current selection"}}if(T!=="explicit"&&x.length===0)return{ok:!1,fatal:!0,error:"No Rem is selected"};if(T==="expected"&&!((g,P)=>{if(g.length!==P.length)return!1;const G=new Set(g),ee=new Set(P);if(G.size!==ee.size)return!1;for(const qt of G)if(!ee.has(qt))return!1;return!0})(x,k))return{ok:!1,fatal:!0,error:`Selection changed (expected=${k.length}, current=${x.length})`};const L=T==="current"?x:k,F=Array.from(new Set(L)),E=await Promise.all(F.map(g=>e.rem.findOne(g))),O=F.filter((g,P)=>!E[P]);if(O.length>0)return{ok:!1,fatal:!0,error:`Cannot access Rems (permission/deleted): ${O.slice(0,3).join(", ")}${O.length>3?"…":""}`};const w=new Set;for(const g of E){const P=g?.parent;typeof P=="string"&&P.trim()&&w.add(P.trim())}if(u&&w.size!==1)return{ok:!1,fatal:!0,error:`Selected Rems do not share the same parent (parents=${Array.from(w).length}); cannot replace in place`};const _=w.size===1?Array.from(w)[0]:"";if(!_)return{ok:!1,fatal:!0,error:"Cannot determine parentId (top-level Rems are not supported)"};const R=[];for(const g of E){let P;try{typeof g?.positionAmongstVisibleSiblings=="function"&&(P=await g.positionAmongstVisibleSiblings(b))}catch{}if(P===void 0)try{typeof g?.positionAmongstSiblings=="function"&&(P=await g.positionAmongstSiblings(b))}catch{}if(typeof P!="number"||!Number.isFinite(P)||P<0)return{ok:!1,fatal:!0,error:"Failed to compute selection position"};R.push(Math.floor(P))}const C=[];for(let g=0;g<F.length;g+=1)C.push({id:F[g],pos:R[g]});C.sort((g,P)=>g.pos-P.pos);const B=C.map(g=>g.pos),V=C.map(g=>g.id),z=B[0]??0;if(p){for(let g=0;g<B.length;g+=1)if(B[g]!==z+g)return{ok:!1,fatal:!0,error:"Selection is not contiguous (use Shift to select a contiguous block)"}}const Z=[];let X=[],Re;const se=async()=>{for(const g of Z)try{const P=await e.rem.findOne(g);P&&await P.remove()}catch{}};if(l){if(Re=await Q(e,d,_),Array.isArray(Re))for(const g of Re)g?._id&&Z.push(g._id);if(Z.length===0)return{ok:!1,fatal:!0,error:"createTreeWithMarkdown returned no created Rems"};if(X=await Ze(e,Re,Z,_,b),X.length===0)return await se(),{ok:!1,fatal:!0,error:"Failed to determine root Rems for moveRems"}}if(l&&I&&X.length!==1)return await se(),{ok:!1,fatal:!0,error:`Assertion failed: single-root (created_roots=${X.length})`,assertion:"single-root"};if(l&&y&&X.length===1)try{const g=await e.rem.findOne(X[0]);if(!g)throw new Error(`created Rem not found: ${X[0]}`);const P=st(g);if(/^\s*(?:[-*+]|\d+\.)\s+/.test(P))return await se(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}catch{return await se(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}if(l)try{b?await e.rem.moveRems(X,_,z,b):await e.rem.moveRems(X,_,z)}catch(g){return await se(),{ok:!1,fatal:!0,error:`Failed to move new content: ${String(g?.message||g)}`}}let $=null;try{const g=await e.rem.createSingleRemWithMarkdown("agent-remnote: replace backup (auto)",_);if(!g?._id)throw new Error("createSingleRemWithMarkdown returned null");$=String(g._id),await It({rem:g,backupKind:"selection_replace",cleanupPolicy:"auto",cleanupState:"pending",op:t,sourceParentId:_,sourceAnchorId:V[0]??""});try{b?await e.rem.moveRems([$],_,1e9,b):await e.rem.moveRems([$],_,1e9)}catch{}b?await e.rem.moveRems(V,$,0,b):await e.rem.moveRems(V,$,0)}catch(g){if(await se(),$){try{const P=[];for(const G of V)try{const ee=await e.rem.findOne(G);if(!ee)continue;ie(ee)===$&&P.push(G)}catch{}if(P.length>0)try{b?await e.rem.moveRems(P,_,z,b):await e.rem.moveRems(P,_,z)}catch{}}catch{}try{const P=await e.rem.findOne($);P&&await P.remove()}catch{}}return{ok:!1,fatal:!0,error:`Failed to move old content to backup: ${String(g?.message||g)}`,backup_policy:a}}let Ee=!1;if($)try{const g=await e.rem.findOne($);g&&await g.remove(),Ee=!0,$=null}catch{Ee=!1}if(!Ee&&$){try{await se()}catch{}let g=!1;try{b?await e.rem.moveRems(V,_,z,b):await e.rem.moveRems(V,_,z),g=!0}catch{}if(g)try{const P=[];for(const G of V)try{const ee=await e.rem.findOne(G);if(!ee)continue;ie(ee)===$&&P.push(G)}catch{}if(P.length===0){const G=await e.rem.findOne($);G&&await G.remove(),$=null}}catch{}return{ok:!1,fatal:!0,error:"Failed to delete replace backup container; rolled back to original content",rolled_back:!0,backup_rem_id:$,backup_policy:a}}return{ok:!0,target_mode:T,parent_id:_,portal_id:b??null,position:z,selection_rem_ids:F,created_ids:Z,deleted_rem_ids:V,backup_deleted:Ee,backup_rem_id:$,backup_policy:a}}async function vr(e,t){const{parent_id:n,markdown:o,indent_mode:r,indent_size:i,parse_mode:s,prepared:c,staged:a,bundle:d,backup:l,assertions:u}=t.payload||{},p=Je(n);if(!p)return{ok:!1,fatal:!0,error:"Missing parent_id"};const f=typeof l=="string"&&l.trim()==="visible"?"visible":"none",m=Array.isArray(u)?u.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean):[],v=m.includes("single-root"),I=m.includes("no-literal-bullet"),y=await e.rem.findOne(p);if(!y)return{ok:!1,fatal:!0,error:`Rem not found: ${p}`};const h=Me(y),{contentChildIds:T,backupChildIds:k}=await yr(e,h),A=[...T],b=new Set(h),x=String(o??"");let M=[],L=[];const F=async()=>{for(const w of M)try{const _=await e.rem.findOne(w);_&&await _.remove()}catch{}M=[]};if(x.trim()){const w=await At(e,{...t,payload:{parent_id:p,markdown:x,position:0,...typeof r=="boolean"?{indent_mode:r}:{},...typeof i=="number"?{indent_size:i}:{},...typeof s=="string"?{parse_mode:s}:{},...c!==void 0?{prepared:c}:{},...a===!0?{staged:!0}:{},...d&&typeof d=="object"?{bundle:d}:{}}});if(M=Array.isArray(w?.created_ids)?w.created_ids.filter(_=>typeof _=="string"&&_.trim()).map(_=>_.trim()):[],M.length===0)try{const _=await e.rem.findOne(p);M=Me(_).filter(R=>!b.has(R))}catch{}try{const _=await e.rem.findOne(p);L=Me(_).filter(R=>!b.has(R))}catch{}}if(x.trim()){if(v&&L.length!==1)return await F(),{ok:!1,fatal:!0,error:`Assertion failed: single-root (created_roots=${L.length})`,assertion:"single-root"};if(I&&L.length===1)try{const w=await e.rem.findOne(L[0]);if(!w)throw new Error(`created Rem not found: ${L[0]}`);const _=st(w);if(/^\s*(?:[-*+]|\d+\.)\s+/.test(_))return await F(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}catch{return await F(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}}if(A.length===0)return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:[],ignored_backup_rem_ids:k,backup_deleted:!0,backup_rem_id:null,backup_policy:f};let E=null;try{const w=await e.rem.createSingleRemWithMarkdown("agent-remnote: children replace backup (auto)",p);if(!w?._id)throw new Error("createSingleRemWithMarkdown returned null");E=String(w._id),await It({rem:w,backupKind:"children_replace",cleanupPolicy:f==="visible"?"visible":"auto",cleanupState:f==="visible"?"retained":"pending",op:t,sourceParentId:p,sourceAnchorId:p});try{await e.rem.moveRems([E],p,1e9)}catch{}await e.rem.moveRems(A,E,0)}catch(w){if(await F(),E){try{const _=[];for(const R of A)try{const C=await e.rem.findOne(R);C&&ie(C)===E&&_.push(R)}catch{}if(_.length>0)try{await e.rem.moveRems(_,p,0)}catch{}}catch{}try{const _=[];for(const R of A)try{const C=await e.rem.findOne(R);C&&ie(C)===E&&_.push(R)}catch{}if(_.length===0){const R=await e.rem.findOne(E);R&&await R.remove()}}catch{}}return{ok:!1,fatal:!0,error:`Failed to move old children to backup: ${String(w?.message||w)}`,backup_rem_id:E,backup_policy:f}}if(f==="visible")return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:A,ignored_backup_rem_ids:k,backup_deleted:!1,backup_rem_id:E,backup_policy:f};let O=!1;if(E&&f==="none"&&await hr(e,[E],ht)>ht){const _=await e.rem.findOne(E),R=await pr({rem:_});return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:A,ignored_backup_rem_ids:k,backup_deleted:!1,backup_rem_id:E,backup_policy:f,backup_hidden:R,backup_cleanup_state:"pending"}}if(E)try{const w=await e.rem.findOne(E);w&&await w.remove(),O=!0,E=null}catch{O=!1}if(!O&&E){await F();let w=!1;try{await e.rem.moveRems(A,p,0),w=!0}catch{}if(w)try{const _=[];for(const R of A)try{const C=await e.rem.findOne(R);C&&ie(C)===E&&_.push(R)}catch{}if(_.length===0){const R=await e.rem.findOne(E);R&&await R.remove(),E=null}}catch{}return{ok:!1,fatal:!0,error:"Failed to delete children replace backup; rolled back to original content",rolled_back:!0,backup_rem_id:E,backup_policy:f}}return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:A,ignored_backup_rem_ids:k,backup_deleted:O,backup_rem_id:E,backup_policy:f}}const Sr=100,Rr=3e3,Er=150;function ze(e,t){const n=typeof e=="number"?e:Number(e);return!Number.isFinite(n)||n<=0?t:Math.floor(n)}function Tr(e){return Array.isArray(e?.children)?e.children.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim()):[]}async function Ir(e,t,n,o){const r=Date.now()+n;for(;;){if(!await e.rem.findOne(t))return!0;if(Date.now()>=r)return!1;await ne(o)}}async function Ar(e,t){const n=[t],o=new Set,r=new Map;for(;n.length>0;){const i=n.shift();if(!i||o.has(i))continue;o.add(i);const s=await e.rem.findOne(i);if(!s)continue;const c=Tr(s);r.set(i,{id:i,childIds:c});for(const a of c)n.push(a)}return r}function Mr(e,t){if(t<=0||e.length===0)return new Set;const n=new Array(t+1).fill(!1),o=new Array(t+1).fill(-1),r=new Array(t+1).fill(-1);n[0]=!0;for(let a=0;a<e.length;a+=1){const d=e[a];for(let l=t;l>=d;l-=1)!n[l]&&n[l-d]&&(n[l]=!0,o[l]=l-d,r[l]=a)}let i=t;for(;i>0&&!n[i];)i-=1;const s=new Set;let c=i;for(;c>0;){const a=r[c];if(a<0)break;s.add(a),c=o[c]}return s}function Pr(e,t,n){const o=r=>{const i=e.get(r);if(!i)return{deleteRootIds:[],residualRootId:r,residualSize:1,nodeCount:1};const s=i.childIds.map(u=>o(u)),c=[];let a=1;for(const u of s)c.push(...u.deleteRootIds),a+=u.nodeCount;const d=Mr(s.map(u=>u.residualSize),Math.max(0,n-1));let l=1;for(let u=0;u<s.length;u+=1){const p=s[u];d.has(u)?l+=p.residualSize:c.push(p.residualRootId)}return{deleteRootIds:c,residualRootId:r,residualSize:l,nodeCount:a}};return o(t)}async function Cr(e,t,n,o){const r=await e.rem.findOne(t);return r?(await r.remove(),Ir(e,t,n,o)):!0}async function xr(e,t,n={}){const o=ze(n.maxDeleteSubtreeNodes,Sr),r=ze(n.verifyTimeoutMs,Rr),i=ze(n.verifyPollMs,Er);if(!await e.rem.findOne(t))return{existed:!1,deleted:!0,mode:"direct",nodeCount:0,batchCount:0};const c=await Ar(e,t),a=Pr(c,t,o),d=[...a.deleteRootIds,a.residualRootId],l=d.length===1?"direct":"bottom_up";for(const u of d)if(!await Cr(e,u,r,i))return{existed:!0,deleted:!1,mode:l,nodeCount:a.nodeCount,batchCount:d.length,failedRemId:u};return{existed:!0,deleted:!0,mode:l,nodeCount:a.nodeCount,batchCount:d.length}}function Or(e){const t=e?.max_delete_subtree_nodes,n=typeof t=="number"?t:Number(t);if(!(!Number.isFinite(n)||n<=0))return Math.floor(n)}async function Mt(e,t,n){const{rem_id:o}=t.payload||{},r=typeof o=="string"?o.trim():"";if(!r)return{ok:!1,fatal:!0,error:"Missing rem_id"};const i=Or(t.payload),s=await xr(e,r,{maxDeleteSubtreeNodes:i??100});return s.deleted?{ok:!0,...n.includeRemIdInSuccess?{rem_id:r}:{},deleted:!0,existed:s.existed,delete_mode:s.mode,node_count:s.nodeCount,batch_count:s.batchCount}:{ok:!1,fatal:!0,error:`Failed to verify ${n.errorContext}; Rem still exists: ${s.failedRemId??r}`,rem_id:r}}async function Lr(e,t){const{parent_id:n,text:o,tags:r,is_document:i,standalone:s,client_temp_id:c,position:a}=t.payload||{},d=typeof n=="string"?n.trim():"";if(!d&&!(s===!0))throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const u=await e.rem.createRem();if(!u)throw new Error("createRem returned null");const p=async()=>{try{await u.remove()}catch{}};try{const m=typeof a=="number"&&Number.isFinite(a)&&a>=0?Math.floor(a):0;if(d&&await e.rem.moveRems([u._id],d,m),i===!0&&typeof u.setIsDocument=="function"&&await u.setIsDocument(!0),o!==void 0&&await u.setText(q(o)),Array.isArray(r)&&r.length>0)for(const v of r)await u.addTag(v)}catch(m){throw await p(),m}const f={ok:!0};return c&&u._id&&(f.created={client_temp_id:c,remote_id:u._id,remote_type:"rem"}),f}async function Nr(e,t){const{url:n,add_title:o,client_temp_id:r,parent_id:i}=t.payload||{},s=typeof i=="string"?i.trim():"";if(!s)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const c=await e.rem.createLinkRem(String(n??""),o!==!1);if(!c)throw new Error("createLinkRem returned null");try{await e.rem.moveRems([c._id],s,0)}catch(d){try{await c.remove()}catch{}throw d}const a={ok:!0};return r&&c._id&&(a.created={client_temp_id:r,remote_id:c._id,remote_type:"rem"}),a}async function Dr(e,t){const{rem_id:n,text:o}=t.payload||{};if(!n)throw new Error("Missing rem_id");const r=await e.rem.findOne(n);if(!r)throw new Error(`Rem not found: ${n}`);return await r.setText(q(o)),{ok:!0}}async function Fr(e,t){const{rem_id:n,new_parent_id:o,position:r,standalone:i,is_document:s,leave_portal:c}=t.payload||{},a=typeof n=="string"?n.trim():"",d=typeof o=="string"?o.trim():"",l=i===!0;if(!a)throw new Error("Missing rem_id");if(!l&&!d)throw new Error("Missing new_parent_id");const u=await e.rem.findOne(a);if(!u)throw new Error(`Rem not found: ${a}`);const p=typeof u.parent=="string"?String(u.parent).trim():"";let f=0;try{if(typeof u.positionAmongstSiblings=="function"){const y=await u.positionAmongstSiblings();typeof y=="number"&&Number.isFinite(y)&&y>=0&&(f=Math.floor(y))}}catch(y){console.warn("[agent-remnote][move] failed to get source position",{error:y})}if(l)if(typeof u.setParent=="function")await u.setParent(null);else throw new Error("Standalone move requires Rem.setParent(null) support");else await e.rem.moveRems([a],d,typeof r=="number"?r:0);s===!0&&typeof u.setIsDocument=="function"&&await u.setIsDocument(!0);const m=[],v=[];let I;if(c===!0)if(!p)m.push("Move succeeded, but leave-portal could not determine the source parent"),v.push(`agent-remnote --json portal create --parent <sourceParentId> --target ${a}`);else{const y=await e.rem.createPortal().catch(h=>(m.push(`Move succeeded, but leave-portal failed: ${String(h?.message||h)}`),null));if(y?._id)try{if(await e.rem.moveRems([y._id],p,f),typeof u.addToPortal!="function")throw new Error("addToPortal not available in SDK");await u.addToPortal(y._id),I=y._id}catch(h){try{await y.remove()}catch{}m.push(`Move succeeded, but leave-portal failed: ${String(h?.message||h)}`),v.push(`agent-remnote --json portal create --parent ${p} --target ${a}`)}}return{ok:!0,rem_id:a,...l?{standalone:!0}:{new_parent_id:d},...c===!0?{leave_portal:!0,portal_created:!!I}:{},...p?{source_parent_id:p}:{},...I?{portal_id:I}:{},...m.length>0?{warnings:m}:{},...v.length>0?{nextActions:v}:{}}}async function $r(e,t){const{rem_ids:n,new_parent_id:o,position:r,is_document:i}=t.payload||{},s=Array.isArray(n)?n.filter(d=>typeof d=="string"&&d.trim().length>0):[],c=typeof o=="string"?o.trim():"";if(s.length===0)throw new Error("Missing rem_ids");if(!c)throw new Error("Missing new_parent_id");const a=typeof r=="number"&&Number.isFinite(r)?Math.floor(r):0;for(let d=0;d<s.length;d+=1){const l=s[d];await e.rem.moveRems([l],c,a+d)}if(i===!0)for(const d of s){const l=await e.rem.findOne(d);if(!l)throw new Error(`Rem not found: ${d}`);typeof l.setIsDocument=="function"&&await l.setIsDocument(!0)}return{ok:!0,rem_ids:s,new_parent_id:c,moved_count:s.length,...i===!0?{is_document:!0}:{}}}async function Wr(e,t){return Mt(e,t,{errorContext:"rem deletion",includeRemIdInSuccess:!1})}async function Br(e,t){return Mt(e,t,{errorContext:"backup deletion",includeRemIdInSuccess:!0})}function De(e){return typeof e=="string"?e.trim():""}function Pt(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<0))return Math.floor(e)}const Ct=1e9;async function xt(e){const t=De(e.parentId);if(!t)throw new Error("Missing parent_id (refusing to create a Portal without a parent)");const n=De(e.targetRemId);if(!n)throw new Error("Missing target_rem_id (or rem_id) for portal target");const o=await e.plugin.rem.createPortal();if(!o?._id)throw new Error("createPortal returned null");const r=async()=>{try{await o.remove()}catch{}};try{const c=Pt(e.position)??Ct;await e.plugin.rem.moveRems([o._id],t,c)}catch(c){throw await r(),c}const i=await e.plugin.rem.findOne(n);if(!i)throw await r(),new Error(`Target Rem not found: ${n}`);try{if(typeof i.addToPortal!="function")throw new Error("addToPortal not available in SDK");await i.addToPortal(o._id)}catch(c){throw await r(),c}const s={ok:!0,portal_id:o._id,target_rem_id:n,parent_id:t};return e.clientTempId&&o._id&&(s.created={client_temp_id:e.clientTempId,remote_id:o._id,remote_type:"rem"}),s}async function Ur(e,t){const{parent_id:n,target_rem_id:o,rem_id:r,position:i,client_temp_id:s}=t.payload||{};return await xt({plugin:e,parentId:n,targetRemId:o??r,position:i,clientTempId:s})}async function qr(e,t){const{parent_id:n,items:o}=t.payload||{},r=De(n);if(!r)throw new Error("Missing parent_id (refusing to create a Portal without a parent)");const i=Array.isArray(o)?o.filter(d=>d&&typeof d=="object").map(d=>d):[];if(i.length===0)throw new Error("Missing items");const s=new Array(i.length),c=i.every(d=>Pt(d.position)===void 0),a=i.map((d,l)=>({item:d,index:l}));for(const d of a){const{item:l,index:u}=d,p=De(l.target_rem_id??l.rem_id),f=await xt({plugin:e,parentId:r,targetRemId:p,position:c?Ct:l.position??u,clientTempId:l.client_temp_id});s[u]={target_rem_id:p,portal_id:String(f.portal_id)}}return{ok:!0,parent_id:r,created_count:s.length,item_results:s}}function Pe(e,t){if(!t||typeof t!="object")return null;const{Query:n,TextMatcher:o,NumberMatcher:r,DateMatcher:i,SingleSelectMatcher:s,MultiSelectMatcher:c,CheckboxMatcher:a}=e||{};if(!n)return null;switch(t.op){case"and":{const d=Array.isArray(t.exprs)?t.exprs.map(l=>Pe(e,l)).filter(Boolean):[];return n.and(d)}case"or":{const d=Array.isArray(t.exprs)?t.exprs.map(l=>Pe(e,l)).filter(Boolean):[];return n.or(d)}case"not":{const d=Pe(e,t.expr);return n.not(d)}case"column_text_contains":return t.column_id?n.tableColumn(t.column_id,n.text(o.Contains,String(t.value??""))):null;case"column_text_prefix":return t.column_id?n.tableColumn(t.column_id,n.text(o.Prefix,String(t.value??""))):null;case"column_text_suffix":return t.column_id?n.tableColumn(t.column_id,n.text(o.Suffix,String(t.value??""))):null;case"column_text_phrase":return t.column_id?n.tableColumn(t.column_id,n.text(o.Phrase,String(t.value??""))):null;case"column_number":{if(!t.column_id||typeof n.number!="function")return null;const d=r[t.matcher]??r.Equals,l=t.value??(typeof t.min=="number"&&typeof t.max=="number"?[t.min,t.max]:void 0);return n.tableColumn(t.column_id,n.number(d,l))}case"column_date":{if(!t.column_id||typeof n.date!="function")return null;const d=i[t.matcher]??i.Equals;let l=t.value;if(d===i.Between||d===i.IsBetween)if(t.from&&t.to)l={from:t.from,to:t.to};else return null;return n.tableColumn(t.column_id,n.date(d,l))}case"column_single_select_in":{if(!t.column_id||typeof n.singleSelect!="function")return null;const d=s?.In??s?.Equals??void 0;return n.tableColumn(t.column_id,n.singleSelect(d,Array.isArray(t.option_ids)?t.option_ids:[t.option_ids]))}case"column_multi_select_contains_any":{if(!t.column_id||typeof n.multiSelect!="function")return null;const d=c?.ContainsAny??c?.Contains??void 0;return n.tableColumn(t.column_id,n.multiSelect(d,Array.isArray(t.option_ids)?t.option_ids:[t.option_ids]))}case"column_multi_select_contains_all":{if(!t.column_id||typeof n.multiSelect!="function")return null;const d=c?.ContainsAll??c?.Contains??void 0;return n.tableColumn(t.column_id,n.multiSelect(d,Array.isArray(t.option_ids)?t.option_ids:[t.option_ids]))}case"column_checkbox_equals":{if(!t.column_id||typeof n.checkbox!="function")return null;const d=a?.Equals??a?.Is??void 0;return n.tableColumn(t.column_id,n.checkbox(d,!!t.value))}default:return null}}async function ct(e,t){const n=typeof t=="string"?t.trim():"";if(n){try{const o=await e.rem.findOne(n);if(o)return o}catch(o){console.warn("[agent-remnote][tableOps] findOne failed",{remId:n,error:String(o?.message||o)})}try{const o=await e.rem.findMany([n]);if(Array.isArray(o)){const r=o.find(i=>i?._id===n);if(r)return r}}catch(o){console.warn("[agent-remnote][tableOps] findMany failed",{remId:n,error:String(o?.message||o)})}}}function Ot(e){return new Error(`Property type mutation is unsupported by the current RemNote plugin runtime: public rem.setPropertyType() is unavailable, and host endpoints rem.setPropertyType/rem.setSlotType are not exposed for ${String(e??"unknown-property")}`)}async function Vr(e,t){const{tag_id:n,client_temp_id:o,parent_id:r,position:i}=t.payload||{},s=typeof r=="string"?r.trim():"";if(!s)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const c=await e.rem.createTable(n);if(!c)throw new Error("createTable returned null");try{const d=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):0;await e.rem.moveRems([c._id],s,d)}catch(d){try{await c.remove()}catch{}throw d}const a={ok:!0};return o&&c._id&&(a.created={client_temp_id:o,remote_id:c._id,remote_type:"rem"}),a}async function zr(e,t){const{tag_id:n,name:o,property_id:r,type:i,options:s}=t.payload||{},c=await e.rem.findOne(n);if(!c)throw new Error("tag_rem not found");const a=await e.rem.createRem();if(!a)throw new Error("createRem returned null");try{if(await we(e,a,c._id,0),await a.setText(q(o??"Property")),a.setIsProperty&&await a.setIsProperty(!0),i)if(typeof a.setPropertyType=="function")await a.setPropertyType(i);else throw Ot(a?._id??r);if(Array.isArray(s)&&s.length>0)for(const l of s){const u=await e.rem.createRem();if(!u)throw new Error("createRem returned null");await we(e,u,a._id,0),await u.setText(q(l))}}catch(l){try{await a.remove()}catch{}throw l}const d={ok:!0};return r&&a._id&&(d.created={client_temp_id:r,remote_id:a._id,remote_type:"property"}),d}async function Gr(e,t){const{property_id:n,type:o}=t.payload||{},r=await ct(e,n);if(!r)throw new Error("property rem not found");if(typeof r.setPropertyType=="function")return await r.setPropertyType(o),{ok:!0};throw Ot(n??r._id)}async function Yr(e,t){const{table_id:n,column_id:o,contains_text:r,expr:i}=t.payload||{},s=await e.rem.findOne(n);if(!s)throw new Error("table rem not found");if(typeof s.setTableFilter!="function")return{ok:!1};const c=await be(()=>import("./index-CTg2hlbS.js").then(I=>I.i),[],import.meta.url),a=c.Query,d=c.TextMatcher,l=c.NumberMatcher,u=c.DateMatcher,p=c.SingleSelectMatcher,f=c.MultiSelectMatcher,m=c.CheckboxMatcher;let v=null;if(i)v=Pe({Query:a,TextMatcher:d,NumberMatcher:l,DateMatcher:u,SingleSelectMatcher:p,MultiSelectMatcher:f,CheckboxMatcher:m},i);else if(o&&r){if(!a||!d)return{ok:!1};v=a.tableColumn(o,a.text(d.Contains,String(r)))}return v?(await s.setTableFilter(v),{ok:!0}):{ok:!1}}async function jr(e,t){const{property_id:n,text:o,option_id:r}=t.payload||{},i=await ct(e,n);if(!i)throw new Error("property rem not found");const s=await e.rem.createRem();if(!s)throw new Error("createRem returned null");try{await we(e,s,i._id,0),await s.setText(q(o))}catch(a){try{await s.remove()}catch{}throw a}const c={ok:!0};return r&&s._id&&(c.created={client_temp_id:r,remote_id:s._id,remote_type:"option"}),c}async function Kr(e,t){const{option_id:n}=t.payload||{},o=await ct(e,n);return o?(await o.remove(),{ok:!0}):{ok:!0}}async function Xr(e,t){const{table_tag_id:n,rem_id:o,text:r,parent_id:i,client_temp_id:s,values:c,extra_tags:a}=t.payload||{};let d=o?await e.rem.findOne(o):void 0;const l=!d;if(!d){if(d=await e.rem.createRem(),!d)throw new Error("createRem returned null");const f=typeof i=="string"?i.trim():"";if(!f)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");try{await we(e,d,f,0),r!==void 0&&await d.setText(q(r))}catch(m){try{await d.remove()}catch{}throw m}}const u=async()=>{if(l)try{await d.remove()}catch{}};try{if(await d.addTag(n),Array.isArray(a))for(const f of a)await d.addTag(f);if(Array.isArray(c))for(const f of c)await d.setTagPropertyValue(f.property_id,q(f.value))}catch(f){throw await u(),f}const p={ok:!0};return!o&&s&&d?._id&&(p.created={client_temp_id:s,remote_id:d._id,remote_type:"row"}),p}async function Hr(e,t){const{table_tag_id:n,rem_id:o,remove_properties:r}=t.payload||{},i=await e.rem.findOne(o);return i?(await i.removeTag(n,!!r),{ok:!0}):{ok:!0}}async function Qr(e,t){const{rem_id:n,property_id:o,option_ids:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");const c=(Array.isArray(r)?r:[r]).filter(Boolean).map(a=>({i:"q",_id:a}));return await i.setTagPropertyValue(o,c),{ok:!0}}async function Jr(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");return await i.setTagPropertyValue(o,[{i:"m",text:r?"Yes":"No"}]),{ok:!0}}async function Zr(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");return await i.setTagPropertyValue(o,[{i:"m",text:String(r)}]),{ok:!0}}async function en(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");let s=null;if(typeof r=="string"||typeof r=="number"){const a=new Date(r);isNaN(a.getTime())||(s=a)}else if(r&&typeof r=="object"&&r.year&&r.month&&r.day){const a=new Date(r.year,r.month-1,r.day);isNaN(a.getTime())||(s=a)}if(!s)throw new Error("Invalid date");const c=await e.date.getDailyDoc(s);if(!c?._id)throw new Error("Daily document not found for that date. Please open it in RemNote first.");return await i.setTagPropertyValue(o,[{i:"q",_id:c._id}]),{ok:!0}}async function tn(e,t){const{rem_id:n,tag_id:o}=t.payload||{};if(!n||!o)throw new Error("Missing rem_id/tag_id");const r=await e.rem.findOne(n);if(!r)throw new Error(`Rem not found: ${n}`);return await r.addTag(o),{ok:!0}}async function rn(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.tag_id;if(!i||!s)throw new Error("Missing rem_id/tag_id");const c=await e.rem.findOne(i);if(!c)throw new Error(`Rem not found: ${i}`);await c.addTag(s),o.push({rem_id:i,tag_id:s})}return{ok:!0,item_results:o,changed_count:o.length}}async function nn(e,t){const{rem_id:n,tag_id:o,remove_properties:r}=t.payload||{};if(!n||!o)throw new Error("Missing rem_id/tag_id");const i=await e.rem.findOne(n);if(!i)throw new Error(`Rem not found: ${n}`);return await i.removeTag(o,!!r),{ok:!0}}async function on(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[],o=!!t.payload?.remove_properties;if(n.length===0)throw new Error("Missing items");const r=[];for(const i of n){const s=i?.rem_id,c=i?.tag_id;if(!s||!c)throw new Error("Missing rem_id/tag_id");const a=await e.rem.findOne(s);if(!a)throw new Error(`Rem not found: ${s}`);await a.removeTag(c,o),r.push({rem_id:s,tag_id:c})}return{ok:!0,item_results:r,changed_count:r.length,...o?{remove_properties:!0}:{}}}async function an(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{};if(!n||!o)throw new Error("Missing rem_id/property_id");const i=await e.rem.findOne(n);if(!i)throw new Error(`Rem not found: ${n}`);return await i.setTagPropertyValue(o,q(r)),{ok:!0}}async function sn(e,t){const{rem_id:n,source_id:o}=t.payload||{},r=await e.rem.findOne(n);if(!r)throw new Error("Rem not found");return await r.addSource(o),{ok:!0}}async function cn(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.source_id,c=await e.rem.findOne(i);if(!c)throw new Error("Rem not found");await c.addSource(s),o.push({rem_id:i,source_id:s})}return{ok:!0,item_results:o,changed_count:o.length}}async function dn(e,t){const{rem_id:n,source_id:o}=t.payload||{},r=await e.rem.findOne(n);if(!r)throw new Error("Rem not found");return await r.removeSource(o),{ok:!0}}async function ln(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.source_id,c=await e.rem.findOne(i);if(!c)throw new Error("Rem not found");await c.removeSource(s),o.push({rem_id:i,source_id:s})}return{ok:!0,item_results:o,changed_count:o.length}}async function un(e,t){const{rem_id:n,status:o}=t.payload||{},r=await e.rem.findOne(n);if(!r)throw new Error("Rem not found");return typeof r.setTodoStatus=="function"?(await r.setTodoStatus(o),{ok:!0}):{ok:!1}}async function fn(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.status,c=await e.rem.findOne(i);if(!c)throw new Error("Rem not found");if(typeof c.setTodoStatus=="function"){await c.setTodoStatus(s),o.push({rem_id:i,status:s});continue}return{ok:!1}}return{ok:!0,item_results:o,changed_count:o.length}}const Lt=new Set,Ge=new Set,Nt=new Map;function mn(e,t){e.idempotency_key&&t&&t.ok&&(Lt.add(e.idempotency_key),Nt.set(e.idempotency_key,t))}async function yn(e,t){const n=t.idempotency_key?String(t.idempotency_key):"";try{if(n&&Lt.has(n)){const i=Nt.get(n);return i&&typeof i=="object"?{...i,dedup:!0}:{ok:!0,dedup:!0}}if(n&&Ge.has(n))return{ok:!1,fatal:!1,error:"idempotency_key is in-flight; retry later"};n&&Ge.add(n);const o=kt(t.op_type);let r;switch(o){case"daily_note_write":r=await ur(e,t);break;case"create_rem":r=await Lr(e,t);break;case"create_portal":r=await Ur(e,t);break;case"create_portal_bulk":r=await qr(e,t);break;case"create_single_rem_with_markdown":r=await br(e,t);break;case"create_tree_with_markdown":r=await At(e,t);break;case"replace_selection_with_markdown":r=await kr(e,t);break;case"replace_children_with_markdown":r=await vr(e,t);break;case"create_link_rem":r=await Nr(e,t);break;case"create_table":r=await Vr(e,t);break;case"add_property":r=await zr(e,t);break;case"set_property_type":r=await Gr(e,t);break;case"set_table_filter":r=await Yr(e,t);break;case"add_option":r=await jr(e,t);break;case"remove_option":r=await Kr(e,t);break;case"table_add_row":r=await Xr(e,t);break;case"table_remove_row":r=await Hr(e,t);break;case"set_cell_select":r=await Qr(e,t);break;case"set_cell_checkbox":r=await Jr(e,t);break;case"set_cell_number":r=await Zr(e,t);break;case"set_cell_date":r=await en(e,t);break;case"update_text":r=await Dr(e,t);break;case"move_rem":r=await Fr(e,t);break;case"move_rem_bulk":r=await $r(e,t);break;case"add_tag":r=await tn(e,t);break;case"add_tag_bulk":r=await rn(e,t);break;case"remove_tag":r=await nn(e,t);break;case"remove_tag_bulk":r=await on(e,t);break;case"set_attribute":case"table_cell_write":r=await an(e,t);break;case"add_source":r=await sn(e,t);break;case"add_source_bulk":r=await cn(e,t);break;case"remove_source":r=await dn(e,t);break;case"remove_source_bulk":r=await ln(e,t);break;case"set_todo_status":r=await un(e,t);break;case"set_todo_status_bulk":r=await fn(e,t);break;case"delete_rem":r=await Wr(e,t);break;case"delete_backup_artifact":r=await Br(e,t);break;default:r={ok:!1,error:`unknown op_type: ${t.op_type}`,fatal:!0};break}return mn(t,r),r}catch(o){const r=String(o?.message||o);return await e.app.toast(`Execution failed: ${r}`),{ok:!1,error:r,fatal:!0}}finally{n&&Ge.delete(n)}}function D(e){return typeof e=="string"?e.trim():""}function hn(e){const t=e?.parent;if(typeof t=="string")return t.trim();const n=t?._id;return typeof n=="string"?n.trim():""}class pn{constructor(){Ue(this,"locked",new Set);Ue(this,"waiters",[])}acquire(t){const n=Array.from(new Set(t.map(i=>String(i||"").trim()).filter(Boolean))).sort();if(n.length===0)return Promise.resolve(()=>{});const r=(()=>{for(const i of n)if(this.locked.has(i))return null;for(const i of n)this.locked.add(i);return()=>{for(const i of n)this.locked.delete(i);this.drain()}})();return r?Promise.resolve(r):new Promise(i=>{this.waiters.push({keys:n,resolve:i}),this.drain()})}drain(){if(this.waiters.length===0)return;const t=new Set;for(let n=0;n<this.waiters.length;n+=1){const o=this.waiters[n],r=o.keys.some(s=>t.has(s)),i=o.keys.every(s=>!this.locked.has(s));if(!r&&i){for(const s of o.keys)this.locked.add(s);this.waiters.splice(n,1),n-=1,o.resolve(()=>{for(const s of o.keys)this.locked.delete(s);this.drain()});continue}for(const s of o.keys)t.add(s)}}}function _n(e){return`rem:${e}`}function wn(e){return`children:${e}`}async function Te(e,t){try{const n=await e.rem.findOne(t);return(n?hn(n):"")||void 0}catch{return}}async function gn(e,t){const n=kt(t.op_type),o=t.payload||{},r=[],i=a=>{const d=String(a||"").trim();d&&r.push(d)},s=a=>{a&&i(_n(a))},c=a=>{a&&i(wn(a))};switch(n){case"create_rem":case"create_portal":case"create_link_rem":case"create_table":case"create_single_rem_with_markdown":case"create_tree_with_markdown":{const a=D(o.parent_id);if(s(a),c(a),n==="create_portal"){const d=D(o.target_rem_id??o.rem_id);s(d)}return r}case"create_portal_bulk":{const a=D(o.parent_id);s(a),c(a);const d=Array.isArray(o.items)?o.items:[];for(const l of d){const u=D(l?.target_rem_id??l?.rem_id);s(u)}return r}case"replace_selection_with_markdown":{const a=o?.target?.rem_ids,d=Array.isArray(a)?a.map(u=>D(u)).filter(Boolean):[];if(d.length===0)return["global:replace_selection_with_markdown"];for(const u of d)s(u);const l=d.length>0?await Te(e,d[0]):void 0;return s(l),c(l),r}case"replace_children_with_markdown":{const a=D(o.parent_id);if(!a)return["global:replace_children_with_markdown"];s(a),c(a);try{const d=await e.rem.findOne(a),l=Array.isArray(d?.children)?d.children.filter(u=>typeof u=="string"&&u.trim()).map(u=>u.trim()):[];for(const u of l)s(u)}catch{}return r}case"update_text":case"add_tag":case"remove_tag":case"set_attribute":case"table_cell_write":case"add_source":case"remove_source":case"set_todo_status":case"set_cell_select":case"set_cell_checkbox":case"set_cell_number":case"set_cell_date":{const a=D(o.rem_id);return s(a),r}case"add_tag_bulk":case"remove_tag_bulk":{const a=Array.isArray(o.items)?o.items:[];for(const d of a){const l=D(d?.rem_id);s(l)}return r}case"set_todo_status_bulk":{const a=Array.isArray(o.items)?o.items:[];for(const d of a){const l=D(d?.rem_id);s(l)}return r}case"add_source_bulk":case"remove_source_bulk":{const a=Array.isArray(o.items)?o.items:[];for(const d of a){const l=D(d?.rem_id);s(l)}return r}case"set_table_filter":{const a=D(o.table_id);return s(a),r}case"add_property":{const a=D(o.tag_id);return s(a),c(a),r}case"set_property_type":{const a=D(o.property_id);return s(a),r}case"add_option":{const a=D(o.property_id);return s(a),c(a),r}case"remove_option":{const a=D(o.option_id);return s(a),r}case"table_add_row":{const a=D(o.rem_id);if(a)return s(a),r;const d=D(o.parent_id);return s(d),c(d),r}case"table_remove_row":{const a=D(o.rem_id);return s(a),r}case"move_rem":{const a=D(o.rem_id),d=D(o.new_parent_id);s(a),s(d),c(d);const l=a?await Te(e,a):void 0;return s(l),c(l),r}case"move_rem_bulk":{const a=Array.isArray(o.rem_ids)?o.rem_ids.map(l=>D(l)).filter(l=>l.length>0):[],d=D(o.new_parent_id);for(const l of a)s(l);s(d),c(d);for(const l of a){const u=l?await Te(e,l):void 0;s(u),c(u)}return r}case"delete_rem":case"delete_backup_artifact":{const a=D(o.rem_id);s(a);const d=a?await Te(e,a):void 0;return s(d),c(d),r}case"daily_note_write":return["global:daily_note_write"];default:return["global:unknown_op"]}}var pt={name:"@remnote/plugin",version:"0.0.2",build_id:"0.0.2:1774461211291",built_at:1774461226265,source_stamp:1774461211291,mode:"dist"};const bn=typeof pt>"u"?void 0:pt,Dt=bn??{name:"@remnote/plugin",version:"0.0.0",build_id:"0.0.0:unknown",built_at:0,source_stamp:0,mode:"unknown"};let N=null,H=null,J=null,de=!1,Y=null,kn=0,ue=0,et=0,W=null,ge=!1,tt=0,Ce=0,rt=!1,xe=!1,Oe=!1,Fe=null,me=null,oe=null,nt=!1,Le=!1,Ne=!1,Ye=null,$e=null;const vn=!0;let U=null;const je="agent-remnote.selection-forwarder",Ke={editor:`${je}.editor`,focusedRem:`${je}.focused-rem`,focusedPortal:`${je}.focused-portal`},ce="agent-remnote.ui-context-forwarder",te={url:`${ce}.url`,openRem:`${ce}.open-rem`,focusedPane:`${ce}.focused-pane`,windowTree:`${ce}.window-tree`,focusedRem:`${ce}.focused-rem`,focusedPortal:`${ce}.focused-portal`,selection:`${ce}.selection`},Ft=8,$t=12e4,Sn=512e3,Rn=256e3,En=250,Tn=2e3,In=5,An=new Set(["PROTOCOL_MISMATCH","INVALID_MESSAGE","UNSUPPORTED_CLIENT","UNSUPPORTED_VERSION"]),Mn=2e4,Pn=3e4,Cn=new pn;function xn(e){return e?!An.has(e):!0}function On(e){const t=Math.max(1,Math.floor(e)),n=En*Math.pow(2,Math.max(0,t-1));return Math.min(Tn,n)}function Ln(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(16,Math.floor(e)):Ft}function Nn(e){return 0}const ye=new Map,ae=new Map,_t=new WeakSet;let he=null;const Dn=1500,Fn=600,$n=5e3,pe=new Map,wt=new WeakSet;function Wn(){if(he){try{clearTimeout(he)}catch{}he=null}for(const e of ae.values()){try{clearTimeout(e.timer)}catch{}try{e.resolve(null)}catch{}}ae.clear(),ye.clear(),pe.clear()}function Wt(){try{Ut()}catch{}try{ut()}catch{}if(Y){try{clearTimeout(Y)}catch{}Y=null}if(J){try{clearTimeout(J)}catch{}J=null}de=!1,ue=0,et=0,Wn()}function Be(e,t){return`${e}:${t}`}function Bn(e){const t=new Map;for(const o of e){const r=t.get(o.ws)??[];r.push(o.payload),t.set(o.ws,r)}const n=[];for(const[o,r]of t.entries()){if(r.length<=1){n.push({ws:o,payload:r[0]??null});continue}n.push({ws:o,payload:{type:"OpAckBatch",items:r}})}return n}function Un(e){wt.has(e)||(wt.add(e),e.addEventListener("message",t=>{let n;try{n=JSON.parse(String(t?.data))}catch{return}if(n?.type!=="LeaseExtendRejected"&&n?.type!=="LeaseExtendOk")return;const o=typeof n?.op_id=="string"?n.op_id:typeof n?.opId=="string"?n.opId:"",r=typeof n?.attempt_id=="string"?n.attempt_id:typeof n?.attemptId=="string"?n.attemptId:"";if(!o||!r)return;const i=Be(o,r);if(n.type==="LeaseExtendRejected"){if(pe.has(i))return;const s=typeof n?.reason=="string"?n.reason:"rejected";pe.set(i,{reason:s,at:Date.now()});try{console.warn("[agent-remnote][lease] rejected",{opId:o,attemptId:r,reason:s,current:n?.current})}catch{}}else pe.delete(i)}))}function qn(e,t,n){Un(e);const o=Be(t,n);let r=!1,i=null;const s=()=>{if(!r){if(pe.has(o)){r=!0;return}try{le(e,{type:"LeaseExtend",op_id:t,attempt_id:n,extendMs:$t})}catch{}i=setTimeout(s,Pn)}};return i=setTimeout(s,Mn),()=>{if(r=!0,pe.delete(o),i)try{clearTimeout(i)}catch{}}}function dt(e){if(_t.has(e))return;_t.add(e);const t=n=>{if(n?.type!=="AckOk"&&n?.type!=="AckRejected")return;const o=typeof n?.op_id=="string"?n.op_id:typeof n?.opId=="string"?n.opId:"",r=typeof n?.attempt_id=="string"?n.attempt_id:typeof n?.attemptId=="string"?n.attemptId:"";if(!o||!r)return;const i=Be(o,r);ye.delete(i);const s=ae.get(i);if(s){ae.delete(i);try{clearTimeout(s.timer)}catch{}s.resolve(n)}if(n.type==="AckRejected")try{console.warn("[agent-remnote][ack] rejected",{opId:o,attemptId:r,reason:n?.reason,current:n?.current})}catch{}};e.addEventListener("message",n=>{let o;try{o=JSON.parse(String(n?.data))}catch{return}if(o?.type==="AckBatch"&&Array.isArray(o?.items)){for(const r of o.items)t(r);return}t(o)})}function ot(){he||(he=setTimeout(()=>{he=null,Vn()},0))}function Vn(){const e=Date.now(),t=[];for(const o of ye.values()){if(!o.ws||o.ws.readyState!==WebSocket.OPEN){ye.delete(o.key);continue}e<o.nextRetryAt||t.push(o)}const n=Bn(t.map(o=>({ws:o.ws,payload:o.payload})));for(const o of n)try{le(o.ws,o.payload)}catch{}for(const o of t){o.retries+=1;const r=Math.min($n,Fn+o.retries*500);o.nextRetryAt=e+r}ye.size>0&&ot()}function zn(e,t){return new Promise(n=>{const o=ae.get(e);if(o){try{clearTimeout(o.timer)}catch{}ae.delete(e)}const r=setTimeout(()=>{ae.delete(e),n(null)},Math.max(1,t));ae.set(e,{resolve:n,timer:r})})}async function Xe(e,t,n=Dn){const o=typeof t?.op_id=="string"?t.op_id:"",r=typeof t?.attempt_id=="string"?t.attempt_id:"";if(!o||!r)return"timeout";dt(e);const i=Be(o,r);ye.set(i,{key:i,op_id:o,attempt_id:r,ws:e,payload:t,retries:0,nextRetryAt:Date.now()});const s=zn(i,n);ot();const c=await s;return c?c.type==="AckOk"?"ok":"rejected":(ot(),"timeout")}const Gn=18e4,Yn=12e4;function Ie(e,t,n,o){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(n,Math.min(o,Math.floor(r))):t}function jn(e){const t=String(e||"").trim();if(!t)return[];const n=t.replace(/[^\p{L}\p{N}]+/gu," ").split(/\s+/).map(r=>r.trim()).filter(Boolean),o=[];for(const r of n){const i=r.toLowerCase();if(!(i.length<2)&&!o.includes(i)&&(o.push(i),o.length>=8))break}return o}function Kn(e,t,n){const o=String(e||"").replace(/\s+/g," ").trim();if(o.length<=n)return{text:o,truncated:!1};const r=jn(t),i=o.toLowerCase();let s=-1;for(const u of r){const p=i.indexOf(u);p<0||(s<0||p<s)&&(s=p)}let c=0;s>=0&&(c=Math.max(0,s-Math.floor(n/3)));let a=c+n;a>o.length&&(a=o.length,c=Math.max(0,a-n));const d=o.slice(c,a).trim(),l=c>0||a<o.length;return{text:d,truncated:l}}function Xn(e,t){return new Promise((n,o)=>{const r=setTimeout(()=>o(new Error("timeout")),t);e.then(i=>{clearTimeout(r),n(i)},i=>{clearTimeout(r),o(i)})})}async function Hn(e,t,n){const o=Date.now(),r=typeof n?.requestId=="string"?n.requestId.trim():"";if(!r)return;const i=typeof n?.queryText=="string"?n.queryText:"",s=typeof n?.searchContextRemId=="string"?n.searchContextRemId.trim():"",c=200,a=Ie(n?.limit,20,1,1e4),d=Ie(a,20,1,100),l=d!==a,u=Ie(n?.timeoutMs,3e3,1,6e4),p=Ie(u,3e3,1,5e3),f={timeoutMs:p,limitRequested:a,limitEffective:d,limitClamped:l,maxPreviewChars:c,durationMs:0},m=v=>{try{t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(v))}catch{}};if(!i.trim())return m({type:"SearchResponse",requestId:r,ok:!1,budget:{...f,durationMs:Date.now()-o},error:{code:"VALIDATION_ERROR",message:"queryText must not be empty"}});try{const v=await e.richText.parseFromMarkdown(i),I=await Xn(e.search.search(v,s||void 0,{numResults:d}),p),y=[];for(const h of I.slice(0,d)){const T=String(h?._id||"").trim();if(!T)continue;let k="";try{k=String(await e.richText.toString(h?.text??[]))}catch{}let A="";try{h?.backText&&(A=String(await e.richText.toString(h.backText)))}catch{}A.trim()||(A=k);const b=Kn(A,i,c);y.push({remId:T,title:k.trim(),snippet:b.text,truncated:b.truncated})}return m({type:"SearchResponse",requestId:r,ok:!0,budget:{...f,durationMs:Date.now()-o},results:y})}catch(v){const I=String(v?.message||v||"search failed"),y=I.toLowerCase().includes("timeout")?"TIMEOUT":"PLUGIN_ERROR";return m({type:"SearchResponse",requestId:r,ok:!1,budget:{...f,durationMs:Date.now()-o},error:{code:y,message:I},nextActions:["Retry later","Check that the plugin is connected and responsive",'Fallback to DB search: agent-remnote read search --query "<keywords>"']})}}function We(){me&&(clearTimeout(me),me=null)}function Bt(e){me||(me=setTimeout(()=>{me=null,ge&&(!N||N.readyState!==WebSocket.OPEN||(_e(e,{force:!1}),Bt(e)))},500))}function Qn(e){rt=!0;try{const r=oe?.editor;r&&e.event.removeListener(S.AppEvents.EditorSelectionChanged,void 0,r)}catch{}try{const r=oe?.focusedRem;r&&e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,r)}catch{}try{const r=oe?.focusedPortal;r&&e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,r)}catch{}try{e.event.removeListener(S.AppEvents.EditorSelectionChanged,Ke.editor)}catch{}try{e.event.removeListener(S.AppEvents.FocusedRemChange,Ke.focusedRem)}catch{}try{e.event.removeListener(S.AppEvents.FocusedPortalChange,Ke.focusedPortal)}catch{}const t=()=>{_e(e,{force:!1})},n=()=>{_e(e,{force:!1})},o=()=>{_e(e,{force:!1})};oe={editor:t,focusedRem:n,focusedPortal:o},e.event.addListener(S.AppEvents.EditorSelectionChanged,void 0,t),e.event.addListener(S.AppEvents.FocusedRemChange,void 0,n),e.event.addListener(S.AppEvents.FocusedPortalChange,void 0,o)}function Jn(e){if(rt){rt=!1,xe=!1,Oe=!1,Fe=null,We();try{const t=oe?.editor;e.event.removeListener(S.AppEvents.EditorSelectionChanged,void 0,t)}catch{}try{const t=oe?.focusedRem;e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,t)}catch{}try{const t=oe?.focusedPortal;e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,t)}catch{}oe=null}}function Zn(e){nt=!0;try{const c=U?.url;c&&e.event.removeListener(S.AppEvents.URLChange,void 0,c)}catch{}try{const c=U?.openRem;c&&e.event.removeListener(S.AppEvents.GlobalOpenRem,void 0,c)}catch{}try{const c=U?.focusedPane;c&&e.event.removeListener(S.AppEvents.FocusedPaneChange,void 0,c)}catch{}try{const c=U?.windowTree;c&&e.event.removeListener(S.AppEvents.CurrentWindowTreeChange,void 0,c)}catch{}try{const c=U?.focusedRem;c&&e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,c)}catch{}try{const c=U?.focusedPortal;c&&e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,c)}catch{}try{e.event.removeListener(S.AppEvents.URLChange,te.url)}catch{}try{e.event.removeListener(S.AppEvents.GlobalOpenRem,te.openRem)}catch{}try{e.event.removeListener(S.AppEvents.FocusedPaneChange,te.focusedPane)}catch{}try{e.event.removeListener(S.AppEvents.CurrentWindowTreeChange,te.windowTree)}catch{}try{e.event.removeListener(S.AppEvents.FocusedRemChange,te.focusedRem)}catch{}try{e.event.removeListener(S.AppEvents.FocusedPortalChange,te.focusedPortal)}catch{}try{e.event.removeListener(S.AppEvents.EditorSelectionChanged,te.selection)}catch{}const t=()=>void re(e,{force:!1,source:"event:URLChange"}),n=()=>void re(e,{force:!1,source:"event:GlobalOpenRem"}),o=()=>void re(e,{force:!1,source:"event:FocusedPaneChange"}),r=()=>void re(e,{force:!1,source:"event:CurrentWindowTreeChange"}),i=()=>void re(e,{force:!1,source:"event:FocusedRemChange"}),s=()=>void re(e,{force:!1,source:"event:FocusedPortalChange"});U={url:t,openRem:n,focusedPane:o,windowTree:r,focusedRem:i,focusedPortal:s},e.event.addListener(S.AppEvents.URLChange,void 0,t),e.event.addListener(S.AppEvents.GlobalOpenRem,void 0,n),e.event.addListener(S.AppEvents.FocusedPaneChange,void 0,o),e.event.addListener(S.AppEvents.CurrentWindowTreeChange,void 0,r),e.event.addListener(S.AppEvents.FocusedRemChange,void 0,i),e.event.addListener(S.AppEvents.FocusedPortalChange,void 0,s)}function eo(e){if(nt){nt=!1,Le=!1,Ne=!1,$e=null;try{const t=U?.url;e.event.removeListener(S.AppEvents.URLChange,void 0,t)}catch{}try{const t=U?.openRem;e.event.removeListener(S.AppEvents.GlobalOpenRem,void 0,t)}catch{}try{const t=U?.focusedPane;e.event.removeListener(S.AppEvents.FocusedPaneChange,void 0,t)}catch{}try{const t=U?.windowTree;e.event.removeListener(S.AppEvents.CurrentWindowTreeChange,void 0,t)}catch{}try{const t=U?.focusedRem;e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,t)}catch{}try{const t=U?.focusedPortal;e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,t)}catch{}try{e.event.removeListener(S.AppEvents.EditorSelectionChanged,te.selection)}catch{}U=null}}async function _e(e,t){if(xe){Oe=!0;return}xe=!0;try{const n=N;if(!n||n.readyState!==WebSocket.OPEN)return;const o=await to(e);let r=o.kind,i=r==="rem"?S.SelectionType.Rem:r==="text"?S.SelectionType.Text:void 0,s=0,c=!1,a=[],d="",l,u=!1;if(o.kind==="rem"){a=o.remIds,s=a.length;const f=200;c=s>f,c&&(a=a.slice(0,f)),s<=0&&(r="none",i=void 0)}else o.kind==="text"&&(d=o.remId,l=o.range,u=o.isReverse,s=1);if(r==="rem"&&a.length>0&&!c){let f="";try{const m=await e.focus.getFocusedRem();m?._id&&(f=String(m._id).trim())}catch{}f&&!a.includes(f)&&(r="none",i=void 0,s=0,c=!1,a=[])}if(r==="text"&&d){let f="";try{const m=await e.focus.getFocusedRem();m?._id&&(f=String(m._id).trim())}catch{}f&&f!==d&&(r="none",i=void 0,s=0,c=!1,d="",l=void 0,u=!1)}const p=r==="rem"?`rem:${s}:${c?"1":"0"}:${a.join(",")}`:r==="text"?`text:${d}:${l?.start??""}-${l?.end??""}:${u?"1":"0"}`:"none";if(!t.force&&Fe===p)return;Fe=p;try{n.send(JSON.stringify({type:"SelectionChanged",kind:r,selectionType:i,remIds:a,totalCount:s,truncated:c,remId:d,range:l,isReverse:u,ts:Date.now()}))}catch{}}finally{xe=!1,Oe&&(Oe=!1,_e(e,{force:!1}))}}async function to(e){try{const t=await e.editor.getSelection();if(!t?.type)return{kind:"none"};if(t.type===S.SelectionType.Rem)return{kind:"rem",remIds:Array.isArray(t.remIds)?t.remIds.filter(o=>typeof o=="string"&&o.trim()):[]};if(t.type===S.SelectionType.Text){const n=typeof t.remId=="string"?t.remId.trim():"",o=t?.range?.start,r=t?.range?.end,i=typeof o=="number"&&Number.isFinite(o)?Math.floor(o):NaN,s=typeof r=="number"&&Number.isFinite(r)?Math.floor(r):NaN,c=t?.isReverse===!0;return n?!Number.isFinite(i)||!Number.isFinite(s)?{kind:"none"}:i===s?{kind:"none"}:{kind:"text",remId:n,range:{start:i,end:s},isReverse:c}:{kind:"none"}}return{kind:"none"}}catch{return{kind:"none"}}}async function ro(e){let t="";try{t=await e.window.getURL()||""}catch{}let n="";try{n=await e.window.getFocusedPaneId()||""}catch{}let o="";try{o=await e.window.getOpenPaneRemId(n)||""}catch{}let r="";try{const a=await e.focus.getFocusedRem();a?._id&&(r=String(a._id))}catch{}let i="";try{const a=await e.focus.getFocusedPortal();a?._id&&(i=String(a._id))}catch{}let s="",c="";try{const d=new URL(t).pathname.split("/").filter(Boolean);d.length>=2&&d[0]==="w"&&(s=String(d[1]||""))}catch{}if(!s)try{const a=await e.kb?.getCurrentKnowledgeBaseData?.();a?._id&&(s=String(a._id)),a?.name&&(c=String(a.name))}catch{}return{url:t,paneId:n,pageRemId:o,focusedRemId:r,focusedPortalId:i,kbId:s,kbName:c}}async function re(e,t){if(Le){Ne=!0,Ye=t.source;return}Le=!0;try{const n=N;if(!n||n.readyState!==WebSocket.OPEN)return;const o=await ro(e),r=`${o.url}|${o.paneId}|${o.pageRemId}|${o.focusedRemId}|${o.focusedPortalId}|${o.kbId}`;if(!t.force&&$e===r)return;$e=r;try{n.send(JSON.stringify({type:"UiContextChanged",...o,source:t.source,ts:Date.now()}))}catch{}if(vn)try{console.log("[agent-remnote][ui-context]",{...o,source:t.source})}catch{}}finally{if(Le=!1,Ne){const n=Ye||"pending";Ne=!1,Ye=null,re(e,{force:!1,source:n})}}}function no(e){const o=Math.min(Math.max(e,0),10),r=Math.min(3e4,500*Math.pow(2,o)),i=r*.2;return Math.max(0,Math.round(r+(Math.random()*2-1)*i))}function Ut(){ge=!1,H&&(clearTimeout(H),H=null),J&&(clearTimeout(J),J=null),We(),tt+=1,Ce=0;const e=N;N=null;try{e&&e.readyState!==WebSocket.CLOSED&&e.close()}catch{}}function lt(e,t,n){if(ge=!0,N&&(N.readyState===WebSocket.OPEN||N.readyState===WebSocket.CONNECTING))return;H&&(clearTimeout(H),H=null);const o=tt+=1,r=new WebSocket(t);N=r;const i=()=>N===r&&tt===o,s=setTimeout(()=>{if(i()&&r.readyState===WebSocket.CONNECTING)try{r.close()}catch{}},8e3);r.onopen=async()=>{if(i()){clearTimeout(s),Ce=0;try{if(r.send(JSON.stringify({type:"Hello"})),r.send(JSON.stringify({type:"Register",protocolVersion:2,clientType:"remnote-plugin",clientInstanceId:n,runtime:Dt,capabilities:{control:!0,worker:!0,readRpc:!0,batchPull:!0}})),Fe=null,_e(e,{force:!0}),$e=null,re(e,{force:!0,source:"connect"}),Bt(e),await e.app.toast("Control channel connected"),await e.settings.getSetting(j.autoSyncOnConnect))try{await Se(e,t,n,{silent:!0})}catch(d){try{console.warn("[agent-remnote][control] auto-sync on connect failed",{message:String(d?.message||d||"unknown error")})}catch{}}}catch{}}},r.onmessage=async a=>{if(i())try{const d=JSON.parse(String(a.data));if(d?.type==="StartSync"){try{await Se(e,t,n,{silent:!0})}catch(l){try{console.warn("[agent-remnote][control] StartSync failed",{message:String(l?.message||l||"unknown error")})}catch{}}return}if(d?.type==="SearchRequest"){Hn(e,r,d);return}}catch{}};const c=()=>{if(!ge||!i()||H)return;const a=no(Ce);Ce+=1,H=setTimeout(()=>{H=null,lt(e,t,n)},a)};r.onclose=()=>{clearTimeout(s),i()&&(We(),c(),N=null)},r.onerror=()=>{clearTimeout(s),We(),c()}}async function oo(e,t=!0){return t&&N&&N.readyState===WebSocket.OPEN?N:(W&&W.readyState===WebSocket.OPEN||(W=await gt(e),W.onclose=()=>{W&&W.readyState!==WebSocket.OPEN&&(W=null)},dt(W)),W)}async function ao(e,t){const n=Math.max(1,Math.min(50,Math.floor(t)));le(e,{type:"RequestOps",leaseMs:$t,maxOps:n,maxBytes:Sn,maxOpBytes:Rn});const o=await Kt(e);if(!o||o.type==="NoWork")return{kind:"no_work"};if(o.type==="Error"){const r=typeof o?.code=="string"?o.code:"",i=typeof o?.message=="string"?o.message:"";if(r==="OP_PAYLOAD_TOO_LARGE")try{le(e,{type:"TriggerStartSync"})}catch{}try{console.warn("[agent-remnote][ws] RequestOps error",{code:r,message:i,details:o?.details,nextActions:o?.nextActions})}catch{}return{kind:"error",code:r,message:i,retryable:xn(r)}}if(o.type==="OpDispatchBatch"){const r=o;return{kind:"ops",ops:Array.isArray(r.ops)?r.ops:[]}}if(o.type==="OpDispatch"){const r=o;if(r?.op_id&&r?.attempt_id)return{kind:"ops",ops:[{op_id:String(r.op_id),attempt_id:String(r.attempt_id),txn_id:String(r.txn_id??""),op_seq:Number(r.op_seq??0),op_type:String(r.op_type??""),payload:r.payload??null,idempotency_key:r.idempotency_key??null,lease_expires_at:typeof r.lease_expires_at=="number"?r.lease_expires_at:void 0}]}}return{kind:"no_work"}}async function Se(e,t,n,o){const r=Date.now();if(o?.silent&&et>r)return;if(de){o?.silent||await e.app.toast("A sync is already running");return}de=!0;const i=kn+=1;ue=i,Y&&(clearTimeout(Y),Y=null),Y=setTimeout(()=>{if(de&&ue===i){ue=0,de=!1,et=Date.now()+Yn,Y=null;try{ut()}catch{}try{N&&N.readyState!==WebSocket.CLOSED&&N.close()}catch{}try{e.app.toast("Sync watchdog tripped; please retry")}catch{}}},Gn),o?.silent||await e.app.toast("Starting sync…");let s=0;try{const c=await oo(t,!0);dt(c);const a=c===N;try{le(c,{type:"Hello"})}catch{}try{le(c,{type:"Register",protocolVersion:2,clientType:"remnote-plugin",clientInstanceId:n,runtime:Dt,capabilities:{control:a,worker:!0,readRpc:!0,batchPull:!0}})}catch{}let d=Ft;try{const m=await e.settings.getSetting(j.syncConcurrency);d=Ln(m)}catch{}const l=new Map;let u=!1;const p=async m=>{let v,I;try{const y=await gn(e,m);v=await Cn.acquire(y),I=qn(c,m.op_id,m.attempt_id);const h=await yn(e,m);if(h&&h.ok)await Xe(c,{type:"OpAck",op_id:m.op_id,attempt_id:m.attempt_id,status:"success",result:h});else{const T=h&&h.fatal||!1,k=h&&h.error||"executor error";await Xe(c,{type:"OpAck",op_id:m.op_id,attempt_id:m.attempt_id,status:T?"failed":"retry",error_code:"EXEC_ERROR",error_message:k})}}catch(y){const h=String(y?.message||y);await Xe(c,{type:"OpAck",op_id:m.op_id,attempt_id:m.attempt_id,status:"retry",error_code:"EXEC_ERROR",error_message:h})}finally{try{I?.()}catch{}try{v?.()}catch{}s+=1,Nn(s)>0}};let f=0;for(;;){for(;!u&&l.size<d;){const m=d-l.size,v=await ao(c,m);if(v.kind==="error"){if(f+=1,v.retryable&&f<=In){const h=On(f);try{console.warn("[agent-remnote][ws] RequestOps transient error; retrying",{code:v.code,message:v.message,streak:f,delayMs:h})}catch{}await ne(h);continue}try{console.warn("[agent-remnote][ws] RequestOps error; stopping pull loop",{code:v.code,message:v.message,streak:f,retryable:v.retryable})}catch{}u=!0;break}if(f=0,v.kind==="no_work"){u=!0;break}const I=v.ops;if(I.length===0){u=!0;break}for(const y of I){const h={type:"OpDispatch",...y},T=p(h).catch(()=>{}).finally(()=>{l.delete(h.op_id)});l.set(h.op_id,T)}}if(u&&l.size===0)break;l.size>0&&await Promise.race(l.values())}if(c!==N){try{c.close()}catch{}W===c&&(W=null)}o?.silent||await e.app.toast("Sync finished (or no work)")}finally{if(!(ue===i))return;de=!1,ue=0,Y&&(clearTimeout(Y),Y=null);try{const a=await e.settings.getSetting(j.autoSyncOnConnect);s>0&&a&&ge&&N&&N.readyState===WebSocket.OPEN&&(J||(J=setTimeout(()=>{J=null,ge&&(!N||N.readyState!==WebSocket.OPEN||de||Se(e,t,n,{silent:!0}))},1500)))}catch{}}}function ut(){try{W&&W.readyState!==WebSocket.CLOSED&&W.close()}catch{}W=null}async function io(e){try{await e.app.registerCommand({id:"start-sync-ops",name:"Start sync",action:async()=>{const t=await Ae(e),n=await He(e);try{await Se(e,t,n,{silent:!1})}catch(o){await e.app.toast(`Failed to start sync: ${o?.message||o}`)}}})}catch{}try{await e.app.registerCommand({id:"show-queue-stats",name:"Show queue stats",action:async()=>{const t=await Ae(e);try{const n=await Xt(t);await e.app.toast(`Pending: ${n.pending} | In-flight: ${n.in_flight} | Dead: ${n.dead}`)}catch(n){await e.app.toast(`Query failed: ${n?.message||n}`)}}})}catch{}try{await e.app.registerCommand({id:"connect-control",name:"Connect control channel",action:async()=>{const t=await Ae(e),n=await He(e);lt(e,t,n)}})}catch{}try{await e.app.registerCommand({id:"disconnect-control",name:"Disconnect control channel",action:async()=>{try{Ut(),ut(),await e.app.toast("Control channel disconnected")}catch(t){await e.app.toast(`Disconnect failed: ${t?.message||t}`)}}})}catch{}}async function lo(e){try{Wt()}catch{}try{const t=globalThis;t.__REMNOTE_BRIDGE_REGISTERED__=!0}catch{}try{await Zt(e)}catch{}try{await Yt(e)}catch{}try{Qn(e)}catch{}try{Zn(e)}catch{}try{await io(e)}catch{}try{const t=await e.settings.getSetting(j.autoConnectControl),n=await e.settings.getSetting(j.autoSyncOnConnect),o=await Ae(e),r=await He(e);if(t)lt(e,o,r);else if(n)try{await Se(e,o,r,{silent:!1})}catch{}}catch{}}async function uo(e){try{Jn(e)}catch{}try{eo(e)}catch{}try{Wt()}catch{}try{const t=globalThis;delete t.__REMNOTE_BRIDGE_REGISTERED__}catch{}}export{uo as a,lo as o};
12
+ `).filter(r=>r.trim().length>0);if(t.length!==1)return e;const n=t[0].match(/^\s*[-*+]\s+(.*)$/),o=t[0].match(/^\s*\d+\.\s+(.*)$/);return n?n[1]:o?o[1]:e}function It(e){return it(at(e))}function Qe(e){return typeof e=="string"?e.trim():""}function ur(e){return Qe(e.title)||"Imported (bundle)"}function fr(e){const t=e?.bundle;if(!t||typeof t!="object")return null;const n=t.enabled===!0,o=Qe(t.title)||Qe(e?.bundle_title);return!n&&!o?null:{title:o||"Imported (bundle)"}}async function mr(e,t){const{text:n,markdown:o,date:r,offset_days:i,prepend:s,position:c}=t.payload||{};let a=null;if(typeof r=="string"||typeof r=="number"){const f=new Date(r);isNaN(f.getTime())||(a=f)}if(!a){const f=typeof i=="number"?i:0,m=new Date;a=new Date(m.getFullYear(),m.getMonth(),m.getDate()+f)}const d=await e.date.getDailyDoc(a);if(!d?._id)throw new Error("Daily document not found for that date. Please open it in RemNote first.");const l=typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):void 0,u=fr(t.payload||{});if(u){const f=[];let m=null;try{const v=ur(u);try{if(m=await X(e,v,d._id),!m?._id)throw new Error("createSingleRemWithMarkdown returned null for bundle title")}catch{if(m=await e.rem.createRem(),!m?._id)throw new Error("createRem failed for bundle title");await m.setText(q(v))}const I=l!==void 0?l:typeof s=="boolean"&&s?0:999999;try{await e.rem.moveRems([m._id],d._id,I)}catch(y){try{await m.remove()}catch{}throw y}if(typeof o=="string"&&o.trim())try{const y=await J(e,o,m._id);if(Array.isArray(y))for(const h of y)h?._id&&f.push(h._id)}catch{const y=await X(e,o,m._id);y?._id&&f.push(y._id)}else if(n!=null){const y=await e.rem.createRem();if(!y)throw new Error("createRem failed");try{await y.setText(q(n))}catch(h){try{await y.remove()}catch{}throw h}try{await e.rem.moveRems([y._id],m._id,999999)}catch(h){try{await y.remove()}catch{}throw h}y?._id&&f.push(y._id)}else throw new Error("Missing content (text/markdown)");return{ok:!0,daily_id:d._id,created_ids:[m._id],bundle:{rem_id:m._id},bundle_inner_created_ids:f.length?f:void 0}}catch(v){if(m?._id)try{await m.remove()}catch{}throw v}}const p=[];if(typeof o=="string"&&o.trim())try{const f=await J(e,o,d._id);if(Array.isArray(f))for(const m of f)m?._id&&p.push(m._id)}catch{const f=await X(e,o,d._id);f?._id&&p.push(f._id)}else if(n!=null){const f=await e.rem.createRem();if(!f)throw new Error("createRem failed");try{await f.setText(q(n))}catch(m){try{await f.remove()}catch{}throw m}try{await e.rem.moveRems([f._id],d._id,typeof s=="boolean"&&s?0:999999)}catch(m){try{await f.remove()}catch{}throw m}f?._id&&p.push(f._id)}else throw new Error("Missing content (text/markdown)");return{ok:!0,daily_id:d._id,created_ids:p}}function Je(e){return typeof e=="string"?e.trim():""}function ve(e){return typeof e=="string"?e.trim():""}function ie(e){const t=e?.parent;if(typeof t=="string")return t.trim();const n=t?._id;return typeof n=="string"?n.trim():""}function st(e){const t=e?.text;return typeof t=="string"?ve(t):Array.isArray(t)&&t.every(n=>typeof n=="string")?ve(t.join("")):""}const yr=["agent-remnote: children replace backup (auto)","agent-remnote: replace backup (auto)"],pt=50;async function hr(e){if(!e)return!1;try{if(typeof e.hasPowerup=="function"&&await e.hasPowerup(fe.code)===!0)return!0}catch{}const t=st(e);return yr.some(n=>t===n||t.startsWith(n))}async function pr(e,t){const n=[],o=[];for(const r of t)try{const i=await e.rem.findOne(r);await hr(i)?o.push(r):n.push(r)}catch{n.push(r)}return{contentChildIds:n,backupChildIds:o}}async function _r(e,t,n){const o=[...t];let r=0;for(;o.length>0;){const i=o.shift();if(i){if(r+=1,r>n)return r;try{const s=await e.rem.findOne(i),c=Me(s);for(const a of c)o.push(a)}catch{}}}return r}async function wr(e){try{if(typeof e.rem?.setHiddenExplicitlyIncludedState=="function")return await e.rem.setHiddenExplicitlyIncludedState("hidden",e.portalId),!0}catch{}return!1}async function At(e){const t=e.rem;if(!t)return;try{typeof t.addPowerup=="function"&&await t.addPowerup(fe.code)}catch{}const n=async(r,i)=>{try{typeof t.setPowerupProperty=="function"&&await t.setPowerupProperty(fe.code,r,[i])}catch{}},o=new Date().toISOString();await n("backup_kind",e.backupKind),await n("cleanup_policy",e.cleanupPolicy),await n("cleanup_state",e.cleanupState),await n("source_txn",e.op.txn_id),await n("source_op",e.op.op_id),await n("source_parent",e.sourceParentId),await n("source_anchor",e.sourceAnchorId),await n("created_at",o)}function Me(e){return Array.isArray(e?.children)?e.children.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim()):[]}async function Ze(e,t,n,o,r){const i=[];if(Array.isArray(t))for(let c=0;c<t.length;c+=1){const a=t[c],d=Je(a?._id);d&&ie(a)===o&&i.push({id:d,rem:a,index:c})}if(i.length===0)for(let c=0;c<n.length;c+=1){const a=Je(n[c]);if(a)try{const d=await e.rem.findOne(a);if(!d)continue;ie(d)===o&&i.push({id:a,rem:d,index:c})}catch{}}if(i.length===0)return[];const s=[];for(const c of i){let a;try{typeof c.rem?.positionAmongstVisibleSiblings=="function"&&(a=await c.rem.positionAmongstVisibleSiblings(r))}catch{}if(a===void 0)try{typeof c.rem?.positionAmongstSiblings=="function"&&(a=await c.rem.positionAmongstSiblings(r))}catch{}typeof a=="number"&&Number.isFinite(a)&&a>=0&&s.push({id:c.id,pos:Math.floor(a),index:c.index})}if(s.length!==i.length){const c=new Set,a=[];for(const d of i)c.has(d.id)||(c.add(d.id),a.push(d.id));return a}return s.sort((c,a)=>c.pos!==a.pos?c.pos-a.pos:c.index-a.index),s.map(c=>c.id)}function gr(e){return ve(e.title)||"Imported (bundle)"}function br(e){const t=e?.bundle;if(!t||typeof t!="object")return null;const n=t.enabled===!0,o=ve(t.title)||ve(e?.bundle_title);return!n&&!o?null:{title:o||"Imported (bundle)"}}function kr(e){if(!e||typeof e!="object")return!1;if(e.staged===!0)return!0;const t=e.staging;return!!(t===!0||t&&typeof t=="object"&&t.enabled===!0)}async function vr(e,t){const{markdown:n,parent_id:o,client_temp_id:r}=t.payload||{},i=typeof o=="string"?o.trim():"";if(!i)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const s=await X(e,String(n??""),i);if(!s)throw new Error("createSingleRemWithMarkdown returned null");const c={ok:!0};return r&&s._id&&(c.created={client_temp_id:r,remote_id:s._id,remote_type:"rem"}),c}async function Mt(e,t){const{markdown:n,parent_id:o,client_temp_ids:r,indent_mode:i,parse_mode:s,indent_size:c,prepared:a,position:d}=t.payload||{},l=typeof o=="string"?o.trim():"";if(!l)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const u=kr(t.payload||{});let p=u;const f=typeof d=="number"&&Number.isFinite(d)&&d>=0?Math.floor(d):void 0,m=typeof s=="string"?s:void 0,v=m==="ast"||m==="prepared",I={ok:!0},y=String(n??""),h=br(t.payload||{}),E=h?gr(h):"";let k=null,A=l,b=null;if(u)try{const T=await X(e,"agent-remnote: staged import (auto)",l);if(!T?._id)throw new Error("createSingleRemWithMarkdown returned null for staged import container");k=String(T._id);try{await e.rem.moveRems([k],l,1e9)}catch{}A=k}catch{if(k)try{const T=await e.rem.findOne(k);T&&await T.remove()}catch{}p=!1,k=null,A=l}const C=async()=>{if(!p||!k)return;const T=f??999999,O=await e.rem.findOne(k),w=Array.isArray(O?.children)?O.children.filter(_=>typeof _=="string"&&_.trim()).map(_=>_.trim()):[];if(w.length===0)throw new Error(`Staged import produced no root Rems (staging_rem_id=${k})`);try{await e.rem.moveRems(w,l,T)}catch(_){try{for(const R of w)try{const P=await e.rem.findOne(R);if(!P)continue;ie(P)===l&&await P.remove()}catch{}}catch{}try{const R=await e.rem.findOne(k);R&&await R.remove()}catch{}throw new Error(`Failed to move staged content to target parent: ${String(_?.message||_)} (rolled_back=true, staging_rem_id=${k})`)}try{const _=await e.rem.findOne(k);_&&await _.remove()}catch{}};if(h){try{if(b=await X(e,E,A),!b?._id)throw new Error("createSingleRemWithMarkdown returned null for bundle title");!p&&f!==void 0&&await e.rem.moveRems([b._id],l,f)}catch{if(b?._id)try{await b.remove()}catch{}if(b=await e.rem.createRem(),!b?._id)throw new Error("createRem failed for bundle title");await b.setText(q(E));try{p?await e.rem.moveRems([b._id],A,999999):await e.rem.moveRems([b._id],l,f??999999)}catch(T){try{await b.remove()}catch{}throw T}}A=String(b._id)}const M=p||h?void 0:f,L=M===void 0&&i!==!1&&!v&&m!=="raw",F=async()=>{b?._id&&(Array.isArray(I.created_ids)&&(I.bundle_inner_created_ids=I.created_ids),I.bundle={rem_id:b._id},I.created_ids=[b._id])};try{if(v&&a&&Array.isArray(a.items)){const w=a;if(w.preface&&w.preface.trim())try{await J(e,w.preface,A)}catch{}const _=[];for(const R of w.items){const P=await X(e,R.heading,A);if(P){if(Array.isArray(r)&&_.length<r.length){const B=r[_.length];B&&_.push({client_temp_id:B,remote_id:P._id,remote_type:"rem"})}if(R.body&&R.body.trim())try{await J(e,R.body,P._id)}catch{}}await ne(10)}return _.length&&(I.id_map=_),await F(),await C(),I}if(v){const w=await or(y);if(w.preface&&w.preface.trim())try{await J(e,w.preface,A)}catch{}const _=[];for(const R of w.items){const P=await X(e,R.heading,A);if(P){if(Array.isArray(r)&&_.length<r.length){const B=r[_.length];B&&_.push({client_temp_id:B,remote_id:P._id,remote_type:"rem"})}if(R.body&&R.body.trim())try{await J(e,R.body,P._id)}catch{}}await ne(10)}return _.length&&(I.id_map=_),await F(),await C(),I}if(L){const w=await dr(e,y,A,typeof c=="number"?c:2),_=Array.isArray(w)?w.filter(R=>R?._id).map(R=>String(R._id)):[];if(_.length>0){const R=await Ze(e,w,_,A);I.created_ids=R.length>0?R:_}if(Array.isArray(w)&&Array.isArray(r)){const R=[];for(let P=0;P<Math.min(w.length,r.length);P+=1){const B=w[P],V=r[P];B&&B._id&&V&&R.push({client_temp_id:V,remote_id:B._id,remote_type:"rem"})}R.length&&(I.id_map=R)}return await F(),await C(),I}const T=await J(e,y,A),O=[];if(Array.isArray(T))for(const w of T)w?._id&&O.push(w._id);if(O.length&&(I.created_ids=O),M!==void 0&&O.length>0){const w=await Ze(e,T,O,A);if(w.length===0)throw new Error("Failed to determine root Rems for moveRems");try{await e.rem.moveRems(w,A,M)}catch(_){for(const R of O)try{const P=await e.rem.findOne(R);P&&await P.remove()}catch{}throw _}}if(Array.isArray(T)&&Array.isArray(r)){const w=[];for(let _=0;_<Math.min(T.length,r.length);_+=1){const R=T[_],P=r[_];R?._id&&P&&w.push({client_temp_id:P,remote_id:R._id,remote_type:"rem"})}w.length&&(I.id_map=w)}return await F(),await C(),I}catch(T){if(b?._id&&!p)try{await b.remove()}catch{}if(p&&k)try{const O=await e.rem.findOne(k);O&&await O.remove()}catch{}throw T}}async function Sr(e,t){const{markdown:n,target:o,require_same_parent:r,require_contiguous:i,portal_id:s,assertions:c}=t.payload||{},a="none",d=String(n??""),l=d.trim().length>0,u=r!==!1,p=i!==!1,f=c===void 0?[]:Array.isArray(c)?c:null;if(f===null)return{ok:!1,fatal:!0,error:"replace_selection_with_markdown assertions must be an array of strings"};const m=f.map(g=>typeof g=="string"?g.trim():"").filter(Boolean);if(f.some(g=>typeof g!="string"||!["single-root","no-literal-bullet"].includes(g.trim())))return{ok:!1,fatal:!0,error:"replace_selection_with_markdown assertions must only include: single-root, no-literal-bullet"};const I=m.includes("single-root"),y=m.includes("no-literal-bullet"),h=typeof o?.mode=="string"?o.mode:"",E=h==="current"?"current":h==="explicit"?"explicit":"expected",k=Array.isArray(o?.rem_ids)?o.rem_ids.map(g=>typeof g=="string"?g.trim():"").filter(Boolean):[];if(E!=="current"&&k.length===0)return{ok:!1,fatal:!0,error:`${E} mode requires target.rem_ids`};let b=(typeof s=="string"?s.trim():"")||void 0;if(!b)try{const g=await e.focus.getFocusedPortal();g?._id&&(b=String(g._id))}catch{}let C=[];if(E!=="explicit")try{const g=await e.editor.getSelection();if(!g?.type||g.type!==S.SelectionType.Rem)return{ok:!1,fatal:!0,error:`Current selectionType=${g?.type??"None"}; only Rem selection is supported`};C=Array.isArray(g.remIds)?g.remIds.filter(x=>typeof x=="string"&&x.trim()).map(x=>x.trim()):[]}catch{return{ok:!1,fatal:!0,error:"Failed to read current selection"}}if(E!=="explicit"&&C.length===0)return{ok:!1,fatal:!0,error:"No Rem is selected"};if(E==="expected"&&!((g,x)=>{if(g.length!==x.length)return!1;const G=new Set(g),ee=new Set(x);if(G.size!==ee.size)return!1;for(const Vt of G)if(!ee.has(Vt))return!1;return!0})(C,k))return{ok:!1,fatal:!0,error:`Selection changed (expected=${k.length}, current=${C.length})`};const L=E==="current"?C:k,F=Array.from(new Set(L)),T=await Promise.all(F.map(g=>e.rem.findOne(g))),O=F.filter((g,x)=>!T[x]);if(O.length>0)return{ok:!1,fatal:!0,error:`Cannot access Rems (permission/deleted): ${O.slice(0,3).join(", ")}${O.length>3?"…":""}`};const w=new Set;for(const g of T){const x=g?.parent;typeof x=="string"&&x.trim()&&w.add(x.trim())}if(u&&w.size!==1)return{ok:!1,fatal:!0,error:`Selected Rems do not share the same parent (parents=${Array.from(w).length}); cannot replace in place`};const _=w.size===1?Array.from(w)[0]:"";if(!_)return{ok:!1,fatal:!0,error:"Cannot determine parentId (top-level Rems are not supported)"};const R=[];for(const g of T){let x;try{typeof g?.positionAmongstVisibleSiblings=="function"&&(x=await g.positionAmongstVisibleSiblings(b))}catch{}if(x===void 0)try{typeof g?.positionAmongstSiblings=="function"&&(x=await g.positionAmongstSiblings(b))}catch{}if(typeof x!="number"||!Number.isFinite(x)||x<0)return{ok:!1,fatal:!0,error:"Failed to compute selection position"};R.push(Math.floor(x))}const P=[];for(let g=0;g<F.length;g+=1)P.push({id:F[g],pos:R[g]});P.sort((g,x)=>g.pos-x.pos);const B=P.map(g=>g.pos),V=P.map(g=>g.id),j=B[0]??0;if(p){for(let g=0;g<B.length;g+=1)if(B[g]!==j+g)return{ok:!1,fatal:!0,error:"Selection is not contiguous (use Shift to select a contiguous block)"}}const H=[];let z=[],Re;const se=async()=>{for(const g of H)try{const x=await e.rem.findOne(g);x&&await x.remove()}catch{}};if(l){if(Re=await J(e,d,_),Array.isArray(Re))for(const g of Re)g?._id&&H.push(g._id);if(H.length===0)return{ok:!1,fatal:!0,error:"createTreeWithMarkdown returned no created Rems"};if(z=await Ze(e,Re,H,_,b),z.length===0)return await se(),{ok:!1,fatal:!0,error:"Failed to determine root Rems for moveRems"}}if(l&&I&&z.length!==1)return await se(),{ok:!1,fatal:!0,error:`Assertion failed: single-root (created_roots=${z.length})`,assertion:"single-root"};if(l&&y&&z.length===1)try{const g=await e.rem.findOne(z[0]);if(!g)throw new Error(`created Rem not found: ${z[0]}`);const x=st(g);if(/^\s*(?:[-*+]|\d+\.)\s+/.test(x))return await se(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}catch{return await se(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}if(l)try{b?await e.rem.moveRems(z,_,j,b):await e.rem.moveRems(z,_,j)}catch(g){return await se(),{ok:!1,fatal:!0,error:`Failed to move new content: ${String(g?.message||g)}`}}let $=null;try{const g=await e.rem.createSingleRemWithMarkdown("agent-remnote: replace backup (auto)",_);if(!g?._id)throw new Error("createSingleRemWithMarkdown returned null");$=String(g._id),await At({rem:g,backupKind:"selection_replace",cleanupPolicy:"auto",cleanupState:"pending",op:t,sourceParentId:_,sourceAnchorId:V[0]??""});try{b?await e.rem.moveRems([$],_,1e9,b):await e.rem.moveRems([$],_,1e9)}catch{}b?await e.rem.moveRems(V,$,0,b):await e.rem.moveRems(V,$,0)}catch(g){if(await se(),$){try{const x=[];for(const G of V)try{const ee=await e.rem.findOne(G);if(!ee)continue;ie(ee)===$&&x.push(G)}catch{}if(x.length>0)try{b?await e.rem.moveRems(x,_,j,b):await e.rem.moveRems(x,_,j)}catch{}}catch{}try{const x=await e.rem.findOne($);x&&await x.remove()}catch{}}return{ok:!1,fatal:!0,error:`Failed to move old content to backup: ${String(g?.message||g)}`,backup_policy:a}}let Ee=!1;if($)try{const g=await e.rem.findOne($);g&&await g.remove(),Ee=!0,$=null}catch{Ee=!1}if(!Ee&&$){try{await se()}catch{}let g=!1;try{b?await e.rem.moveRems(V,_,j,b):await e.rem.moveRems(V,_,j),g=!0}catch{}if(g)try{const x=[];for(const G of V)try{const ee=await e.rem.findOne(G);if(!ee)continue;ie(ee)===$&&x.push(G)}catch{}if(x.length===0){const G=await e.rem.findOne($);G&&await G.remove(),$=null}}catch{}return{ok:!1,fatal:!0,error:"Failed to delete replace backup container; rolled back to original content",rolled_back:!0,backup_rem_id:$,backup_policy:a}}return{ok:!0,target_mode:E,parent_id:_,portal_id:b??null,position:j,selection_rem_ids:F,created_ids:H,deleted_rem_ids:V,backup_deleted:Ee,backup_rem_id:$,backup_policy:a}}async function Rr(e,t){const{parent_id:n,markdown:o,indent_mode:r,indent_size:i,parse_mode:s,prepared:c,staged:a,bundle:d,backup:l,assertions:u}=t.payload||{},p=Je(n);if(!p)return{ok:!1,fatal:!0,error:"Missing parent_id"};const f=typeof l=="string"&&l.trim()==="visible"?"visible":"none",m=Array.isArray(u)?u.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean):[],v=m.includes("single-root"),I=m.includes("no-literal-bullet"),y=await e.rem.findOne(p);if(!y)return{ok:!1,fatal:!0,error:`Rem not found: ${p}`};const h=Me(y),{contentChildIds:E,backupChildIds:k}=await pr(e,h),A=[...E],b=new Set(h),C=String(o??"");let M=[],L=[];const F=async()=>{for(const w of M)try{const _=await e.rem.findOne(w);_&&await _.remove()}catch{}M=[]};if(C.trim()){const w=await Mt(e,{...t,payload:{parent_id:p,markdown:C,position:0,...typeof r=="boolean"?{indent_mode:r}:{},...typeof i=="number"?{indent_size:i}:{},...typeof s=="string"?{parse_mode:s}:{},...c!==void 0?{prepared:c}:{},...a===!0?{staged:!0}:{},...d&&typeof d=="object"?{bundle:d}:{}}});if(M=Array.isArray(w?.created_ids)?w.created_ids.filter(_=>typeof _=="string"&&_.trim()).map(_=>_.trim()):[],M.length===0)try{const _=await e.rem.findOne(p);M=Me(_).filter(R=>!b.has(R))}catch{}try{const _=await e.rem.findOne(p);L=Me(_).filter(R=>!b.has(R))}catch{}}if(C.trim()){if(v&&L.length!==1)return await F(),{ok:!1,fatal:!0,error:`Assertion failed: single-root (created_roots=${L.length})`,assertion:"single-root"};if(I&&L.length===1)try{const w=await e.rem.findOne(L[0]);if(!w)throw new Error(`created Rem not found: ${L[0]}`);const _=st(w);if(/^\s*(?:[-*+]|\d+\.)\s+/.test(_))return await F(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}catch{return await F(),{ok:!1,fatal:!0,error:"Assertion failed: no-literal-bullet",assertion:"no-literal-bullet"}}}if(A.length===0)return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:[],ignored_backup_rem_ids:k,backup_deleted:!0,backup_rem_id:null,backup_policy:f};let T=null;try{const w=await e.rem.createSingleRemWithMarkdown("agent-remnote: children replace backup (auto)",p);if(!w?._id)throw new Error("createSingleRemWithMarkdown returned null");T=String(w._id),await At({rem:w,backupKind:"children_replace",cleanupPolicy:f==="visible"?"visible":"auto",cleanupState:f==="visible"?"retained":"pending",op:t,sourceParentId:p,sourceAnchorId:p});try{await e.rem.moveRems([T],p,1e9)}catch{}await e.rem.moveRems(A,T,0)}catch(w){if(await F(),T){try{const _=[];for(const R of A)try{const P=await e.rem.findOne(R);P&&ie(P)===T&&_.push(R)}catch{}if(_.length>0)try{await e.rem.moveRems(_,p,0)}catch{}}catch{}try{const _=[];for(const R of A)try{const P=await e.rem.findOne(R);P&&ie(P)===T&&_.push(R)}catch{}if(_.length===0){const R=await e.rem.findOne(T);R&&await R.remove()}}catch{}}return{ok:!1,fatal:!0,error:`Failed to move old children to backup: ${String(w?.message||w)}`,backup_rem_id:T,backup_policy:f}}if(f==="visible")return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:A,ignored_backup_rem_ids:k,backup_deleted:!1,backup_rem_id:T,backup_policy:f};let O=!1;if(T&&f==="none"&&await _r(e,[T],pt)>pt){const _=await e.rem.findOne(T),R=await wr({rem:_});return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:A,ignored_backup_rem_ids:k,backup_deleted:!1,backup_rem_id:T,backup_policy:f,backup_hidden:R,backup_cleanup_state:"pending"}}if(T)try{const w=await e.rem.findOne(T);w&&await w.remove(),O=!0,T=null}catch{O=!1}if(!O&&T){await F();let w=!1;try{await e.rem.moveRems(A,p,0),w=!0}catch{}if(w)try{const _=[];for(const R of A)try{const P=await e.rem.findOne(R);P&&ie(P)===T&&_.push(R)}catch{}if(_.length===0){const R=await e.rem.findOne(T);R&&await R.remove(),T=null}}catch{}return{ok:!1,fatal:!0,error:"Failed to delete children replace backup; rolled back to original content",rolled_back:!0,backup_rem_id:T,backup_policy:f}}return{ok:!0,parent_id:p,created_ids:M,deleted_rem_ids:A,ignored_backup_rem_ids:k,backup_deleted:O,backup_rem_id:T,backup_policy:f}}const Er=100,Tr=3e3,Ir=150;function ze(e,t){const n=typeof e=="number"?e:Number(e);return!Number.isFinite(n)||n<=0?t:Math.floor(n)}function Ar(e){return Array.isArray(e?.children)?e.children.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim()):[]}async function Mr(e,t,n,o){const r=Date.now()+n;for(;;){if(!await e.rem.findOne(t))return!0;if(Date.now()>=r)return!1;await ne(o)}}async function Pr(e,t){const n=[t],o=new Set,r=new Map;for(;n.length>0;){const i=n.shift();if(!i||o.has(i))continue;o.add(i);const s=await e.rem.findOne(i);if(!s)continue;const c=Ar(s);r.set(i,{id:i,childIds:c});for(const a of c)n.push(a)}return r}function xr(e,t){if(t<=0||e.length===0)return new Set;const n=new Array(t+1).fill(!1),o=new Array(t+1).fill(-1),r=new Array(t+1).fill(-1);n[0]=!0;for(let a=0;a<e.length;a+=1){const d=e[a];for(let l=t;l>=d;l-=1)!n[l]&&n[l-d]&&(n[l]=!0,o[l]=l-d,r[l]=a)}let i=t;for(;i>0&&!n[i];)i-=1;const s=new Set;let c=i;for(;c>0;){const a=r[c];if(a<0)break;s.add(a),c=o[c]}return s}function Cr(e,t,n){const o=r=>{const i=e.get(r);if(!i)return{deleteRootIds:[],residualRootId:r,residualSize:1,nodeCount:1};const s=i.childIds.map(u=>o(u)),c=[];let a=1;for(const u of s)c.push(...u.deleteRootIds),a+=u.nodeCount;const d=xr(s.map(u=>u.residualSize),Math.max(0,n-1));let l=1;for(let u=0;u<s.length;u+=1){const p=s[u];d.has(u)?l+=p.residualSize:c.push(p.residualRootId)}return{deleteRootIds:c,residualRootId:r,residualSize:l,nodeCount:a}};return o(t)}async function Or(e,t,n,o){const r=await e.rem.findOne(t);return r?(await r.remove(),Mr(e,t,n,o)):!0}async function Lr(e,t,n={}){const o=ze(n.maxDeleteSubtreeNodes,Er),r=ze(n.verifyTimeoutMs,Tr),i=ze(n.verifyPollMs,Ir);if(!await e.rem.findOne(t))return{existed:!1,deleted:!0,mode:"direct",nodeCount:0,batchCount:0};const c=await Pr(e,t),a=Cr(c,t,o),d=[...a.deleteRootIds,a.residualRootId],l=d.length===1?"direct":"bottom_up";for(const u of d)if(!await Or(e,u,r,i))return{existed:!0,deleted:!1,mode:l,nodeCount:a.nodeCount,batchCount:d.length,failedRemId:u};return{existed:!0,deleted:!0,mode:l,nodeCount:a.nodeCount,batchCount:d.length}}function Nr(e){const t=e?.max_delete_subtree_nodes,n=typeof t=="number"?t:Number(t);if(!(!Number.isFinite(n)||n<=0))return Math.floor(n)}async function Pt(e,t,n){const{rem_id:o}=t.payload||{},r=typeof o=="string"?o.trim():"";if(!r)return{ok:!1,fatal:!0,error:"Missing rem_id"};const i=Nr(t.payload),s=await Lr(e,r,{maxDeleteSubtreeNodes:i??100});return s.deleted?{ok:!0,...n.includeRemIdInSuccess?{rem_id:r}:{},deleted:!0,existed:s.existed,delete_mode:s.mode,node_count:s.nodeCount,batch_count:s.batchCount}:{ok:!1,fatal:!0,error:`Failed to verify ${n.errorContext}; Rem still exists: ${s.failedRemId??r}`,rem_id:r}}async function Dr(e,t){const{parent_id:n,text:o,tags:r,is_document:i,standalone:s,client_temp_id:c,position:a}=t.payload||{},d=typeof n=="string"?n.trim():"";if(!d&&!(s===!0))throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const u=await e.rem.createRem();if(!u)throw new Error("createRem returned null");const p=async()=>{try{await u.remove()}catch{}};try{const m=typeof a=="number"&&Number.isFinite(a)&&a>=0?Math.floor(a):0;if(d&&await e.rem.moveRems([u._id],d,m),i===!0&&typeof u.setIsDocument=="function"&&await u.setIsDocument(!0),o!==void 0&&await u.setText(q(o)),Array.isArray(r)&&r.length>0)for(const v of r)await u.addTag(v)}catch(m){throw await p(),m}const f={ok:!0};return c&&u._id&&(f.created={client_temp_id:c,remote_id:u._id,remote_type:"rem"}),f}async function Fr(e,t){const{url:n,add_title:o,client_temp_id:r,parent_id:i}=t.payload||{},s=typeof i=="string"?i.trim():"";if(!s)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const c=await e.rem.createLinkRem(String(n??""),o!==!1);if(!c)throw new Error("createLinkRem returned null");try{await e.rem.moveRems([c._id],s,0)}catch(d){try{await c.remove()}catch{}throw d}const a={ok:!0};return r&&c._id&&(a.created={client_temp_id:r,remote_id:c._id,remote_type:"rem"}),a}async function $r(e,t){const{rem_id:n,text:o}=t.payload||{};if(!n)throw new Error("Missing rem_id");const r=await e.rem.findOne(n);if(!r)throw new Error(`Rem not found: ${n}`);return await r.setText(q(o)),{ok:!0}}async function Wr(e,t){const{rem_id:n,new_parent_id:o,position:r,standalone:i,is_document:s,leave_portal:c}=t.payload||{},a=typeof n=="string"?n.trim():"",d=typeof o=="string"?o.trim():"",l=i===!0;if(!a)throw new Error("Missing rem_id");if(!l&&!d)throw new Error("Missing new_parent_id");const u=await e.rem.findOne(a);if(!u)throw new Error(`Rem not found: ${a}`);const p=typeof u.parent=="string"?String(u.parent).trim():"";let f=0;try{if(typeof u.positionAmongstSiblings=="function"){const y=await u.positionAmongstSiblings();typeof y=="number"&&Number.isFinite(y)&&y>=0&&(f=Math.floor(y))}}catch(y){console.warn("[agent-remnote][move] failed to get source position",{error:y})}if(l)if(typeof u.setParent=="function")await u.setParent(null);else throw new Error("Standalone move requires Rem.setParent(null) support");else await e.rem.moveRems([a],d,typeof r=="number"?r:0);s===!0&&typeof u.setIsDocument=="function"&&await u.setIsDocument(!0);const m=[],v=[];let I;if(c===!0)if(!p)m.push("Move succeeded, but leave-portal could not determine the source parent"),v.push(`agent-remnote --json portal create --parent <sourceParentId> --target ${a}`);else{const y=await e.rem.createPortal().catch(h=>(m.push(`Move succeeded, but leave-portal failed: ${String(h?.message||h)}`),null));if(y?._id)try{if(await e.rem.moveRems([y._id],p,f),typeof u.addToPortal!="function")throw new Error("addToPortal not available in SDK");await u.addToPortal(y._id),I=y._id}catch(h){try{await y.remove()}catch{}m.push(`Move succeeded, but leave-portal failed: ${String(h?.message||h)}`),v.push(`agent-remnote --json portal create --parent ${p} --target ${a}`)}}return{ok:!0,rem_id:a,...l?{standalone:!0}:{new_parent_id:d},...c===!0?{leave_portal:!0,portal_created:!!I}:{},...p?{source_parent_id:p}:{},...I?{portal_id:I}:{},...m.length>0?{warnings:m}:{},...v.length>0?{nextActions:v}:{}}}async function Br(e,t){const{rem_ids:n,new_parent_id:o,position:r,is_document:i}=t.payload||{},s=Array.isArray(n)?n.filter(d=>typeof d=="string"&&d.trim().length>0):[],c=typeof o=="string"?o.trim():"";if(s.length===0)throw new Error("Missing rem_ids");if(!c)throw new Error("Missing new_parent_id");const a=typeof r=="number"&&Number.isFinite(r)?Math.floor(r):0;for(let d=0;d<s.length;d+=1){const l=s[d];await e.rem.moveRems([l],c,a+d)}if(i===!0)for(const d of s){const l=await e.rem.findOne(d);if(!l)throw new Error(`Rem not found: ${d}`);typeof l.setIsDocument=="function"&&await l.setIsDocument(!0)}return{ok:!0,rem_ids:s,new_parent_id:c,moved_count:s.length,...i===!0?{is_document:!0}:{}}}async function Ur(e,t){return Pt(e,t,{errorContext:"rem deletion",includeRemIdInSuccess:!1})}async function qr(e,t){return Pt(e,t,{errorContext:"backup deletion",includeRemIdInSuccess:!0})}function De(e){return typeof e=="string"?e.trim():""}function xt(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<0))return Math.floor(e)}const Ct=1e9;async function Ot(e){const t=De(e.parentId);if(!t)throw new Error("Missing parent_id (refusing to create a Portal without a parent)");const n=De(e.targetRemId);if(!n)throw new Error("Missing target_rem_id (or rem_id) for portal target");const o=await e.plugin.rem.createPortal();if(!o?._id)throw new Error("createPortal returned null");const r=async()=>{try{await o.remove()}catch{}};try{const c=xt(e.position)??Ct;await e.plugin.rem.moveRems([o._id],t,c)}catch(c){throw await r(),c}const i=await e.plugin.rem.findOne(n);if(!i)throw await r(),new Error(`Target Rem not found: ${n}`);try{if(typeof i.addToPortal!="function")throw new Error("addToPortal not available in SDK");await i.addToPortal(o._id)}catch(c){throw await r(),c}const s={ok:!0,portal_id:o._id,target_rem_id:n,parent_id:t};return e.clientTempId&&o._id&&(s.created={client_temp_id:e.clientTempId,remote_id:o._id,remote_type:"rem"}),s}async function Vr(e,t){const{parent_id:n,target_rem_id:o,rem_id:r,position:i,client_temp_id:s}=t.payload||{};return await Ot({plugin:e,parentId:n,targetRemId:o??r,position:i,clientTempId:s})}async function zr(e,t){const{parent_id:n,items:o}=t.payload||{},r=De(n);if(!r)throw new Error("Missing parent_id (refusing to create a Portal without a parent)");const i=Array.isArray(o)?o.filter(d=>d&&typeof d=="object").map(d=>d):[];if(i.length===0)throw new Error("Missing items");const s=new Array(i.length),c=i.every(d=>xt(d.position)===void 0),a=i.map((d,l)=>({item:d,index:l}));for(const d of a){const{item:l,index:u}=d,p=De(l.target_rem_id??l.rem_id),f=await Ot({plugin:e,parentId:r,targetRemId:p,position:c?Ct:l.position??u,clientTempId:l.client_temp_id});s[u]={target_rem_id:p,portal_id:String(f.portal_id)}}return{ok:!0,parent_id:r,created_count:s.length,item_results:s}}function Pe(e,t){if(!t||typeof t!="object")return null;const{Query:n,TextMatcher:o,NumberMatcher:r,DateMatcher:i,SingleSelectMatcher:s,MultiSelectMatcher:c,CheckboxMatcher:a}=e||{};if(!n)return null;switch(t.op){case"and":{const d=Array.isArray(t.exprs)?t.exprs.map(l=>Pe(e,l)).filter(Boolean):[];return n.and(d)}case"or":{const d=Array.isArray(t.exprs)?t.exprs.map(l=>Pe(e,l)).filter(Boolean):[];return n.or(d)}case"not":{const d=Pe(e,t.expr);return n.not(d)}case"column_text_contains":return t.column_id?n.tableColumn(t.column_id,n.text(o.Contains,String(t.value??""))):null;case"column_text_prefix":return t.column_id?n.tableColumn(t.column_id,n.text(o.Prefix,String(t.value??""))):null;case"column_text_suffix":return t.column_id?n.tableColumn(t.column_id,n.text(o.Suffix,String(t.value??""))):null;case"column_text_phrase":return t.column_id?n.tableColumn(t.column_id,n.text(o.Phrase,String(t.value??""))):null;case"column_number":{if(!t.column_id||typeof n.number!="function")return null;const d=r[t.matcher]??r.Equals,l=t.value??(typeof t.min=="number"&&typeof t.max=="number"?[t.min,t.max]:void 0);return n.tableColumn(t.column_id,n.number(d,l))}case"column_date":{if(!t.column_id||typeof n.date!="function")return null;const d=i[t.matcher]??i.Equals;let l=t.value;if(d===i.Between||d===i.IsBetween)if(t.from&&t.to)l={from:t.from,to:t.to};else return null;return n.tableColumn(t.column_id,n.date(d,l))}case"column_single_select_in":{if(!t.column_id||typeof n.singleSelect!="function")return null;const d=s?.In??s?.Equals??void 0;return n.tableColumn(t.column_id,n.singleSelect(d,Array.isArray(t.option_ids)?t.option_ids:[t.option_ids]))}case"column_multi_select_contains_any":{if(!t.column_id||typeof n.multiSelect!="function")return null;const d=c?.ContainsAny??c?.Contains??void 0;return n.tableColumn(t.column_id,n.multiSelect(d,Array.isArray(t.option_ids)?t.option_ids:[t.option_ids]))}case"column_multi_select_contains_all":{if(!t.column_id||typeof n.multiSelect!="function")return null;const d=c?.ContainsAll??c?.Contains??void 0;return n.tableColumn(t.column_id,n.multiSelect(d,Array.isArray(t.option_ids)?t.option_ids:[t.option_ids]))}case"column_checkbox_equals":{if(!t.column_id||typeof n.checkbox!="function")return null;const d=a?.Equals??a?.Is??void 0;return n.tableColumn(t.column_id,n.checkbox(d,!!t.value))}default:return null}}async function ct(e,t){const n=typeof t=="string"?t.trim():"";if(n){try{const o=await e.rem.findOne(n);if(o)return o}catch(o){console.warn("[agent-remnote][tableOps] findOne failed",{remId:n,error:String(o?.message||o)})}try{const o=await e.rem.findMany([n]);if(Array.isArray(o)){const r=o.find(i=>i?._id===n);if(r)return r}}catch(o){console.warn("[agent-remnote][tableOps] findMany failed",{remId:n,error:String(o?.message||o)})}}}function Lt(e){return new Error(`Property type mutation is unsupported by the current RemNote plugin runtime: public rem.setPropertyType() is unavailable, and host endpoints rem.setPropertyType/rem.setSlotType are not exposed for ${String(e??"unknown-property")}`)}async function Gr(e,t){const{tag_id:n,client_temp_id:o,parent_id:r,position:i}=t.payload||{},s=typeof r=="string"?r.trim():"";if(!s)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");const c=await e.rem.createTable(n);if(!c)throw new Error("createTable returned null");try{const d=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):0;await e.rem.moveRems([c._id],s,d)}catch(d){try{await c.remove()}catch{}throw d}const a={ok:!0};return o&&c._id&&(a.created={client_temp_id:o,remote_id:c._id,remote_type:"rem"}),a}async function Yr(e,t){const{tag_id:n,name:o,property_id:r,type:i,options:s}=t.payload||{},c=await e.rem.findOne(n);if(!c)throw new Error("tag_rem not found");const a=await e.rem.createRem();if(!a)throw new Error("createRem returned null");try{if(await we(e,a,c._id,0),await a.setText(q(o??"Property")),a.setIsProperty&&await a.setIsProperty(!0),i)if(typeof a.setPropertyType=="function")await a.setPropertyType(i);else throw Lt(a?._id??r);if(Array.isArray(s)&&s.length>0)for(const l of s){const u=await e.rem.createRem();if(!u)throw new Error("createRem returned null");await we(e,u,a._id,0),await u.setText(q(l))}}catch(l){try{await a.remove()}catch{}throw l}const d={ok:!0};return r&&a._id&&(d.created={client_temp_id:r,remote_id:a._id,remote_type:"property"}),d}async function jr(e,t){const{property_id:n,type:o}=t.payload||{},r=await ct(e,n);if(!r)throw new Error("property rem not found");if(typeof r.setPropertyType=="function")return await r.setPropertyType(o),{ok:!0};throw Lt(n??r._id)}async function Kr(e,t){const{table_id:n,column_id:o,contains_text:r,expr:i}=t.payload||{},s=await e.rem.findOne(n);if(!s)throw new Error("table rem not found");if(typeof s.setTableFilter!="function")return{ok:!1};const c=await be(()=>import("./index-CTg2hlbS.js").then(I=>I.i),[],import.meta.url),a=c.Query,d=c.TextMatcher,l=c.NumberMatcher,u=c.DateMatcher,p=c.SingleSelectMatcher,f=c.MultiSelectMatcher,m=c.CheckboxMatcher;let v=null;if(i)v=Pe({Query:a,TextMatcher:d,NumberMatcher:l,DateMatcher:u,SingleSelectMatcher:p,MultiSelectMatcher:f,CheckboxMatcher:m},i);else if(o&&r){if(!a||!d)return{ok:!1};v=a.tableColumn(o,a.text(d.Contains,String(r)))}return v?(await s.setTableFilter(v),{ok:!0}):{ok:!1}}async function Xr(e,t){const{property_id:n,text:o,option_id:r}=t.payload||{},i=await ct(e,n);if(!i)throw new Error("property rem not found");const s=await e.rem.createRem();if(!s)throw new Error("createRem returned null");try{await we(e,s,i._id,0),await s.setText(q(o))}catch(a){try{await s.remove()}catch{}throw a}const c={ok:!0};return r&&s._id&&(c.created={client_temp_id:r,remote_id:s._id,remote_type:"option"}),c}async function Hr(e,t){const{option_id:n}=t.payload||{},o=await ct(e,n);return o?(await o.remove(),{ok:!0}):{ok:!0}}async function Qr(e,t){const{table_tag_id:n,rem_id:o,text:r,parent_id:i,client_temp_id:s,values:c,extra_tags:a}=t.payload||{};let d=o?await e.rem.findOne(o):void 0;const l=!d;if(!d){if(d=await e.rem.createRem(),!d)throw new Error("createRem returned null");const f=typeof i=="string"?i.trim():"";if(!f)throw new Error("Missing parent_id (refusing to create a Rem without a parent)");try{await we(e,d,f,0),r!==void 0&&await d.setText(q(r))}catch(m){try{await d.remove()}catch{}throw m}}const u=async()=>{if(l)try{await d.remove()}catch{}};try{if(await d.addTag(n),Array.isArray(a))for(const f of a)await d.addTag(f);if(Array.isArray(c))for(const f of c)await d.setTagPropertyValue(f.property_id,q(f.value))}catch(f){throw await u(),f}const p={ok:!0};return!o&&s&&d?._id&&(p.created={client_temp_id:s,remote_id:d._id,remote_type:"row"}),p}async function Jr(e,t){const{table_tag_id:n,rem_id:o,remove_properties:r}=t.payload||{},i=await e.rem.findOne(o);return i?(await i.removeTag(n,!!r),{ok:!0}):{ok:!0}}async function Zr(e,t){const{rem_id:n,property_id:o,option_ids:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");const c=(Array.isArray(r)?r:[r]).filter(Boolean).map(a=>({i:"q",_id:a}));return await i.setTagPropertyValue(o,c),{ok:!0}}async function en(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");return await i.setTagPropertyValue(o,[{i:"m",text:r?"Yes":"No"}]),{ok:!0}}async function tn(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");return await i.setTagPropertyValue(o,[{i:"m",text:String(r)}]),{ok:!0}}async function rn(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{},i=await e.rem.findOne(n);if(!i)throw new Error("Rem not found");let s=null;if(typeof r=="string"||typeof r=="number"){const a=new Date(r);isNaN(a.getTime())||(s=a)}else if(r&&typeof r=="object"&&r.year&&r.month&&r.day){const a=new Date(r.year,r.month-1,r.day);isNaN(a.getTime())||(s=a)}if(!s)throw new Error("Invalid date");const c=await e.date.getDailyDoc(s);if(!c?._id)throw new Error("Daily document not found for that date. Please open it in RemNote first.");return await i.setTagPropertyValue(o,[{i:"q",_id:c._id}]),{ok:!0}}async function nn(e,t){const{rem_id:n,tag_id:o}=t.payload||{};if(!n||!o)throw new Error("Missing rem_id/tag_id");const r=await e.rem.findOne(n);if(!r)throw new Error(`Rem not found: ${n}`);return await r.addTag(o),{ok:!0}}async function on(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.tag_id;if(!i||!s)throw new Error("Missing rem_id/tag_id");const c=await e.rem.findOne(i);if(!c)throw new Error(`Rem not found: ${i}`);await c.addTag(s),o.push({rem_id:i,tag_id:s})}return{ok:!0,item_results:o,changed_count:o.length}}async function an(e,t){const{rem_id:n,tag_id:o,remove_properties:r}=t.payload||{};if(!n||!o)throw new Error("Missing rem_id/tag_id");const i=await e.rem.findOne(n);if(!i)throw new Error(`Rem not found: ${n}`);return await i.removeTag(o,!!r),{ok:!0}}async function sn(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[],o=!!t.payload?.remove_properties;if(n.length===0)throw new Error("Missing items");const r=[];for(const i of n){const s=i?.rem_id,c=i?.tag_id;if(!s||!c)throw new Error("Missing rem_id/tag_id");const a=await e.rem.findOne(s);if(!a)throw new Error(`Rem not found: ${s}`);await a.removeTag(c,o),r.push({rem_id:s,tag_id:c})}return{ok:!0,item_results:r,changed_count:r.length,...o?{remove_properties:!0}:{}}}async function cn(e,t){const{rem_id:n,property_id:o,value:r}=t.payload||{};if(!n||!o)throw new Error("Missing rem_id/property_id");const i=await e.rem.findOne(n);if(!i)throw new Error(`Rem not found: ${n}`);return await i.setTagPropertyValue(o,q(r)),{ok:!0}}async function dn(e,t){const{rem_id:n,source_id:o}=t.payload||{},r=await e.rem.findOne(n);if(!r)throw new Error("Rem not found");return await r.addSource(o),{ok:!0}}async function ln(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.source_id,c=await e.rem.findOne(i);if(!c)throw new Error("Rem not found");await c.addSource(s),o.push({rem_id:i,source_id:s})}return{ok:!0,item_results:o,changed_count:o.length}}async function un(e,t){const{rem_id:n,source_id:o}=t.payload||{},r=await e.rem.findOne(n);if(!r)throw new Error("Rem not found");return await r.removeSource(o),{ok:!0}}async function fn(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.source_id,c=await e.rem.findOne(i);if(!c)throw new Error("Rem not found");await c.removeSource(s),o.push({rem_id:i,source_id:s})}return{ok:!0,item_results:o,changed_count:o.length}}async function mn(e,t){const{rem_id:n,status:o}=t.payload||{},r=await e.rem.findOne(n);if(!r)throw new Error("Rem not found");return typeof r.setTodoStatus=="function"?(await r.setTodoStatus(o),{ok:!0}):{ok:!1}}async function yn(e,t){const n=Array.isArray(t.payload?.items)?t.payload.items:[];if(n.length===0)throw new Error("Missing items");const o=[];for(const r of n){const i=r?.rem_id,s=r?.status,c=await e.rem.findOne(i);if(!c)throw new Error("Rem not found");if(typeof c.setTodoStatus=="function"){await c.setTodoStatus(s),o.push({rem_id:i,status:s});continue}return{ok:!1}}return{ok:!0,item_results:o,changed_count:o.length}}const Nt=new Set,Ge=new Set,Dt=new Map;function hn(e,t){e.idempotency_key&&t&&t.ok&&(Nt.add(e.idempotency_key),Dt.set(e.idempotency_key,t))}async function pn(e,t){const n=t.idempotency_key?String(t.idempotency_key):"";try{if(n&&Nt.has(n)){const i=Dt.get(n);return i&&typeof i=="object"?{...i,dedup:!0}:{ok:!0,dedup:!0}}if(n&&Ge.has(n))return{ok:!1,fatal:!1,error:"idempotency_key is in-flight; retry later"};n&&Ge.add(n);const o=vt(t.op_type);let r;switch(o){case"daily_note_write":r=await mr(e,t);break;case"create_rem":r=await Dr(e,t);break;case"create_portal":r=await Vr(e,t);break;case"create_portal_bulk":r=await zr(e,t);break;case"create_single_rem_with_markdown":r=await vr(e,t);break;case"create_tree_with_markdown":r=await Mt(e,t);break;case"replace_selection_with_markdown":r=await Sr(e,t);break;case"replace_children_with_markdown":r=await Rr(e,t);break;case"create_link_rem":r=await Fr(e,t);break;case"create_table":r=await Gr(e,t);break;case"add_property":r=await Yr(e,t);break;case"set_property_type":r=await jr(e,t);break;case"set_table_filter":r=await Kr(e,t);break;case"add_option":r=await Xr(e,t);break;case"remove_option":r=await Hr(e,t);break;case"table_add_row":r=await Qr(e,t);break;case"table_remove_row":r=await Jr(e,t);break;case"set_cell_select":r=await Zr(e,t);break;case"set_cell_checkbox":r=await en(e,t);break;case"set_cell_number":r=await tn(e,t);break;case"set_cell_date":r=await rn(e,t);break;case"update_text":r=await $r(e,t);break;case"move_rem":r=await Wr(e,t);break;case"move_rem_bulk":r=await Br(e,t);break;case"add_tag":r=await nn(e,t);break;case"add_tag_bulk":r=await on(e,t);break;case"remove_tag":r=await an(e,t);break;case"remove_tag_bulk":r=await sn(e,t);break;case"set_attribute":case"table_cell_write":r=await cn(e,t);break;case"add_source":r=await dn(e,t);break;case"add_source_bulk":r=await ln(e,t);break;case"remove_source":r=await un(e,t);break;case"remove_source_bulk":r=await fn(e,t);break;case"set_todo_status":r=await mn(e,t);break;case"set_todo_status_bulk":r=await yn(e,t);break;case"delete_rem":r=await Ur(e,t);break;case"delete_backup_artifact":r=await qr(e,t);break;default:r={ok:!1,error:`unknown op_type: ${t.op_type}`,fatal:!0};break}return hn(t,r),r}catch(o){const r=String(o?.message||o);return await e.app.toast(`Execution failed: ${r}`),{ok:!1,error:r,fatal:!0}}finally{n&&Ge.delete(n)}}function D(e){return typeof e=="string"?e.trim():""}function _n(e){const t=e?.parent;if(typeof t=="string")return t.trim();const n=t?._id;return typeof n=="string"?n.trim():""}class wn{constructor(){Ue(this,"locked",new Set);Ue(this,"waiters",[])}acquire(t){const n=Array.from(new Set(t.map(i=>String(i||"").trim()).filter(Boolean))).sort();if(n.length===0)return Promise.resolve(()=>{});const r=(()=>{for(const i of n)if(this.locked.has(i))return null;for(const i of n)this.locked.add(i);return()=>{for(const i of n)this.locked.delete(i);this.drain()}})();return r?Promise.resolve(r):new Promise(i=>{this.waiters.push({keys:n,resolve:i}),this.drain()})}drain(){if(this.waiters.length===0)return;const t=new Set;for(let n=0;n<this.waiters.length;n+=1){const o=this.waiters[n],r=o.keys.some(s=>t.has(s)),i=o.keys.every(s=>!this.locked.has(s));if(!r&&i){for(const s of o.keys)this.locked.add(s);this.waiters.splice(n,1),n-=1,o.resolve(()=>{for(const s of o.keys)this.locked.delete(s);this.drain()});continue}for(const s of o.keys)t.add(s)}}}function gn(e){return`rem:${e}`}function bn(e){return`children:${e}`}async function Te(e,t){try{const n=await e.rem.findOne(t);return(n?_n(n):"")||void 0}catch{return}}async function kn(e,t){const n=vt(t.op_type),o=t.payload||{},r=[],i=a=>{const d=String(a||"").trim();d&&r.push(d)},s=a=>{a&&i(gn(a))},c=a=>{a&&i(bn(a))};switch(n){case"create_rem":case"create_portal":case"create_link_rem":case"create_table":case"create_single_rem_with_markdown":case"create_tree_with_markdown":{const a=D(o.parent_id);if(s(a),c(a),n==="create_portal"){const d=D(o.target_rem_id??o.rem_id);s(d)}return r}case"create_portal_bulk":{const a=D(o.parent_id);s(a),c(a);const d=Array.isArray(o.items)?o.items:[];for(const l of d){const u=D(l?.target_rem_id??l?.rem_id);s(u)}return r}case"replace_selection_with_markdown":{const a=o?.target?.rem_ids,d=Array.isArray(a)?a.map(u=>D(u)).filter(Boolean):[];if(d.length===0)return["global:replace_selection_with_markdown"];for(const u of d)s(u);const l=d.length>0?await Te(e,d[0]):void 0;return s(l),c(l),r}case"replace_children_with_markdown":{const a=D(o.parent_id);if(!a)return["global:replace_children_with_markdown"];s(a),c(a);try{const d=await e.rem.findOne(a),l=Array.isArray(d?.children)?d.children.filter(u=>typeof u=="string"&&u.trim()).map(u=>u.trim()):[];for(const u of l)s(u)}catch{}return r}case"update_text":case"add_tag":case"remove_tag":case"set_attribute":case"table_cell_write":case"add_source":case"remove_source":case"set_todo_status":case"set_cell_select":case"set_cell_checkbox":case"set_cell_number":case"set_cell_date":{const a=D(o.rem_id);return s(a),r}case"add_tag_bulk":case"remove_tag_bulk":{const a=Array.isArray(o.items)?o.items:[];for(const d of a){const l=D(d?.rem_id);s(l)}return r}case"set_todo_status_bulk":{const a=Array.isArray(o.items)?o.items:[];for(const d of a){const l=D(d?.rem_id);s(l)}return r}case"add_source_bulk":case"remove_source_bulk":{const a=Array.isArray(o.items)?o.items:[];for(const d of a){const l=D(d?.rem_id);s(l)}return r}case"set_table_filter":{const a=D(o.table_id);return s(a),r}case"add_property":{const a=D(o.tag_id);return s(a),c(a),r}case"set_property_type":{const a=D(o.property_id);return s(a),r}case"add_option":{const a=D(o.property_id);return s(a),c(a),r}case"remove_option":{const a=D(o.option_id);return s(a),r}case"table_add_row":{const a=D(o.rem_id);if(a)return s(a),r;const d=D(o.parent_id);return s(d),c(d),r}case"table_remove_row":{const a=D(o.rem_id);return s(a),r}case"move_rem":{const a=D(o.rem_id),d=D(o.new_parent_id);s(a),s(d),c(d);const l=a?await Te(e,a):void 0;return s(l),c(l),r}case"move_rem_bulk":{const a=Array.isArray(o.rem_ids)?o.rem_ids.map(l=>D(l)).filter(l=>l.length>0):[],d=D(o.new_parent_id);for(const l of a)s(l);s(d),c(d);for(const l of a){const u=l?await Te(e,l):void 0;s(u),c(u)}return r}case"delete_rem":case"delete_backup_artifact":{const a=D(o.rem_id);s(a);const d=a?await Te(e,a):void 0;return s(d),c(d),r}case"daily_note_write":return["global:daily_note_write"];default:return["global:unknown_op"]}}var _t={name:"@remnote/plugin",version:"0.0.2",build_id:"0.0.2:1774922238299",built_at:1774923294946,source_stamp:1774922238299,mode:"dist"};const vn=typeof _t>"u"?void 0:_t,Ft=vn??{name:"@remnote/plugin",version:"0.0.0",build_id:"0.0.0:unknown",built_at:0,source_stamp:0,mode:"unknown"};let N=null,Q=null,Z=null,de=!1,Y=null,Sn=0,ue=0,et=0,W=null,ge=!1,tt=0,xe=0,rt=!1,Ce=!1,Oe=!1,Fe=null,me=null,oe=null,nt=!1,Le=!1,Ne=!1,Ye=null,$e=null;const Rn=!0;let U=null;const je="agent-remnote.selection-forwarder",Ke={editor:`${je}.editor`,focusedRem:`${je}.focused-rem`,focusedPortal:`${je}.focused-portal`},ce="agent-remnote.ui-context-forwarder",te={url:`${ce}.url`,openRem:`${ce}.open-rem`,focusedPane:`${ce}.focused-pane`,windowTree:`${ce}.window-tree`,focusedRem:`${ce}.focused-rem`,focusedPortal:`${ce}.focused-portal`,selection:`${ce}.selection`},$t=8,Wt=12e4,En=512e3,Tn=256e3,In=250,An=2e3,Mn=5,Pn=new Set(["PROTOCOL_MISMATCH","INVALID_MESSAGE","UNSUPPORTED_CLIENT","UNSUPPORTED_VERSION"]),xn=2e4,Cn=3e4,On=new wn;function Ln(e){return e?!Pn.has(e):!0}function Nn(e){const t=Math.max(1,Math.floor(e)),n=In*Math.pow(2,Math.max(0,t-1));return Math.min(An,n)}function Dn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(16,Math.floor(e)):$t}function Fn(e){return 0}const ye=new Map,ae=new Map,wt=new WeakSet;let he=null;const $n=1500,Wn=600,Bn=5e3,pe=new Map,gt=new WeakSet;function Un(){if(he){try{clearTimeout(he)}catch{}he=null}for(const e of ae.values()){try{clearTimeout(e.timer)}catch{}try{e.resolve(null)}catch{}}ae.clear(),ye.clear(),pe.clear()}function Bt(){try{qt()}catch{}try{ut()}catch{}if(Y){try{clearTimeout(Y)}catch{}Y=null}if(Z){try{clearTimeout(Z)}catch{}Z=null}de=!1,ue=0,et=0,Un()}function Be(e,t){return`${e}:${t}`}function qn(e){const t=new Map;for(const o of e){const r=t.get(o.ws)??[];r.push(o.payload),t.set(o.ws,r)}const n=[];for(const[o,r]of t.entries()){if(r.length<=1){n.push({ws:o,payload:r[0]??null});continue}n.push({ws:o,payload:{type:"OpAckBatch",items:r}})}return n}function Vn(e){gt.has(e)||(gt.add(e),e.addEventListener("message",t=>{let n;try{n=JSON.parse(String(t?.data))}catch{return}if(n?.type!=="LeaseExtendRejected"&&n?.type!=="LeaseExtendOk")return;const o=typeof n?.op_id=="string"?n.op_id:typeof n?.opId=="string"?n.opId:"",r=typeof n?.attempt_id=="string"?n.attempt_id:typeof n?.attemptId=="string"?n.attemptId:"";if(!o||!r)return;const i=Be(o,r);if(n.type==="LeaseExtendRejected"){if(pe.has(i))return;const s=typeof n?.reason=="string"?n.reason:"rejected";pe.set(i,{reason:s,at:Date.now()});try{console.warn("[agent-remnote][lease] rejected",{opId:o,attemptId:r,reason:s,current:n?.current})}catch{}}else pe.delete(i)}))}function zn(e,t,n){Vn(e);const o=Be(t,n);let r=!1,i=null;const s=()=>{if(!r){if(pe.has(o)){r=!0;return}try{le(e,{type:"LeaseExtend",op_id:t,attempt_id:n,extendMs:Wt})}catch{}i=setTimeout(s,Cn)}};return i=setTimeout(s,xn),()=>{if(r=!0,pe.delete(o),i)try{clearTimeout(i)}catch{}}}function dt(e){if(wt.has(e))return;wt.add(e);const t=n=>{if(n?.type!=="AckOk"&&n?.type!=="AckRejected")return;const o=typeof n?.op_id=="string"?n.op_id:typeof n?.opId=="string"?n.opId:"",r=typeof n?.attempt_id=="string"?n.attempt_id:typeof n?.attemptId=="string"?n.attemptId:"";if(!o||!r)return;const i=Be(o,r);ye.delete(i);const s=ae.get(i);if(s){ae.delete(i);try{clearTimeout(s.timer)}catch{}s.resolve(n)}if(n.type==="AckRejected")try{console.warn("[agent-remnote][ack] rejected",{opId:o,attemptId:r,reason:n?.reason,current:n?.current})}catch{}};e.addEventListener("message",n=>{let o;try{o=JSON.parse(String(n?.data))}catch{return}if(o?.type==="AckBatch"&&Array.isArray(o?.items)){for(const r of o.items)t(r);return}t(o)})}function ot(){he||(he=setTimeout(()=>{he=null,Gn()},0))}function Gn(){const e=Date.now(),t=[];for(const o of ye.values()){if(!o.ws||o.ws.readyState!==WebSocket.OPEN){ye.delete(o.key);continue}e<o.nextRetryAt||t.push(o)}const n=qn(t.map(o=>({ws:o.ws,payload:o.payload})));for(const o of n)try{le(o.ws,o.payload)}catch{}for(const o of t){o.retries+=1;const r=Math.min(Bn,Wn+o.retries*500);o.nextRetryAt=e+r}ye.size>0&&ot()}function Yn(e,t){return new Promise(n=>{const o=ae.get(e);if(o){try{clearTimeout(o.timer)}catch{}ae.delete(e)}const r=setTimeout(()=>{ae.delete(e),n(null)},Math.max(1,t));ae.set(e,{resolve:n,timer:r})})}async function Xe(e,t,n=$n){const o=typeof t?.op_id=="string"?t.op_id:"",r=typeof t?.attempt_id=="string"?t.attempt_id:"";if(!o||!r)return"timeout";dt(e);const i=Be(o,r);ye.set(i,{key:i,op_id:o,attempt_id:r,ws:e,payload:t,retries:0,nextRetryAt:Date.now()});const s=Yn(i,n);ot();const c=await s;return c?c.type==="AckOk"?"ok":"rejected":(ot(),"timeout")}const jn=18e4,Kn=12e4;function Ie(e,t,n,o){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(n,Math.min(o,Math.floor(r))):t}function Xn(e){const t=String(e||"").trim();if(!t)return[];const n=t.replace(/[^\p{L}\p{N}]+/gu," ").split(/\s+/).map(r=>r.trim()).filter(Boolean),o=[];for(const r of n){const i=r.toLowerCase();if(!(i.length<2)&&!o.includes(i)&&(o.push(i),o.length>=8))break}return o}function Hn(e,t,n){const o=String(e||"").replace(/\s+/g," ").trim();if(o.length<=n)return{text:o,truncated:!1};const r=Xn(t),i=o.toLowerCase();let s=-1;for(const u of r){const p=i.indexOf(u);p<0||(s<0||p<s)&&(s=p)}let c=0;s>=0&&(c=Math.max(0,s-Math.floor(n/3)));let a=c+n;a>o.length&&(a=o.length,c=Math.max(0,a-n));const d=o.slice(c,a).trim(),l=c>0||a<o.length;return{text:d,truncated:l}}function Qn(e,t){return new Promise((n,o)=>{const r=setTimeout(()=>o(new Error("timeout")),t);e.then(i=>{clearTimeout(r),n(i)},i=>{clearTimeout(r),o(i)})})}async function Jn(e,t,n){const o=Date.now(),r=typeof n?.requestId=="string"?n.requestId.trim():"";if(!r)return;const i=typeof n?.queryText=="string"?n.queryText:"",s=typeof n?.searchContextRemId=="string"?n.searchContextRemId.trim():"",c=200,a=Ie(n?.limit,20,1,1e4),d=Ie(a,20,1,100),l=d!==a,u=Ie(n?.timeoutMs,3e3,1,6e4),p=Ie(u,3e3,1,5e3),f={timeoutMs:p,limitRequested:a,limitEffective:d,limitClamped:l,maxPreviewChars:c,durationMs:0},m=v=>{try{t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(v))}catch{}};if(!i.trim())return m({type:"SearchResponse",requestId:r,ok:!1,budget:{...f,durationMs:Date.now()-o},error:{code:"VALIDATION_ERROR",message:"queryText must not be empty"}});try{const v=await e.richText.parseFromMarkdown(i),I=await Qn(e.search.search(v,s||void 0,{numResults:d}),p),y=[];for(const h of I.slice(0,d)){const E=String(h?._id||"").trim();if(!E)continue;let k="";try{k=String(await e.richText.toString(h?.text??[]))}catch{}let A="";try{h?.backText&&(A=String(await e.richText.toString(h.backText)))}catch{}A.trim()||(A=k);const b=Hn(A,i,c);y.push({remId:E,title:k.trim(),snippet:b.text,truncated:b.truncated})}return m({type:"SearchResponse",requestId:r,ok:!0,budget:{...f,durationMs:Date.now()-o},results:y})}catch(v){const I=String(v?.message||v||"search failed"),y=I.toLowerCase().includes("timeout")?"TIMEOUT":"PLUGIN_ERROR";return m({type:"SearchResponse",requestId:r,ok:!1,budget:{...f,durationMs:Date.now()-o},error:{code:y,message:I},nextActions:["Retry later","Check that the plugin is connected and responsive",'Fallback to DB search: agent-remnote read search --query "<keywords>"']})}}function We(){me&&(clearTimeout(me),me=null)}function Ut(e){me||(me=setTimeout(()=>{me=null,ge&&(!N||N.readyState!==WebSocket.OPEN||(_e(e,{force:!1}),Ut(e)))},500))}function Zn(e){rt=!0;try{const r=oe?.editor;r&&e.event.removeListener(S.AppEvents.EditorSelectionChanged,void 0,r)}catch{}try{const r=oe?.focusedRem;r&&e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,r)}catch{}try{const r=oe?.focusedPortal;r&&e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,r)}catch{}try{e.event.removeListener(S.AppEvents.EditorSelectionChanged,Ke.editor)}catch{}try{e.event.removeListener(S.AppEvents.FocusedRemChange,Ke.focusedRem)}catch{}try{e.event.removeListener(S.AppEvents.FocusedPortalChange,Ke.focusedPortal)}catch{}const t=()=>{_e(e,{force:!1})},n=()=>{_e(e,{force:!1})},o=()=>{_e(e,{force:!1})};oe={editor:t,focusedRem:n,focusedPortal:o},e.event.addListener(S.AppEvents.EditorSelectionChanged,void 0,t),e.event.addListener(S.AppEvents.FocusedRemChange,void 0,n),e.event.addListener(S.AppEvents.FocusedPortalChange,void 0,o)}function eo(e){if(rt){rt=!1,Ce=!1,Oe=!1,Fe=null,We();try{const t=oe?.editor;e.event.removeListener(S.AppEvents.EditorSelectionChanged,void 0,t)}catch{}try{const t=oe?.focusedRem;e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,t)}catch{}try{const t=oe?.focusedPortal;e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,t)}catch{}oe=null}}function to(e){nt=!0;try{const c=U?.url;c&&e.event.removeListener(S.AppEvents.URLChange,void 0,c)}catch{}try{const c=U?.openRem;c&&e.event.removeListener(S.AppEvents.GlobalOpenRem,void 0,c)}catch{}try{const c=U?.focusedPane;c&&e.event.removeListener(S.AppEvents.FocusedPaneChange,void 0,c)}catch{}try{const c=U?.windowTree;c&&e.event.removeListener(S.AppEvents.CurrentWindowTreeChange,void 0,c)}catch{}try{const c=U?.focusedRem;c&&e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,c)}catch{}try{const c=U?.focusedPortal;c&&e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,c)}catch{}try{e.event.removeListener(S.AppEvents.URLChange,te.url)}catch{}try{e.event.removeListener(S.AppEvents.GlobalOpenRem,te.openRem)}catch{}try{e.event.removeListener(S.AppEvents.FocusedPaneChange,te.focusedPane)}catch{}try{e.event.removeListener(S.AppEvents.CurrentWindowTreeChange,te.windowTree)}catch{}try{e.event.removeListener(S.AppEvents.FocusedRemChange,te.focusedRem)}catch{}try{e.event.removeListener(S.AppEvents.FocusedPortalChange,te.focusedPortal)}catch{}try{e.event.removeListener(S.AppEvents.EditorSelectionChanged,te.selection)}catch{}const t=()=>void re(e,{force:!1,source:"event:URLChange"}),n=()=>void re(e,{force:!1,source:"event:GlobalOpenRem"}),o=()=>void re(e,{force:!1,source:"event:FocusedPaneChange"}),r=()=>void re(e,{force:!1,source:"event:CurrentWindowTreeChange"}),i=()=>void re(e,{force:!1,source:"event:FocusedRemChange"}),s=()=>void re(e,{force:!1,source:"event:FocusedPortalChange"});U={url:t,openRem:n,focusedPane:o,windowTree:r,focusedRem:i,focusedPortal:s},e.event.addListener(S.AppEvents.URLChange,void 0,t),e.event.addListener(S.AppEvents.GlobalOpenRem,void 0,n),e.event.addListener(S.AppEvents.FocusedPaneChange,void 0,o),e.event.addListener(S.AppEvents.CurrentWindowTreeChange,void 0,r),e.event.addListener(S.AppEvents.FocusedRemChange,void 0,i),e.event.addListener(S.AppEvents.FocusedPortalChange,void 0,s)}function ro(e){if(nt){nt=!1,Le=!1,Ne=!1,$e=null;try{const t=U?.url;e.event.removeListener(S.AppEvents.URLChange,void 0,t)}catch{}try{const t=U?.openRem;e.event.removeListener(S.AppEvents.GlobalOpenRem,void 0,t)}catch{}try{const t=U?.focusedPane;e.event.removeListener(S.AppEvents.FocusedPaneChange,void 0,t)}catch{}try{const t=U?.windowTree;e.event.removeListener(S.AppEvents.CurrentWindowTreeChange,void 0,t)}catch{}try{const t=U?.focusedRem;e.event.removeListener(S.AppEvents.FocusedRemChange,void 0,t)}catch{}try{const t=U?.focusedPortal;e.event.removeListener(S.AppEvents.FocusedPortalChange,void 0,t)}catch{}try{e.event.removeListener(S.AppEvents.EditorSelectionChanged,te.selection)}catch{}U=null}}async function _e(e,t){if(Ce){Oe=!0;return}Ce=!0;try{const n=N;if(!n||n.readyState!==WebSocket.OPEN)return;const o=await no(e);let r=o.kind,i=r==="rem"?S.SelectionType.Rem:r==="text"?S.SelectionType.Text:void 0,s=0,c=!1,a=[],d="",l,u=!1;if(o.kind==="rem"){a=o.remIds,s=a.length;const f=200;c=s>f,c&&(a=a.slice(0,f)),s<=0&&(r="none",i=void 0)}else o.kind==="text"&&(d=o.remId,l=o.range,u=o.isReverse,s=1);if(r==="rem"&&a.length>0&&!c){let f="";try{const m=await e.focus.getFocusedRem();m?._id&&(f=String(m._id).trim())}catch{}f&&!a.includes(f)&&(r="none",i=void 0,s=0,c=!1,a=[])}if(r==="text"&&d){let f="";try{const m=await e.focus.getFocusedRem();m?._id&&(f=String(m._id).trim())}catch{}f&&f!==d&&(r="none",i=void 0,s=0,c=!1,d="",l=void 0,u=!1)}const p=r==="rem"?`rem:${s}:${c?"1":"0"}:${a.join(",")}`:r==="text"?`text:${d}:${l?.start??""}-${l?.end??""}:${u?"1":"0"}`:"none";if(!t.force&&Fe===p)return;Fe=p;try{n.send(JSON.stringify({type:"SelectionChanged",kind:r,selectionType:i,remIds:a,totalCount:s,truncated:c,remId:d,range:l,isReverse:u,ts:Date.now()}))}catch{}}finally{Ce=!1,Oe&&(Oe=!1,_e(e,{force:!1}))}}async function no(e){try{const t=await e.editor.getSelection();if(!t?.type)return{kind:"none"};if(t.type===S.SelectionType.Rem)return{kind:"rem",remIds:Array.isArray(t.remIds)?t.remIds.filter(o=>typeof o=="string"&&o.trim()):[]};if(t.type===S.SelectionType.Text){const n=typeof t.remId=="string"?t.remId.trim():"",o=t?.range?.start,r=t?.range?.end,i=typeof o=="number"&&Number.isFinite(o)?Math.floor(o):NaN,s=typeof r=="number"&&Number.isFinite(r)?Math.floor(r):NaN,c=t?.isReverse===!0;return n?!Number.isFinite(i)||!Number.isFinite(s)?{kind:"none"}:i===s?{kind:"none"}:{kind:"text",remId:n,range:{start:i,end:s},isReverse:c}:{kind:"none"}}return{kind:"none"}}catch{return{kind:"none"}}}async function oo(e){let t="";try{t=await e.window.getURL()||""}catch{}let n="";try{n=await e.window.getFocusedPaneId()||""}catch{}let o="";try{o=await e.window.getOpenPaneRemId(n)||""}catch{}let r="";try{const a=await e.focus.getFocusedRem();a?._id&&(r=String(a._id))}catch{}let i="";try{const a=await e.focus.getFocusedPortal();a?._id&&(i=String(a._id))}catch{}let s="",c="";try{const d=new URL(t).pathname.split("/").filter(Boolean);d.length>=2&&d[0]==="w"&&(s=String(d[1]||""))}catch{}if(!s)try{const a=await e.kb?.getCurrentKnowledgeBaseData?.();a?._id&&(s=String(a._id)),a?.name&&(c=String(a.name))}catch{}return{url:t,paneId:n,pageRemId:o,focusedRemId:r,focusedPortalId:i,kbId:s,kbName:c}}async function re(e,t){if(Le){Ne=!0,Ye=t.source;return}Le=!0;try{const n=N;if(!n||n.readyState!==WebSocket.OPEN)return;const o=await oo(e),r=`${o.url}|${o.paneId}|${o.pageRemId}|${o.focusedRemId}|${o.focusedPortalId}|${o.kbId}`;if(!t.force&&$e===r)return;$e=r;try{n.send(JSON.stringify({type:"UiContextChanged",...o,source:t.source,ts:Date.now()}))}catch{}if(Rn)try{console.log("[agent-remnote][ui-context]",{...o,source:t.source})}catch{}}finally{if(Le=!1,Ne){const n=Ye||"pending";Ne=!1,Ye=null,re(e,{force:!1,source:n})}}}function ao(e){const o=Math.min(Math.max(e,0),10),r=Math.min(3e4,500*Math.pow(2,o)),i=r*.2;return Math.max(0,Math.round(r+(Math.random()*2-1)*i))}function qt(){ge=!1,Q&&(clearTimeout(Q),Q=null),Z&&(clearTimeout(Z),Z=null),We(),tt+=1,xe=0;const e=N;N=null;try{e&&e.readyState!==WebSocket.CLOSED&&e.close()}catch{}}function lt(e,t,n){if(ge=!0,N&&(N.readyState===WebSocket.OPEN||N.readyState===WebSocket.CONNECTING))return;Q&&(clearTimeout(Q),Q=null);const o=tt+=1,r=new WebSocket(t);N=r;const i=()=>N===r&&tt===o,s=setTimeout(()=>{if(i()&&r.readyState===WebSocket.CONNECTING)try{r.close()}catch{}},8e3);r.onopen=async()=>{if(i()){clearTimeout(s),xe=0;try{if(r.send(JSON.stringify({type:"Hello"})),r.send(JSON.stringify({type:"Register",protocolVersion:2,clientType:"remnote-plugin",clientInstanceId:n,runtime:Ft,capabilities:{control:!0,worker:!0,readRpc:!0,batchPull:!0}})),Fe=null,_e(e,{force:!0}),$e=null,re(e,{force:!0,source:"connect"}),Ut(e),await e.app.toast("Control channel connected"),await e.settings.getSetting(K.autoSyncOnConnect))try{await Se(e,t,n,{silent:!0})}catch(d){try{console.warn("[agent-remnote][control] auto-sync on connect failed",{message:String(d?.message||d||"unknown error")})}catch{}}}catch{}}},r.onmessage=async a=>{if(i())try{const d=JSON.parse(String(a.data));if(d?.type==="StartSync"){try{await Se(e,t,n,{silent:!0})}catch(l){try{console.warn("[agent-remnote][control] StartSync failed",{message:String(l?.message||l||"unknown error")})}catch{}}return}if(d?.type==="SearchRequest"){Jn(e,r,d);return}}catch{}};const c=()=>{if(!ge||!i()||Q)return;const a=ao(xe);xe+=1,Q=setTimeout(()=>{Q=null,lt(e,t,n)},a)};r.onclose=()=>{clearTimeout(s),i()&&(We(),c(),N=null)},r.onerror=()=>{clearTimeout(s),We(),c()}}async function io(e,t=!0){return t&&N&&N.readyState===WebSocket.OPEN?N:(W&&W.readyState===WebSocket.OPEN||(W=await bt(e),W.onclose=()=>{W&&W.readyState!==WebSocket.OPEN&&(W=null)},dt(W)),W)}async function so(e,t){const n=Math.max(1,Math.min(50,Math.floor(t)));le(e,{type:"RequestOps",leaseMs:Wt,maxOps:n,maxBytes:En,maxOpBytes:Tn});const o=await Xt(e);if(!o||o.type==="NoWork")return{kind:"no_work"};if(o.type==="Error"){const r=typeof o?.code=="string"?o.code:"",i=typeof o?.message=="string"?o.message:"";if(r==="OP_PAYLOAD_TOO_LARGE")try{le(e,{type:"TriggerStartSync"})}catch{}try{console.warn("[agent-remnote][ws] RequestOps error",{code:r,message:i,details:o?.details,nextActions:o?.nextActions})}catch{}return{kind:"error",code:r,message:i,retryable:Ln(r)}}if(o.type==="OpDispatchBatch"){const r=o;return{kind:"ops",ops:Array.isArray(r.ops)?r.ops:[]}}if(o.type==="OpDispatch"){const r=o;if(r?.op_id&&r?.attempt_id)return{kind:"ops",ops:[{op_id:String(r.op_id),attempt_id:String(r.attempt_id),txn_id:String(r.txn_id??""),op_seq:Number(r.op_seq??0),op_type:String(r.op_type??""),payload:r.payload??null,idempotency_key:r.idempotency_key??null,lease_expires_at:typeof r.lease_expires_at=="number"?r.lease_expires_at:void 0}]}}return{kind:"no_work"}}async function Se(e,t,n,o){const r=Date.now();if(o?.silent&&et>r)return;if(de){o?.silent||await e.app.toast("A sync is already running");return}de=!0;const i=Sn+=1;ue=i,Y&&(clearTimeout(Y),Y=null),Y=setTimeout(()=>{if(de&&ue===i){ue=0,de=!1,et=Date.now()+Kn,Y=null;try{ut()}catch{}try{N&&N.readyState!==WebSocket.CLOSED&&N.close()}catch{}try{e.app.toast("Sync watchdog tripped; please retry")}catch{}}},jn),o?.silent||await e.app.toast("Starting sync…");let s=0;try{const c=await io(t,!0);dt(c);const a=c===N;try{le(c,{type:"Hello"})}catch{}try{le(c,{type:"Register",protocolVersion:2,clientType:"remnote-plugin",clientInstanceId:n,runtime:Ft,capabilities:{control:a,worker:!0,readRpc:!0,batchPull:!0}})}catch{}let d=$t;try{const m=await e.settings.getSetting(K.syncConcurrency);d=Dn(m)}catch{}const l=new Map;let u=!1;const p=async m=>{let v,I;try{const y=await kn(e,m);v=await On.acquire(y),I=zn(c,m.op_id,m.attempt_id);const h=await pn(e,m);if(h&&h.ok)await Xe(c,{type:"OpAck",op_id:m.op_id,attempt_id:m.attempt_id,status:"success",result:h});else{const E=h&&h.fatal||!1,k=h&&h.error||"executor error";await Xe(c,{type:"OpAck",op_id:m.op_id,attempt_id:m.attempt_id,status:E?"failed":"retry",error_code:"EXEC_ERROR",error_message:k})}}catch(y){const h=String(y?.message||y);await Xe(c,{type:"OpAck",op_id:m.op_id,attempt_id:m.attempt_id,status:"retry",error_code:"EXEC_ERROR",error_message:h})}finally{try{I?.()}catch{}try{v?.()}catch{}s+=1,Fn(s)>0}};let f=0;for(;;){for(;!u&&l.size<d;){const m=d-l.size,v=await so(c,m);if(v.kind==="error"){if(f+=1,v.retryable&&f<=Mn){const h=Nn(f);try{console.warn("[agent-remnote][ws] RequestOps transient error; retrying",{code:v.code,message:v.message,streak:f,delayMs:h})}catch{}await ne(h);continue}try{console.warn("[agent-remnote][ws] RequestOps error; stopping pull loop",{code:v.code,message:v.message,streak:f,retryable:v.retryable})}catch{}u=!0;break}if(f=0,v.kind==="no_work"){u=!0;break}const I=v.ops;if(I.length===0){u=!0;break}for(const y of I){const h={type:"OpDispatch",...y},E=p(h).catch(()=>{}).finally(()=>{l.delete(h.op_id)});l.set(h.op_id,E)}}if(u&&l.size===0)break;l.size>0&&await Promise.race(l.values())}if(c!==N){try{c.close()}catch{}W===c&&(W=null)}o?.silent||await e.app.toast("Sync finished (or no work)")}finally{if(!(ue===i))return;de=!1,ue=0,Y&&(clearTimeout(Y),Y=null);try{const a=await e.settings.getSetting(K.autoSyncOnConnect);s>0&&a&&ge&&N&&N.readyState===WebSocket.OPEN&&(Z||(Z=setTimeout(()=>{Z=null,ge&&(!N||N.readyState!==WebSocket.OPEN||de||Se(e,t,n,{silent:!0}))},1500)))}catch{}}}function ut(){try{W&&W.readyState!==WebSocket.CLOSED&&W.close()}catch{}W=null}async function co(e){try{await e.app.registerCommand({id:"start-sync-ops",name:"Start sync",action:async()=>{const t=await Ae(e),n=await He(e);try{await Se(e,t,n,{silent:!1})}catch(o){await e.app.toast(`Failed to start sync: ${o?.message||o}`)}}})}catch{}try{await e.app.registerCommand({id:"show-queue-stats",name:"Show queue stats",action:async()=>{const t=await Ae(e);try{const n=await Ht(t);await e.app.toast(`Pending: ${n.pending} | In-flight: ${n.in_flight} | Dead: ${n.dead}`)}catch(n){await e.app.toast(`Query failed: ${n?.message||n}`)}}})}catch{}try{await e.app.registerCommand({id:"connect-control",name:"Connect control channel",action:async()=>{const t=await Ae(e),n=await He(e);lt(e,t,n)}})}catch{}try{await e.app.registerCommand({id:"disconnect-control",name:"Disconnect control channel",action:async()=>{try{qt(),ut(),await e.app.toast("Control channel disconnected")}catch(t){await e.app.toast(`Disconnect failed: ${t?.message||t}`)}}})}catch{}}async function fo(e){try{Bt()}catch{}try{const t=globalThis;t.__REMNOTE_BRIDGE_REGISTERED__=!0}catch{}try{await er(e)}catch{}try{await jt(e)}catch{}try{Zn(e)}catch{}try{to(e)}catch{}try{await co(e)}catch{}try{const t=await e.settings.getSetting(K.autoConnectControl),n=await e.settings.getSetting(K.autoSyncOnConnect),o=await Ae(e),r=await He(e);if(t)lt(e,o,r);else if(n)try{await Se(e,o,r,{silent:!1})}catch{}}catch{}}async function mo(e){try{eo(e)}catch{}try{ro(e)}catch{}try{Bt()}catch{}try{const t=globalThis;delete t.__REMNOTE_BRIDGE_REGISTERED__}catch{}}export{mo as a,fo as o};