agent-remnote 1.3.0 → 1.3.3

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