@reviseio/engine 3.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/chunks/{AgentHtmlConverter-BnK7NaYA.js → AgentHtmlConverter-CnnB8-WI.js} +3 -3
  3. package/chunks/{AgentPageRenderer-DLwq6nAa.js → AgentPageRenderer-DLgUGrGy.js} +4 -4
  4. package/chunks/{BlockDiff-BdlcKY-t.js → BlockDiff-B6-aJxHo.js} +1 -1
  5. package/chunks/{CanvasRenderer-Bqsj1S0p.js → CanvasRenderer-C1Vegx9Y.js} +2 -2
  6. package/chunks/{DocumentCompare-BqyiP87r.js → DocumentCompare-C8295s35.js} +1 -1
  7. package/chunks/{DocumentLayoutEngine-7iOYvyVb.js → DocumentLayoutEngine-C62pyGVf.js} +3 -3
  8. package/chunks/{DocumentMutator-DIrZBuLr.js → DocumentMutator-Bat_oLBQ.js} +2 -2
  9. package/chunks/{DocumentScrubber-Cz8Q05hF.js → DocumentScrubber-BZQn_z92.js} +1 -1
  10. package/chunks/{DocumentSession-lXSXqua5.js → DocumentSession-BDcazSEv.js} +1 -1
  11. package/chunks/{DocxConverter-BfDw7777.js → DocxConverter-BC31uYIL.js} +3 -3
  12. package/chunks/{DocxGraft-D0uCnGCo.js → DocxGraft-L10HXM3U.js} +2 -2
  13. package/chunks/{HtmlConverter-7Xj_g9Jr.js → HtmlConverter-C5ihhZ6G.js} +3 -3
  14. package/chunks/{MarkdownConverter-cnW_oePY.js → MarkdownConverter-DofaSeC4.js} +1 -1
  15. package/chunks/{OdtConverter-GwRDMnwS.js → OdtConverter-c1fTWoAt.js} +1 -1
  16. package/chunks/{OfficeImportShared-nlMtIUni.js → OfficeImportShared-CrOpHpJ-.js} +1 -1
  17. package/chunks/{PdfConverter-yOlWiVIj.js → PdfConverter-DX7fsRH5.js} +5 -5
  18. package/chunks/{RtfConverter--wLd0qrw.js → RtfConverter-hbJ2529G.js} +66 -66
  19. package/chunks/{TableBorders-C5pNsuxP.js → TableBorders-DVhdvo6f.js} +1 -1
  20. package/chunks/TextDecoding-IPbuUqcC.js +2 -0
  21. package/chunks/TextFileDecoder-BZBBejlR.js +10 -0
  22. package/chunks/{TxtConverter-BoRVCDZw.js → TxtConverter-YHv5FXWb.js} +1 -1
  23. package/chunks/{Typography-DAGM5kfI.js → Typography-B4gndEdB.js} +1 -1
  24. package/chunks/XmlConverter-BRRluy9k.js +55 -0
  25. package/chunks/{capture-Dtinb4bY.js → capture-i_dPkQIS.js} +1 -1
  26. package/chunks/{carrier-RNy67HN4.js → carrier-pYM9xf6x.js} +1 -1
  27. package/chunks/{chromeImageLayout-bgHYmqTp.js → chromeImageLayout-BiQ3Iz1-.js} +1 -1
  28. package/chunks/{engine-TnK8N-gT.js → engine-LMUnxdm2.js} +18 -18
  29. package/chunks/{footnoteFlatten-BcKaWzVs.js → footnoteFlatten-EE85Hjre.js} +1 -1
  30. package/chunks/{graftExport-DxAALMHp.js → graftExport-G-dG7Vcc.js} +1 -1
  31. package/chunks/{index-CTti7wRd.js → index-BLb10wQt.js} +3 -3
  32. package/chunks/{serverDocumentSession-BmYdjC6e.js → serverDocumentSession-DGDU5Lh3.js} +5 -5
  33. package/chunks/{signatures-CU2LMLBp.js → signatures-DTNDS2PH.js} +1 -1
  34. package/engine.js +1 -1
  35. package/package.json +2 -2
  36. package/chunks/TextFileDecoder--rsVs3NR.js +0 -9
  37. package/chunks/XmlConverter-CO8Z28dX.js +0 -55
@@ -1,8 +1,8 @@
1
- import{n as hl,q as us,r as Ae,P as Gt,s as Po,u as In,v as hs,w as fl,y as mt,x as It,D as fs,z as pl,A as et,a as G,B as ml,C as rt,E as ot,F as st,G as lt,H as de,I as Z,J as We,K as at,L as ct,M as ps,N as Jt,O as Ht,Q as bl,R as ms,e as bs,S as yl,T as ys,U as qt,V as Je,W as ks,X as kl,Y as Sl,Z as Il,_ as vn,$ as xn,a0 as vl,a1 as xl,a2 as wl,a3 as Qt,a4 as Al,a5 as Ss,a6 as Is,a7 as vs,a8 as xs,a9 as Tl,aa as ws,ab as Cl,ac as Pl,ad as As,g as gt,ae as Mo,af as ge,ag as Te,ah as wn,ai as Ce,aj as Bo,ak as An,al as Tn,am as Ml,an as Zt,ao as Bl,b as El,d as Eo,ap as Ts,aq as Cs,f as Ps,ar as Ms,as as Nl,i as Ll,at as Fl,au as Ol,av as No,aw as Rl,ax as Dl,ay as $l,az as jl,aA as Yt,aB as _l,aC as Lo,aD as Xl,aE as Ul,aF as zl,aG as Bs,aH as Wl,aI as Jl,aJ as Hl,aK as ql,aL as Yl,aM as Kl,aN as Es}from"./engine-TnK8N-gT.js";import{f as W,h as Cn,t as He,k as Ct,a as xt,i as Xt,l as Ns,m as Fo,n as Oo,g as ue,o as Ls,c as Pe,p as Ro,q as Vl,r as Gl,s as Ql}from"./CanvasRenderer-Bqsj1S0p.js";import{d as Do,S as St,f as Pn,b as Fs,c as qe,A as it,e as Zl,m as $o,g as tc,h as Me,i as ec,n as nc,j as Be,s as Os,k as jo,l as oc,o as rc}from"./AgentHtmlConverter-BnK7NaYA.js";import*as I from"yjs";import{b as Mn}from"./TableGrid-DbroRucl.js";import{j as Pt,i as Bn}from"./signatures-CU2LMLBp.js";import{w as sc,r as ic,a as En}from"./ParagraphDiffAnalysis-DrmStvmz.js";import{MarkdownConverter as Nn}from"./MarkdownConverter-cnW_oePY.js";import{s as Ye,a as _o,b as Xo,c as Rs}from"./DocumentStylesheet-CEEt18sr.js";import{a as Ds,g as ac}from"./BidiText-Bkp4Y90s.js";import{C as $s,a as js,b as _s,H as Ln,h as Ke,n as lc}from"./Typography-DAGM5kfI.js";import{a as Xs,s as Us,b as cc,n as zs}from"./TableBorders-C5pNsuxP.js";import{d as dc,a as te}from"./index-CTti7wRd.js";import{R as Nt,A as Ws}from"./suggestionAuthorship-B-IuLQlE.js";import{d as gc,p as uc}from"./chromeImageLayout-bgHYmqTp.js";function hc(s){const t=s.children.filter(e=>e.type==="text");return t.length===0?[{type:"text",text:""}]:t}function Fn(s){return hc(s).reduce((t,e)=>t+e.text.length,0)}function fc(s,t){const e=W(s,t);if(!e||!e.id)return null;if(e.type==="paragraph"){let n=0;for(const o of e.children)o.type==="text"&&(n+=o.text.length);return{block:e.id,offset:n}}if(e.type==="list"){const n=e;let o=0;for(let r=0;r<n.children.length;r++)o+=Fn(n.children[r]),r<n.children.length-1&&(o+=1);return{block:e.id,offset:o}}return{block:e.id,offset:0}}function kt(s){if(!s||typeof s!="object")return"";const t=s;if(t.type==="text"&&typeof t.text=="string")return t.text;if((t.type==="code"||t.type==="math")&&typeof t.content=="string")return t.content;if(Array.isArray(t.children)){const e=t.type==="list"?" ":"";return t.children.map(n=>kt(n)).join(e)}return""}const Js={P:"paragraph",LI:"list-item",TD:"table-cell",TH:"table-cell",TR:"table-row",TABLE:"table",UL:"list",OL:"list",H1:"paragraph",H2:"paragraph",H3:"paragraph",H4:"paragraph",H5:"paragraph",H6:"paragraph"};function Hs(s,t){if(!/<[^>]+\bid\s*=/i.test(t))return null;const e=kt(s);if(e.includes(t)||e.includes(Do(t)))return null;const n=document.createElement("template");n.innerHTML=t;const o=[...n.content.querySelectorAll("[id]")].filter(c=>Js[c.tagName]);if(!o.length)return null;const r=new Map,i=(c,d=null)=>{if(!c||typeof c!="object")return;const g=c;g.id&&(d?d.add(g.id):r.set(g.id,[...r.get(g.id)??[],g])),g.children?.forEach(u=>i(u,d))};i(s);const a=new Set,l=new Set;for(const c of o){const d=r.get(c.id)??[];if(a.has(c.id)||d.length!==1||d[0].type!==Js[c.tagName])throw new St("target_stale",`HTML matcher id '${c.id}' is missing, contradictory, or outside the authorized target. Read the target again.`,"target_resolution");a.add(c.id);const g=d[0],u=kt(g),f=c.textContent??"",h=Pn(u,f,"prefer-exact");if(u!==f&&!h.some(y=>y.start===0&&y.end===u.length))throw new St("target_stale",`HTML matcher text for '${c.id}' no longer matches that block. Read it again before editing.`,"matching");const p=new Set;i(g,p);const m=o.filter(y=>y!==c&&c.contains(y));if(m.some(y=>!p.has(y.id)))throw new St("target_stale",`HTML matcher ids contradict the document hierarchy inside '${c.id}'.`,"target_resolution");m.length||p.forEach(y=>l.add(y))}return l}function Ee(s,t){const e=W(s,t);return e?.type==="list"&&e.id!==t?e.children.find(n=>n.id===t)??null:e}function Uo(s){if(!(!s||s.type!=="paragraph"&&s.type!=="list-item"))return it.toAgentHtml({type:"doc",children:[{...s,type:"paragraph"}]})}function On(s,t,e="prefer-exact"){const n=Hs(s,t),o=Fs(kt(s),t,e,qe(t)?Uo(s):void 0);if(!n)return o;const r=qs(s);return o.filter(i=>{const a=r.filter(l=>l.start<i.end&&i.start<l.end);return a.length>0&&a.every(l=>n.has(l.blockId))})}function qs(s){const t=[];let e=0;const n=o=>{if(!o||typeof o!="object")return;const r=o,i=Array.isArray(r.children)?r.children:[],a=r.type==="list"||r.type==="table"||r.type==="table-row"||r.type==="table-cell"||r.type==="container";if(r.id&&!a){const l=kt(o);if(l.length>0){t.push({blockId:r.id,start:e,end:e+l.length,text:l}),e+=l.length;return}}i.forEach((l,c)=>{r.type==="list"&&c>0&&(e+=1),n(l)})};return n(s),t}function pc(s,t,e){const n=[];for(const o of s){const r=Math.max(t,o.start),i=Math.min(e,o.end);i<=r||n.push({blockId:o.blockId,start:r-o.start,end:i-o.start})}return n}function Ys(s){const t=new Map;let e=0;const n=o=>{if(!o||typeof o!="object")return;const r=o;if(r.type==="text"&&typeof r.text=="string"){const i=e;e+=r.text.length;for(const a of r.marks?.comment?.split(",")??[]){const l=a.trim();if(!l)continue;const c=t.get(l);t.set(l,{start:c?Math.min(c.start,i):i,end:c?Math.max(c.end,e):e})}return}if((r.type==="code"||r.type==="math")&&typeof r.content=="string"){e+=r.content.length;return}if(Array.isArray(r.children)){const i=r.type==="list"?1:0;r.children.forEach((a,l)=>{i&&l>0&&(e+=i),n(a)})}};return n(s),t}const Ks=300;function zo(s,t,e,n,o){const r=Ys(t);return(s.comments??[]).filter(i=>!i.parentId&&i.resolved!==!0).filter(i=>!o.has(i.id)).filter(i=>{if(i.anchorBlockId===e)return!0;const a=r.get(i.id);return a?n?n.start<a.end&&a.start<n.end:!0:!1}).map(i=>({id:i.id,author:i.agentName??i.author,bodyMd:i.bodyMd.length>Ks?`${i.bodyMd.slice(0,Ks)}…`:i.bodyMd}))}function Vs(s,t){const e=t.length===1?"thread":"threads";return{success:!1,overlappingThreadIds:t.map(n=>n.id),errorCode:"comment_overlap",error:`That text in block ${s} already carries ${t.length} unresolved comment ${e}: ${t.map(n=>`${n.id} (${n.author}): "${n.bodyMd}"`).join("; ")}. If your point is already covered there, do not repeat it: reply with reply_to_comment_id="${t[0].id}". If you are raising a genuinely different point, retry with acknowledge_existing_thread_ids=[${t.map(n=>`"${n.id}"`).join(", ")}].`}}function mc(s,t,e,n,o,r,i,a){const l=r&&typeof r=="object"?["text"in r,"start_text"in r||"end_text"in r,"whole_block"in r]:[],c=l.length>0&&("text"in r?typeof r.text=="string"&&r.text.length>0:"whole_block"in r?r.whole_block===!0:typeof r.start_text=="string"&&r.start_text.length>0&&typeof r.end_text=="string"&&r.end_text.length>0);if(l.filter(Boolean).length!==1||!c)return{success:!1,error:"Anchor must contain exactly one of: text, start_text/end_text, or whole_block=true.",errorCode:"invalid_anchor"};const d=new Set((a??[]).map(w=>w.trim()).filter(Boolean)),g=Ee(s,n);if(!g)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in r){const w=zo(s,g,n,null,d);if(w.length>0)return Vs(n,w);const A=e.addBlockComment(n,o,i);return A?{success:!0,commentId:A}:{success:!1,error:`Could not attach a comment to block ${n}`}}const u=Ee(t,n),f=kt(u??g);let h=-1,p=-1;const m="text"in r?On(u??g,r.text):Zl(f,r.start_text,r.end_text,Uo(u??g),(w,A)=>On(u??g,w,A));if(m.length!==1)return{success:!1,error:m.length?`Anchor text matched ${m.length} locations in block '${n}'. Provide unique text or an HTML fragment that identifies the formatting, such as <b>claim</b> for bold or <i>claim</i> for italic. Start/end boundary text is included in the comment range; do not use surrounding separators unless they should also be commented on.`:`Anchor text was not found in block '${n}'.`,errorCode:m.length?"anchor_ambiguous":"anchor_not_found"};({start:h,end:p}=m[0]);const y=qs(u??g),b=pc(y,h,p);if(b.length===0)return{success:!1,error:`The anchor range in block ${n} does not map to commentable text`};const k=[];for(const w of b){const A=Ee(t,w.blockId),P=Ee(s,w.blockId);if(!A||!P)return{success:!1,error:`The anchor range in block ${n} could not be mapped to its live text; read the block again and retry`};let T={start:w.start,end:w.end};if(kt(P)!==kt(A)){const E=e.mapAcceptedSuggestionRangeToLiveRange(w.blockId,w.start,w.end);if(!E)return{success:!1,error:`The anchor range in block ${n} could not be mapped across pending suggestions; read the block again and retry`};T=E}k.push({blockId:w.blockId,...T})}const S=new Map;for(const w of zo(s,g,n,{start:h,end:p},d))s.comments?.some(A=>A.id===w.id&&A.anchorBlockId===n)&&S.set(w.id,w);for(const w of k){const A=Ee(s,w.blockId);if(A)for(const P of zo(s,A,w.blockId,{start:w.start,end:w.end},d))S.set(P.id,P)}const v=Array.from(S.values());if(v.length>0)return Vs(n,v);const x=e.addCommentToRanges(k,o,i);return x?{success:!0,commentId:x,range:{start:h,end:p}}:{success:!1,error:`Could not attach a comment to block ${n}`}}function Gs(s,t){const e=s.comments??[];let n=e.find(r=>r.id===t);if(!n)return null;const o=new Set([n.id]);for(;n.parentId&&!o.has(n.parentId);){o.add(n.parentId);const r=e.find(i=>i.id===n.parentId);if(!r)break;n=r}return n}function bc(s,t,e,n,o){const r=Gs(s,e);if(!r)return{success:!1,error:`Comment ${e} not found`,errorCode:"target_not_found"};if(r.resolved)return{success:!1,error:`Comment thread ${r.id} is resolved; leave a new comment instead`,errorCode:"already_resolved"};const i=t.replyToComment(r.id,n,o);return i?{success:!0,commentId:i,threadId:r.id}:{success:!1,error:`Could not reply to comment ${e}`,errorCode:"comment_mutation_failed"}}function yc(s,t,e){const n=W(s.getDocument(),t),o=W(s.getDocumentWithAcceptedSuggestions(),t);if(!n||!o)throw new St("target_missing",`Footnote target '${t}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||o.type!=="paragraph")throw new St("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const r=e?On(o,e):[];if(e&&r.length!==1)throw new St(r.length?"anchor_ambiguous":"anchor_not_found",r.length?`Anchor text matched ${r.length} locations in block ${t}; include unique surrounding text.`:`Anchor text ${JSON.stringify(e)} not found in block ${t}. Read it again.`,"matching");let i=e?r[0].end:kt(o).length;if(kt(n)!==kt(o)){const a=kc(n,kt(o),i);if(a===null)throw new St("target_stale","Anchor could not be mapped across pending suggestions. Read the block again.","target_resolution");i=a}return{block:t,offset:i}}function kc(s,t,e){let n="",o=0,r=e===0?0:null;for(const i of s.children){if(i.type!=="text")return null;const a=i.text.length;i.marks?.deletion||(r===null&&n.length+a>=e&&(r=o+(e-n.length)),n+=i.text),o+=a}return n===t?r:null}function Wo(s,t){return{indentStepPx:Ae(t).indentStepPx,storedAsUnits:s.get(Gt.paragraphIndentStorageVersion)===Po}}const Qs=new WeakMap;function Jo(s){return s.getXmlFragment("content")}function Zs(s,t){let e=t,n=null;for(;e;){if(n=e.parent,n===s)return e instanceof I.XmlElement&&e.getAttribute("id")||null;e=n}return null}function Sc(s){const t=Jo(s),e={nestedBlocks:new WeakMap,doc:null,blockCache:new Map,elementByBlockId:new Map,dirtyBlockIds:new Set,structuralChange:!1,observer:()=>{}},n=o=>{for(const r of o){let i=r.target;for(;i&&i!==t;)i instanceof I.XmlElement&&e.nestedBlocks.delete(i),i=i.parent;if(r.target===t&&r instanceof I.YXmlEvent&&r.childListChanged){e.structuralChange=!0;continue}if(r instanceof I.YXmlEvent&&r.childListChanged){const l=Zs(t,r.target);l!==null&&e.dirtyBlockIds.add(l);continue}const a=Zs(t,r.target);a!==null&&e.dirtyBlockIds.add(a)}};return e.observer=n,t.observeDeep(n),e}function ti(s){let t=Qs.get(s);return t||(t=Sc(s),Qs.set(s,t)),t}function Rn(s,t){const e=ti(s);e.nestedBlocks=new WeakMap,e.doc=t,e.blockCache.clear(),e.elementByBlockId.clear();const n=Jo(s).toArray();for(const o of t.children)o.id&&e.blockCache.set(o.id,o);for(const o of n)if(o instanceof I.XmlElement){const r=o.getAttribute("id");r&&e.elementByBlockId.set(r,o)}e.dirtyBlockIds.clear(),e.structuralChange=!1}function Dn(s,t,e){const n=e.nestedBlocks.get(s);if(n)return n;const o=In(s,t,void 0,r=>Dn(r,t,e));return o&&e.nestedBlocks.set(s,o),o}const $n=new WeakMap;function Ic(s){let t=$n.get(s);t||(t={blocks:[],dirty:!0,observing:!1},$n.set(s,t));const e=s.getXmlFragment("chrome");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=$n.get(s);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof I.XmlElement||o?.constructor?.name==="YXmlElement"){const r=In(o,Wo(s.getMap("metadata"),void 0));r&&r.type==="header-footer"&&n.push(r)}t.blocks=n,t.dirty=!1}return t.blocks}const jn=new WeakMap;function vc(s){let t=jn.get(s);t||(t={blocks:[],dirty:!0,observing:!1},jn.set(s,t));const e=s.getXmlFragment("notes");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=jn.get(s);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof I.XmlElement||o?.constructor?.name==="YXmlElement"){const r=In(o,Wo(s.getMap("metadata"),void 0));r&&r.type==="footnote"&&n.push(r)}t.blocks=n,t.dirty=!1}return t.blocks}function xc(s){return!!($n.get(s)?.dirty||jn.get(s)?.dirty)}function _n(s,t){const e=vc(t);e.length>0?(s.notes=e,fl(s)):delete s.notes}function Xn(s,t){const e=t.getMap("comments"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,r)=>(o.createdAt??"").localeCompare(r.createdAt??"")),s.comments=n):delete s.comments}function Ho(s,t){const e=t.getMap("oxml-ranges"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,r)=>o.id.localeCompare(r.id)),s.oxmlRanges=n):delete s.oxmlRanges}function Un(s,t){const e=t.getMap("sdt-wrappers"),n=[];if(e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0){const o=new Map;s.children.forEach((i,a)=>{i.id&&o.set(i.id,a)});const r=i=>i.blockIds?.[0]??i.startBlockId??"";n.sort((i,a)=>(o.get(r(i))??Number.MAX_SAFE_INTEGER)-(o.get(r(a))??Number.MAX_SAFE_INTEGER)||i.id.localeCompare(a.id)),s.sdtWrappers=n}else delete s.sdtWrappers}function zn(s,t){const e=Ic(t);e.length>0?s.chrome=e:delete s.chrome;const n=hs(e);n.headers?s.headers=n.headers:delete s.headers,n.footers?s.footers=n.footers:delete s.footers}function Kt(s){const t=ti(s),e=Jo(s),n=s.getMap("metadata"),o=n?.get("title"),r=n?.get("pageless"),i=n?.get("watermark"),a=typeof i=="string"&&i.trim()!==""?i:void 0,l=hl(s),c=n?.get("stylesheet"),d=c&&typeof c=="object"&&Array.isArray(c.paragraphStyles)&&c.paragraphStyles.length>0?c:void 0,g=n?.get("stylesXml"),u=typeof g=="string"&&g.length>0?g:void 0,f=n?.get("docxSource"),h=f&&typeof f=="object"&&Array.isArray(f.spans)?f:void 0,p=n?.get("coreProperties"),m=p&&typeof p=="object"&&Object.keys(p).length>0?p:void 0,y=n?.get("fontSubstitutes"),b=y&&typeof y=="object"&&Object.keys(y).length>0?y:void 0,k=us(n),S=Wo(n,k);if(t.indentContext&&(t.indentContext.indentStepPx!==S.indentStepPx||t.indentContext.storedAsUnits!==S.storedAsUnits)&&(t.nestedBlocks=new WeakMap,t.doc=null,t.blockCache.clear(),t.elementByBlockId.clear()),t.indentContext=S,!t.doc){const v=[],x=e.toArray();for(let w=0;w<x.length;w++){const A=x[w];if(A instanceof I.XmlElement){const P=Dn(A,S,t);P&&(v.push(P),t.blockCache.set(P.id,P),t.elementByBlockId.set(P.id,A))}}return t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(e.length!==t.doc.children.length&&(t.structuralChange=!0),t.structuralChange){const v=[],x=new Map,w=new Map,A=e.toArray();for(let P=0;P<A.length;P++){const T=A[P];if(T instanceof I.XmlElement){const E=T.getAttribute("id"),B=E?t.dirtyBlockIds.has(E):!0,N=E?t.blockCache.get(E):void 0,R=E!==null&&t.elementByBlockId.get(E)===T;if(E&&!B&&N&&R)v.push(N),x.set(E,N),w.set(E,T);else{const M=Dn(T,S,t);M&&(v.push(M),x.set(M.id,M),w.set(M.id,T))}}}return t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.blockCache=x,t.elementByBlockId=w,t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(t.dirtyBlockIds.size>0){const v=[...t.doc.children],x=e.toArray();for(let w=0;w<v.length;w++){const A=v[w];if(A?.id&&t.dirtyBlockIds.has(A.id)&&w<x.length){const P=x[w];if(P instanceof I.XmlElement){const T=Dn(P,S,t);T&&(t.blockCache.delete(A.id),v[w]=T,t.blockCache.set(T.id,T),t.elementByBlockId.set(T.id,P))}}}t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.dirtyBlockIds.clear()}return o!==void 0?t.doc.title=o:delete t.doc.title,r!==void 0?t.doc.pageless=r:delete t.doc.pageless,k?t.doc.pageLayout=k:delete t.doc.pageLayout,u?t.doc.stylesXml=u:delete t.doc.stylesXml,h?t.doc.docxSource=h:delete t.doc.docxSource,m?t.doc.coreProperties=m:delete t.doc.coreProperties,b?t.doc.fontSubstitutes=b:delete t.doc.fontSubstitutes,t.doc.chromeImages!==l&&(t.doc={...t.doc},l?t.doc.chromeImages=l:delete t.doc.chromeImages),t.doc.watermark!==a&&(t.doc={...t.doc},a!==void 0?t.doc.watermark=a:delete t.doc.watermark),t.doc.stylesheet!==d&&(t.doc={...t.doc},d!==void 0?t.doc.stylesheet=d:delete t.doc.stylesheet),xc(s)&&(t.doc={...t.doc}),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),t.doc}const qo=new WeakMap,Ve="__revise_end_of_document__";function wt(s,t){qo.set(s,{...qo.get(s),...t})}function Rt(s){return qo.get(s)}function Wn(s){if(s.name==="insert_block")return Rt(s)?.stableId}function wc(s){return!!Rt(s)?.allowNoopContinuation}function Ac(s){if(s.name==="replace_block")return Rt(s)?.multiBlockReplace}const Jn=/\\+u[0-9a-fA-F]{4}/;function ei(s){let t="";const e=[],n=[];for(let o=0;o<s.length;){const r=s.slice(o).match(/^(\\+u)([0-9a-fA-F]{4})/),i=r?o+r[0].length:o+1,a=r?String.fromCharCode(Number.parseInt(r[2],16)):s[o],l=Me(a);t+=l;for(let c=0;c<l.length;c++)e.push(o),n.push(i);o=i}return{text:t,sourceStarts:e,sourceEnds:n}}function Yo(s,t){return s.flatMap(e=>{if(e.length<=0)return[];const n=t.sourceStarts[e.offset],o=t.sourceEnds[e.offset+e.length-1];return n===void 0||o===void 0||o<n?[]:[{offset:n,length:o-n}]})}function Ko(s){return s.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function Tc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(s,t){const e=t.split(/(\s+)/),n=[];for(const l of e)/^\s+$/.test(l)?n.push("\\s+"):l.length>0&&n.push(Tc(l));if(n.length===0)return[];const o=n.join(""),r=new RegExp(o,"g"),i=[];let a;for(;(a=r.exec(s))!==null;)i.push({offset:a.index,length:a[0].length});return i}function Cc(s,t,e,n,o){const r=[];let i=s.indexOf(t);for(;i!==-1;){const a=i+n-e.length,l=Math.min(i+o-e.length+1,s.length);for(let c=a;c<l;c++)if(s.substring(c,c+e.length)===e){const d=c+e.length-i;d>=n&&d<=o&&r.push({offset:i,length:d})}i=s.indexOf(t,i+1)}return r}function Hn(s,t){const e=$o(t);if(e.length>1)for(const n of e){const o=Pn(s,n);if(o.length)return o.map(({start:r,end:i})=>({offset:r,length:i-r}))}for(const n of e){if(qe(n))continue;const o=Pc(s,n);if(o.length)return o}return[]}function Pc(s,t){if(!t)return[];if(/^\s*$/.test(t))return Vo(s,t);if(Jn.test(s)||Jn.test(t))return oi(s,t);const e=sc();return e!==null?e:oi(s,t)}function oi(s,t){const e=Pn(s,t);if(e.length)return e.map(({start:d,end:g})=>({offset:d,length:g-d}));const n=Me(s),o=Me(t),r=Vo(n,o);if(r.length>0)return r;const i=ni(n,o);if(i.length>0)return i;let a,l;if(Jn.test(s)||Jn.test(t)){a=ei(s),l=ei(t).text;const d=Vo(a.text,l);if(d.length>0)return Yo(d,a);const g=ni(a.text,l);if(g.length>0)return Yo(g,a)}const c=8;if(o.length>=c*2){const d=ri(n,o,c);if(d!==null)return[d]}if(a&&l&&l.length>=c*2){const d=ri(a.text,l,c);if(d!==null)return Yo([d],a)}return[]}function Mc(s,t){let e="";for(const n of s.children)n.type==="text"&&(e+=n.text);return Hn(e,t)}function Vo(s,t){const e=[];let n=s.indexOf(t);for(;n!==-1;)e.push({offset:n,length:t.length}),n=s.indexOf(t,n+t.length);return e}function ri(s,t,e){const n=Math.floor(t.length/2);for(let o=n;o>=e;o--){const r=t.substring(0,o),i=t.substring(t.length-o),a=Math.max(5,Math.floor(t.length*.2)),l=Math.max(o*2,t.length-a),c=t.length+a,d=Cc(s,r,i,l,c);if(d.length===1)return d[0]}return null}function si(s,t){const e=Do(s);return t.code||t.latex?e:tc(e)}function Go(s,t){const e=W(s,t);if(!e)return null;if(e.id===t)return{block:e,container:e};if(e.type==="list"){const n=e,o=n.children.find(r=>r.id===t);return o?{block:o,container:{...n,children:[o]}}:null}return null}function Bc(s){return s instanceof St&&s.code==="text_not_found"}class Ec{constructor(t){this.doc=t,this.forks=new Map,this.texts=new Map,this.dirty=new Set}text(t,e){if(this.dirty.delete(t)){const n=this.forks.get(t),o=n?Go(mt(n),t):null;this.texts.set(t,o?kt(o.block):null)}if(!this.texts.has(t)){if(e!==void 0)return e;const n=Go(this.doc,t);this.texts.set(t,n?kt(n.block):null)}return this.texts.get(t)}apply(t,e,n,o){const r=this.forkOf(t);if(!r)return!1;try{Wt(r,{name:o?"replace_all":"replace",arguments:{id:t,find:e,replace:n}})}catch(i){if(Bc(i))return!1;throw i}return this.dirty.add(t),!0}get forkCount(){return this.forks.size}forkOf(t){if(!this.forks.has(t)){const e=Go(this.doc,t);let n=null;e&&(n=new I.Doc,n.getXmlFragment("content").insert(0,[It(e.container)])),this.forks.set(t,n)}return this.forks.get(t)}}function Qo(s,t){if(qe(t)){let e=null;for(const n of s){const o=n.html?ec(n.text,n.html,t):[];if(o.length){if(o.length>1||e!==null)return null;e=n.blockId}}if(e!==null)return e}for(const e of["exact","normalized"]){let n=null;for(const o of s){const r=Fs(o.text,t,e);if(r.length){if(r.length>1||n!==null)return null;n=o.blockId}}if(n!==null)return n}return null}function ee(s){const t=$o(s).at(-1);return nc(Me(t)).text}function ii(s){return s?.type==="paragraph"||s?.type==="list-item"||s?.type==="code"||s?.type==="math"}function Ge(s){const t=[],e=(n,o)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&ii(n)&&t.push({blockId:n.id,topLevelBlockId:o,text:kt(n)}),Array.isArray(n.children)))for(const r of n.children)e(r,o)};for(const n of s.children)e(n,n.id??null);for(const n of s.notes??[])e(n,n.id);return t}function Zo(s,t){const e=n=>!n||typeof n!="object"?!1:n.id===t?!0:Array.isArray(n.children)&&n.children.some(e);for(const n of s.notes??[])if(e(n))return n.id;return null}function ai(s,t){const e=Zo(s,t);if(!e)return null;if(t!==e)return t;const n=s.notes?.find(i=>i.id===e);if(!n)return t;const o=[],r=i=>{!i||typeof i!="object"||(typeof i.id=="string"&&(i.type==="paragraph"||i.type==="list-item"||i.type==="code"||i.type==="math")&&o.push(i.id),Array.isArray(i.children)&&i.children.forEach(r))};return n.children.forEach(r),o.length===1?o[0]:t}function qn(s,t){return t.has(s.blockId)||s.topLevelBlockId!==null&&t.has(s.topLevelBlockId)}class tr{constructor(t){this.doc=t,this.normalized=new Map,this.candidates=null,this.simulation=new Ec(t)}contains(t,e){return this.qualifies(t,e)}qualifies(t,e,n){const o=this.simulation.text(t,n);if(o===null)return!1;const r=ee(e);if(!r||/^\s*$/.test(r))return!1;let i=this.normalized.get(o);if(i===void 0&&(i=ee(o),this.normalized.size>4096&&this.normalized.clear(),this.normalized.set(o,i)),!i.includes(r))return!1;if(Hn(o,e).length>0)return!0;const a=Ko(e);return a!==e&&a.trim()!==""&&Hn(o,a).length>0}apply(t,e,n,o){return this.simulation.apply(t,e,n,o)}loadedTargets(t,e){if(!e||e.size===0)return[];const n=ee(t);return!n||/^\s*$/.test(n)?[]:(this.candidates??(this.candidates=Ge(this.doc)),this.candidates.filter(o=>qn(o,e)&&this.qualifies(o.blockId,t,o.text)).map(o=>o.blockId))}}function Nc(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return[];const t=ee(s.find);return!t||/^\s*$/.test(t)?[]:Ge(s.doc).filter(e=>qn(e,s.loadedBlockIds)&&ee(e.text).includes(t)).map(e=>e.blockId)}function li(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return null;const t=ee(s.find);if(!t||/^\s*$/.test(t))return null;const e=W(s.doc,s.requestedBlockId);if(e&&ee(kt(e)).includes(t))return null;const n=$o(s.find).at(-1),o=Ge(s.doc).filter(i=>i.blockId!==s.requestedBlockId&&qn(i,s.loadedBlockIds));if(o.some(i=>Pn(i.text,n).length>0))return Qo(o,n);let r=null;for(const i of o)if(ee(i.text).includes(t)){if(r!==null)return null;r=i.blockId}return r}function Lc(s,t,e){const n=W(s,t);if(!n||n.id!==t||!["table","table-row","table-cell"].includes(n.type))return null;const o=Ge({children:[n]});return Qo(o,e)}const ci=new WeakSet;function er(s){ci.add(s)}function Fc(s){if(s.action.name!=="replace"&&s.action.name!=="replace_all"){const d=s.action.arguments?.id;return typeof d=="string"&&d&&s.opaqueBlockIds.add(d),{action:s.action}}if(!s.action.arguments||typeof s.action.arguments!="object")return{action:s.action};const t=s.action.arguments,e=typeof t.id=="string"?t.id.trim():"",n=typeof t.find=="string"?t.find:"";if(!e||!n)return{action:s.action};const o=typeof t.replace=="string"?t.replace:"",r=s.action.name==="replace_all",i=d=>{try{s.plannedTexts.apply(d,n,o,r)}catch{s.opaqueBlockIds.add(d)}};if(ci.has(s.action)||s.opaqueBlockIds.has(e))return i(e),{action:s.action};const a=Lc(s.doc,e,n)??(s.plannedTexts.contains(e,n)?null:li({doc:s.doc,requestedBlockId:e,find:n,loadedBlockIds:s.loadedBlockIds}));if(i(a??e),!a)return{action:s.action};const l={...s.action,arguments:{...t,id:a}},c=Rt(s.action);return c&&wt(l,c),{action:l,retarget:{fromBlockId:e,toBlockId:a}}}function Oc(s){const t=[],e=[],n=new tr(s.doc),o=new Set;for(const r of s.actions){const i=Fc({action:r,doc:s.doc,loadedBlockIds:s.loadedBlockIds,plannedTexts:n,opaqueBlockIds:o});t.push(i.action),i.retarget&&e.push(i.retarget)}return{actions:t,retargets:e}}function nr(s){return s.children.map(t=>{const e={type:"doc",children:[t]};return it.toInternalHtml(e).trim()})}function Rc(s,t=0){const e=Nn.fromMarkdown(s);if(t){for(const n of e.children)if(n.type==="list")for(const o of n.children)o.indentLevel=Math.min(8,t+(o.indentLevel??0))}return nr(e)}function Dc(s){return s.replace(/<span\b([^>]*?)\sdir\s*=\s*["']?(ltr|rtl|auto)["']?([^>]*)>([\s\S]*?)<\/span>/gi,(t,e,n,o,r)=>{const i=n.toLowerCase(),a=i==="ltr"?"⁦":i==="rtl"?"⁧":"⁨",l=`${e}${o}`.trim(),c=l?`<span ${l}>${r}</span>`:r;return`${a}${c}⁩`})}function $c(s,t,e,n){return nr(it.fromAgentHtml(Dc(s),{existingDocument:t,replacementBlock:e,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const he=/<\/?[a-z][^>]*>/i;function Ne(s){return s.replace(/\s+/g," ").trim()}function di(s){return Ne(s).replace(/^>\s+/,"")}function jc(s,t){if(s.replace==="")return null;const e=s.format==="html"||he.test(s.replace),n=e?it.fromAgentHtml(s.replace,{replacementBlock:W(t,s.id)??void 0,existingDocument:t,preserveImageReferenceIds:!0}):Nn.fromMarkdown(s.replace);if(n.children.length!==1||n.children[0].type!=="list")return null;const o=n.children[0].children;if(o.length===0)return null;const r=W(t,s.id);if(!r||r.type!=="list")return null;const i=r,a=he.test(s.find)?it.fromAgentHtml(s.find,{existingDocument:t,preserveImageReferenceIds:!0}):Nn.fromMarkdown(s.find),l=a.children.length===1&&a.children[0].type==="list"?a.children[0].children.map(y=>Ne(kt(y))):[Ne(kt(a))];if(l.length===0||l.some(y=>y===""))return null;const c=i.children.map(y=>Ne(kt(y))),d=[];for(let y=0;y+l.length<=c.length;y++)l.every((b,k)=>c[y+k]===b)&&(d.push(y),y+=l.length-1);if(d.length===0)throw new Error(`replace: the replacement contains ${o.length} list items, so "find" must match complete list item(s) in block '${s.id}' — it did not. Include each full item's text in "find" (or use insert_markdown to add items).`);if(d.length>1&&!s.all)throw new Error(`replace: "find" matches ${d.length} runs of list items in block '${s.id}'. Include more items in "find" so it matches exactly one location, or set all: true.`);const g=s.all?d:[d[0]],u=[];let f=0;for(const y of g)u.push(...i.children.slice(f,y)),u.push(...o),f=y+l.length;u.push(...i.children.slice(f));const h=g.length===1&&g[0]===0&&l.length===i.children.length,p=h?{...n.children[0],id:i.id}:{...i,children:u},m=h&&e?s.replace:nr({children:[p]})[0];return{name:"replace_block",arguments:{id:i.id,content:[m]}}}function _c(s,t){if(s.replace===""||s.all)return null;const e=W(t,s.id);if(!e)return null;const n=s.format==="html"||!s.format&&he.test(s.find)?kt(it.fromAgentHtml(s.find,{existingDocument:t,preserveImageReferenceIds:!0})):kt(Nn.fromMarkdown(s.find)),o=kt(e);if(di(n)!==di(o))return null;const r=s.format==="html"||!s.format&&he.test(s.replace)?$c(s.replace,t,e):Rc(s.replace),i=r.length===1&&/^<p\b[^>]*>[\s\S]*<\/p>$/i.test(r[0]),a=(s.format==="html"||!s.format&&he.test(s.replace))&&/^<p\s+[^>]+>/i.test(s.replace.trim()),l=e.type==="footnote"?ai(t,s.id):null,c=l!==null&&l!==s.id&&W(t,l)?.type==="paragraph",d=s.format!=="markdown"&&he.test(s.find)&&!he.test(s.find.replace(/<\/?(?:b|strong|i|em|u|s|strike|sup|sub|code|mark|span|a|br)\b[^>]*>/gi,""));return i&&!a&&(e.type==="table-cell"||c||e.type==="paragraph"&&(d||Ne(s.find)===Ne(o)))?null:{name:"replace_block",arguments:{id:s.id,content:r}}}function Xc(s,t){return jc(s,t)??_c(s,t)}function or(s,t){const e=W(s,t);return e?hi(e):null}const Yn=s=>s===void 0||typeof s=="function";function Ut(s,t){if(s===t)return!0;if(typeof s!="object"||typeof t!="object"||!s||!t)return typeof s=="number"&&typeof t=="number"?!Number.isFinite(s)&&!Number.isFinite(t):!1;const e=s.toJSON,n=t.toJSON;if(typeof e=="function"||typeof n=="function")return Ut(typeof e=="function"?e.call(s):s,typeof n=="function"?n.call(t):t);if(Array.isArray(s)||Array.isArray(t)){if(!Array.isArray(s)||!Array.isArray(t)||s.length!==t.length)return!1;for(let l=0;l<s.length;l++)if(!Ut(s[l],t[l]))return!1;return!0}const o=s,r=t,i=Object.keys(o).filter(l=>!Yn(o[l])),a=Object.keys(r).filter(l=>!Yn(r[l]));if(i.length!==a.length)return!1;for(const l of i)if(Yn(r[l])||!Object.prototype.hasOwnProperty.call(r,l)||!Ut(o[l],r[l]))return!1;return!0}const gi=16777619,Uc=1114113,zc=1114114,Wc=1114115,Jc=1114116,rr=1114117,Hc=1114118,ui=1114119;function Kn(s,t){switch(typeof t){case"string":return sr(_t(_t(s,Uc),t.length),t);case"number":return Number.isFinite(t)?sr(_t(s,zc),String(t)):_t(s,rr);case"boolean":return _t(s,t?Wc:Jc);case"object":break;default:return _t(s,rr)}if(t===null)return _t(s,rr);const e=t;if(typeof e.toJSON=="function")return Kn(s,e.toJSON());if(Array.isArray(t)){s=_t(_t(s,Hc),t.length);for(const r of t)s=Kn(s,r);return s}const n=t;let o=Object.keys(n);for(let r=1;r<o.length;r++)if(o[r-1]>o[r]){o=[...o].sort();break}s=_t(s,ui);for(const r of o){const i=n[r];Yn(i)||(s=sr(_t(s,r.length),r),s=Kn(s,i))}return _t(s,ui)}function _t(s,t){return Math.imul(s^t,gi)}function sr(s,t){for(let e=0;e<t.length;e++)s=Math.imul(s^t.charCodeAt(e),gi);return s}function hi(s){return(Kn(2166136261,s)>>>0).toString(36)}function qc(s,t){const e=new Map;for(const n of t){if(e.has(n))continue;const o=or(s,n);o!==null&&e.set(n,o)}return e}const fi=50,pi="document_state_changed",Yc=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function ir(s,t){const e=s.name==="replace"&&!!s.arguments&&typeof s.arguments=="object"&&Object.prototype.hasOwnProperty.call(s.arguments,"replacements"),n=s.name==="replace_many";if(!e&&!n)return{actions:[s]};const o=n?"replace_many":"replace";if(!s.arguments||typeof s.arguments!="object")return{actions:[],error:`${o} requires object arguments`};const r=s.arguments.id,i=s.arguments.replacements;if(!Array.isArray(i)||i.length===0)return{actions:[],error:`${o} requires a non-empty replacements array`};if(i.length>fi)return{actions:[],error:`${o} supports at most ${fi} replacements per call`};const a=[],l=t?new tr(t.doc):null;for(let d=0;d<i.length;d++){const g=i[d];if(!g||typeof g!="object")return{actions:[],error:`${o} replacement #${d+1} must be an object`};if(typeof g.find!="string")return{actions:[],error:`${o} replacement #${d+1} is missing "find"`};if(g.find.length===0&&(n||typeof r!="string"||r.trim().length===0))return{actions:[],error:n?`${o} replacement #${d+1} has an empty "find"`:`${o} replacement #${d+1} has an empty "find" and therefore requires a direct block id`};if(typeof g.replace!="string")return{actions:[],error:`${o} replacement #${d+1} is missing "replace"`};if(g.occurrence!==void 0&&g.occurrence!==null&&g.occurrence!=="unique"&&g.occurrence!=="all")return{actions:[],error:`${o} replacement #${d+1} has invalid "occurrence"; use "unique" or "all"`};if(g.comment!==void 0&&g.comment!==null&&(typeof g.comment!="string"||g.comment.trim().length===0))return{actions:[],error:`${o} replacement #${d+1} comment must be a non-empty string when provided`};let u=typeof r=="string"&&r.trim()?[r.trim()]:[];const f=u.length===0;if(u.length===0&&g.find.length>0&&t){const h=l?l.loadedTargets(g.find,t.loadedBlockIds):[];if(g.occurrence==="all")u=h;else if(l)u=h.length===1?h:[];else{const p=li({doc:t.doc,requestedBlockId:"",find:g.find,loadedBlockIds:t.loadedBlockIds});u=p?[p]:[]}}if(u.length===0){const h=t&&g.find.length>0?l?l.loadedTargets(g.find,t.loadedBlockIds):Nc({doc:t.doc,find:g.find,loadedBlockIds:t.loadedBlockIds}):[];return{actions:[],error:t?.loadedBlockIds?.size&&g.find.length>0?h.length===0?`${o} replacement #${d+1}: find text was not found in any loaded block. Check the exact text, or read the block that contains it.`:`${o} replacement #${d+1}: find text appears in ${h.length} loaded blocks (${h.slice(0,10).join(", ")}). Pass a block id, or use occurrence "all" to replace it in every one.`:`${o} replacement #${d+1} requires a block id unless its find text uniquely identifies one loaded block`}}for(const h of u){try{l?.apply(h,g.find,g.replace,g.occurrence==="all")}catch{}const p=u.length===1?`${s.id||o}-${d+1}`:`${s.id||o}-${d+1}-${h}`;if(t&&!g.comment)try{const y=Xc({type:"replace",id:h,find:g.find,replace:g.replace,format:"html",all:g.occurrence==="all"},t.doc);if(y){const b={...y,id:p};f&&er(b),a.push(b);continue}}catch(y){return{actions:[],error:y instanceof Error?y.message:String(y),failure:Be(y)}}const m={id:p,name:g.occurrence==="all"?"replace_all":"replace",arguments:{id:h,find:g.find,replace:g.replace,...typeof g.comment=="string"?{comment:g.comment.trim()}:{}}};f&&er(m),a.push(m)}}const c=Array.from(new Set(a.map(d=>d.arguments?.id).filter(d=>typeof d=="string"&&d.length>0)));return{actions:a,blockId:c.length===1?c[0]:void 0}}function Kc(s){const{toolCall:t,docBefore:e,resultSets:n}=s,o=t.arguments;if(!o||typeof o!="object")return null;const r=o.search_result_id;if(r==null)return null;if(typeof r!="string"||r.trim().length===0)return{actions:[],targetBlockIds:[],error:"search_result_id must be a non-empty string"};const i=r.trim();if(!Yc.has(t.name))return{actions:[],targetBlockIds:[],error:`${t.name} does not support search_result_id`};if(typeof o.id=="string"&&String(o.id).trim().length>0||Array.isArray(o.ids))return{actions:[],targetBlockIds:[],error:`${t.name} accepts either search_result_id or direct id/ids targets, not both.`};const a=n.get(i);if(!a)return{actions:[],targetBlockIds:[],error:`Search result '${i}' is unavailable. Search result references are request-scoped; rerun search_document in this request, then retry.`,errorCode:pi};for(const u of a.blockIds){if(Zo(e,u))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const f=or(e,u);if(f===null||f!==a.blockHashes.get(u))return{actions:[],targetBlockIds:[],error:`Search result '${i}' is stale because block '${u}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:pi}}const{search_result_id:l,...c}=o,d=[];let g=[...a.blockIds];if(t.name==="replace"){const u=c.replacements,f=(Array.isArray(u)?u:[c]).map(k=>k&&typeof k=="object"?k:{}),h=new tr(e),p=f.map(()=>!1),m=(k,S,v,x)=>{try{return h.apply(k,S,v,x)}catch{return!0}},y=a.blockIds.map(k=>f.flatMap((S,v)=>{const{find:x,replace:w}=S;return typeof x!="string"||x.length===0||h.contains(k,x)&&m(k,x,typeof w=="string"?w:"",S.occurrence==="all"||!Array.isArray(u))?(p[v]=!0,[v]):[]})),b=p.flatMap((k,S)=>k?[]:[S]);if(b.length>0)return{actions:[],targetBlockIds:[],error:`Search result '${i}' has no block containing the find text of ${Array.isArray(u)?`replacement ${b.map(k=>`#${k+1}`).join(", ")}`:"this replacement"}. Check the exact text; no replacement was applied.`};g=[];for(let k=0;k<a.blockIds.length;k++){const S=a.blockIds[k],v=y[k];if(v.length===0)continue;const x=Array.isArray(u)?v.map(A=>u[A]):null,w=ir({...t,id:`${t.id||"replace"}-search-${k+1}`,arguments:{...c,...x?{replacements:x}:{},id:S}});if(w.error)return{actions:[],targetBlockIds:[],error:w.error};for(const A of w.actions)er(A),d.push(A);g.push(S)}}else if(t.name==="replace_block"){const u=o.count;if(u!=null&&u!==1)return{actions:[],targetBlockIds:[],error:"replace_block with search_result_id applies independently to each matched block, so count must be omitted or 1."};for(let f=0;f<a.blockIds.length;f++)d.push({...t,id:`${t.id||"replace_block"}-search-${f+1}`,arguments:{...c,id:a.blockIds[f],count:1}})}else if(t.name==="remove_block")for(let u=0;u<a.blockIds.length;u++)d.push({...t,id:`${t.id||"remove_block"}-search-${u+1}`,arguments:{id:a.blockIds[u],count:1}});else{const u=o.selectors,f=(Array.isArray(u)?u:typeof u=="string"?[u]:[]).flatMap(p=>typeof p=="string"?p.split(",").map(m=>m.trim()):[p]);if(f.length===0||f.some(p=>typeof p!="string"||p.trim().length===0))return{actions:[],targetBlockIds:[],error:"style_blocks requires one or more non-empty selectors"};const h=a.blockIds.flatMap(p=>f.map(m=>{const y=String(m).trim();return/^(?:\*|all|document|:root)$/i.test(y)?`#${p}`:`#${p} ${y}`}));d.push({...t,arguments:{...c,selectors:h}})}return{actions:d,targetBlockIds:g,resultSet:a}}function mi(s,t){const e={...t};for(const n of["lang","oxmlRPr","oxmlRange","sdtInline","field","aiGenerated","__htmlClassName"])e[n]===void 0&&s?.[n]!==void 0&&Object.assign(e,{[n]:s[n]});for(const n of fs)e[n]===void 0&&s?.[n]===!1&&(e[n]=!1);if(e.docxRunPropertyResets===void 0){const n=pl(s?.docxRunPropertyResets)?.split(",").filter(o=>o==="color"?e.color===void 0:e.backgroundColor===void 0);n?.length&&(e.docxRunPropertyResets=n.join(","))}return e}function Vn(s,t){const e=s.map(i=>i.text).join("");if(!e||e!==t.map(i=>i.text).join("")){const i=new Set(s.filter(l=>l.text.length>0).map(l=>l.marks?.lang)),a=i.size===1?[...i][0]:void 0;return a===void 0?t:t.map(l=>({...l,marks:{lang:a,...l.marks}}))}const n=[];let o=0,r=0;for(const i of t){if(i.text.length===0){n.push({...i,marks:i.marks?{...i.marks}:void 0});continue}let a=0;for(;a<i.text.length;){for(;r===s[o].text.length;)o++,r=0;const l=s[o],c=Math.min(i.text.length-a,l.text.length-r);n.push({...i,text:i.text.slice(a,a+c),marks:mi(l.marks,i.marks)}),a+=c,r+=c}}return n}function Vc(s,t){const e=Mn(s),n=Array.from({length:e.cols},(l,c)=>Math.max(.001,s.columnWidths[c]||100/e.cols)),o=new Map;for(const l of t){const c=e.byId.get(l.cellId);if(!c)throw new St("target_stale","The requested table cell no longer exists. Read the table again.","target_resolution");if(!Number.isFinite(l.percent)||l.percent<=0||l.percent>100)throw new St("attribute_value_unsupported","Cell width must be greater than 0 and at most 100 percent.");const d=n.slice(c.col,c.col+c.colSpan).reduce((g,u)=>g+u,0);for(let g=c.col;g<c.col+c.colSpan;g++){const u=l.percent*n[g]/d;if(o.has(g)&&Math.abs(o.get(g)-u)>.001)throw new St("attribute_conflict","Conflicting cell widths constrain the same table column. Set each column once, using one unmerged row.");o.set(g,u)}}const r=[...o.values()].reduce((l,c)=>l+c,0),i=n.map((l,c)=>c).filter(l=>!o.has(l));if(r>100.001||!i.length&&Math.abs(r-100)>.001||i.length&&r>=100)throw new St("attribute_conflict","Requested column widths conflict: they must leave space for other columns and sum to 100 percent when all columns are specified.");const a=i.reduce((l,c)=>l+n[c],0);return n.map((l,c)=>o.get(c)??(100-r)*l/a)}function bi(s,t,e,n){if(!n?.length)return;const o=t==="row"?s.cols:s.rows;if(n.length>o)return{success:!1,error:`content[${o}] is outside the table's ${o} ${t==="row"?"columns":"rows"}. Supply at most ${o} entries for this insertion.`};for(const r of s.cells){const i=t==="row"?r.row:r.col,a=t==="row"?r.rowSpan:r.colSpan;if(i>=e||i+a<=e)continue;const l=t==="row"?r.col:r.row,c=t==="row"?r.colSpan:r.rowSpan;for(let d=l;d<l+c;d++)if(n[d]?.length)return{success:!1,error:`content[${d}] targets a position covered by a merged cell. Leave that slot empty or insert outside the merged span; the table was not changed.`}}}function Gc(s,t){return{type:"paragraph",id:G(),...s?{direction:s}:{},children:[{type:"text",text:"",...t?{marks:t}:{}}]}}function yi(s){const t=s?.children.find(n=>n.type==="paragraph")?.children.find(n=>n.type==="text")?.marks;if(!t)return;const e={};return t.fontFamily&&t.fontFamily!==ml&&(e.fontFamily=t.fontFamily),typeof t.fontSize=="number"&&(e.fontSize=t.fontSize),typeof t.color=="string"&&t.color&&(e.color=t.color),Object.keys(e).length>0?e:void 0}function ki(s){const t=s?.children.find(n=>n.type==="paragraph");if(!t)return;let e="";for(const n of t.children)e+=n.text??"";return Ds(t.direction,e)==="rtl"?"rtl":void 0}function Qc(s,t){return{type:"table-cell",id:G(),children:[Gc(s,t)]}}function Si(s,t,e){return!s||s.length===0?Qc(t,e):{type:"table-cell",id:G(),children:s}}function Gn(s,t){const e=s.get("content",I.XmlFragment);function n(o){for(let r=0;r<o.length;r++){const i=o.get(r);if(i instanceof I.XmlElement){if(i.nodeName==="table"&&i.getAttribute("id")===t)return i;if(i.nodeName==="container"||i.nodeName==="footnote"||i.nodeName==="table"||i.nodeName==="table-row"||i.nodeName==="table-cell"){const a=n(i);if(a)return a}}}return null}return n(e)??n(s.getXmlFragment("notes"))}function ar(s,t){const e=Number(rt(s,t));return Number.isFinite(e)&&e>1?Math.floor(e):1}function Ii(s){if(!s)return;const t=In(s.el,{indentStepPx:48,storedAsUnits:!1});return t?.type==="table-cell"?t:void 0}function Qn(s){const t=[];for(let a=0;a<s.length;a++){const l=s.get(a);l instanceof I.XmlElement&&l.nodeName==="table-row"&&t.push(l)}const e=s.getAttribute("columnWidths");let n=0;try{const a=e?JSON.parse(e):[];n=Array.isArray(a)?a.length:0}catch{n=0}for(const a of t){let l=0;for(let c=0;c<a.length;c++){const d=a.get(c);d instanceof I.XmlElement&&d.nodeName==="table-cell"&&(l+=ar(d,"colSpan"))}n=Math.max(n,l)}n=Math.max(n,1);const o=t.length,r=Array.from({length:o},()=>new Array(n).fill(void 0)),i=[];for(let a=0;a<o;a++){const l=t[a];let c=0,d=0;for(let g=0;g<l.length;g++){const u=l.get(g);if(!(u instanceof I.XmlElement)||u.nodeName!=="table-cell")continue;for(;c<n&&r[a][c]!==void 0;)c++;if(c>=n)break;const f=Math.min(ar(u,"colSpan"),n-c),h=Math.min(ar(u,"rowSpan"),o-a),p={el:u,row:a,col:c,rowSpan:h,colSpan:f,physicalIndex:d};i.push(p);for(let m=a;m<a+h;m++)for(let y=c;y<c+f;y++)r[m][y]===void 0&&(r[m][y]=p);c+=f,d++}}return{rows:o,cols:n,cells:i,occupancy:r,rowEls:t}}function Qe(s,t,e){e>1?s.setAttribute(t,String(e)):et(s,t)}function vi(s){return It(s)}function Zc(s){const t=new I.XmlElement("table-row");t.setAttribute("id",s.id);let e=0;for(const n of s.children){const o=vi(n);t.insert(e++,[o])}return t}function td(s,t,e){const n=Gn(s,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=Qn(n);return o.rows===0?{success:!1,error:"Table has no rows."}:e<0||e>=o.cols?{success:!1,error:`Invalid column index ${e}. Table has ${o.cols} columns.`}:o.cols<=1?{success:!1,error:"Cannot remove the last column from a table."}:(s.transact(()=>{for(const i of o.cells)i.col<=e&&e<i.col+i.colSpan&&(i.colSpan>1?Qe(i.el,"colSpan",i.colSpan-1):o.rowEls[i.row].delete(i.physicalIndex,1));const r=n.getAttribute("columnWidths");if(r){const i=JSON.parse(r);if(e<i.length){const a=i[e];i.splice(e,1);const l=i.reduce((d,g)=>d+g,0),c=l>0?i.map(d=>d+a*d/l):i;n.setAttribute("columnWidths",JSON.stringify(c))}}}),{success:!0})}function ed(s,t){const e=Qn(s);if(t<0||t>=e.rows)return;for(const r of e.cells)r.row<t&&r.row+r.rowSpan>t&&Qe(r.el,"rowSpan",r.rowSpan-1);const n=e.cells.filter(r=>r.row===t&&r.rowSpan>1).sort((r,i)=>r.col-i.col);if(n.length>0&&t+1<e.rows){const r=e.rowEls[t+1],i=e.cells.filter(l=>l.row===t+1);let a=0;for(const l of n){const c=l.el.clone();Qe(c,"rowSpan",l.rowSpan-1);const d=i.filter(g=>g.col<l.col).length+a;r.insert(d,[c]),a++}}const o=e.rowEls[t];for(let r=0;r<s.length;r++)if(s.get(r)===o){s.delete(r,1);break}}function nd(s,t,e){const n=Gn(s,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=[...new Set(e)],r=o.find(i=>!Number.isInteger(i)||i<0||i>=n.length);return r!==void 0?{success:!1,error:`Invalid row index ${r}. Table has ${n.length} rows.`}:o.length===0?{success:!1,error:"No rows to remove."}:o.length>=n.length?{success:!1,error:"Cannot remove the last row from a table. To delete every row, remove the table block instead."}:(s.transact(()=>{for(const i of o.sort((a,l)=>l-a))ed(n,i)}),{success:!0})}const Zn=s=>s==null?void 0:Array.isArray(s)?s:[s];function xi(s,t){const e=[...Zn(t.rowIds)??[],...Zn(t.rowId)??[]],n=[...Zn(t.rowIndices)??[],...Zn(t.rowIndex)??[]];if(e.length&&n.length)return{error:"Pass rowIds or rowIndices, not both. Prefer rowIds: the stable <tr id> values from the table you read."};if(!e.length&&!n.length)return{error:"Pass rowIds: the stable <tr id> of each row to remove (one string or an array)."};const o=e.length>0,r=[],i=[];for(const l of o?e:n)if(o){const c=typeof l=="string"?s.children.findIndex(d=>d.id===l):-1;c<0?i.push(`Row ${JSON.stringify(l)} not found`):r.push(c)}else!Number.isInteger(l)||Number(l)<0||Number(l)>=s.children.length?i.push(`Invalid row index ${JSON.stringify(l)} (table has ${s.children.length} rows)`):r.push(Number(l));if(i.length)return{error:`${i.join("; ")} in table ${s.id}. No rows were removed. Read the table and use current row IDs.`};if(new Set(r).size!==r.length)return{error:`Each row may be listed once. No rows were removed from table ${s.id}.`};if(r.length>=s.children.length)return{error:`Cannot remove the last row from table ${s.id}. To delete every row, remove the table block instead.`};const a=[...r].sort((l,c)=>l-c);return{rowIndices:a,rowIds:a.map(l=>s.children[l].id),byId:o}}function od(s,t,e,n,o){const r=Gn(s,t);if(!r)return{success:!1,error:`Table with ID "${t}" not found.`};const i=Qn(r);if(i.rows===0)return{success:!1,error:"Table has no rows."};const a=i.cols;if(n<0||n>=a)return{success:!1,error:`Invalid reference column index ${n}. Table has ${a} columns.`};const l=e==="before"?n:n+1;return bi(i,"column",l,o)||(s.transact(()=>{for(let g=0;g<i.rows;g++){const u=l>0&&l<a&&i.occupancy[g][l-1]===i.occupancy[g][l]?i.occupancy[g][l]:void 0;if(u){u.row===g&&Qe(u.el,"colSpan",u.colSpan+1);continue}const f=o?.[g],h=Ii(i.occupancy[g]?.[n]),p=Si(f,ki(h),yi(h)),m=vi(p),y=i.cells.filter(b=>b.row===g&&b.col<l).length;i.rowEls[g].insert(y,[m])}const d=r.getAttribute("columnWidths");if(d){const g=JSON.parse(d),u=100/(a+1),f=(100-u)/100,h=g.map(p=>p*f);h.splice(l,0,u),r.setAttribute("columnWidths",JSON.stringify(h))}}),{success:!0})}function rd(s,t,e,n){const o=Qn(t);return bi(o,"row",e,n)||(s.transact(()=>{const i=o.cells.filter(u=>u.row<e&&u.row+u.rowSpan>e),a=new Set;for(const u of i){Qe(u.el,"rowSpan",u.rowSpan+1);for(let f=u.col;f<u.col+u.colSpan;f++)a.add(f)}const l=[];for(let u=0;u<o.cols;u++){if(a.has(u))continue;const f=Ii(o.occupancy[e-1]?.[u]??o.occupancy[e]?.[u]);l.push(Si(n?.[u],ki(f),yi(f)))}const c={id:G(),children:l},d=Zc(c);let g=t.length;if(e<o.rows){const u=o.rowEls[e];for(let f=0;f<t.length;f++)if(t.get(f)===u){g=f;break}}t.insert(g,[d])}),{success:!0})}function sd(s,t,e,n,o){const r=Gn(s,t);if(!r)return{success:!1,error:`Table with ID "${t}" not found.`};if(n<0||n>=r.length)return{success:!1,error:`Invalid reference row index ${n}. Table has ${r.length} rows.`};const i=r.get(0);if(!(i instanceof I.XmlElement)||i.nodeName!=="table-row")return{success:!1,error:"Table has no rows."};const a=e==="before"?n:n+1;return rd(s,r,a,o)}const wi=new Set(["com","org","net","edu","gov","mil","int","io","co","ai","app","dev","tech","cloud","software","digital","online","site","website","web","blog","biz","info","pro","company","agency","studio","media","news","shop","store","uk","de","fr","es","it","nl","be","at","ch","cx","pl","ru","cn","jp","kr","in","au","nz","ca","us","mx","br","ar","za","ie","se","no","dk","fi","pt","cz","gr","hu","ro","ua","il","ae","sg","hk","tw","id","my","ph","th","vn","tr","me","tv","cc","gg","fm","ly","to","is","im","ws","la","ac","sh","vc","xyz","top","live","space"]),Ai=/^(?:mailto|tel):\S+$/i,Ti=/^[^\s@/?#:]+@[^\s@/?#:]+\.[a-z]{2,}$/i;function id(s){if(!s||s.length<4)return!1;if(Ai.test(s)||Ti.test(s))return!0;if(/^https?:\/\//i.test(s))try{return new URL(s),!0}catch{return!1}if(s.split(/[/?#]/,1)[0].includes("@"))return!1;if(/^www\./i.test(s))try{return new URL(`https://${s}`),!0}catch{return!1}if(!s.includes(".")||!/^[a-zA-Z0-9]/.test(s))return!1;try{const t=new URL(`https://${s}`).hostname.split(".").filter(n=>n.length>0);if(t.length<2)return!1;const e=t[t.length-1].toLowerCase();if(wi.has(e))return!0;if(t.length>=3){const n=t[t.length-2].toLowerCase();if(wi.has(n))return!0}return!1}catch{return!1}}function ad(s){return/^https?:\/\//i.test(s)||Ai.test(s)?s:Ti.test(s)?`mailto:${s}`:`https://${s}`}function Ci(s){return s===" "||s===" "||s===`
1
+ import{n as hl,q as us,r as Ae,P as Gt,s as Po,u as In,v as hs,w as fl,y as mt,x as It,D as fs,z as pl,A as et,a as G,B as ml,C as rt,E as ot,F as st,G as lt,H as de,I as Z,J as We,K as at,L as ct,M as ps,N as Jt,O as Ht,Q as bl,R as ms,e as bs,S as yl,T as ys,U as qt,V as Je,W as ks,X as kl,Y as Sl,Z as Il,_ as vn,$ as xn,a0 as vl,a1 as xl,a2 as wl,a3 as Qt,a4 as Al,a5 as Ss,a6 as Is,a7 as vs,a8 as xs,a9 as Tl,aa as ws,ab as Cl,ac as Pl,ad as As,g as gt,ae as Mo,af as ge,ag as Te,ah as wn,ai as Ce,aj as Bo,ak as An,al as Tn,am as Ml,an as Zt,ao as Bl,b as El,d as Eo,ap as Ts,aq as Cs,f as Ps,ar as Ms,as as Nl,i as Ll,at as Fl,au as Ol,av as No,aw as Rl,ax as Dl,ay as $l,az as jl,aA as Yt,aB as _l,aC as Lo,aD as Xl,aE as Ul,aF as zl,aG as Bs,aH as Wl,aI as Jl,aJ as Hl,aK as ql,aL as Yl,aM as Kl,aN as Es}from"./engine-LMUnxdm2.js";import{f as W,h as Cn,t as He,k as Ct,a as xt,i as Xt,l as Ns,m as Fo,n as Oo,g as ue,o as Ls,c as Pe,p as Ro,q as Vl,r as Gl,s as Ql}from"./CanvasRenderer-C1Vegx9Y.js";import{d as Do,S as St,f as Pn,b as Fs,c as qe,A as it,e as Zl,m as $o,g as tc,h as Me,i as ec,n as nc,j as Be,s as Os,k as jo,l as oc,o as rc}from"./AgentHtmlConverter-CnnB8-WI.js";import*as I from"yjs";import{b as Mn}from"./TableGrid-DbroRucl.js";import{j as Pt,i as Bn}from"./signatures-DTNDS2PH.js";import{w as sc,r as ic,a as En}from"./ParagraphDiffAnalysis-DrmStvmz.js";import{MarkdownConverter as Nn}from"./MarkdownConverter-DofaSeC4.js";import{s as Ye,a as _o,b as Xo,c as Rs}from"./DocumentStylesheet-CEEt18sr.js";import{a as Ds,g as ac}from"./BidiText-Bkp4Y90s.js";import{C as $s,a as js,b as _s,H as Ln,h as Ke,n as lc}from"./Typography-B4gndEdB.js";import{a as Xs,s as Us,b as cc,n as zs}from"./TableBorders-DVhdvo6f.js";import{d as dc,a as te}from"./index-BLb10wQt.js";import{R as Nt,A as Ws}from"./suggestionAuthorship-B-IuLQlE.js";import{d as gc,p as uc}from"./chromeImageLayout-BiQ3Iz1-.js";function hc(s){const t=s.children.filter(e=>e.type==="text");return t.length===0?[{type:"text",text:""}]:t}function Fn(s){return hc(s).reduce((t,e)=>t+e.text.length,0)}function fc(s,t){const e=W(s,t);if(!e||!e.id)return null;if(e.type==="paragraph"){let n=0;for(const o of e.children)o.type==="text"&&(n+=o.text.length);return{block:e.id,offset:n}}if(e.type==="list"){const n=e;let o=0;for(let r=0;r<n.children.length;r++)o+=Fn(n.children[r]),r<n.children.length-1&&(o+=1);return{block:e.id,offset:o}}return{block:e.id,offset:0}}function kt(s){if(!s||typeof s!="object")return"";const t=s;if(t.type==="text"&&typeof t.text=="string")return t.text;if((t.type==="code"||t.type==="math")&&typeof t.content=="string")return t.content;if(Array.isArray(t.children)){const e=t.type==="list"?" ":"";return t.children.map(n=>kt(n)).join(e)}return""}const Js={P:"paragraph",LI:"list-item",TD:"table-cell",TH:"table-cell",TR:"table-row",TABLE:"table",UL:"list",OL:"list",H1:"paragraph",H2:"paragraph",H3:"paragraph",H4:"paragraph",H5:"paragraph",H6:"paragraph"};function Hs(s,t){if(!/<[^>]+\bid\s*=/i.test(t))return null;const e=kt(s);if(e.includes(t)||e.includes(Do(t)))return null;const n=document.createElement("template");n.innerHTML=t;const o=[...n.content.querySelectorAll("[id]")].filter(c=>Js[c.tagName]);if(!o.length)return null;const r=new Map,i=(c,d=null)=>{if(!c||typeof c!="object")return;const g=c;g.id&&(d?d.add(g.id):r.set(g.id,[...r.get(g.id)??[],g])),g.children?.forEach(u=>i(u,d))};i(s);const a=new Set,l=new Set;for(const c of o){const d=r.get(c.id)??[];if(a.has(c.id)||d.length!==1||d[0].type!==Js[c.tagName])throw new St("target_stale",`HTML matcher id '${c.id}' is missing, contradictory, or outside the authorized target. Read the target again.`,"target_resolution");a.add(c.id);const g=d[0],u=kt(g),f=c.textContent??"",h=Pn(u,f,"prefer-exact");if(u!==f&&!h.some(y=>y.start===0&&y.end===u.length))throw new St("target_stale",`HTML matcher text for '${c.id}' no longer matches that block. Read it again before editing.`,"matching");const p=new Set;i(g,p);const m=o.filter(y=>y!==c&&c.contains(y));if(m.some(y=>!p.has(y.id)))throw new St("target_stale",`HTML matcher ids contradict the document hierarchy inside '${c.id}'.`,"target_resolution");m.length||p.forEach(y=>l.add(y))}return l}function Ee(s,t){const e=W(s,t);return e?.type==="list"&&e.id!==t?e.children.find(n=>n.id===t)??null:e}function Uo(s){if(!(!s||s.type!=="paragraph"&&s.type!=="list-item"))return it.toAgentHtml({type:"doc",children:[{...s,type:"paragraph"}]})}function On(s,t,e="prefer-exact"){const n=Hs(s,t),o=Fs(kt(s),t,e,qe(t)?Uo(s):void 0);if(!n)return o;const r=qs(s);return o.filter(i=>{const a=r.filter(l=>l.start<i.end&&i.start<l.end);return a.length>0&&a.every(l=>n.has(l.blockId))})}function qs(s){const t=[];let e=0;const n=o=>{if(!o||typeof o!="object")return;const r=o,i=Array.isArray(r.children)?r.children:[],a=r.type==="list"||r.type==="table"||r.type==="table-row"||r.type==="table-cell"||r.type==="container";if(r.id&&!a){const l=kt(o);if(l.length>0){t.push({blockId:r.id,start:e,end:e+l.length,text:l}),e+=l.length;return}}i.forEach((l,c)=>{r.type==="list"&&c>0&&(e+=1),n(l)})};return n(s),t}function pc(s,t,e){const n=[];for(const o of s){const r=Math.max(t,o.start),i=Math.min(e,o.end);i<=r||n.push({blockId:o.blockId,start:r-o.start,end:i-o.start})}return n}function Ys(s){const t=new Map;let e=0;const n=o=>{if(!o||typeof o!="object")return;const r=o;if(r.type==="text"&&typeof r.text=="string"){const i=e;e+=r.text.length;for(const a of r.marks?.comment?.split(",")??[]){const l=a.trim();if(!l)continue;const c=t.get(l);t.set(l,{start:c?Math.min(c.start,i):i,end:c?Math.max(c.end,e):e})}return}if((r.type==="code"||r.type==="math")&&typeof r.content=="string"){e+=r.content.length;return}if(Array.isArray(r.children)){const i=r.type==="list"?1:0;r.children.forEach((a,l)=>{i&&l>0&&(e+=i),n(a)})}};return n(s),t}const Ks=300;function zo(s,t,e,n,o){const r=Ys(t);return(s.comments??[]).filter(i=>!i.parentId&&i.resolved!==!0).filter(i=>!o.has(i.id)).filter(i=>{if(i.anchorBlockId===e)return!0;const a=r.get(i.id);return a?n?n.start<a.end&&a.start<n.end:!0:!1}).map(i=>({id:i.id,author:i.agentName??i.author,bodyMd:i.bodyMd.length>Ks?`${i.bodyMd.slice(0,Ks)}…`:i.bodyMd}))}function Vs(s,t){const e=t.length===1?"thread":"threads";return{success:!1,overlappingThreadIds:t.map(n=>n.id),errorCode:"comment_overlap",error:`That text in block ${s} already carries ${t.length} unresolved comment ${e}: ${t.map(n=>`${n.id} (${n.author}): "${n.bodyMd}"`).join("; ")}. If your point is already covered there, do not repeat it: reply with reply_to_comment_id="${t[0].id}". If you are raising a genuinely different point, retry with acknowledge_existing_thread_ids=[${t.map(n=>`"${n.id}"`).join(", ")}].`}}function mc(s,t,e,n,o,r,i,a){const l=r&&typeof r=="object"?["text"in r,"start_text"in r||"end_text"in r,"whole_block"in r]:[],c=l.length>0&&("text"in r?typeof r.text=="string"&&r.text.length>0:"whole_block"in r?r.whole_block===!0:typeof r.start_text=="string"&&r.start_text.length>0&&typeof r.end_text=="string"&&r.end_text.length>0);if(l.filter(Boolean).length!==1||!c)return{success:!1,error:"Anchor must contain exactly one of: text, start_text/end_text, or whole_block=true.",errorCode:"invalid_anchor"};const d=new Set((a??[]).map(w=>w.trim()).filter(Boolean)),g=Ee(s,n);if(!g)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in r){const w=zo(s,g,n,null,d);if(w.length>0)return Vs(n,w);const A=e.addBlockComment(n,o,i);return A?{success:!0,commentId:A}:{success:!1,error:`Could not attach a comment to block ${n}`}}const u=Ee(t,n),f=kt(u??g);let h=-1,p=-1;const m="text"in r?On(u??g,r.text):Zl(f,r.start_text,r.end_text,Uo(u??g),(w,A)=>On(u??g,w,A));if(m.length!==1)return{success:!1,error:m.length?`Anchor text matched ${m.length} locations in block '${n}'. Provide unique text or an HTML fragment that identifies the formatting, such as <b>claim</b> for bold or <i>claim</i> for italic. Start/end boundary text is included in the comment range; do not use surrounding separators unless they should also be commented on.`:`Anchor text was not found in block '${n}'.`,errorCode:m.length?"anchor_ambiguous":"anchor_not_found"};({start:h,end:p}=m[0]);const y=qs(u??g),b=pc(y,h,p);if(b.length===0)return{success:!1,error:`The anchor range in block ${n} does not map to commentable text`};const k=[];for(const w of b){const A=Ee(t,w.blockId),P=Ee(s,w.blockId);if(!A||!P)return{success:!1,error:`The anchor range in block ${n} could not be mapped to its live text; read the block again and retry`};let T={start:w.start,end:w.end};if(kt(P)!==kt(A)){const E=e.mapAcceptedSuggestionRangeToLiveRange(w.blockId,w.start,w.end);if(!E)return{success:!1,error:`The anchor range in block ${n} could not be mapped across pending suggestions; read the block again and retry`};T=E}k.push({blockId:w.blockId,...T})}const S=new Map;for(const w of zo(s,g,n,{start:h,end:p},d))s.comments?.some(A=>A.id===w.id&&A.anchorBlockId===n)&&S.set(w.id,w);for(const w of k){const A=Ee(s,w.blockId);if(A)for(const P of zo(s,A,w.blockId,{start:w.start,end:w.end},d))S.set(P.id,P)}const v=Array.from(S.values());if(v.length>0)return Vs(n,v);const x=e.addCommentToRanges(k,o,i);return x?{success:!0,commentId:x,range:{start:h,end:p}}:{success:!1,error:`Could not attach a comment to block ${n}`}}function Gs(s,t){const e=s.comments??[];let n=e.find(r=>r.id===t);if(!n)return null;const o=new Set([n.id]);for(;n.parentId&&!o.has(n.parentId);){o.add(n.parentId);const r=e.find(i=>i.id===n.parentId);if(!r)break;n=r}return n}function bc(s,t,e,n,o){const r=Gs(s,e);if(!r)return{success:!1,error:`Comment ${e} not found`,errorCode:"target_not_found"};if(r.resolved)return{success:!1,error:`Comment thread ${r.id} is resolved; leave a new comment instead`,errorCode:"already_resolved"};const i=t.replyToComment(r.id,n,o);return i?{success:!0,commentId:i,threadId:r.id}:{success:!1,error:`Could not reply to comment ${e}`,errorCode:"comment_mutation_failed"}}function yc(s,t,e){const n=W(s.getDocument(),t),o=W(s.getDocumentWithAcceptedSuggestions(),t);if(!n||!o)throw new St("target_missing",`Footnote target '${t}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||o.type!=="paragraph")throw new St("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const r=e?On(o,e):[];if(e&&r.length!==1)throw new St(r.length?"anchor_ambiguous":"anchor_not_found",r.length?`Anchor text matched ${r.length} locations in block ${t}; include unique surrounding text.`:`Anchor text ${JSON.stringify(e)} not found in block ${t}. Read it again.`,"matching");let i=e?r[0].end:kt(o).length;if(kt(n)!==kt(o)){const a=kc(n,kt(o),i);if(a===null)throw new St("target_stale","Anchor could not be mapped across pending suggestions. Read the block again.","target_resolution");i=a}return{block:t,offset:i}}function kc(s,t,e){let n="",o=0,r=e===0?0:null;for(const i of s.children){if(i.type!=="text")return null;const a=i.text.length;i.marks?.deletion||(r===null&&n.length+a>=e&&(r=o+(e-n.length)),n+=i.text),o+=a}return n===t?r:null}function Wo(s,t){return{indentStepPx:Ae(t).indentStepPx,storedAsUnits:s.get(Gt.paragraphIndentStorageVersion)===Po}}const Qs=new WeakMap;function Jo(s){return s.getXmlFragment("content")}function Zs(s,t){let e=t,n=null;for(;e;){if(n=e.parent,n===s)return e instanceof I.XmlElement&&e.getAttribute("id")||null;e=n}return null}function Sc(s){const t=Jo(s),e={nestedBlocks:new WeakMap,doc:null,blockCache:new Map,elementByBlockId:new Map,dirtyBlockIds:new Set,structuralChange:!1,observer:()=>{}},n=o=>{for(const r of o){let i=r.target;for(;i&&i!==t;)i instanceof I.XmlElement&&e.nestedBlocks.delete(i),i=i.parent;if(r.target===t&&r instanceof I.YXmlEvent&&r.childListChanged){e.structuralChange=!0;continue}if(r instanceof I.YXmlEvent&&r.childListChanged){const l=Zs(t,r.target);l!==null&&e.dirtyBlockIds.add(l);continue}const a=Zs(t,r.target);a!==null&&e.dirtyBlockIds.add(a)}};return e.observer=n,t.observeDeep(n),e}function ti(s){let t=Qs.get(s);return t||(t=Sc(s),Qs.set(s,t)),t}function Rn(s,t){const e=ti(s);e.nestedBlocks=new WeakMap,e.doc=t,e.blockCache.clear(),e.elementByBlockId.clear();const n=Jo(s).toArray();for(const o of t.children)o.id&&e.blockCache.set(o.id,o);for(const o of n)if(o instanceof I.XmlElement){const r=o.getAttribute("id");r&&e.elementByBlockId.set(r,o)}e.dirtyBlockIds.clear(),e.structuralChange=!1}function Dn(s,t,e){const n=e.nestedBlocks.get(s);if(n)return n;const o=In(s,t,void 0,r=>Dn(r,t,e));return o&&e.nestedBlocks.set(s,o),o}const $n=new WeakMap;function Ic(s){let t=$n.get(s);t||(t={blocks:[],dirty:!0,observing:!1},$n.set(s,t));const e=s.getXmlFragment("chrome");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=$n.get(s);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof I.XmlElement||o?.constructor?.name==="YXmlElement"){const r=In(o,Wo(s.getMap("metadata"),void 0));r&&r.type==="header-footer"&&n.push(r)}t.blocks=n,t.dirty=!1}return t.blocks}const jn=new WeakMap;function vc(s){let t=jn.get(s);t||(t={blocks:[],dirty:!0,observing:!1},jn.set(s,t));const e=s.getXmlFragment("notes");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=jn.get(s);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof I.XmlElement||o?.constructor?.name==="YXmlElement"){const r=In(o,Wo(s.getMap("metadata"),void 0));r&&r.type==="footnote"&&n.push(r)}t.blocks=n,t.dirty=!1}return t.blocks}function xc(s){return!!($n.get(s)?.dirty||jn.get(s)?.dirty)}function _n(s,t){const e=vc(t);e.length>0?(s.notes=e,fl(s)):delete s.notes}function Xn(s,t){const e=t.getMap("comments"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,r)=>(o.createdAt??"").localeCompare(r.createdAt??"")),s.comments=n):delete s.comments}function Ho(s,t){const e=t.getMap("oxml-ranges"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,r)=>o.id.localeCompare(r.id)),s.oxmlRanges=n):delete s.oxmlRanges}function Un(s,t){const e=t.getMap("sdt-wrappers"),n=[];if(e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0){const o=new Map;s.children.forEach((i,a)=>{i.id&&o.set(i.id,a)});const r=i=>i.blockIds?.[0]??i.startBlockId??"";n.sort((i,a)=>(o.get(r(i))??Number.MAX_SAFE_INTEGER)-(o.get(r(a))??Number.MAX_SAFE_INTEGER)||i.id.localeCompare(a.id)),s.sdtWrappers=n}else delete s.sdtWrappers}function zn(s,t){const e=Ic(t);e.length>0?s.chrome=e:delete s.chrome;const n=hs(e);n.headers?s.headers=n.headers:delete s.headers,n.footers?s.footers=n.footers:delete s.footers}function Kt(s){const t=ti(s),e=Jo(s),n=s.getMap("metadata"),o=n?.get("title"),r=n?.get("pageless"),i=n?.get("watermark"),a=typeof i=="string"&&i.trim()!==""?i:void 0,l=hl(s),c=n?.get("stylesheet"),d=c&&typeof c=="object"&&Array.isArray(c.paragraphStyles)&&c.paragraphStyles.length>0?c:void 0,g=n?.get("stylesXml"),u=typeof g=="string"&&g.length>0?g:void 0,f=n?.get("docxSource"),h=f&&typeof f=="object"&&Array.isArray(f.spans)?f:void 0,p=n?.get("coreProperties"),m=p&&typeof p=="object"&&Object.keys(p).length>0?p:void 0,y=n?.get("fontSubstitutes"),b=y&&typeof y=="object"&&Object.keys(y).length>0?y:void 0,k=us(n),S=Wo(n,k);if(t.indentContext&&(t.indentContext.indentStepPx!==S.indentStepPx||t.indentContext.storedAsUnits!==S.storedAsUnits)&&(t.nestedBlocks=new WeakMap,t.doc=null,t.blockCache.clear(),t.elementByBlockId.clear()),t.indentContext=S,!t.doc){const v=[],x=e.toArray();for(let w=0;w<x.length;w++){const A=x[w];if(A instanceof I.XmlElement){const P=Dn(A,S,t);P&&(v.push(P),t.blockCache.set(P.id,P),t.elementByBlockId.set(P.id,A))}}return t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(e.length!==t.doc.children.length&&(t.structuralChange=!0),t.structuralChange){const v=[],x=new Map,w=new Map,A=e.toArray();for(let P=0;P<A.length;P++){const T=A[P];if(T instanceof I.XmlElement){const E=T.getAttribute("id"),B=E?t.dirtyBlockIds.has(E):!0,N=E?t.blockCache.get(E):void 0,R=E!==null&&t.elementByBlockId.get(E)===T;if(E&&!B&&N&&R)v.push(N),x.set(E,N),w.set(E,T);else{const M=Dn(T,S,t);M&&(v.push(M),x.set(M.id,M),w.set(M.id,T))}}}return t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.blockCache=x,t.elementByBlockId=w,t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(t.dirtyBlockIds.size>0){const v=[...t.doc.children],x=e.toArray();for(let w=0;w<v.length;w++){const A=v[w];if(A?.id&&t.dirtyBlockIds.has(A.id)&&w<x.length){const P=x[w];if(P instanceof I.XmlElement){const T=Dn(P,S,t);T&&(t.blockCache.delete(A.id),v[w]=T,t.blockCache.set(T.id,T),t.elementByBlockId.set(T.id,P))}}}t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.dirtyBlockIds.clear()}return o!==void 0?t.doc.title=o:delete t.doc.title,r!==void 0?t.doc.pageless=r:delete t.doc.pageless,k?t.doc.pageLayout=k:delete t.doc.pageLayout,u?t.doc.stylesXml=u:delete t.doc.stylesXml,h?t.doc.docxSource=h:delete t.doc.docxSource,m?t.doc.coreProperties=m:delete t.doc.coreProperties,b?t.doc.fontSubstitutes=b:delete t.doc.fontSubstitutes,t.doc.chromeImages!==l&&(t.doc={...t.doc},l?t.doc.chromeImages=l:delete t.doc.chromeImages),t.doc.watermark!==a&&(t.doc={...t.doc},a!==void 0?t.doc.watermark=a:delete t.doc.watermark),t.doc.stylesheet!==d&&(t.doc={...t.doc},d!==void 0?t.doc.stylesheet=d:delete t.doc.stylesheet),xc(s)&&(t.doc={...t.doc}),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),t.doc}const qo=new WeakMap,Ve="__revise_end_of_document__";function wt(s,t){qo.set(s,{...qo.get(s),...t})}function Rt(s){return qo.get(s)}function Wn(s){if(s.name==="insert_block")return Rt(s)?.stableId}function wc(s){return!!Rt(s)?.allowNoopContinuation}function Ac(s){if(s.name==="replace_block")return Rt(s)?.multiBlockReplace}const Jn=/\\+u[0-9a-fA-F]{4}/;function ei(s){let t="";const e=[],n=[];for(let o=0;o<s.length;){const r=s.slice(o).match(/^(\\+u)([0-9a-fA-F]{4})/),i=r?o+r[0].length:o+1,a=r?String.fromCharCode(Number.parseInt(r[2],16)):s[o],l=Me(a);t+=l;for(let c=0;c<l.length;c++)e.push(o),n.push(i);o=i}return{text:t,sourceStarts:e,sourceEnds:n}}function Yo(s,t){return s.flatMap(e=>{if(e.length<=0)return[];const n=t.sourceStarts[e.offset],o=t.sourceEnds[e.offset+e.length-1];return n===void 0||o===void 0||o<n?[]:[{offset:n,length:o-n}]})}function Ko(s){return s.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function Tc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(s,t){const e=t.split(/(\s+)/),n=[];for(const l of e)/^\s+$/.test(l)?n.push("\\s+"):l.length>0&&n.push(Tc(l));if(n.length===0)return[];const o=n.join(""),r=new RegExp(o,"g"),i=[];let a;for(;(a=r.exec(s))!==null;)i.push({offset:a.index,length:a[0].length});return i}function Cc(s,t,e,n,o){const r=[];let i=s.indexOf(t);for(;i!==-1;){const a=i+n-e.length,l=Math.min(i+o-e.length+1,s.length);for(let c=a;c<l;c++)if(s.substring(c,c+e.length)===e){const d=c+e.length-i;d>=n&&d<=o&&r.push({offset:i,length:d})}i=s.indexOf(t,i+1)}return r}function Hn(s,t){const e=$o(t);if(e.length>1)for(const n of e){const o=Pn(s,n);if(o.length)return o.map(({start:r,end:i})=>({offset:r,length:i-r}))}for(const n of e){if(qe(n))continue;const o=Pc(s,n);if(o.length)return o}return[]}function Pc(s,t){if(!t)return[];if(/^\s*$/.test(t))return Vo(s,t);if(Jn.test(s)||Jn.test(t))return oi(s,t);const e=sc();return e!==null?e:oi(s,t)}function oi(s,t){const e=Pn(s,t);if(e.length)return e.map(({start:d,end:g})=>({offset:d,length:g-d}));const n=Me(s),o=Me(t),r=Vo(n,o);if(r.length>0)return r;const i=ni(n,o);if(i.length>0)return i;let a,l;if(Jn.test(s)||Jn.test(t)){a=ei(s),l=ei(t).text;const d=Vo(a.text,l);if(d.length>0)return Yo(d,a);const g=ni(a.text,l);if(g.length>0)return Yo(g,a)}const c=8;if(o.length>=c*2){const d=ri(n,o,c);if(d!==null)return[d]}if(a&&l&&l.length>=c*2){const d=ri(a.text,l,c);if(d!==null)return Yo([d],a)}return[]}function Mc(s,t){let e="";for(const n of s.children)n.type==="text"&&(e+=n.text);return Hn(e,t)}function Vo(s,t){const e=[];let n=s.indexOf(t);for(;n!==-1;)e.push({offset:n,length:t.length}),n=s.indexOf(t,n+t.length);return e}function ri(s,t,e){const n=Math.floor(t.length/2);for(let o=n;o>=e;o--){const r=t.substring(0,o),i=t.substring(t.length-o),a=Math.max(5,Math.floor(t.length*.2)),l=Math.max(o*2,t.length-a),c=t.length+a,d=Cc(s,r,i,l,c);if(d.length===1)return d[0]}return null}function si(s,t){const e=Do(s);return t.code||t.latex?e:tc(e)}function Go(s,t){const e=W(s,t);if(!e)return null;if(e.id===t)return{block:e,container:e};if(e.type==="list"){const n=e,o=n.children.find(r=>r.id===t);return o?{block:o,container:{...n,children:[o]}}:null}return null}function Bc(s){return s instanceof St&&s.code==="text_not_found"}class Ec{constructor(t){this.doc=t,this.forks=new Map,this.texts=new Map,this.dirty=new Set}text(t,e){if(this.dirty.delete(t)){const n=this.forks.get(t),o=n?Go(mt(n),t):null;this.texts.set(t,o?kt(o.block):null)}if(!this.texts.has(t)){if(e!==void 0)return e;const n=Go(this.doc,t);this.texts.set(t,n?kt(n.block):null)}return this.texts.get(t)}apply(t,e,n,o){const r=this.forkOf(t);if(!r)return!1;try{Wt(r,{name:o?"replace_all":"replace",arguments:{id:t,find:e,replace:n}})}catch(i){if(Bc(i))return!1;throw i}return this.dirty.add(t),!0}get forkCount(){return this.forks.size}forkOf(t){if(!this.forks.has(t)){const e=Go(this.doc,t);let n=null;e&&(n=new I.Doc,n.getXmlFragment("content").insert(0,[It(e.container)])),this.forks.set(t,n)}return this.forks.get(t)}}function Qo(s,t){if(qe(t)){let e=null;for(const n of s){const o=n.html?ec(n.text,n.html,t):[];if(o.length){if(o.length>1||e!==null)return null;e=n.blockId}}if(e!==null)return e}for(const e of["exact","normalized"]){let n=null;for(const o of s){const r=Fs(o.text,t,e);if(r.length){if(r.length>1||n!==null)return null;n=o.blockId}}if(n!==null)return n}return null}function ee(s){const t=$o(s).at(-1);return nc(Me(t)).text}function ii(s){return s?.type==="paragraph"||s?.type==="list-item"||s?.type==="code"||s?.type==="math"}function Ge(s){const t=[],e=(n,o)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&ii(n)&&t.push({blockId:n.id,topLevelBlockId:o,text:kt(n)}),Array.isArray(n.children)))for(const r of n.children)e(r,o)};for(const n of s.children)e(n,n.id??null);for(const n of s.notes??[])e(n,n.id);return t}function Zo(s,t){const e=n=>!n||typeof n!="object"?!1:n.id===t?!0:Array.isArray(n.children)&&n.children.some(e);for(const n of s.notes??[])if(e(n))return n.id;return null}function ai(s,t){const e=Zo(s,t);if(!e)return null;if(t!==e)return t;const n=s.notes?.find(i=>i.id===e);if(!n)return t;const o=[],r=i=>{!i||typeof i!="object"||(typeof i.id=="string"&&(i.type==="paragraph"||i.type==="list-item"||i.type==="code"||i.type==="math")&&o.push(i.id),Array.isArray(i.children)&&i.children.forEach(r))};return n.children.forEach(r),o.length===1?o[0]:t}function qn(s,t){return t.has(s.blockId)||s.topLevelBlockId!==null&&t.has(s.topLevelBlockId)}class tr{constructor(t){this.doc=t,this.normalized=new Map,this.candidates=null,this.simulation=new Ec(t)}contains(t,e){return this.qualifies(t,e)}qualifies(t,e,n){const o=this.simulation.text(t,n);if(o===null)return!1;const r=ee(e);if(!r||/^\s*$/.test(r))return!1;let i=this.normalized.get(o);if(i===void 0&&(i=ee(o),this.normalized.size>4096&&this.normalized.clear(),this.normalized.set(o,i)),!i.includes(r))return!1;if(Hn(o,e).length>0)return!0;const a=Ko(e);return a!==e&&a.trim()!==""&&Hn(o,a).length>0}apply(t,e,n,o){return this.simulation.apply(t,e,n,o)}loadedTargets(t,e){if(!e||e.size===0)return[];const n=ee(t);return!n||/^\s*$/.test(n)?[]:(this.candidates??(this.candidates=Ge(this.doc)),this.candidates.filter(o=>qn(o,e)&&this.qualifies(o.blockId,t,o.text)).map(o=>o.blockId))}}function Nc(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return[];const t=ee(s.find);return!t||/^\s*$/.test(t)?[]:Ge(s.doc).filter(e=>qn(e,s.loadedBlockIds)&&ee(e.text).includes(t)).map(e=>e.blockId)}function li(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return null;const t=ee(s.find);if(!t||/^\s*$/.test(t))return null;const e=W(s.doc,s.requestedBlockId);if(e&&ee(kt(e)).includes(t))return null;const n=$o(s.find).at(-1),o=Ge(s.doc).filter(i=>i.blockId!==s.requestedBlockId&&qn(i,s.loadedBlockIds));if(o.some(i=>Pn(i.text,n).length>0))return Qo(o,n);let r=null;for(const i of o)if(ee(i.text).includes(t)){if(r!==null)return null;r=i.blockId}return r}function Lc(s,t,e){const n=W(s,t);if(!n||n.id!==t||!["table","table-row","table-cell"].includes(n.type))return null;const o=Ge({children:[n]});return Qo(o,e)}const ci=new WeakSet;function er(s){ci.add(s)}function Fc(s){if(s.action.name!=="replace"&&s.action.name!=="replace_all"){const d=s.action.arguments?.id;return typeof d=="string"&&d&&s.opaqueBlockIds.add(d),{action:s.action}}if(!s.action.arguments||typeof s.action.arguments!="object")return{action:s.action};const t=s.action.arguments,e=typeof t.id=="string"?t.id.trim():"",n=typeof t.find=="string"?t.find:"";if(!e||!n)return{action:s.action};const o=typeof t.replace=="string"?t.replace:"",r=s.action.name==="replace_all",i=d=>{try{s.plannedTexts.apply(d,n,o,r)}catch{s.opaqueBlockIds.add(d)}};if(ci.has(s.action)||s.opaqueBlockIds.has(e))return i(e),{action:s.action};const a=Lc(s.doc,e,n)??(s.plannedTexts.contains(e,n)?null:li({doc:s.doc,requestedBlockId:e,find:n,loadedBlockIds:s.loadedBlockIds}));if(i(a??e),!a)return{action:s.action};const l={...s.action,arguments:{...t,id:a}},c=Rt(s.action);return c&&wt(l,c),{action:l,retarget:{fromBlockId:e,toBlockId:a}}}function Oc(s){const t=[],e=[],n=new tr(s.doc),o=new Set;for(const r of s.actions){const i=Fc({action:r,doc:s.doc,loadedBlockIds:s.loadedBlockIds,plannedTexts:n,opaqueBlockIds:o});t.push(i.action),i.retarget&&e.push(i.retarget)}return{actions:t,retargets:e}}function nr(s){return s.children.map(t=>{const e={type:"doc",children:[t]};return it.toInternalHtml(e).trim()})}function Rc(s,t=0){const e=Nn.fromMarkdown(s);if(t){for(const n of e.children)if(n.type==="list")for(const o of n.children)o.indentLevel=Math.min(8,t+(o.indentLevel??0))}return nr(e)}function Dc(s){return s.replace(/<span\b([^>]*?)\sdir\s*=\s*["']?(ltr|rtl|auto)["']?([^>]*)>([\s\S]*?)<\/span>/gi,(t,e,n,o,r)=>{const i=n.toLowerCase(),a=i==="ltr"?"⁦":i==="rtl"?"⁧":"⁨",l=`${e}${o}`.trim(),c=l?`<span ${l}>${r}</span>`:r;return`${a}${c}⁩`})}function $c(s,t,e,n){return nr(it.fromAgentHtml(Dc(s),{existingDocument:t,replacementBlock:e,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const he=/<\/?[a-z][^>]*>/i;function Ne(s){return s.replace(/\s+/g," ").trim()}function di(s){return Ne(s).replace(/^>\s+/,"")}function jc(s,t){if(s.replace==="")return null;const e=s.format==="html"||he.test(s.replace),n=e?it.fromAgentHtml(s.replace,{replacementBlock:W(t,s.id)??void 0,existingDocument:t,preserveImageReferenceIds:!0}):Nn.fromMarkdown(s.replace);if(n.children.length!==1||n.children[0].type!=="list")return null;const o=n.children[0].children;if(o.length===0)return null;const r=W(t,s.id);if(!r||r.type!=="list")return null;const i=r,a=he.test(s.find)?it.fromAgentHtml(s.find,{existingDocument:t,preserveImageReferenceIds:!0}):Nn.fromMarkdown(s.find),l=a.children.length===1&&a.children[0].type==="list"?a.children[0].children.map(y=>Ne(kt(y))):[Ne(kt(a))];if(l.length===0||l.some(y=>y===""))return null;const c=i.children.map(y=>Ne(kt(y))),d=[];for(let y=0;y+l.length<=c.length;y++)l.every((b,k)=>c[y+k]===b)&&(d.push(y),y+=l.length-1);if(d.length===0)throw new Error(`replace: the replacement contains ${o.length} list items, so "find" must match complete list item(s) in block '${s.id}' — it did not. Include each full item's text in "find" (or use insert_markdown to add items).`);if(d.length>1&&!s.all)throw new Error(`replace: "find" matches ${d.length} runs of list items in block '${s.id}'. Include more items in "find" so it matches exactly one location, or set all: true.`);const g=s.all?d:[d[0]],u=[];let f=0;for(const y of g)u.push(...i.children.slice(f,y)),u.push(...o),f=y+l.length;u.push(...i.children.slice(f));const h=g.length===1&&g[0]===0&&l.length===i.children.length,p=h?{...n.children[0],id:i.id}:{...i,children:u},m=h&&e?s.replace:nr({children:[p]})[0];return{name:"replace_block",arguments:{id:i.id,content:[m]}}}function _c(s,t){if(s.replace===""||s.all)return null;const e=W(t,s.id);if(!e)return null;const n=s.format==="html"||!s.format&&he.test(s.find)?kt(it.fromAgentHtml(s.find,{existingDocument:t,preserveImageReferenceIds:!0})):kt(Nn.fromMarkdown(s.find)),o=kt(e);if(di(n)!==di(o))return null;const r=s.format==="html"||!s.format&&he.test(s.replace)?$c(s.replace,t,e):Rc(s.replace),i=r.length===1&&/^<p\b[^>]*>[\s\S]*<\/p>$/i.test(r[0]),a=(s.format==="html"||!s.format&&he.test(s.replace))&&/^<p\s+[^>]+>/i.test(s.replace.trim()),l=e.type==="footnote"?ai(t,s.id):null,c=l!==null&&l!==s.id&&W(t,l)?.type==="paragraph",d=s.format!=="markdown"&&he.test(s.find)&&!he.test(s.find.replace(/<\/?(?:b|strong|i|em|u|s|strike|sup|sub|code|mark|span|a|br)\b[^>]*>/gi,""));return i&&!a&&(e.type==="table-cell"||c||e.type==="paragraph"&&(d||Ne(s.find)===Ne(o)))?null:{name:"replace_block",arguments:{id:s.id,content:r}}}function Xc(s,t){return jc(s,t)??_c(s,t)}function or(s,t){const e=W(s,t);return e?hi(e):null}const Yn=s=>s===void 0||typeof s=="function";function Ut(s,t){if(s===t)return!0;if(typeof s!="object"||typeof t!="object"||!s||!t)return typeof s=="number"&&typeof t=="number"?!Number.isFinite(s)&&!Number.isFinite(t):!1;const e=s.toJSON,n=t.toJSON;if(typeof e=="function"||typeof n=="function")return Ut(typeof e=="function"?e.call(s):s,typeof n=="function"?n.call(t):t);if(Array.isArray(s)||Array.isArray(t)){if(!Array.isArray(s)||!Array.isArray(t)||s.length!==t.length)return!1;for(let l=0;l<s.length;l++)if(!Ut(s[l],t[l]))return!1;return!0}const o=s,r=t,i=Object.keys(o).filter(l=>!Yn(o[l])),a=Object.keys(r).filter(l=>!Yn(r[l]));if(i.length!==a.length)return!1;for(const l of i)if(Yn(r[l])||!Object.prototype.hasOwnProperty.call(r,l)||!Ut(o[l],r[l]))return!1;return!0}const gi=16777619,Uc=1114113,zc=1114114,Wc=1114115,Jc=1114116,rr=1114117,Hc=1114118,ui=1114119;function Kn(s,t){switch(typeof t){case"string":return sr(_t(_t(s,Uc),t.length),t);case"number":return Number.isFinite(t)?sr(_t(s,zc),String(t)):_t(s,rr);case"boolean":return _t(s,t?Wc:Jc);case"object":break;default:return _t(s,rr)}if(t===null)return _t(s,rr);const e=t;if(typeof e.toJSON=="function")return Kn(s,e.toJSON());if(Array.isArray(t)){s=_t(_t(s,Hc),t.length);for(const r of t)s=Kn(s,r);return s}const n=t;let o=Object.keys(n);for(let r=1;r<o.length;r++)if(o[r-1]>o[r]){o=[...o].sort();break}s=_t(s,ui);for(const r of o){const i=n[r];Yn(i)||(s=sr(_t(s,r.length),r),s=Kn(s,i))}return _t(s,ui)}function _t(s,t){return Math.imul(s^t,gi)}function sr(s,t){for(let e=0;e<t.length;e++)s=Math.imul(s^t.charCodeAt(e),gi);return s}function hi(s){return(Kn(2166136261,s)>>>0).toString(36)}function qc(s,t){const e=new Map;for(const n of t){if(e.has(n))continue;const o=or(s,n);o!==null&&e.set(n,o)}return e}const fi=50,pi="document_state_changed",Yc=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function ir(s,t){const e=s.name==="replace"&&!!s.arguments&&typeof s.arguments=="object"&&Object.prototype.hasOwnProperty.call(s.arguments,"replacements"),n=s.name==="replace_many";if(!e&&!n)return{actions:[s]};const o=n?"replace_many":"replace";if(!s.arguments||typeof s.arguments!="object")return{actions:[],error:`${o} requires object arguments`};const r=s.arguments.id,i=s.arguments.replacements;if(!Array.isArray(i)||i.length===0)return{actions:[],error:`${o} requires a non-empty replacements array`};if(i.length>fi)return{actions:[],error:`${o} supports at most ${fi} replacements per call`};const a=[],l=t?new tr(t.doc):null;for(let d=0;d<i.length;d++){const g=i[d];if(!g||typeof g!="object")return{actions:[],error:`${o} replacement #${d+1} must be an object`};if(typeof g.find!="string")return{actions:[],error:`${o} replacement #${d+1} is missing "find"`};if(g.find.length===0&&(n||typeof r!="string"||r.trim().length===0))return{actions:[],error:n?`${o} replacement #${d+1} has an empty "find"`:`${o} replacement #${d+1} has an empty "find" and therefore requires a direct block id`};if(typeof g.replace!="string")return{actions:[],error:`${o} replacement #${d+1} is missing "replace"`};if(g.occurrence!==void 0&&g.occurrence!==null&&g.occurrence!=="unique"&&g.occurrence!=="all")return{actions:[],error:`${o} replacement #${d+1} has invalid "occurrence"; use "unique" or "all"`};if(g.comment!==void 0&&g.comment!==null&&(typeof g.comment!="string"||g.comment.trim().length===0))return{actions:[],error:`${o} replacement #${d+1} comment must be a non-empty string when provided`};let u=typeof r=="string"&&r.trim()?[r.trim()]:[];const f=u.length===0;if(u.length===0&&g.find.length>0&&t){const h=l?l.loadedTargets(g.find,t.loadedBlockIds):[];if(g.occurrence==="all")u=h;else if(l)u=h.length===1?h:[];else{const p=li({doc:t.doc,requestedBlockId:"",find:g.find,loadedBlockIds:t.loadedBlockIds});u=p?[p]:[]}}if(u.length===0){const h=t&&g.find.length>0?l?l.loadedTargets(g.find,t.loadedBlockIds):Nc({doc:t.doc,find:g.find,loadedBlockIds:t.loadedBlockIds}):[];return{actions:[],error:t?.loadedBlockIds?.size&&g.find.length>0?h.length===0?`${o} replacement #${d+1}: find text was not found in any loaded block. Check the exact text, or read the block that contains it.`:`${o} replacement #${d+1}: find text appears in ${h.length} loaded blocks (${h.slice(0,10).join(", ")}). Pass a block id, or use occurrence "all" to replace it in every one.`:`${o} replacement #${d+1} requires a block id unless its find text uniquely identifies one loaded block`}}for(const h of u){try{l?.apply(h,g.find,g.replace,g.occurrence==="all")}catch{}const p=u.length===1?`${s.id||o}-${d+1}`:`${s.id||o}-${d+1}-${h}`;if(t&&!g.comment)try{const y=Xc({type:"replace",id:h,find:g.find,replace:g.replace,format:"html",all:g.occurrence==="all"},t.doc);if(y){const b={...y,id:p};f&&er(b),a.push(b);continue}}catch(y){return{actions:[],error:y instanceof Error?y.message:String(y),failure:Be(y)}}const m={id:p,name:g.occurrence==="all"?"replace_all":"replace",arguments:{id:h,find:g.find,replace:g.replace,...typeof g.comment=="string"?{comment:g.comment.trim()}:{}}};f&&er(m),a.push(m)}}const c=Array.from(new Set(a.map(d=>d.arguments?.id).filter(d=>typeof d=="string"&&d.length>0)));return{actions:a,blockId:c.length===1?c[0]:void 0}}function Kc(s){const{toolCall:t,docBefore:e,resultSets:n}=s,o=t.arguments;if(!o||typeof o!="object")return null;const r=o.search_result_id;if(r==null)return null;if(typeof r!="string"||r.trim().length===0)return{actions:[],targetBlockIds:[],error:"search_result_id must be a non-empty string"};const i=r.trim();if(!Yc.has(t.name))return{actions:[],targetBlockIds:[],error:`${t.name} does not support search_result_id`};if(typeof o.id=="string"&&String(o.id).trim().length>0||Array.isArray(o.ids))return{actions:[],targetBlockIds:[],error:`${t.name} accepts either search_result_id or direct id/ids targets, not both.`};const a=n.get(i);if(!a)return{actions:[],targetBlockIds:[],error:`Search result '${i}' is unavailable. Search result references are request-scoped; rerun search_document in this request, then retry.`,errorCode:pi};for(const u of a.blockIds){if(Zo(e,u))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const f=or(e,u);if(f===null||f!==a.blockHashes.get(u))return{actions:[],targetBlockIds:[],error:`Search result '${i}' is stale because block '${u}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:pi}}const{search_result_id:l,...c}=o,d=[];let g=[...a.blockIds];if(t.name==="replace"){const u=c.replacements,f=(Array.isArray(u)?u:[c]).map(k=>k&&typeof k=="object"?k:{}),h=new tr(e),p=f.map(()=>!1),m=(k,S,v,x)=>{try{return h.apply(k,S,v,x)}catch{return!0}},y=a.blockIds.map(k=>f.flatMap((S,v)=>{const{find:x,replace:w}=S;return typeof x!="string"||x.length===0||h.contains(k,x)&&m(k,x,typeof w=="string"?w:"",S.occurrence==="all"||!Array.isArray(u))?(p[v]=!0,[v]):[]})),b=p.flatMap((k,S)=>k?[]:[S]);if(b.length>0)return{actions:[],targetBlockIds:[],error:`Search result '${i}' has no block containing the find text of ${Array.isArray(u)?`replacement ${b.map(k=>`#${k+1}`).join(", ")}`:"this replacement"}. Check the exact text; no replacement was applied.`};g=[];for(let k=0;k<a.blockIds.length;k++){const S=a.blockIds[k],v=y[k];if(v.length===0)continue;const x=Array.isArray(u)?v.map(A=>u[A]):null,w=ir({...t,id:`${t.id||"replace"}-search-${k+1}`,arguments:{...c,...x?{replacements:x}:{},id:S}});if(w.error)return{actions:[],targetBlockIds:[],error:w.error};for(const A of w.actions)er(A),d.push(A);g.push(S)}}else if(t.name==="replace_block"){const u=o.count;if(u!=null&&u!==1)return{actions:[],targetBlockIds:[],error:"replace_block with search_result_id applies independently to each matched block, so count must be omitted or 1."};for(let f=0;f<a.blockIds.length;f++)d.push({...t,id:`${t.id||"replace_block"}-search-${f+1}`,arguments:{...c,id:a.blockIds[f],count:1}})}else if(t.name==="remove_block")for(let u=0;u<a.blockIds.length;u++)d.push({...t,id:`${t.id||"remove_block"}-search-${u+1}`,arguments:{id:a.blockIds[u],count:1}});else{const u=o.selectors,f=(Array.isArray(u)?u:typeof u=="string"?[u]:[]).flatMap(p=>typeof p=="string"?p.split(",").map(m=>m.trim()):[p]);if(f.length===0||f.some(p=>typeof p!="string"||p.trim().length===0))return{actions:[],targetBlockIds:[],error:"style_blocks requires one or more non-empty selectors"};const h=a.blockIds.flatMap(p=>f.map(m=>{const y=String(m).trim();return/^(?:\*|all|document|:root)$/i.test(y)?`#${p}`:`#${p} ${y}`}));d.push({...t,arguments:{...c,selectors:h}})}return{actions:d,targetBlockIds:g,resultSet:a}}function mi(s,t){const e={...t};for(const n of["lang","oxmlRPr","oxmlRange","sdtInline","field","aiGenerated","__htmlClassName"])e[n]===void 0&&s?.[n]!==void 0&&Object.assign(e,{[n]:s[n]});for(const n of fs)e[n]===void 0&&s?.[n]===!1&&(e[n]=!1);if(e.docxRunPropertyResets===void 0){const n=pl(s?.docxRunPropertyResets)?.split(",").filter(o=>o==="color"?e.color===void 0:e.backgroundColor===void 0);n?.length&&(e.docxRunPropertyResets=n.join(","))}return e}function Vn(s,t){const e=s.map(i=>i.text).join("");if(!e||e!==t.map(i=>i.text).join("")){const i=new Set(s.filter(l=>l.text.length>0).map(l=>l.marks?.lang)),a=i.size===1?[...i][0]:void 0;return a===void 0?t:t.map(l=>({...l,marks:{lang:a,...l.marks}}))}const n=[];let o=0,r=0;for(const i of t){if(i.text.length===0){n.push({...i,marks:i.marks?{...i.marks}:void 0});continue}let a=0;for(;a<i.text.length;){for(;r===s[o].text.length;)o++,r=0;const l=s[o],c=Math.min(i.text.length-a,l.text.length-r);n.push({...i,text:i.text.slice(a,a+c),marks:mi(l.marks,i.marks)}),a+=c,r+=c}}return n}function Vc(s,t){const e=Mn(s),n=Array.from({length:e.cols},(l,c)=>Math.max(.001,s.columnWidths[c]||100/e.cols)),o=new Map;for(const l of t){const c=e.byId.get(l.cellId);if(!c)throw new St("target_stale","The requested table cell no longer exists. Read the table again.","target_resolution");if(!Number.isFinite(l.percent)||l.percent<=0||l.percent>100)throw new St("attribute_value_unsupported","Cell width must be greater than 0 and at most 100 percent.");const d=n.slice(c.col,c.col+c.colSpan).reduce((g,u)=>g+u,0);for(let g=c.col;g<c.col+c.colSpan;g++){const u=l.percent*n[g]/d;if(o.has(g)&&Math.abs(o.get(g)-u)>.001)throw new St("attribute_conflict","Conflicting cell widths constrain the same table column. Set each column once, using one unmerged row.");o.set(g,u)}}const r=[...o.values()].reduce((l,c)=>l+c,0),i=n.map((l,c)=>c).filter(l=>!o.has(l));if(r>100.001||!i.length&&Math.abs(r-100)>.001||i.length&&r>=100)throw new St("attribute_conflict","Requested column widths conflict: they must leave space for other columns and sum to 100 percent when all columns are specified.");const a=i.reduce((l,c)=>l+n[c],0);return n.map((l,c)=>o.get(c)??(100-r)*l/a)}function bi(s,t,e,n){if(!n?.length)return;const o=t==="row"?s.cols:s.rows;if(n.length>o)return{success:!1,error:`content[${o}] is outside the table's ${o} ${t==="row"?"columns":"rows"}. Supply at most ${o} entries for this insertion.`};for(const r of s.cells){const i=t==="row"?r.row:r.col,a=t==="row"?r.rowSpan:r.colSpan;if(i>=e||i+a<=e)continue;const l=t==="row"?r.col:r.row,c=t==="row"?r.colSpan:r.rowSpan;for(let d=l;d<l+c;d++)if(n[d]?.length)return{success:!1,error:`content[${d}] targets a position covered by a merged cell. Leave that slot empty or insert outside the merged span; the table was not changed.`}}}function Gc(s,t){return{type:"paragraph",id:G(),...s?{direction:s}:{},children:[{type:"text",text:"",...t?{marks:t}:{}}]}}function yi(s){const t=s?.children.find(n=>n.type==="paragraph")?.children.find(n=>n.type==="text")?.marks;if(!t)return;const e={};return t.fontFamily&&t.fontFamily!==ml&&(e.fontFamily=t.fontFamily),typeof t.fontSize=="number"&&(e.fontSize=t.fontSize),typeof t.color=="string"&&t.color&&(e.color=t.color),Object.keys(e).length>0?e:void 0}function ki(s){const t=s?.children.find(n=>n.type==="paragraph");if(!t)return;let e="";for(const n of t.children)e+=n.text??"";return Ds(t.direction,e)==="rtl"?"rtl":void 0}function Qc(s,t){return{type:"table-cell",id:G(),children:[Gc(s,t)]}}function Si(s,t,e){return!s||s.length===0?Qc(t,e):{type:"table-cell",id:G(),children:s}}function Gn(s,t){const e=s.get("content",I.XmlFragment);function n(o){for(let r=0;r<o.length;r++){const i=o.get(r);if(i instanceof I.XmlElement){if(i.nodeName==="table"&&i.getAttribute("id")===t)return i;if(i.nodeName==="container"||i.nodeName==="footnote"||i.nodeName==="table"||i.nodeName==="table-row"||i.nodeName==="table-cell"){const a=n(i);if(a)return a}}}return null}return n(e)??n(s.getXmlFragment("notes"))}function ar(s,t){const e=Number(rt(s,t));return Number.isFinite(e)&&e>1?Math.floor(e):1}function Ii(s){if(!s)return;const t=In(s.el,{indentStepPx:48,storedAsUnits:!1});return t?.type==="table-cell"?t:void 0}function Qn(s){const t=[];for(let a=0;a<s.length;a++){const l=s.get(a);l instanceof I.XmlElement&&l.nodeName==="table-row"&&t.push(l)}const e=s.getAttribute("columnWidths");let n=0;try{const a=e?JSON.parse(e):[];n=Array.isArray(a)?a.length:0}catch{n=0}for(const a of t){let l=0;for(let c=0;c<a.length;c++){const d=a.get(c);d instanceof I.XmlElement&&d.nodeName==="table-cell"&&(l+=ar(d,"colSpan"))}n=Math.max(n,l)}n=Math.max(n,1);const o=t.length,r=Array.from({length:o},()=>new Array(n).fill(void 0)),i=[];for(let a=0;a<o;a++){const l=t[a];let c=0,d=0;for(let g=0;g<l.length;g++){const u=l.get(g);if(!(u instanceof I.XmlElement)||u.nodeName!=="table-cell")continue;for(;c<n&&r[a][c]!==void 0;)c++;if(c>=n)break;const f=Math.min(ar(u,"colSpan"),n-c),h=Math.min(ar(u,"rowSpan"),o-a),p={el:u,row:a,col:c,rowSpan:h,colSpan:f,physicalIndex:d};i.push(p);for(let m=a;m<a+h;m++)for(let y=c;y<c+f;y++)r[m][y]===void 0&&(r[m][y]=p);c+=f,d++}}return{rows:o,cols:n,cells:i,occupancy:r,rowEls:t}}function Qe(s,t,e){e>1?s.setAttribute(t,String(e)):et(s,t)}function vi(s){return It(s)}function Zc(s){const t=new I.XmlElement("table-row");t.setAttribute("id",s.id);let e=0;for(const n of s.children){const o=vi(n);t.insert(e++,[o])}return t}function td(s,t,e){const n=Gn(s,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=Qn(n);return o.rows===0?{success:!1,error:"Table has no rows."}:e<0||e>=o.cols?{success:!1,error:`Invalid column index ${e}. Table has ${o.cols} columns.`}:o.cols<=1?{success:!1,error:"Cannot remove the last column from a table."}:(s.transact(()=>{for(const i of o.cells)i.col<=e&&e<i.col+i.colSpan&&(i.colSpan>1?Qe(i.el,"colSpan",i.colSpan-1):o.rowEls[i.row].delete(i.physicalIndex,1));const r=n.getAttribute("columnWidths");if(r){const i=JSON.parse(r);if(e<i.length){const a=i[e];i.splice(e,1);const l=i.reduce((d,g)=>d+g,0),c=l>0?i.map(d=>d+a*d/l):i;n.setAttribute("columnWidths",JSON.stringify(c))}}}),{success:!0})}function ed(s,t){const e=Qn(s);if(t<0||t>=e.rows)return;for(const r of e.cells)r.row<t&&r.row+r.rowSpan>t&&Qe(r.el,"rowSpan",r.rowSpan-1);const n=e.cells.filter(r=>r.row===t&&r.rowSpan>1).sort((r,i)=>r.col-i.col);if(n.length>0&&t+1<e.rows){const r=e.rowEls[t+1],i=e.cells.filter(l=>l.row===t+1);let a=0;for(const l of n){const c=l.el.clone();Qe(c,"rowSpan",l.rowSpan-1);const d=i.filter(g=>g.col<l.col).length+a;r.insert(d,[c]),a++}}const o=e.rowEls[t];for(let r=0;r<s.length;r++)if(s.get(r)===o){s.delete(r,1);break}}function nd(s,t,e){const n=Gn(s,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=[...new Set(e)],r=o.find(i=>!Number.isInteger(i)||i<0||i>=n.length);return r!==void 0?{success:!1,error:`Invalid row index ${r}. Table has ${n.length} rows.`}:o.length===0?{success:!1,error:"No rows to remove."}:o.length>=n.length?{success:!1,error:"Cannot remove the last row from a table. To delete every row, remove the table block instead."}:(s.transact(()=>{for(const i of o.sort((a,l)=>l-a))ed(n,i)}),{success:!0})}const Zn=s=>s==null?void 0:Array.isArray(s)?s:[s];function xi(s,t){const e=[...Zn(t.rowIds)??[],...Zn(t.rowId)??[]],n=[...Zn(t.rowIndices)??[],...Zn(t.rowIndex)??[]];if(e.length&&n.length)return{error:"Pass rowIds or rowIndices, not both. Prefer rowIds: the stable <tr id> values from the table you read."};if(!e.length&&!n.length)return{error:"Pass rowIds: the stable <tr id> of each row to remove (one string or an array)."};const o=e.length>0,r=[],i=[];for(const l of o?e:n)if(o){const c=typeof l=="string"?s.children.findIndex(d=>d.id===l):-1;c<0?i.push(`Row ${JSON.stringify(l)} not found`):r.push(c)}else!Number.isInteger(l)||Number(l)<0||Number(l)>=s.children.length?i.push(`Invalid row index ${JSON.stringify(l)} (table has ${s.children.length} rows)`):r.push(Number(l));if(i.length)return{error:`${i.join("; ")} in table ${s.id}. No rows were removed. Read the table and use current row IDs.`};if(new Set(r).size!==r.length)return{error:`Each row may be listed once. No rows were removed from table ${s.id}.`};if(r.length>=s.children.length)return{error:`Cannot remove the last row from table ${s.id}. To delete every row, remove the table block instead.`};const a=[...r].sort((l,c)=>l-c);return{rowIndices:a,rowIds:a.map(l=>s.children[l].id),byId:o}}function od(s,t,e,n,o){const r=Gn(s,t);if(!r)return{success:!1,error:`Table with ID "${t}" not found.`};const i=Qn(r);if(i.rows===0)return{success:!1,error:"Table has no rows."};const a=i.cols;if(n<0||n>=a)return{success:!1,error:`Invalid reference column index ${n}. Table has ${a} columns.`};const l=e==="before"?n:n+1;return bi(i,"column",l,o)||(s.transact(()=>{for(let g=0;g<i.rows;g++){const u=l>0&&l<a&&i.occupancy[g][l-1]===i.occupancy[g][l]?i.occupancy[g][l]:void 0;if(u){u.row===g&&Qe(u.el,"colSpan",u.colSpan+1);continue}const f=o?.[g],h=Ii(i.occupancy[g]?.[n]),p=Si(f,ki(h),yi(h)),m=vi(p),y=i.cells.filter(b=>b.row===g&&b.col<l).length;i.rowEls[g].insert(y,[m])}const d=r.getAttribute("columnWidths");if(d){const g=JSON.parse(d),u=100/(a+1),f=(100-u)/100,h=g.map(p=>p*f);h.splice(l,0,u),r.setAttribute("columnWidths",JSON.stringify(h))}}),{success:!0})}function rd(s,t,e,n){const o=Qn(t);return bi(o,"row",e,n)||(s.transact(()=>{const i=o.cells.filter(u=>u.row<e&&u.row+u.rowSpan>e),a=new Set;for(const u of i){Qe(u.el,"rowSpan",u.rowSpan+1);for(let f=u.col;f<u.col+u.colSpan;f++)a.add(f)}const l=[];for(let u=0;u<o.cols;u++){if(a.has(u))continue;const f=Ii(o.occupancy[e-1]?.[u]??o.occupancy[e]?.[u]);l.push(Si(n?.[u],ki(f),yi(f)))}const c={id:G(),children:l},d=Zc(c);let g=t.length;if(e<o.rows){const u=o.rowEls[e];for(let f=0;f<t.length;f++)if(t.get(f)===u){g=f;break}}t.insert(g,[d])}),{success:!0})}function sd(s,t,e,n,o){const r=Gn(s,t);if(!r)return{success:!1,error:`Table with ID "${t}" not found.`};if(n<0||n>=r.length)return{success:!1,error:`Invalid reference row index ${n}. Table has ${r.length} rows.`};const i=r.get(0);if(!(i instanceof I.XmlElement)||i.nodeName!=="table-row")return{success:!1,error:"Table has no rows."};const a=e==="before"?n:n+1;return rd(s,r,a,o)}const wi=new Set(["com","org","net","edu","gov","mil","int","io","co","ai","app","dev","tech","cloud","software","digital","online","site","website","web","blog","biz","info","pro","company","agency","studio","media","news","shop","store","uk","de","fr","es","it","nl","be","at","ch","cx","pl","ru","cn","jp","kr","in","au","nz","ca","us","mx","br","ar","za","ie","se","no","dk","fi","pt","cz","gr","hu","ro","ua","il","ae","sg","hk","tw","id","my","ph","th","vn","tr","me","tv","cc","gg","fm","ly","to","is","im","ws","la","ac","sh","vc","xyz","top","live","space"]),Ai=/^(?:mailto|tel):\S+$/i,Ti=/^[^\s@/?#:]+@[^\s@/?#:]+\.[a-z]{2,}$/i;function id(s){if(!s||s.length<4)return!1;if(Ai.test(s)||Ti.test(s))return!0;if(/^https?:\/\//i.test(s))try{return new URL(s),!0}catch{return!1}if(s.split(/[/?#]/,1)[0].includes("@"))return!1;if(/^www\./i.test(s))try{return new URL(`https://${s}`),!0}catch{return!1}if(!s.includes(".")||!/^[a-zA-Z0-9]/.test(s))return!1;try{const t=new URL(`https://${s}`).hostname.split(".").filter(n=>n.length>0);if(t.length<2)return!1;const e=t[t.length-1].toLowerCase();if(wi.has(e))return!0;if(t.length>=3){const n=t[t.length-2].toLowerCase();if(wi.has(n))return!0}return!1}catch{return!1}}function ad(s){return/^https?:\/\//i.test(s)||Ai.test(s)?s:Ti.test(s)?`mailto:${s}`:`https://${s}`}function Ci(s){return s===" "||s===" "||s===`
2
2
  `||s==="\r"}function Pi(s){if(!s||s.length<4)return[];const t=[];let e=0;for(;e<s.length;){if(Ci(s[e])){e++;continue}let n=e,o=e;for(;o<s.length&&!Ci(s[o]);)o++;const r=s.slice(n,o);id(r)&&t.push({url:ad(r),originalText:r,start:n,end:o}),e=o}return t}function bt(s){for(const t of s.toArray())if(t instanceof I.XmlText)return t;return null}function lr(s){const t=String(s.getAttribute("id")??"");throw new St("target_type_mismatch",`Target '${t}' is a ${s.nodeName}, not a directly editable text block. Read its contents and target a paragraph ID instead${s.nodeName==="table-cell"?", or use the table-cell editing tool":""}. No change was made.`,"target_resolution",!0,"unchanged",{targetId:t,targetType:s.nodeName})}function Le(s){return s instanceof I.XmlElement&&s.nodeName==="header-footer"}function Fe(){throw new Error("Headers and footers have fixed left, center, and right paragraph slots. Edit or replace one existing paragraph; do not insert, remove, split, join, or change the block type of a slot.")}function ld(s,t){const e=bt(s),n=s.parent instanceof I.XmlElement&&s.parent.nodeName==="list"?s.parent.getAttribute("variant")??void 0:void 0;if(e)return[{blockId:t,yBlock:s,yText:e,blockText:fe(e),listVariant:s.nodeName==="list-item"?n:void 0}];if(s.nodeName==="list"){const i=[];for(const a of s.toArray()){if(!(a instanceof I.XmlElement)||a.nodeName!=="list-item")continue;const l=bt(a);if(!l)continue;const c=a.getAttribute("id")||t;i.push({blockId:c,yBlock:a,yText:l,blockText:fe(l),listVariant:s.getAttribute("variant")??void 0})}return i}const o=[],r=i=>{for(const a of i.toArray()){if(!(a instanceof I.XmlElement))continue;const l=bt(a);l?o.push({blockId:a.getAttribute("id")??t,yBlock:a,yText:l,blockText:fe(l)}):r(a)}};return r(s),o}function cd(s,t){const e=new Set,n=r=>{const i=r.getAttribute("id"),a=typeof i=="string"?i:"",l=bt(r);if(a&&l&&!e.has(a)){const c=t({blockId:a,yBlock:r,yText:l,blockText:fe(l)});if(e.add(a),c===!0)return!0}for(const c of r.toArray())if(c instanceof I.XmlElement&&n(c))return!0;return!1},o=We(s);for(const r of o.toArray())if(r instanceof I.XmlElement&&n(r))return}function dd(s,t,e,n=3){const o=qe(e)?rc(e):Do(e);if(!o||/^\s*$/.test(o))return null;const r=Me(o);if(!r||/^\s*$/.test(r))return null;const i=[];let a=0,l=!1;return cd(s,c=>{if(!(c.blockId===t||!Me(c.blockText).includes(r))&&(a++,i.length<n&&i.push(c.blockId),a>n))return l=!0,!0}),a===0?null:{blockIds:i,totalMatches:a,truncated:l}}function gd(s,t,e){const n=dd(s,t,e);if(!n||n.blockIds.length===0)return"";if(n.totalMatches===1)return` Did you mean block '${n.blockIds[0]}'?`;const o=n.blockIds.map(a=>`'${a}'`).join(", "),r=n.totalMatches-n.blockIds.length,i=r>0?n.truncated?` and at least ${r} more`:` and ${r} more`:"";return` This text appears in other blocks: ${o}${i}. Did you mean one of those block IDs?`}function ud(s,t){if(t.length<=20)return"";const e=s.indexOf(t.slice(0,20));if(e<0)return"";let n=20;for(;n<t.length&&s[e+n]===t[n];)n++;if(n>=t.length)return"";const o=Math.max(0,n-20),r=t.slice(o,n+40),i=s.slice(e+o,e+n+40);return` The first ${n} characters of find match the block, then they differ: find has ${JSON.stringify(r)} where the block reads ${JSON.stringify(i)}.`}const cr=new WeakMap;function dr(s){return cr.get(s)}const pt=s=>({kind:"block",...s}),Mt=s=>({kind:"textMark",...s}),hd=new Set(["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","code","superscript","subscript"]),Mi={fontSize:{integer:!0,min:1,max:512},letterSpacing:{min:-20,max:100}},fd=[pt({attr:"align",nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"],aliases:["textAlign","text-align"]}),pt({attr:"heading",nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6}),pt({attr:"lineSpacing",nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4,aliases:["lineHeight","line-height"]}),pt({attr:"leftIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20,aliases:["marginLeft","margin-left","left-indent","indent","indents"]}),pt({attr:"direction",nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"],aliases:["dir"]}),pt({attr:"firstLineIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1,aliases:["textIndent","text-indent","first-line-indent"]}),pt({attr:"spaceBefore",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginTop","margin-top"]}),pt({attr:"spaceAfter",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginBottom","margin-bottom"]}),pt({attr:"width",nodeNames:["image"],valueType:"number",integer:!0,min:1}),pt({attr:"height",nodeNames:["image"],valueType:"number",integer:!0,min:1}),pt({attr:"alt",nodeNames:["image"],valueType:"string"}),pt({attr:"language",nodeNames:["code"],valueType:"string"}),pt({attr:"renderDiagram",nodeNames:["code"],valueType:"boolean"}),pt({attr:"showDiagramSource",nodeNames:["code"],valueType:"boolean"}),pt({attr:"displayMode",nodeNames:["math"],valueType:"string",enumValues:["inline","block"]}),pt({attr:"variant",nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"],aliases:["listStyleType","list-style-type"]}),pt({attr:"startNumber",nodeNames:["list"],valueType:"number",integer:!0,min:1}),pt({attr:"numberingChainId",nodeNames:["list"],valueType:"string"}),pt({attr:"checked",nodeNames:["list-item"],valueType:"boolean"}),pt({attr:"indentLevel",nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10}),pt({attr:"tableWidth",nodeNames:["table"],valueType:"number",integer:!0,min:1,aliases:["width"]}),pt({attr:"borderColor",nodeNames:["table","table-cell","container"],valueType:"string",aliases:["border-color"]}),pt({attr:"borderWidth",nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0,aliases:["border-width"]}),pt({attr:"borders",nodeNames:["table","table-cell"],valueType:"string",aliases:["border"]}),pt({attr:"cellPadding",nodeNames:["table"],valueType:"number",integer:!0,min:0,aliases:["cell-padding","padding"]}),pt({attr:"hasHeader",nodeNames:["table"],valueType:"boolean"}),pt({attr:"verticalAlign",nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"],aliases:["vertical-align"]}),pt({attr:"backgroundColor",nodeNames:["table-cell"],valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),pt({attr:"padding",nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}),Mt({attr:"bold",valueType:"boolean",aliases:["fontWeight","font-weight"]}),Mt({attr:"italic",valueType:"boolean",aliases:["fontStyle","font-style"]}),Mt({attr:"underline",valueType:"boolean",aliases:["textDecoration","text-decoration"]}),Mt({attr:"strikethrough",valueType:"boolean",aliases:["strike","line-through"]}),Mt({attr:"doubleStrikethrough",valueType:"boolean",aliases:["double-strikethrough","double-strike","dstrike"]}),Mt({attr:"smallCaps",valueType:"boolean",aliases:["small-caps","fontVariant","font-variant"]}),Mt({attr:"allCaps",valueType:"boolean",aliases:["all-caps","caps"]}),Mt({attr:"letterSpacing",valueType:"number",min:-20,max:100,aliases:["letter-spacing","characterSpacing","character-spacing"]}),Mt({attr:"code",valueType:"boolean"}),Mt({attr:"superscript",valueType:"boolean"}),Mt({attr:"subscript",valueType:"boolean"}),Mt({attr:"fontSize",valueType:"number",integer:!0,min:1,max:512,aliases:["font-size"]}),Mt({attr:"fontFamily",valueType:"string",aliases:["font-family"]}),Mt({attr:"backgroundColor",valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),Mt({attr:"color",valueType:"string"}),Mt({attr:"link",valueType:"string",aliases:["href"]})],gr=new Map,Bi=(s,t)=>{const e=s.toLowerCase(),n=gr.get(e)??[];n.push(t),gr.set(e,n)};for(const s of fd){Bi(s.attr,s);for(const t of s.aliases??[])Bi(t,s)}const Ei={align:{nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"]},heading:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6},lineSpacing:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4},leftIndent:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20},direction:{nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"]},firstLineIndent:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1},spaceBefore:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:0},spaceAfter:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:0},width:{nodeNames:["image"],valueType:"number",integer:!0,min:1},height:{nodeNames:["image"],valueType:"number",integer:!0,min:1},alt:{nodeNames:["image"],valueType:"string"},src:{nodeNames:["image"],valueType:"string"},language:{nodeNames:["code"],valueType:"string"},renderDiagram:{nodeNames:["code"],valueType:"boolean"},showDiagramSource:{nodeNames:["code"],valueType:"boolean"},displayMode:{nodeNames:["math"],valueType:"string",enumValues:["inline","block"]},variant:{nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"]},startNumber:{nodeNames:["list"],valueType:"number",integer:!0,min:1},numberingChainId:{nodeNames:["list"],valueType:"string"},checked:{nodeNames:["list-item"],valueType:"boolean"},indentLevel:{nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10},tableWidth:{nodeNames:["table"],valueType:"number",integer:!0,min:1},borderColor:{nodeNames:["table","table-cell","container"],valueType:"string"},borderWidth:{nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0},borders:{nodeNames:["table","table-cell"],valueType:"string"},cellPadding:{nodeNames:["table"],valueType:"number",integer:!0,min:0},hasHeader:{nodeNames:["table"],valueType:"boolean"},verticalAlign:{nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"]},backgroundColor:{nodeNames:["table-cell"],valueType:"string"},padding:{nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}};function fe(s){const t=st(s);let e="";for(const n of t)n.insert&&typeof n.insert=="string"&&(e+=n.insert);return e}function Ni(s,t,e){if(fe(t).length===0)return!!ye(s.getAttribute("_emptyTextMarks"))[e];const n=st(t);for(const o of n)if(!(!o.insert||typeof o.insert!="string"||o.insert.length===0)&&(o.attributes||{})[e]!==!0)return!1;return!0}function pd(s,t,e){const n=ye(s.getAttribute("_emptyTextMarks"));e?n[t]=!0:delete n[t],Object.keys(n).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(n))}function to(s,t,e){if(e>0)return;const n=t.children.find(o=>o.type==="text"&&o.text===""&&Object.keys(o.marks??{}).length>0);n?.marks&&s.setAttribute("_emptyTextMarks",JSON.stringify(n.marks))}function ur(s,t,e){const n=ye(s.getAttribute("_emptyTextMarks"));e==null?delete n[t]:n[t]=e,Object.keys(n).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(n))}function md(s,t,e){const n=Oe(s,t);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${s}" expects a number.`);if(e.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${s}" expects an integer value.`);if(e.min!==void 0&&n<e.min)throw new Error(`set_block_attribute "${s}" must be >= ${e.min}.`);if(e.max!==void 0&&n>e.max)throw new Error(`set_block_attribute "${s}" must be <= ${e.max}.`);return n}function bd(s){if(s==null)return"set";if(s==="set"||s==="toggle"||s==="remove")return s;throw new Error('set_block_attribute operation must be one of "set", "toggle", or "remove".')}function Li(s,t){let e=Array.isArray(t)?t:[t];if(typeof t=="string"){const r=t.trim();if(r.startsWith("[")&&r.endsWith("]"))try{const i=JSON.parse(r);Array.isArray(i)&&(e=i)}catch{}}const n=[],o=new Set;for(const r of e){if(typeof r!="string"||r.trim().length===0)throw new Error(`${s} requires a valid block ID or a non-empty list of block IDs.`);const i=r.trim();o.has(i)||(o.add(i),n.push(i))}if(n.length===0)throw new Error(`${s} requires a valid block ID or a non-empty list of block IDs.`);return n}function Fi(s){if(s===!0||s===!1)return s;if(typeof s=="string"){const t=s.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}return!1}function Oi(s,t,e){if(e.valueType==="string"){if(typeof t!="string")throw new Error(`set_block_attribute "${s}" expects a string value.`);if(e.enumValues&&!e.enumValues.includes(t))throw new Error(`set_block_attribute "${s}" must be one of: ${e.enumValues.join(", ")}.`);return t}if(e.valueType==="boolean"){if(typeof t!="boolean")throw new Error(`set_block_attribute "${s}" expects a boolean value.`);return String(t)}const n=Oe(s,t);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${s}" expects a number.`);if(e.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${s}" expects an integer value.`);if(e.min!==void 0&&n<e.min)throw new Error(`set_block_attribute "${s}" must be >= ${e.min}.`);if(e.max!==void 0&&n>e.max)throw new Error(`set_block_attribute "${s}" must be <= ${e.max}.`);return String(n)}function hr(s,t,e){if(e===void 0){et(s,t);return}s.setAttribute(t,String(e))}function Ri(s,t,e){if(t==="toggle")throw new Error('set_block_attribute "indentLevel" does not support toggle. Use operation "set" with a numeric value or "remove".');const n=t==="remove"?0:Number(Oi("indentLevel",e,{valueType:"number",integer:!0,min:0,max:20})),o=n>0?Jt(1):void 0,r=n>1?Ht(n-1):void 0;hr(s,"firstLineIndent",o),hr(s,"leftIndent",r)}function fr(s,t,e){if(e===null){et(s,t);return}const n=t==="leftIndent"?Ht(e):Jt(e);hr(s,t,n)}function Oe(s,t){if(typeof t=="number")return t;if(typeof t!="string")return Number.NaN;const e=t.trim();if(!e)return Number.NaN;const n=e.toLowerCase();if(s==="leftIndent"||s==="firstLineIndent"){const i=bl(e,{firstLine:s==="firstLineIndent"});if(i!==void 0)return i}const o=n.match(/^(-?\d+(?:\.\d+)?)(px|pt|in|cm|mm)$/);if(o){const i=Number(o[1]),a=o[2],l={px:1,pt:4/3,in:96,cm:96/2.54,mm:96/25.4};return i*l[a]}if(s==="heading"){const i=n.match(/^h([1-6])$/);if(i)return Number(i[1])}if(s==="lineSpacing"){const i={single:1,"1x":1,"1.0x":1,one:1,double:2,"2x":2,"2.0x":2,onehalf:1.5,"one-half":1.5,"one and a half":1.5,"one-and-a-half":1.5,"1.5x":1.5};if(i[n]!==void 0)return i[n]}const r=Number(e);return Number.isFinite(r)?r:Number.NaN}function ne(s,t,e){const n=fe(e);s.push({kind:"replace",paragraphId:t,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,n.length,0)),text:n,oldText:n})}function Bt(s){const t=s.getAttribute("id");return typeof t=="string"&&t.length>0?t:s.nodeName}function eo(s){return gr.get(s.trim().toLowerCase())??[]}function pe(s,t,e,n){if(typeof e!="string")throw new Error(`${s} "${t}" expects a string value.`);const o=e.trim();if(o.length===0)throw new Error(`${s} "${t}" expects a non-empty string.`);if(/[<>;]/.test(o))throw new Error(`${s} "${t}" contains unsupported characters.`);if(t==="fontFamily"&&yd(o))throw new Error(`${s} "fontFamily" does not support CSS-wide values like "inherit"; use a concrete font family such as "Arial, sans-serif".`);const r=o.toLowerCase();if(n&&!n.includes(r))throw new Error(`${s} "${t}" must be one of: ${n.join(", ")}.`);return n?r:o}function yd(s){const t=s.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(t)}function pr(s,t,e){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(["true","yes","on","1"].includes(n))return!0;if(["false","no","off","0","none"].includes(n))return!1}if(e===1)return!0;if(e===0)return!1;throw new Error(`${s} "${t}" expects a boolean value.`)}function Di(s,t,e){if(typeof e!="string"&&typeof e!="number")return e;const n=s.trim().toLowerCase(),o=typeof e=="number"?String(e):e.trim().toLowerCase();if(n==="fontstyle"||n==="font-style"){if(t==="italic"){if(o==="italic"||o==="oblique")return!0;if(o==="normal")return!1}return e}if(n==="fontweight"||n==="font-weight"){if(t==="bold"){if(o==="bold"||o==="bolder")return!0;if(o==="normal"||o==="lighter")return!1;const r=Number(o);if(Number.isFinite(r))return r>=600}return e}if(n==="textdecoration"||n==="text-decoration"){if(t==="underline"){if(o.includes("underline"))return!0;if(o==="none")return!1}return e}return(n==="line-through"||n==="strike")&&t==="strikethrough"?o!=="false"&&o!=="none":e}function Re(s,t,e,n){const o=Oe(t,e);if(!Number.isFinite(o))throw new Error(`${s} "${t}" expects a number.`);const r=n.integer?Math.round(o):o;if(n.min!==void 0&&r<n.min)throw new Error(`${s} "${t}" must be >= ${n.min}.`);if(n.max!==void 0&&r>n.max)throw new Error(`${s} "${t}" must be <= ${n.max}.`);return r}function Ft(s,t,e,n){const o=Bt(t);if(e){ne(s,o,e);return}const r=`Updated ${n} on ${t.nodeName} block.`;s.push({kind:"replace",paragraphId:o,text:r,oldText:r})}function no(s,t){const e=s.parent;if(s.nodeName!=="paragraph"||!(e instanceof I.XmlElement)||e.nodeName!=="footnote"||!s.doc)return null;const n=Kt(s.doc).notes?.find(o=>o.id===e.getAttribute("id"))?.children.find(o=>o.id===s.getAttribute("id"));return!n||n.type!=="paragraph"||typeof t=="string"&&n.children.length>0&&n.children.every(o=>o.marks?.fontFamily===t)?null:"Note-body fontFamily is inherited from its reference numeral. Style the reference paragraph to change the note font."}function $i(s){const{toolName:t,yBlock:e,yText:n,attribute:o,operation:r,value:i,config:a,anchors:l}=s;if(!n||e.nodeName!=="paragraph"&&e.nodeName!=="list-item")throw new Error(`${t} "${o}" only supports paragraph or list-item text blocks.`);if(r==="toggle"&&a.valueType!=="boolean")throw new Error(`${t} "${o}" does not support toggle. Use operation "set" with a value or "remove".`);let c;if(r==="remove"||i===null)c=null;else if(r==="toggle")c=!Ni(e,n,o);else if(a.valueType==="boolean")c=i===void 0?!0:pr(t,o,i);else{if(i===void 0)throw new Error(`${t} "${o}" requires a value.`);a.valueType==="number"?c=Re(t,o,i,a):c=pe(t,o,i)}if(o==="fontFamily"){const d=no(e,c);if(d)throw new Error(d)}if(n.length>0)at(n,0,n.length,{[o]:c===null?null:c}),ne(l,Bt(e),n);else{ur(e,o,c);const d=`Text mark "${o}" ${c===null?"removed":"set"}.`;l.push({kind:"replace",paragraphId:Bt(e),text:d,oldText:d})}}const ji=new Set(["fontSize","fontFamily","color"]);function _i(s){const{toolName:t,yBlock:e,attribute:n,operation:o,value:r,config:i,anchors:a}=s;if(!ji.has(n))throw new Error(`${t} "${n}" cannot style a table of contents: its entries are generated from the document's headings. A table of contents supports fontSize, fontFamily, color; style the headings themselves for other text formatting.`);if(o==="toggle")throw new Error(`${t} "${n}" does not support toggle. Use operation "set" with a value or "remove".`);if(o==="remove"||r===null)e.removeAttribute(n);else{if(r===void 0)throw new Error(`${t} "${n}" requires a value.`);if(n==="fontSize"){const l=Re(t,n,r,i);if(!kl(l))throw new Error(`${t} "fontSize" on a table of contents must be between ${Sl} and ${Il} px.`);e.setAttribute(n,String(l))}else if(n==="color"){const l=typeof r=="string"?ks(r):void 0;if(!l)throw new Error(`${t} "color" expects a CSS color string or null.`);e.setAttribute(n,l)}else e.setAttribute(n,pe(t,n,r))}Ft(a,e,null,n)}function kd(s){const{yBlock:t}=s;if(t.nodeName==="paragraph"||t.nodeName==="list-item"){$i({...s,yText:bt(t)});return}if(t.nodeName==="toc"){_i(s);return}const e=[],n=[],o=l=>{for(let c=0;c<l.length;c++){const d=l.get(c);if(d instanceof I.XmlElement&&!s.independentlySelectedTargets?.has(d)){if(d.nodeName==="paragraph"||d.nodeName==="list-item"){e.push(d);continue}if(d.nodeName==="toc"){ji.has(s.attribute)&&n.push(d);continue}o(d)}}};if(o(t),s.attribute==="fontFamily"&&s.operation!=="toggle"){const l=s.operation==="remove"||s.value===null?null:pe(s.toolName,s.attribute,s.value);for(const c of e){const d=no(c,l);if(d)throw new Error(d)}}let r=0;const i=[],a=l=>{try{$i({...s,yBlock:l,yText:bt(l)}),r++}catch(c){i.push(c instanceof Error?c.message:String(c))}};for(const l of e)a(l);for(const l of n)try{_i({...s,yBlock:l}),r++}catch(c){i.push(c instanceof Error?c.message:String(c))}if(r===0)throw new Error(i[0]??`${s.toolName} "${s.attribute}" found no descendant text blocks to style.`)}function Sd(s){const{toolName:t,yBlock:e,ranges:n,attribute:o,operation:r,value:i,config:a,anchors:l}=s,c=bt(e);if(!c)throw new Error(`${t} inline selector matched a block without text content.`);let d;if(r==="remove"||i===null?d=null:a.valueType==="boolean"?d=pr(t,o,i):a.valueType==="number"?d=Re(t,o,i,a):d=pe(t,o,i),o==="fontFamily"){const g=no(e,d);if(g)throw new Error(g)}for(const g of n)at(c,g.start,g.length,{[o]:d===null?null:d});ne(l,Bt(e),c)}function oo(s){const{toolName:t,yBlock:e,attribute:n,operation:o,value:r,config:i,anchors:a}=s;if(!i.nodeNames.includes(e.nodeName))throw new Error(`${t} "${n}" is not valid for ${e.nodeName} blocks.`);const l=n==="heading"&&e.nodeName==="paragraph"?{heading:rt(e,"heading"),styleId:rt(e,"styleId")}:void 0;if(n==="indentLevel"&&e.nodeName==="paragraph"){Ri(e,o,r),Ft(a,e,bt(e),n);return}if(n==="padding"&&e.nodeName==="table-cell"){if(o==="remove"||r===null)et(e,n);else{const c=Re(t,n,r,i);e.setAttribute(n,JSON.stringify({top:c,right:c,bottom:c,left:c}))}Ft(a,e,null,n);return}if(n==="borders"&&(e.nodeName==="table"||e.nodeName==="table-cell")){if(o==="remove"||r===null)et(e,"borders");else{const c=pe(t,n,r),d=Xs(c);if(!d)throw new Error(`${t} "border" expects a CSS border shorthand like "1px solid #cccccc" or "none".`);const g={top:d,right:d,bottom:d,left:d};e.nodeName==="table"&&(g.insideH=d,g.insideV=d);const u=Us(g);u&&e.setAttribute("borders",u)}Ft(a,e,null,"borders");return}if(e.nodeName==="table-cell"&&(n==="borderColor"||n==="borderWidth")){if(o==="remove"||r===null)et(e,"borders");else{const c=cc(rt(e,"borders")),d=n==="borderColor"?pe(t,n,r):Re(t,n,r,i),g=["top","right","bottom","left"],u={};for(const h of g){const p=c?.[h]??{style:"single",width:1,color:"#cccccc"};u[h]={...p,...n==="borderColor"?{color:d}:{width:d}}}const f=Us(u);f&&e.setAttribute("borders",f)}Ft(a,e,null,"borders");return}if(o==="remove"||r===null)et(e,n);else if(o==="toggle"){if(i.valueType!=="boolean")throw new Error(`${t} "${n}" only supports toggle for boolean attributes.`);const c=Fi(rt(e,n));e.setAttribute(n,String(!c))}else{if(r===void 0)throw new Error(`${t} "${n}" requires "value" when operation is "set".`);let c;i.valueType==="string"?c=pe(t,n,r,i.enumValues):i.valueType==="boolean"?c=String(pr(t,n,r)):c=String(Re(t,n,r,i)),e.nodeName==="paragraph"&&(n==="leftIndent"||n==="firstLineIndent")?fr(e,n,Number(c)):e.setAttribute(n,c)}l&&Id(e,l),Ft(a,e,bt(e),n)}function Xi(s){const t=Number(s);return Number.isInteger(t)&&t>=1&&t<=6?t:void 0}function Id(s,t){const e=s.doc?.getMap("metadata").get("stylesheet"),n=Xi(rt(s,"heading")),o=Ye(e,n);if(!e||!o)return;const r=(typeof t.styleId=="string"?_o(e,t.styleId):void 0)??Ye(e,Xi(t.heading));n!==void 0&&o.styleId.toLowerCase()!=="normal"?s.setAttribute("styleId",o.styleId):et(s,"styleId");const i=r?.paragraphAttrs??{},a=o.paragraphAttrs??{},l=(f,h)=>Object.prototype.hasOwnProperty.call(f,h),c=["align","lineSpacing","spaceBefore","spaceAfter","contextualSpacing","leftIndent","firstLineIndent","direction","borders","shading","tabStops"];for(const f of c){if(!l(i,f)&&!l(a,f))continue;const h=a[f];h===void 0||h===!1?et(s,f):f==="leftIndent"||f==="firstLineIndent"?fr(s,f,Number(h)):s.setAttribute(f,String(h))}const d=["keepNext","keepLines","widowControl"];if(d.some(f=>l(i,f)||l(a,f))){const f={};vn(f,rt(s,"pagination"));for(const p of d)!l(i,p)&&!l(a,p)||(a[p]===void 0?delete f[p]:f[p]=a[p]);const h=qt(f);h===void 0?et(s,"pagination"):s.setAttribute("pagination",h)}const g=Xo(r?.runMarks,o.runMarks),u=bt(s);if(u&&u.length>0)at(u,0,u.length,g);else for(const[f,h]of Object.entries(g))ur(s,f,h===!1?null:h)}function vd(s){if(s.config.nodeNames.includes(s.yBlock.nodeName)){oo(s);return}if(!(s.config.nodeNames.includes("paragraph")||s.config.nodeNames.includes("list-item"))){oo(s);return}let t=0;const e=[],n=o=>{for(let r=0;r<o.length;r++){const i=o.get(r);if(i instanceof I.XmlElement&&!s.independentlySelectedTargets.has(i)){if(i.nodeName==="paragraph"||i.nodeName==="list-item"){try{oo({...s,yBlock:i}),t++}catch(a){e.push(a instanceof Error?a.message:String(a))}continue}n(i)}}};if(n(s.yBlock),t===0)throw new Error(e[0]??`${s.toolName} "${s.attribute}" found no descendant text blocks to style.`)}function xd(s){const t=[],e=n=>{n.nodeName!=="footnote"&&n.nodeName!=="header-footer"&&t.push(n);for(let o=0;o<n.length;o++){const r=n.get(o);r instanceof I.XmlElement&&e(r)}};for(const n of[We(s),s.getXmlFragment("notes")])for(const o of n.toArray())o instanceof I.XmlElement&&e(o);return t}function mr(s){switch(s.nodeName){case"paragraph":{const t=s.getAttribute("heading");return typeof t=="string"&&/^[1-6]$/.test(t)?[`h${t}`]:["p"]}case"list":return s.getAttribute("variant")==="ordered"?["ol"]:["ul"];case"list-item":return["li"];case"code":return["pre"];case"math":return["latex"];case"image":return["img"];case"table":return["table"];case"table-row":return["tr"];case"table-cell":return["td"];case"container":return["div"];default:return[s.nodeName]}}function wd(s,t){const e=[],n=o=>{for(let r=0;r<o.length;r++){const i=o.get(r);i instanceof I.XmlElement&&(mr(i).includes(t)&&e.push(i),n(i))}};return n(s),e}function Ad(s){const t=s.match(/^#([A-Za-z0-9_-]+)\s+([a-zA-Z][a-zA-Z0-9-]*)$/);return t?{id:t[1],tag:t[2].toLowerCase()}:null}function Ze(s){return s.toLowerCase()==="th"?"td":s.toLowerCase()}function br(s){const t=s.match(/^(\*|[a-zA-Z][a-zA-Z0-9-]*)(?::(?:(first-child)|(last-child)|nth-child\(\s*(\d+|odd|even)\s*\)))?$/);if(!t)return null;const e=t[2]?1:t[3]?"last":t[4]==="odd"||t[4]==="even"?t[4]:t[4]?Number(t[4]):void 0;return typeof e=="number"&&e<1?null:{tag:Ze(t[1]),nthChild:e}}function tn(s,t){if(t.tag!=="*"&&!mr(s).includes(t.tag))return!1;if(t.nthChild===void 0)return!0;const e=s.parent;if(!(e instanceof I.XmlElement)&&!(e instanceof I.XmlFragment))return!1;const n=e.toArray().filter(r=>r instanceof I.XmlElement),o=n.indexOf(s)+1;return o===0?!1:t.nthChild==="last"?o===n.length:t.nthChild==="odd"?o%2===1:t.nthChild==="even"?o%2===0:o===t.nthChild}function Ui(s,t){if(!tn(s,t[t.length-1]))return!1;let e=s.parent;for(let n=t.length-2;n>=0;n--){for(;e instanceof I.XmlElement&&!tn(e,t[n]);)e=e.parent;if(!(e instanceof I.XmlElement))return!1;e=e.parent}return!0}const yr={span:"*",b:"bold",strong:"bold",i:"italic",em:"italic",u:"underline",s:"strikethrough",strike:"strikethrough",del:"strikethrough",code:"code",sup:"superscript",sub:"subscript",mark:"backgroundColor",a:"link"};function Td(s){const t=s.split(/\s+/).filter(Boolean),e=t.findIndex(o=>yr[o.toLowerCase()]!==void 0);if(e<0)return null;const n=t.slice(e).map(o=>o.toLowerCase());return n.some(o=>!yr[o])?null:{scopeSelector:e===0?"*":t.slice(0,e).join(" "),markAttributes:Array.from(new Set(n.map(o=>yr[o])))}}function Cd(s){if(s.nodeName==="paragraph"||s.nodeName==="list-item")return[s];const t=[],e=n=>{for(let o=0;o<n.length;o++){const r=n.get(o);r instanceof I.XmlElement&&(r.nodeName==="paragraph"||r.nodeName==="list-item"?t.push(r):e(r))}};return e(s),t}function Pd(s,t){if(t==="*")return!0;const e=s?.[t];return t==="link"||t==="backgroundColor"?typeof e=="string"&&e.length>0:e===!0}function Md(s,t){const e=[];let n=0;for(const o of st(s)){if(typeof o.insert!="string")continue;const r=o.insert.length,i=o.attributes;if(r>0&&t.every(a=>Pd(i,a))){const a=e[e.length-1];a&&a.start+a.length===n?a.length+=r:e.push({start:n,length:r})}n+=r}return e}function Bd(s,t){const e=[...s,...t].sort((o,r)=>o.start-r.start),n=[];for(const o of e){const r=n[n.length-1];r&&o.start<=r.start+r.length?r.length=Math.max(r.length,o.start+o.length-r.start):n.push({...o})}return n}function Ed(s){const t=Array.isArray(s)?s:[s],e=[],n=new Set;for(const o of t){if(typeof o!="string")throw new Error("style_blocks selectors must be strings.");for(const r of o.split(",")){const i=r.trim(),a=["all","document",":root"].includes(i.toLowerCase())?"*":i.replace(/\s*>\s*/g," ");a&&(n.has(a)||(n.add(a),e.push(a)))}}if(e.length===0)throw new Error("style_blocks requires at least one selector.");return e}function zi(s,t){const e=xd(s),n=[],o=new Set,r=[],i=[],a=l=>{const c=Bt(l),d=`${l.nodeName}:${c}`;o.has(d)||(o.add(d),n.push(l))};for(const l of t){if(l==="*"){for(const m of e)a(m);continue}const c=l.match(/^(p|h[1-6]|li)\[data-style-id=(?:"([^"]+)"|'([^']+)'|([^\]]+))\]$/i);if(c){const m=Ze(c[1]),y=(c[2]??c[3]??c[4]).trim(),b=e.filter(k=>tn(k,{tag:m})&&k.getAttribute("styleId")===y);b.length===0&&r.push(l);for(const k of b)a(k);continue}const d=l.match(/^#([A-Za-z0-9_-]+)\s*~\s*(\*|[a-zA-Z][a-zA-Z0-9-]*)$/);if(d){const m=Z(s,d[1]),y=m?.parent;if(!m||!(y instanceof I.XmlElement)&&!(y instanceof I.XmlFragment)){r.push(l);continue}const b=y.toArray(),k=b.indexOf(m),S=Ze(d[2]),v=e.filter(x=>x.parent===y&&b.indexOf(x)>k&&tn(x,{tag:S}));v.length===0&&r.push(l);for(const x of v)a(x);continue}const g=l.match(/^#([A-Za-z0-9_-]+)\s+(.+)$/);if(g){const m=Z(s,g[1]);if(!m){r.push(l);continue}const y=g[2].split(/\s+/).filter(Boolean).map(br);if(y.some(v=>v===null)){i.push(`selector "${l}" is not supported; descendants may use block tags, :first-child, and :nth-child(n).`);continue}const b=y,k=v=>{let x=v;for(;x;){if(x===m)return!0;x=x.parent}return!1},S=e.filter(v=>k(v)&&(b.length!==1||b[0].tag!=="*"||v!==m)&&Ui(v,b));S.length===0&&r.push(l);for(const v of S)a(v);continue}const u=Ad(l);if(u){if(u.tag==="span"){i.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}const m=Z(s,u.id);if(!m){r.push(l);continue}const y=wd(m,Ze(u.tag));if(y.length===0){r.push(l);continue}for(const b of y)a(b);continue}if(l.includes(" ")&&!l.startsWith("#")){const m=l.split(/\s+/).filter(Boolean).map(br);if(m.some(k=>k===null)){i.push(`selector "${l}" is not supported; descendant selectors may use block tags, :first-child, and :nth-child(n).`);continue}const y=m;if(y.some(k=>k.tag==="span")){i.push(`selector "${l}" contains an inline selector; target its containing block instead.`);continue}const b=e.filter(k=>Ui(k,y));b.length===0&&r.push(l);for(const k of b)a(k);continue}if(l.startsWith("#")){const m=l.slice(1).trim();if(!m||/[\s.#:[\]>+~]/.test(m)){i.push(`selector "${l}" is not supported; use #blockId with a plain block ID.`);continue}const y=Z(s,m);y?a(y):r.push(l);continue}const f=br(l);if(f){let m=0;for(const y of e)tn(y,f)&&(a(y),m+=1);m===0&&r.push(l);continue}if(!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(l)){i.push(`selector "${l}" is not supported; use *, #id, or tag selectors like p, h2, li, table.`);continue}const h=Ze(l);if(h==="span"){i.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}let p=0;for(const m of e)mr(m).includes(h)&&(a(m),p++);p===0&&r.push(l)}return{targets:n,unmatchedSelectors:r,invalidSelectorErrors:i}}function Nd(s,t){const e=Ed(t),n=[],o=[];for(const c of e){const d=Td(c);d?o.push({selector:c,parsed:d}):n.push(c)}const r=n.length>0?zi(s,n):{targets:[],unmatchedSelectors:[],invalidSelectorErrors:[]},i=new Map,a=[...r.unmatchedSelectors],l=[...r.invalidSelectorErrors];for(const{selector:c,parsed:d}of o){const g=zi(s,[d.scopeSelector]);if(g.invalidSelectorErrors.length>0){l.push(...g.invalidSelectorErrors.map(h=>`selector "${c}": ${h}`));continue}let u=0;const f=new Set;for(const h of g.targets)for(const p of Cd(h)){const m=Bt(p);if(f.has(m))continue;f.add(m);const y=bt(p);if(!y)continue;const b=Md(y,d.markAttributes);if(b.length===0)continue;u+=b.length;const k=i.get(m);k?k.ranges=Bd(k.ranges,b):i.set(m,{yBlock:p,ranges:b})}u===0&&a.push(c)}return{targets:r.targets,inlineTargets:Array.from(i.values()),unmatchedSelectors:a,invalidSelectorErrors:l}}function me(s){return s.trim().toLowerCase().replace(/[-_\s]/g,"")}function Ld(s){let t;if(Array.isArray(s))t=s.map((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`style_blocks attrs[${n}] must be an object.`);const o=e;if(typeof o.name!="string"||o.name.trim().length===0)throw new Error(`style_blocks attrs[${n}].name must be a string.`);return[o.name,o.value]});else if(s&&typeof s=="object")t=Object.entries(s);else throw new Error("style_blocks requires an attrs array or object.");if(t.length===0)throw new Error("style_blocks requires at least one attr.");return t.map(([e,n])=>({rawName:e,canonicalName:me(e),value:n}))}function Fd(s){const t=[],e=[],n=new Set,o=(r,i,a)=>{const l=`${i.kind}:${i.attr}`;let c=a;if(i.kind==="textMark"&&i.attr==="color"||i.kind==="block"&&(i.attr==="borderColor"||i.attr==="backgroundColor")){if(a!==null&&typeof a!="string")throw new Error(`style_blocks "${i.attr}" expects a CSS color string or null.`);if(typeof a=="string"&&(c=ks(a),!c))throw new Error(`style_blocks "${i.attr}" does not support ${JSON.stringify(a)}. Use a CSS named color, hex color, or CSS color function.`)}if(i.attr==="variant"&&typeof a=="string"){const g=a.trim().toLowerCase();["decimal","number","numbered","numeric","ol"].includes(g)?c="ordered":["disc","circle","square","bullet","bulleted","ul"].includes(g)?c="unordered":["check","checklist","checkbox","task"].includes(g)&&(c="todo")}const d={rawName:r,entry:i,value:c};if(n.has(l)){const g=t.findIndex(u=>`${u.entry.kind}:${u.entry.attr}`===l);g>=0&&(t[g]=d);return}n.add(l),t.push(d)};for(const{rawName:r,value:i}of s){if(r.trim().toLowerCase()==="border"){if(typeof i=="string"&&Xs(i)){for(const d of eo("borders"))o(r,d,i);continue}const l=eo("borderWidth"),c=eo("borderColor");if(i===null||typeof i=="number"){for(const d of l)o(r,d,i);if(i===null)for(const d of c)o(r,d,null);continue}if(typeof i=="string"){const d=i.match(/(?:^|\s)(\d+(?:\.\d+)?)(?:px|pt)?(?:\s|$)/i),g=Array.from(i.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(u=>!["solid","dashed","dotted","double","none"].includes(u[1].toLowerCase()));if(d)for(const u of l)o(r,u,d[1]);if(g)for(const u of c)o(r,u,g[1]);if(d||g)continue}e.push(r);continue}const a=eo(r);if(a.length===0){e.push(r);continue}for(const l of a)o(r,l,i)}return Object.assign(t,{unsupportedAttrs:e})}function Wi(s,t,e){const n=new Map;for(const r of s){const i=me(r.rawName),a=n.get(i)??[];a.push(r),n.set(i,a)}const o=[];for(const r of n.values()){const i=r.filter(c=>c.entry.kind==="textMark"),a=r.filter(c=>c.entry.kind==="block");if(i.length===0&&a.length>1){const c=a.filter(d=>d.entry.kind==="block"&&d.entry.nodeNames.some(g=>g===t.nodeName));o.push(...c.length?c:r);continue}if(i.length===0||a.length===0){o.push(...r);continue}if(e){o.push(...i);continue}const l=a.filter(c=>c.entry.kind==="block"&&c.entry.nodeNames.some(d=>d===t.nodeName));o.push(...l.length>0?l:i)}return o}function Ji(s){const t=[];for(const e of s){if(e.entry.kind!=="textMark"||e.entry.attr!=="backgroundColor"||e.value===null)continue;if(typeof e.value!="string")throw new Error(`style_blocks "backgroundColor" expects one of: ${Ln.join(", ")}.`);const n=e.value.trim(),o=Ke(n);if(!o)throw new Error(`style_blocks "backgroundColor" does not support ${JSON.stringify(n)} as a text highlight. Use one of: ${Ln.join(", ")}.`);e.value=o,n.toLowerCase()!==o&&t.push(`${e.rawName}: ${n} -> ${o}`)}return t}function De(s,t,e,n){s[e].push(n);const o=s.issuesByRawName.get(t.canonicalName)??[];o.push(n),s.issuesByRawName.set(t.canonicalName,o)}function ro(s,t){for(let e=s.length-1;e>=0;e--)if(s[e].canonicalName===t)return s[e]}function zt(s){return typeof s=="string"?s.trim().toLowerCase():void 0}function en(s){if(typeof s!="string")return;const t=s.trim().match(/^(-?\d+(?:\.\d+)?)%$/);if(!t)return;const e=Number(t[1]);return Number.isFinite(e)&&e>0?e:void 0}function so(s){return s===0?!0:typeof s=="string"&&/^[-+]?0+(?:\.0+)?(?:px|pt|in|cm|mm|%)?$/i.test(s.trim())}function Od(s){let t=s;for(;t.parent instanceof I.XmlElement;)t=t.parent;return t}function kr(s,t){const e=Bt(Od(t)),n=s.children.findIndex(c=>c.id===e),o=n>=0?s.children.slice(n).find(c=>c.type==="section-break"):void 0,r=ms(s.pageLayout,o?.type==="section-break"?o.layout:void 0),{pageWidth:i}=bs(r),a=Math.max(1,i-r.marginLeftPx-r.marginRightPx),l=r.columnGapTwips/15;return Math.max(1,Math.round(dc(a,r.columnCount,l)))}function Rd(s){if(s===null)return{remove:!0};if(typeof s=="number")return!Number.isFinite(s)||s<0?null:s===0?{remove:!0}:{remove:!1,style:"single",width:s};if(typeof s!="string")return null;const t=s.trim(),e=t.toLowerCase();if(e==="none"||so(e))return{remove:!0};const n=t.match(/(?:^|\s)(\d+(?:\.\d+)?)(px|pt)?(?=\s|$)/i),o=e.match(/(?:^|\s)(solid|double|dashed|dotted|none)(?=\s|$)/),r=Array.from(t.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(c=>!["solid","double","dashed","dotted","none"].includes(c[1].toLowerCase()));if(!n&&!o&&!r)return null;if(o?.[1]==="none")return{remove:!0};const i=n?Number(n[1]):void 0,a=i===void 0?void 0:n?.[2]?.toLowerCase()==="pt"?i*(4/3):i,l=o?.[1];return{remove:!1,style:l==="double"||l==="dashed"||l==="dotted"?l:"single",...a!==void 0?{width:a}:{},...r?{color:r[1]}:{}}}function Dd(s){if(s.yBlock.nodeName!=="paragraph")return;const t={bordertop:"top",borderright:"right",borderbottom:"bottom",borderleft:"left"};for(const e of s.rawAttrs){const n=t[e.canonicalName];if(e.canonicalName!=="border"&&!n)continue;s.result.handledRawNames.add(e.canonicalName);const o=Rd(e.value);if(!o){De(s.result,e,"errors",`${Bt(s.yBlock)}.borders: style_blocks "${e.rawName}" expects CSS border syntax such as "1px solid #cccccc".`);continue}let r={};try{const a=JSON.parse(String(rt(s.yBlock,"borders")??"{}"));a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r={}}const i=n?[n]:["top","right","bottom","left"];if(o.remove)for(const a of i)delete r[a];else for(const a of i){const l=r[a]??{style:"single",width:1,color:"#000000"};r[a]={style:o.style??l.style,width:o.width??l.width,color:o.color??l.color}}Object.keys(r).length>0?s.yBlock.setAttribute("borders",JSON.stringify(r)):et(s.yBlock,"borders"),Ft(s.anchors,s.yBlock,bt(s.yBlock),"borders"),s.result.appliedAttrs.push(`${e.rawName} -> paragraph borders`),s.result.exactMappings.push(`${e.rawName} -> paragraph borders`)}}function $d(s){if(s.yBlock.nodeName!=="image")return;const t=x=>ro(s.rawAttrs,x),e=t("display");e&&zt(e.value)==="block"&&(s.result.handledRawNames.add(e.canonicalName),De(s.result,e,"ignoredAttrs",`${e.rawName}: block`));const n=t("float"),o=zt(n?.value);n&&(o==="left"||o==="right")&&(s.result.handledRawNames.add(n.canonicalName),s.yBlock.setAttribute("align",o),Ft(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push(`${n.rawName} -> align`),s.result.approximateMappings.push(`${n.rawName}: ${o} -> align: ${o} without text wrapping`));const r=t("marginleft"),i=t("marginright"),a=zt(r?.value),l=zt(i?.value);let c;a==="auto"&&l==="auto"?c="center":a==="auto"&&(!i||so(i.value))?c="right":l==="auto"&&(!r||so(r.value))&&(c="left"),c&&(r&&s.result.handledRawNames.add(r.canonicalName),i&&s.result.handledRawNames.add(i.canonicalName),s.yBlock.setAttribute("align",c),Ft(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push("auto margins -> align"),s.result.exactMappings.push(`margin-left/margin-right auto -> align: ${c}`));for(const x of["margintop","marginright","marginbottom","marginleft"]){const w=t(x);!w||s.result.handledRawNames.has(w.canonicalName)||(s.result.handledRawNames.add(w.canonicalName),so(w.value)?De(s.result,w,"ignoredAttrs",`${w.rawName}: ${String(w.value)}`):De(s.result,w,"unsupportedImageSpacing",`${w.rawName}: ${String(w.value)}`))}const d=t("width"),g=t("maxwidth"),u=t("height"),f=zt(u?.value)==="auto",h=en(d?.value),p=en(g?.value),m=kr(s.doc,s.yBlock),y=Math.max(1,Number(s.yBlock.getAttribute("width"))||1),b=Math.max(1,Number(s.yBlock.getAttribute("height"))||1);let k=y,S=!1,v=!1;if(h!==void 0&&d)k=Math.max(1,Math.round(m*h/100)),s.result.handledRawNames.add(d.canonicalName),S=!0,v=!0;else if(f&&d){const x=Oe("width",d.value);Number.isFinite(x)&&x>0&&(k=Math.max(1,Math.round(x)),s.result.handledRawNames.add(d.canonicalName),S=!0,v=!0)}if(p!==void 0&&g){const x=Math.max(1,Math.round(m*p/100));k=Math.min(k,x),s.result.handledRawNames.add(g.canonicalName),S=!0,s.result.approximateMappings.push(`${g.rawName}: ${String(g.value)} -> fixed ${k}px snapshot`)}if(S){s.yBlock.setAttribute("width",String(k));const x=u&&!f?Oe("height",u.value):Number.NaN,w=f||!Number.isFinite(x);if(w){const A=Math.max(1,Math.round(b*k/y));s.yBlock.setAttribute("height",String(A))}f&&u&&s.result.handledRawNames.add(u.canonicalName),Ft(s.anchors,s.yBlock,null,"width/height"),s.result.appliedAttrs.push("responsive image size -> fixed snapshot"),v&&d&&s.result.approximateMappings.push(`${d.rawName}: ${String(d.value)} -> fixed ${k}px snapshot${w?" with auto height":""}`)}else f&&u&&(s.result.handledRawNames.add(u.canonicalName),De(s.result,u,"ignoredAttrs",`${u.rawName}: auto`))}function jd(s){if(s.yBlock.nodeName!=="table")return;const t=i=>ro(s.rawAttrs,i),e=t("width"),n=en(e?.value);if(e&&n!==void 0){const i=kr(s.doc,s.yBlock),a=Math.max(1,Math.round(i*n/100));s.result.handledRawNames.add(e.canonicalName),s.yBlock.setAttribute("tableWidth",String(a)),Ft(s.anchors,s.yBlock,null,"tableWidth"),s.result.appliedAttrs.push("responsive table width -> fixed snapshot"),s.result.approximateMappings.push(`${e.rawName}: ${String(e.value)} -> fixed ${a}px snapshot`)}const o=t("marginleft"),r=t("marginright");zt(o?.value)==="auto"&&zt(r?.value)==="auto"&&(s.result.handledRawNames.add(o.canonicalName),s.result.handledRawNames.add(r.canonicalName),s.yBlock.setAttribute("align","center"),Ft(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push("auto margins -> align"),s.result.exactMappings.push("margin-left/margin-right auto -> align: center"))}function _d(s){if(s.yBlock.nodeName!=="paragraph")return;const t=a=>ro(s.rawAttrs,a),e=t("breakafter"),n=t("breakbefore"),o=t("breakinside");if(!e&&!n&&!o)return;const r=new Set(String(rt(s.yBlock,"pagination")??"").split(",").filter(Boolean));e&&(s.result.handledRawNames.add(e.canonicalName),e.value===null||zt(e.value)==="auto"?r.delete("keepNext"):["avoid","avoid-page"].includes(zt(e.value)??"")&&r.add("keepNext"),s.result.appliedAttrs.push(`${e.rawName} -> keepNext`)),o&&(s.result.handledRawNames.add(o.canonicalName),o.value===null||zt(o.value)==="auto"?r.delete("keepLines"):["avoid","avoid-page"].includes(zt(o.value)??"")&&r.add("keepLines"),s.result.appliedAttrs.push(`${o.rawName} -> keepLines`)),n&&(s.result.handledRawNames.add(n.canonicalName),De(s.result,n,"ignoredAttrs",`${n.rawName}: ${String(n.value)}`));const i=Array.from(r).join(",");i?s.yBlock.setAttribute("pagination",i):et(s.yBlock,"pagination"),Ft(s.anchors,s.yBlock,bt(s.yBlock),"pagination")}function Xd(s){const t={issuesByRawName:new Map,handledRawNames:new Set,appliedAttrs:[],exactMappings:[],approximateMappings:[],ignoredAttrs:[],unsupportedImageSpacing:[],errors:[]};return Dd({yBlock:s.yBlock,rawAttrs:s.rawAttrs,anchors:s.anchors,result:t}),_d({...s,result:t}),$d({...s,result:t}),jd({...s,result:t}),t}function Ud(s){const{inlineRangeCount:t,unsupportedAttrs:e,unmatchedSelectors:n,invalidSelectorErrors:o,skippedTargetErrors:r,exactCompatibilityMappings:i,approximateCompatibilityMappings:a,ignoredCompatibilityAttrs:l,unsupportedImageSpacing:c}=s,d=s.styleEffects,g=[`style_blocks ${d.outcome==="partial"?"partially applied requested styling":d.outcome==="unchanged"?"verified requested styling unchanged":"applied requested styling"}. Matched ${d.targetBlockIds.length} blocks${t?` and ${t} inline ranges`:""}; changed ${d.changedBlockIds.length} blocks.`,...d.attributes.map(u=>`${u.name}: applied to ${u.appliedBlockIds.length} targets (including already-equal values), skipped on ${new Set(u.skipped.map(f=>f.blockId)).size}.`)];if(i.length>0&&g.push(`Compatibility mappings: ${Array.from(new Set(i)).join("; ")}.`),a.length>0&&g.push(`Approximate compatibility mappings: ${Array.from(new Set(a)).join("; ")}.`),l.length>0&&g.push(`Ignored compatibility attrs: ${Array.from(new Set(l)).join(", ")}.`),c.length>0&&g.push(`Unsupported image spacing ignored: ${Array.from(new Set(c)).join(", ")}.`),n.length>0&&g.push(`Unmatched selectors: ${n.join(", ")}.`),o.length>0&&g.push(`Invalid selectors ignored: ${o.join("; ")}.`),e.length>0&&g.push(`Unsupported attrs ignored: ${e.join(", ")}.`),r.length>0){const u=Array.from(new Set(r)),f=u.slice(0,12),h=u.length-f.length;g.push(`Skipped invalid target/style pairs: ${f.join("; ")}${h>0?`; and ${h} more`:""}.`)}return g.join(" ")}function zd(s){const t=ye(s.getAttribute("_emptyTextMarks"));for(const e of _s)delete t[e];Object.keys(t).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(t))}function Wd(s,t=1){if(typeof s!="number"||!Number.isFinite(s))return t;const e=Math.floor(s);return e>=1?e:t}function Jd(s){const t=bt(s);if(t){const n=st(t);let o="";for(const r of n)r.insert&&typeof r.insert=="string"&&(o+=r.insert);return o}const e=s.nodeName;return e==="list"?"List removed":e==="table"?"Table removed":e==="code"?"Code block removed":e==="math"?"Math block removed":e==="image"?"Image removed":"Block removed"}function Hi(s,t,e){const n=Jd(s),o=bt(s),r=t&&t.length>0?t:void 0;if(o&&n.length>0){e.push({kind:"delete",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(o,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(o,n.length,0)),text:n});return}e.push({kind:"delete",paragraphId:r,text:n})}function Hd(s,t){const e=s.parent;if(!(e instanceof I.XmlElement)&&!(e instanceof I.XmlFragment)||s.nodeName!=="list")return null;const n=e.toArray().indexOf(s);if(n<0)return null;const o=[];for(const r of s.toArray()){if(!(r instanceof I.XmlElement)||r.nodeName!=="list-item")continue;const i=new I.XmlElement("paragraph");i.setAttribute("id",r.getAttribute("id")||G());const a=rt(r,"direction");(a==="ltr"||a==="rtl")&&i.setAttribute("direction",a);for(const g of["lineSpacing","spaceBefore","spaceAfter","contextualSpacing"]){const u=rt(r,g)??rt(s,g);u!==void 0&&i.setAttribute(g,String(u))}const l=r.getAttribute("_emptyTextMarks");l&&i.setAttribute("_emptyTextMarks",l);const c=bt(r),d=new I.XmlText;c&&yl(d,st(c)),i.insert(0,[d]),o.push(i)}if(o.length===0)return null;Hi(s,s.getAttribute("id"),t),e.delete(n,1),e.insert(n,o);for(const r of o){const i=bt(r);if(!i)continue;const a=fe(i);t.push({kind:"insert",paragraphId:r.getAttribute("id"),from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(i,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(i,a.length,0)),text:a})}return o}function qi(s,t){if(t.link)return[{text:s,marks:t}];const e=Pi(s);if(e.length===0)return[{text:s,marks:t}];const n=[];let o=0;for(const r of e)r.start>o&&n.push({text:s.slice(o,r.start),marks:t}),n.push({text:r.originalText,marks:{...t,link:r.url}}),o=r.end;return o<s.length&&n.push({text:s.slice(o),marks:t}),n}function io(s){return It(ys(s,t=>!t.text||t.marks?.link?t:qi(t.text,t.marks||{}).map(e=>({type:"text",text:e.text,marks:e.marks}))))}function Yi(s,t){return Pt(Bn(t==="todo"?{...s,checked:s.checked??!1}:s))}function Ki(s,t,e,n=!1){return s.flatMap(o=>{if(o.type==="list")return o.children.map(r=>({...r,indentLevel:(n?0:t)+(r.indentLevel??0)}));if(o.type==="paragraph")return[{type:"list-item",id:o.id,children:o.children,direction:o.direction,lineSpacing:o.lineSpacing,spaceBefore:o.spaceBefore,spaceAfter:o.spaceAfter,indentLevel:t}];throw new Error(`Cannot put a ${o.type} inside a list item. Insert it before or after the containing list instead.`)}).map((o,r)=>({...o,id:r===0?e:o.id||G()}))}function oe(s,t,e,n){const o=qi(e,n);let r=t;for(const i of o)lt(s,r,i.text,i.marks),r+=i.text.length;return r}function Vi(s,t,e){const n=s.toString(),o=e??n.length,r=n.slice(t,o),i=Pi(r);for(const a of i){const l=t+a.start;at(s,l,a.end-a.start,{link:a.url})}}function Sr(s,t){if(!Je(s,t)||s.children.length!==t.children.length)return!1;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(n.type!==o.type||n.type!=="text"||o.type!=="text"||n.text!==o.text||JSON.stringify(n.marks||{})!==JSON.stringify(o.marks||{}))return!1}return!0}function ao(s,t){const e=["heading","align","leftIndent","firstLineIndent","spaceBefore","spaceAfter","lineSpacing","styleId","direction","borders","shading","tabStops"];for(const o of e){const r=t[o];r===void 0?et(s,o):s.setAttribute(o,String(r))}const n=qt(t);n===void 0?et(s,"pagination"):s.setAttribute("pagination",n)}function qd(s,t){if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++){const n=s[e],o=t[e];if(n.type!==o.type||n.text!==o.text||JSON.stringify(n.marks||{})!==JSON.stringify(o.marks||{}))return!1}return!0}function Yd(s,t){return s.type!==t.type?!1:s.type==="paragraph"&&t.type==="paragraph"?Sr(s,t):qd(s.children,t.children)}function Gi(s){return s.map(t=>({...t,marks:t.marks?{...t.marks}:void 0}))}function Qi(s,t){const e=n=>{for(const o of n){if(o.type==="paragraph"&&o.id===t)return o;if(o.type==="list"){for(const r of o.children)if(r.id===t)return r;continue}if(o.type==="container"||o.type==="table-cell"){const r=e(o.children);if(r)return r;continue}if(o.type==="table")for(const r of o.children)for(const i of r.children){const a=e(i.children);if(a)return a}}return null};return e(s.children)}function Zi(s){return s.replace(/&#0?39;|&apos;/g,"'").trim()}function Kd(s,t,e){const n=s.indexOf(t);return n===-1?s:s.slice(0,n)+e+s.slice(n+t.length)}function Vd(s,t){if(t.type==="paragraph")return Zi(it.toAgentHtml({type:"doc",children:[{...t,children:Gi(t.children)}]}));if(s.listVariant==="todo")return null;const e={type:"list",id:"__agent_html_replace__",variant:s.listVariant==="ordered"?"ordered":"unordered",children:[{...t,children:Gi(t.children),indentLevel:void 0}]},n=Zi(it.toAgentHtml({type:"doc",children:[e]})).match(/^<(?:ul|ol)(?:\s[^>]*)?>([\s\S]*)<\/(?:ul|ol)>$/);return n?n[1].trim():null}function Gd(s,t,e,n){try{if(e.type==="paragraph"){const i=it.fromAgentHtml(t,{existingDocument:n,replacementBlock:e});return i.children.length!==1||i.children[0].type!=="paragraph"?null:i.children[0]}if(s.listVariant==="todo")return null;const o=s.listVariant==="ordered"?"ol":"ul",r=it.fromAgentHtml(`<${o}>${t}</${o}>`,{existingDocument:n});return r.children.length!==1||r.children[0].type!=="list"||r.children[0].children.length!==1?null:r.children[0].children[0]}catch{return null}}function Qd(s,t){const e=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/i,n=s.match(e),o=t.match(e),r=n?.[1]??n?.[2],i=o?.[1]??o?.[2];if(!r||!i||r===i)return null;const a=Ke(r),l=Ke(i);return!a||a!==l?null:`Highlight colors ${JSON.stringify(r)} and ${JSON.stringify(i)} both resolve to ${JSON.stringify(a)}, so this replacement is a no-op. Use a different canonical highlight color: ${Ln.join(", ")}.`}function Zd(s){const t=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/gi;for(const e of s.matchAll(t)){const n=e[1]??e[2];if(n&&!Ke(n))throw new Error(`Unsupported highlight color ${JSON.stringify(n)}. Use one of: ${Ln.join(", ")}.`)}}function ta(s){const t=s?.comment;return typeof t!="string"||t.length===0?[]:Array.from(new Set(t.split(",").map(e=>e.trim()).filter(Boolean))).sort()}function re(s,t={}){const e=Object.entries(s??{}).filter(([n,o])=>o!==void 0&&(n!=="comment"||!t.ignoreComment)).map(([n,o])=>n==="comment"?[n,ta(s).join(",")]:[n,o]).filter(([,n])=>n!=="").sort(([n],[o])=>n<o?-1:n>o?1:0);return JSON.stringify(e)}function tg(s){return Object.fromEntries(Object.entries(s).sort(([t],[e])=>t<e?-1:t>e?1:0))}function lo(s){return s.flatMap(t=>{const{comment:e,...n}=t.marks??{},o=ta(t.marks);return Array.from({length:t.text.length},(r,i)=>({value:t.text[i],marks:n,comment:o}))})}function eg(s){return s.length===0?[]:s.reduce((t,e)=>t.filter(n=>e.includes(n)))}const be=-1,Ir=0,nn=1;function ng(s){const t=[];for(let e=0;e<s.length;e++){const[n,o]=s[e],r=s[e+1];if(!(r!==void 0&&(n===be&&r[0]===nn||n===nn&&r[0]===be))){t.push([n,o]);continue}const i=n===be?o:r[1],a=n===nn?o:r[1];let l=0;const c=Math.min(i.length,a.length);for(;l<c&&i[l]===a[l];)l++;let d=0;const g=c-l;for(;d<g&&i[i.length-1-d]===a[a.length-1-d];)d++;l>0&&t.push([Ir,i.slice(0,l)]);const u=i.slice(l,i.length-d),f=a.slice(l,a.length-d);u.length>0&&t.push([be,u]),f.length>0&&t.push([nn,f]),d>0&&t.push([Ir,i.slice(i.length-d)]),e++}return t}function og(s,t){const e=lo(s),n=lo(t),o=ng(ic([],e.map(d=>d.value).join(""),n.map(d=>d.value).join(""))),r=new Array(n.length),i=new Array(n.length);let a=0,l=0;for(let d=0;d<o.length;d++){const[g,u]=o[d];if(g===Ir){for(let S=0;S<u.length;S++)r[l+S]=e[a+S].comment,i[l+S]=e[a+S].marks.lang;a+=u.length,l+=u.length;continue}if(g===be){a+=u.length;continue}if(g!==nn)continue;const f=o[d-1],h=o[d+1],p=[];f?.[0]===be&&p.push(...e.slice(a-f[1].length,a)),h?.[0]===be&&p.push(...e.slice(a,a+h[1].length));const m=p.length>0?p:[e[a-1],e[a]].filter(S=>!!S),y=eg(m.map(S=>S.comment)),b=m[0]?.marks.lang,k=typeof b=="string"&&m.every(S=>S.marks.lang===b)?b:void 0;for(let S=0;S<u.length;S++)r[l+S]=y,i[l+S]=k;l+=u.length}const c=[];return n.forEach((d,g)=>{const u=r[g]??[],f=tg({...d.marks,...d.marks.lang===void 0&&i[g]!==void 0?{lang:i[g]}:{},...u.length>0?{comment:u.join(",")}:{}}),h=c[c.length-1];h&&re(h.marks)===re(f)?h.text+=d.value:c.push({type:"text",text:d.value,...Object.keys(f).length>0?{marks:f}:{}})}),c}function rg(s,t){const e=lo(s),n=lo(t);return e.length===n.length&&e.every((o,r)=>o.value===n[r].value&&re(o.marks)===re(n[r].marks)&&o.comment.join(",")===n[r].comment.join(","))}function ea(s,t,e,n,o){if(e=jo(e),n=jo(n),e.length===0)return null;const r=Qi(t,s.blockId);if(!r)return null;const i=Vd(s,r),a=i?jo(i):null;if(!a||!a.includes(e))return null;const l=oc(a,e).length;if(!o&&l>1)throw new Error(`Found ${l} matches for ${JSON.stringify(e)} in block '${s.blockId}' once comment-thread tags are ignored (threads don't distinguish text). Include more surrounding text so it matches exactly one location, or use replace_all.`);Zd(n);const c=o?a.split(e).join(n):Kd(a,e,n);if(c===a)return null;const d=Gd(s,c,r,t);if(!d)throw new Error(`Matched AgentHtml in block '${s.blockId}', but the replacement is not a supported single-block text update.`);if(d.type!==r.type)throw new Error(`Matched AgentHtml in block '${s.blockId}', but the replacement changes the block structure. Keep replace() within a single compatible text block.`);const g={...d,children:og(r.children,Vn(r.children,d.children))};if(Yd(r,g)||rg(r.children,g.children)&&(r.type!=="paragraph"||g.type!=="paragraph"||Je(r,g)))throw new Error(Qd(e,n)??`Matched AgentHtml in block '${s.blockId}', but the replacement would not change any supported text or formatting.`);return{blockId:s.blockId,yBlock:s.yBlock,currentBlock:r,replacementBlock:g}}function co(s,t){const e=bt(s.yBlock);if(!e)throw new Error(`Target block '${s.blockId}' has no text content to replace.`);const n=h=>h.flatMap(p=>Array.from({length:p.text.length},(m,y)=>({value:p.text[y],marks:p.marks||{}}))),o=(h,p)=>h.value===p.value&&re(h.marks)===re(p.marks),r=n(s.currentBlock.children),i=n(s.replacementBlock.children);let a=0;for(;a<r.length&&a<i.length&&o(r[a],i[a]);)a++;let l=0;for(;l<r.length-a&&l<i.length-a&&o(r[r.length-l-1],i[i.length-l-1]);)l++;const c=r.length-a-l,d=i.slice(a,i.length-l),g=I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,a,-1));c>0&&e.delete(a,c);let u=a;const f=[];for(let h=0;h<d.length;){const p=d[h].marks;let m=d[h].value;for(h++;h<d.length&&re(d[h].marks)===re(p);)m+=d[h].value,h++;f.push({type:"text",text:m,marks:p}),u=oe(e,u,m,p)}s.currentBlock.type==="paragraph"&&s.replacementBlock.type==="paragraph"&&(s.replacementBlock.heading?s.yBlock.setAttribute("heading",String(s.replacementBlock.heading)):s.yBlock.removeAttribute("heading"),s.replacementBlock.align?s.yBlock.setAttribute("align",s.replacementBlock.align):et(s.yBlock,"align")),t.push({kind:"replace",paragraphId:s.blockId,previewStartOffset:a,sourceFrom:g,previewTextNodes:f,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,a,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,u,0)),text:d.map(h=>h.value).join(""),oldText:r.slice(a,r.length-l).map(h=>h.value).join("")})}function Wt(s,t,e,n){const o=[];wt(t,{verifiedUnchanged:!1,styleEffects:void 0}),cr.delete(t);const r=t.name;n&&r!=="insert_block"&&(n.lastInsertedBlock=void 0);const i=t.arguments;if(r==="replace_many"||r==="replace"&&Array.isArray(i?.replacements)){const a=ir({...t,id:e??"replacement-batch"},{doc:Kt(s),loadedBlockIds:null});if(a.error){const d=a.failure;throw new St(d?.code??"invalid_arguments",a.error,d?.phase??"validation",d?.retryable,d?.mutationOutcome,d?.details)}let l=n,c=!0;for(const d of a.actions){const g=d,u=Wt(s,g,e,l);if(c=c&&!!Rt(g)?.verifiedUnchanged,o.push(...u),!l){const f=Kt(s);l={document:f,htmlParsingContext:it.createParsingContext(f),refreshDocumentIncrementally:!0}}}return wt(t,{verifiedUnchanged:c}),o}switch(t.name){case"move_blocks":throw new St("move_requires_live_session","move_blocks must execute through the tracked-move session operation, not the generic replacement planner.");case"insert_block":{const{referenceId:a,position:l,content:c}=t.arguments;if(typeof a!="string"||!a.trim())throw new Error("insert_block referenceId is required. Resolve blank-document anchors before applying the action.");const d=Wn(t),g=n?.document??mt(s);if(!Array.isArray(c))throw new Error("insert_block content must be an array");if(c.length!==1)throw new Error("insert_block should only receive a single block after preprocessing. Got array with "+c.length+" items");const u=c[0];let f,h;if(a===Ve)f=We(s),h=f.length;else if(n?.lastInsertedBlock&&n.lastInsertedBlock.id===a)f=n.lastInsertedBlock.yParent,h=l==="before"?n.lastInsertedBlock.index:n.lastInsertedBlock.index+1;else{const S=ot(s,a);if(!S)throw new Error(`Reference block '${a}' not found in the current document. Read the document again and use a current block ID.`);f=S.yParent,h=l==="before"?S.index:S.index+1}if((Le(f)||f===s.getXmlFragment("chrome"))&&Fe(),f instanceof I.XmlElement&&(f.nodeName==="table"||f.nodeName==="table-row"))throw new Error("insert_block cannot insert beside a table row or cell. Use a paragraph ID inside the cell to insert cell content, the table ID to insert beside the table, or insert_table_row / insert_table_column to change the table structure.");let p,m;const y=n?.lastInsertedBlock;if(y?.yParent===f&&y.index===h-1)p=y.block,m=y.insertionFont;else if(h>0){const S=f.get(h-1);if(S instanceof I.XmlElement){const v=S.getAttribute("id");v&&(p=n?.lastInsertedBlock?.id===v?n.lastInsertedBlock.block:W(g,v)??void 0)}}m??(m=it.insertionFontFor(p));let b;if(u.includes("<")&&u.includes(">")?b=it.fromAgentHtml(u,{previousBlock:p,insertionFont:m,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:f instanceof I.XmlElement&&f.nodeName==="list"?Number(Z(s,a)?.getAttribute("indentLevel")??0):void 0}):b=it.fromAgentHtml(`<p>${u}</p>`,{previousBlock:p,insertionFont:m,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:f instanceof I.XmlElement&&f.nodeName==="list"?Number(Z(s,a)?.getAttribute("indentLevel")??0):void 0}),b.children.length!==1)throw new Error(`insert_block should produce exactly one block. Got ${b.children.length} blocks from content: ${u}`);const k=b.children[0];if(!d)throw new Error("insert_block must have stableId set by preprocessor");if(k.id=d,f instanceof I.XmlElement&&f.nodeName==="list"){const S=Z(s,a),v=Ki([k],Number(S?.getAttribute("indentLevel")??0),d,!0);f.insert(h,v.map(x=>It(x))),o.push({kind:"insert",paragraphId:f.getAttribute("id"),text:v.map(x=>x.children.map(w=>w.text).join("")).join(`
3
3
  `)});break}if(k.type==="paragraph"){const S=k,v=new I.XmlElement("paragraph");v.setAttribute("id",d),ao(v,S);const x=new I.XmlText;let w=0;S.children.forEach(P=>{if(P.type==="text"){const T=P;w=oe(x,w,T.text,T.marks||{})}}),to(v,S,w),v.insert(0,[x]),f.insert(h,[v]);const A=S.children.filter(P=>P.type==="text").map(P=>P.text).join("");o.push({kind:"insert",paragraphId:d,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,A.length,0)),text:A})}else if(k.type==="list"){const S=io(k);f.insert(h,[S]);const v=[];for(const x of S.toArray()){if(!(x instanceof I.XmlElement))continue;const w=ct(x);if(!w)continue;const A=st(w).map(P=>typeof P.insert=="string"?P.insert:"").join("");A.length&&v.push({yText:w,plainText:A})}v.forEach(({yText:x,plainText:w})=>{o.push({kind:"insert",paragraphId:d,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,w.length,0)),text:w})})}else if(k.type==="table"){const S=io({...k,id:d});f.insert(h,[S]),o.push({kind:"insert",paragraphId:d,text:"Table inserted"})}else if(k.type==="code"){const S=k,v=new I.XmlElement("code");v.setAttribute("id",d),S.language&&v.setAttribute("language",S.language),S.renderDiagram!==void 0&&v.setAttribute("renderDiagram",String(S.renderDiagram)),S.showDiagramSource!==void 0&&v.setAttribute("showDiagramSource",String(S.showDiagramSource));const x=new I.XmlText;v.insert(0,[x]),lt(x,0,S.content||""),f.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Code block inserted"})}else if(k.type==="math"){const S=k,v=new I.XmlElement("math");v.setAttribute("id",d),S.displayMode&&v.setAttribute("displayMode",S.displayMode),S.align&&v.setAttribute("align",S.align);const x=new I.XmlText;v.insert(0,[x]),lt(x,0,S.content||""),f.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Math block inserted"})}else if(k.type==="page-break"){const S=new I.XmlElement("page-break");S.setAttribute("id",d),f.insert(h,[S]),o.push({kind:"insert",paragraphId:d,text:"Page break inserted"})}else if(k.type==="toc"){const S=It({...k,id:d});f.insert(h,[S]),o.push({kind:"insert",paragraphId:d,text:"Table of contents inserted"})}else if(k.type==="image"){const S=k,v=new I.XmlElement("image");v.setAttribute("id",d),v.setAttribute("src",S.src),S.sourceUrl&&v.setAttribute("sourceUrl",S.sourceUrl),v.setAttribute("width",String(S.width)),v.setAttribute("height",String(S.height)),S.alt&&v.setAttribute("alt",S.alt),S.align&&v.setAttribute("align",S.align),f.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Image inserted"})}else throw new Error(`insert_block expected a paragraph, list, table, code, math, image, table-of-contents, or page-break block but got ${k.type}`);n&&(n.lastInsertedBlock={id:d,yParent:f,index:h,block:k,insertionFont:m},f===s.getXmlFragment("content")?n.document.children.splice(h,0,k):(n.document=mt(s),n.htmlParsingContext=it.createParsingContext(n.document)));break}case"replace":case"replace_all":{const{id:a}=t.arguments;let{find:l,replace:c}=t.arguments;const d=n?.document??mt(s),g=Z(s,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);let u=ld(g,a);const f=Hs(Qi(d,a)??W(d,a),l);if(f&&(u=u.filter(y=>f.has(y.blockId))),f&&u.length===0)throw new St("target_stale","HTML matcher identities no longer resolve to editable text within this target. Read the target again.","target_resolution");if(u.length===0)break;if(l.length===0){if(u.length!==1||u[0].blockText.length!==0)throw new Error(`An empty find may only fill one truly empty text block; block '${a}' is not an unambiguous empty target.`);const y=u[0];xr(y.yText,0,0,l,c,y.blockId,o,ye(y.yBlock.getAttribute("_emptyTextMarks")));break}const h=y=>u.map(b=>({...b,matches:Hn(b.blockText,y)})).filter(b=>b.matches.length>0);if(qe(l)){const y=u.map(b=>ea(b,d,l,c,t.name==="replace_all")).filter(b=>b!==null);if(y.length>0){if(t.name==="replace"&&y.length>1)throw new Error(`Found ${y.length} exact AgentHtml matches for "${l}" in block '${a}'. Include more surrounding AgentHtml so it matches exactly one location, or use replace_all.`);if(t.name==="replace")co(y[0],o);else for(const b of y)co(b,o);break}}let p=h(l);if(p.length===0){const y=Ko(l);if(y!==l&&y.trim()!==""){const b=h(y);b.length>0&&(l=y,c=Ko(c),p=b)}}if(p.length===0){const y=u.map(A=>ea(A,d,l,c,t.name==="replace_all")).filter(A=>A!==null);if(y.length>0){if(t.name==="replace")co(y[0],o);else for(const A of y)co(A,o);break}const b=u.map(A=>A.blockText).join(`
4
4
  `),k=Os(b.length>100?b.slice(0,100)+"...":b),S=gd(s,a,l),v=/(?:\*\*|__|^>|^#{1,6}\s|^[-*+]\s|^\d+[.)]\s|\|)/m.test(l)?" The requested find contains Markdown syntax, while this preview is stored plain text; formatting markers are not literal characters.":"";if(l.includes("<")&&l.includes(">"))throw new St("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}. If you're matching AgentHtml from the document context, the snippet must match the exact block HTML.${S}`,"matching");const x=u.map(A=>ud(A.blockText,l)).find(Boolean)??"",w=typeof c=="string"&&c.trim().length>=4&&!c.includes(l)&&b.includes(c)?` The block already contains the replacement text ${JSON.stringify(c)}, so this edit may already be applied; check the current block before retrying.`:"";throw new St("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}.${w}${x}${v} Make sure the text you're searching for exists exactly as written (case-sensitive, including punctuation and spaces).${S}`,"matching")}const m=p.reduce((y,b)=>y+b.matches.length,0);if((t.name==="replace_all"||m===1)&&p.every(y=>y.matches.every(b=>na(y.yText,b.offset,b.length,l,c)))){wt(t,{verifiedUnchanged:!0});break}if(t.name==="replace"){const y=p.reduce((S,v)=>S+v.matches.length,0);if(y>1)throw new Error(`Found ${y} matches for "${l}" in block '${a}'. Include more surrounding context in "find" so it matches exactly one location, or use replace_all to change every occurrence.`);const b=p[0],k=b.matches[0];xr(b.yText,k.offset,k.length,l,c,b.blockId,o)}else for(const y of p){let b=-1;y.matches=y.matches.filter(k=>k.offset<b?!1:(b=k.offset+k.length,!0));for(let k=y.matches.length-1;k>=0;k--){const S=y.matches[k];xr(y.yText,S.offset,S.length,l,c,y.blockId,o)}}break}case"replace_block":{const{id:a,content:l,count:c}=t.arguments;if(c!==void 0&&(!Number.isFinite(c)||Math.floor(c)<1))throw new Error("replace_block count must be a positive integer.");const d=Wd(c,1),g=n?.document??mt(s),u=W(g,a);if(!u){const S=g.children.map(v=>v.id).filter(v=>v).slice(0,10);throw console.error(`[ForkActionApplicator] Block with id '${a}' not found. Available IDs:`,S),new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`)}const f=ot(s,a);if(!f)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:h,yParent:p,index:m}=f,y=Le(p);if((h.nodeName==="header-footer"||y&&d!==1)&&Fe(),d>1){const S=Math.max(0,p.length-(m+1)),v=Math.min(d-1,S);for(let x=0;x<v;x++){const w=p.get(m+1);if(!(w instanceof I.XmlElement))break;const A=w.getAttribute("id");Hi(w,A??void 0,o),p.delete(m+1,1)}}const b=Cn(g,a),k=b>0?g.children[b-1]:void 0;{const S=(Array.isArray(l)?l:[l]).join(""),v=it.fromAgentHtml(S,{previousBlock:k,replacementBlock:u,existingDocument:g,listItemBaseIndent:h.nodeName==="list-item"?Number(h.getAttribute("indentLevel")??0):void 0});if(y&&(v.children.length!==1||v.children[0].type!=="paragraph")&&Fe(),h.nodeName==="list-item"&&p instanceof I.XmlElement&&p.nodeName==="list"){const x=Ki(v.children,Number(h.getAttribute("indentLevel")??0),a,!0);if(d===1&&x.length===1&&u.type==="list"){const w=u.children.find(A=>A.id===a);if(u.variant==="todo"&&x[0].checked===void 0&&w?.checked!==void 0&&(x[0].checked=w.checked),x[0].children=Vn(w?.children??[],x[0].children),w&&Yi(w,u.variant)===Yi(x[0],u.variant)){wt(t,{verifiedUnchanged:!0});break}}p.delete(m,1),p.insert(m,x.map(w=>It(w))),o.push({kind:"replace",paragraphId:p.getAttribute("id"),oldText:"List item",text:x.map(w=>w.children.map(A=>A.text).join("")).join(`
5
- `)});break}if(u.type==="paragraph"){const x=A=>A.children.filter(P=>!P.marks?.footnoteRef),w=it.extractUniformTextFontFamily(x(u));if(w){for(const A of v.children)if(A.type==="paragraph"&&it.extractUniformTextFontFamily(x(A)))for(const P of x(A))P.marks={...P.marks,fontFamily:w}}}if(v.children.length>0)if(v.children.length===1){const x=v.children[0];if(d===1&&(u.type==="paragraph"||u.type==="list")&&x.type===u.type){if(u.type==="paragraph"&&x.type==="paragraph")x.children=Vn(u.children,x.children);else if(u.type==="list"&&x.type==="list"){const O=new Map(u.children.map(L=>[L.id,L])),$=u.children.length===x.children.length&&x.children.every((L,D)=>L.children.map(H=>H.text).join("")===u.children[D].children.map(H=>H.text).join(""));x.children=x.children.map((L,D)=>({...L,children:Vn((O.get(L.id)??($?u.children[D]:void 0))?.children??[],L.children)}))}const N=O=>Array.isArray(O)?O.map(N):O&&typeof O=="object"?Object.fromEntries(Object.entries(O).filter(([$,L])=>$!=="id"&&L!==void 0&&!($==="marks"&&Object.keys(L).length===0)).sort(([$],[L])=>$.localeCompare(L)).map(([$,L])=>[$,N(L)])):O,R=O=>JSON.stringify(N(O)),M=O=>it.toInternalHtml({type:"doc",children:[N(O)]});if(R(u)===R(x)||M(u)===M(x)){wt(t,{verifiedUnchanged:!0});break}}if(!(h instanceof I.XmlElement))break;if(x.type==="list"){p.delete(m,1);const N=io({...x,id:a});p.insert(m,[N]);const R=u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:R});break}if(x.type==="table"){const N=x;p.delete(m,1);const R=io({...N,id:a});p.insert(m,[R]);const M=u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:M});break}if(x.type==="code"){const N=x;p.delete(m,1);const R=new I.XmlElement("code");R.setAttribute("id",a),N.language&&R.setAttribute("language",N.language),N.renderDiagram!==void 0&&R.setAttribute("renderDiagram",String(N.renderDiagram)),N.showDiagramSource!==void 0&&R.setAttribute("showDiagramSource",String(N.showDiagramSource));const M=new I.XmlText;R.insert(0,[M]),lt(M,0,N.content||""),p.insert(m,[R]);const O=u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Code block replaced",oldText:O});break}if(x.type==="math"){const N=x;p.delete(m,1);const R=new I.XmlElement("math");R.setAttribute("id",a),N.displayMode&&R.setAttribute("displayMode",N.displayMode),N.align&&R.setAttribute("align",N.align);const M=new I.XmlText;R.insert(0,[M]),lt(M,0,N.content||""),p.insert(m,[R]);const O=u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Math block replaced",oldText:O});break}if(x.type==="page-break"){p.delete(m,1);const N=new I.XmlElement("page-break");N.setAttribute("id",a),p.insert(m,[N]);const R=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Page break replaced",oldText:R});break}if(x.type==="toc"){p.delete(m,1);const N=It({...x,id:a});p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(x.type==="image"){const N=x;p.delete(m,1);const R=new I.XmlElement("image");R.setAttribute("id",a),R.setAttribute("src",N.src),N.sourceUrl&&R.setAttribute("sourceUrl",N.sourceUrl),R.setAttribute("width",String(N.width)),R.setAttribute("height",String(N.height)),N.alt&&R.setAttribute("alt",N.alt),N.align&&R.setAttribute("align",N.align),p.insert(m,[R]);const M=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Image replaced",oldText:M});break}if((u.type==="math"||u.type==="code")&&x.type==="paragraph"){p.delete(m,1);const N=new I.XmlElement("paragraph");N.setAttribute("id",a),ao(N,x);const R=new I.XmlText;let M=0;for(const O of x.children)O.type==="text"&&(M=oe(R,M,O.text,O.marks||{}));to(N,x,M),N.insert(0,[R]),p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:x.children.filter(O=>O.type==="text").map(O=>O.text).join(""),oldText:u.type==="code"?"Code block":"Math block"});break}if((u.type==="list"||u.type==="table")&&x.type==="paragraph"){p.delete(m,1);const N=new I.XmlElement("paragraph");N.setAttribute("id",a),ao(N,x);const R=new I.XmlText;let M=0;for(const O of x.children)O.type==="text"&&(M=oe(R,M,O.text,O.marks||{}));to(N,x,M),N.insert(0,[R]),p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:x.children.filter(O=>O.type==="text").map(O=>O.text).join(""),oldText:u.type==="table"?"Table":"List"});break}const w=bt(h);w||lr(h);const A=u.type==="paragraph"?u:null,P=w.length,T=v.children[0],E=A!==null&&Sr(A,T);let B=0;if(!E){if(P>0&&w.delete(0,P),T.children.length>0){for(const N of T.children)if(N.type==="text"){const R=N;B=oe(w,B,R.text,R.marks||{})}}ao(h,T)}if(!E){const N=u.type==="paragraph"?u.children.filter(R=>R.type==="text").map(R=>R.text).join(""):"";o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,B,0)),text:T.children.filter(R=>R.type==="text").map(R=>R.text).join(""),oldText:N})}}else{if(!(h instanceof I.XmlElement))throw new St("target_type_mismatch","Target is not an editable block. Read the current document and target a paragraph ID.","target_resolution");const x=bt(h);x||lr(h);const w=u.type==="paragraph"?u:null,A=x.length,P=u.type==="paragraph"?u.children.filter(R=>R.type==="text").map(R=>R.text).join(""):"",T=v.children[0],E=w!==null&&Sr(w,T);let B=0;if(!E){if(A>0&&x.delete(0,A),T.children.length>0){for(const R of T.children)if(R.type==="text"){const M=R;B=oe(x,B,M.text,M.marks||{})}}T.heading&&h.setAttribute("heading",String(T.heading)),T.align&&h.setAttribute("align",T.align)}E||o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,B,0)),text:T.children.filter(R=>R.type==="text").map(R=>R.text).join(""),oldText:P});let N=m+1;for(let R=1;R<v.children.length;R++){const M=v.children[R],O=new I.XmlElement("paragraph"),$=M.id||G();O.setAttribute("id",$),M.heading&&O.setAttribute("heading",String(M.heading)),M.align&&O.setAttribute("align",M.align);const L=new I.XmlText;let D=0;M.children.forEach(F=>{if(F.type==="text"){const X=F;D=oe(L,D,X.text,X.marks||{})}}),to(O,M,D),O.insert(0,[L]),p.insert(N,[O]),N++;const H=M.children.filter(F=>F.type==="text").map(F=>F.text).join("");o.push({kind:"insert",paragraphId:$,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(L,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(L,H.length,0)),text:H})}}}break}case"style_blocks":{const{selectors:a,attrs:l}=t.arguments,{targets:c,inlineTargets:d,unmatchedSelectors:g,invalidSelectorErrors:u}=Nd(s,a),f=Ld(l),h=Fd(f);if(c.length===0&&d.length===0)throw new Error(`style_blocks matched no blocks. Unmatched selectors: ${g.length>0?g.join(", "):"all"}. ${u.length>0?`Invalid selectors: ${u.join("; ")}.`:""}`);const p=[],m=new Map,y=(J,K,q)=>{const Q=me(J);let ut=m.get(Q);ut||(ut={name:J,applied:new Set,skipped:new Map},m.set(Q,ut)),q?ut.skipped.set(`${K}\0${q}`,{blockId:K,reason:q}):ut.applied.add(K)},b=o.length,k=new Set,S=new Set,v=new Set(c),x=new Set,w=[],A=[],P=[],T=[],E=Kt(s),B=new Set([...c,...d.map(J=>J.yBlock)].map(Bt)),N=J=>"id"in J&&B.has(String(J.id))||"children"in J&&J.children.some(K=>N(K)),R=J=>[...J.children,...J.notes??[],...J.chrome??[]],M=new Set(R(E).filter(N).map(J=>J.id)),O=J=>Pt({order:J.children.map(K=>K.id),noteOrder:(J.notes??[]).map(K=>K.id),chromeOrder:(J.chrome??[]).map(K=>K.id),targets:R(J).filter(K=>M.has(K.id))}),$=O(E),L=new Set,D=new Set,H=ro(f,"width");if(H&&!(c.some(J=>J.nodeName==="image")&&en(H.value)===void 0)){const J=new Map;for(const q of c){if(q.nodeName!=="table-cell")continue;let Q=q.parent;for(;Q instanceof I.XmlElement&&Q.nodeName!=="table";)Q=Q.parent;if(!(Q instanceof I.XmlElement))continue;const ut=W(E,Bt(Q));if(!ut||ut.type!=="table")continue;const yt=en(H.value),Lt=Oe("width",H.value),dt=ut.tableWidth??kr(E,Q),ht=yt??(typeof Lt=="number"&&Number.isFinite(Lt)?Lt/dt*100:NaN);J.has(Q)||J.set(Q,[]),J.get(Q).push({cellId:Bt(q),percent:ht}),L.add(q)}const K=[...J].map(([q,Q])=>({table:q,requests:Q,widths:Vc(W(E,Bt(q)),Q)}));for(const q of K){const Q=String(q.table.getAttribute("columnWidths")??""),ut=JSON.stringify(q.widths),yt=W(E,Bt(q.table)),Lt=Mn(yt);for(const dt of q.requests){const ht=Lt.byId.get(dt.cellId),vt=Tt=>Tt.slice(ht.col,ht.col+ht.colSpan).reduce((ce,Sn)=>ce+Sn,0);Math.abs(vt(yt.columnWidths)-vt(q.widths))>.001&&D.add(dt.cellId)}Q!==ut&&(q.table.setAttribute("columnWidths",ut),Ft(o,q.table,null,"columnWidths"),k.add(Bt(q.table))),x.add(H.canonicalName),S.add("columnWidths")}}for(const J of c){const K=Bt(J);let q=!1;const Q=Xd({doc:E,yBlock:J,rawAttrs:f,anchors:o});L.has(J)&&H&&(Q.handledRawNames.add(H.canonicalName),Q.appliedAttrs.push("cell width -> table columns"));for(const dt of Q.handledRawNames){const ht=f.find(Tt=>Tt.canonicalName===dt),vt=Q.issuesByRawName.get(dt)??[];y(ht?.rawName??dt,K,vt.length?vt.join("; "):void 0),x.add(dt)}for(const dt of Q.appliedAttrs)S.add(dt),k.add(K);w.push(...Q.exactMappings),A.push(...Q.approximateMappings),P.push(...Q.ignoredAttrs),T.push(...Q.unsupportedImageSpacing),p.push(...Q.errors);const ut=Wi(h,J,!1);A.push(...Ji(ut));const yt=ut.some(({rawName:dt,value:ht})=>["liststyletype","list-style-type"].includes(dt.toLowerCase())&&typeof ht=="string"&&ht.toLowerCase()==="none"),Lt=[];for(const{rawName:dt,entry:ht,value:vt}of ut){if(yt&&J.nodeName==="list"&&ht.kind!=="textMark"&&ht.nodeNames.includes("paragraph")&&!ht.nodeNames.includes("list-item")){Lt.push({rawName:dt,entry:ht,value:vt});continue}if(!Q.handledRawNames.has(me(dt)))try{if(ht.attr==="variant"&&typeof vt=="string"&&vt.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(dt.trim().toLowerCase())){if(J.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');q=!0;continue}if(ht.kind==="textMark"){const Tt=Di(dt,ht.attr,vt);kd({toolName:"style_blocks",yBlock:J,attribute:ht.attr,operation:Tt===null?"remove":"set",value:Tt,config:ht,anchors:o,independentlySelectedTargets:v}),k.add(K),S.add(`${dt} -> ${ht.attr}`),y(dt,K);continue}vd({toolName:"style_blocks",yBlock:J,attribute:ht.attr,operation:vt===null?"remove":"set",value:vt,config:{nodeNames:ht.nodeNames,valueType:ht.valueType,integer:ht.integer,min:ht.min,max:ht.max,enumValues:ht.enumValues},anchors:o,independentlySelectedTargets:v}),k.add(K),S.add(`${dt} -> ${ht.attr}`),y(dt,K)}catch(Tt){y(dt,K,Tt instanceof Error?Tt.message:String(Tt)),p.push(`${K}.${ht.attr}: ${Tt instanceof Error?Tt.message:String(Tt)}`)}}if(q){const dt=Hd(J,o);if(dt){for(const{rawName:ht,entry:vt,value:Tt}of Lt)if(vt.kind!=="textMark")try{for(const ce of dt)oo({toolName:"style_blocks",yBlock:ce,attribute:vt.attr,operation:Tt===null?"remove":"set",value:Tt,config:vt,anchors:o});S.add(`${ht} -> ${vt.attr}`),y(ht,K)}catch(ce){const Sn=ce instanceof Error?ce.message:String(ce);y(ht,K,Sn),p.push(`${K}.${vt.attr}: ${Sn}`)}k.add(K),S.add("listStyleType -> plain paragraphs"),y("listStyleType",K)}else p.push(`${K}.variant: could not convert the list to plain paragraphs.`)}}for(const{yBlock:J,ranges:K}of d){const q=Bt(J),Q=Wi(h,J,!0);A.push(...Ji(Q));for(const{rawName:ut,entry:yt,value:Lt}of Q){if(yt.kind!=="textMark"){const dt="Block attributes cannot apply to an inline range; select its block instead.";y(ut,q,dt),p.push(`${q}.${yt.attr}: ${dt}`);continue}try{const dt=Di(ut,yt.attr,Lt);Sd({toolName:"style_blocks",yBlock:J,ranges:K,attribute:yt.attr,operation:dt===null?"remove":"set",value:dt,config:yt,anchors:o}),k.add(q),S.add(`${ut} -> ${yt.attr}`),y(ut,q)}catch(dt){y(ut,q,dt instanceof Error?dt.message:String(dt)),p.push(`${q}.${yt.attr}: ${dt instanceof Error?dt.message:String(dt)}`)}}}for(const J of h.unsupportedAttrs??[]){const K=m.get(me(J)),q=new Set([...K?.skipped.values()??[]].map(Q=>Q.blockId));for(const Q of B)!K?.applied.has(Q)&&!q.has(Q)&&y(J,Q,"Unsupported attribute for this target.")}const F=Kt(s),X=J=>{const K=new Map,q=Q=>{"id"in Q&&Q.id&&K.set(Q.id,Q),"children"in Q&&Q.children.forEach(ut=>q(ut))};return R(J).forEach(q),K},C=X(E),j=X(F),U=J=>Pt(C.get(J)??null)!==Pt(j.get(J)??null),z=[...new Set([...B,...o.slice(b).map(J=>J.paragraphId).filter(J=>!!J)])].filter(U),tt=[...B].filter(J=>U(J)||D.has(J)),_=[...m.values()].map(J=>({name:J.name,appliedBlockIds:[...J.applied],skipped:[...J.skipped.values()]})),V=_.every(J=>J.skipped.length===0)&&S.size>0&&p.length===0&&g.length===0&&u.length===0&&P.length===0&&T.length===0&&(h.unsupportedAttrs??[]).every(J=>x.has(me(J))),nt={outcome:V?tt.length?"complete":"unchanged":"partial",targetBlockIds:[...B],changedBlockIds:tt,affectedBlockIds:z,attributes:_};if(wt(t,{styleEffects:nt}),V&&$===O(F)&&wt(t,{verifiedUnchanged:!0}),o.length===b&&!Rt(t)?.verifiedUnchanged){if(T.length||P.length)throw new St("attribute_unsupported","These image layout attributes cannot be represented. Use width/height or align for image sizing/placement, and document blockGap or surrounding paragraph spacing for separation.","validation");if(h.length===0){const J=h.unsupportedAttrs??[];throw new Error(J.length>0?`style_blocks has no supported attrs. Unsupported attrs: ${J.join(", ")}.`:"style_blocks requires at least one attr.")}throw new Error(`style_blocks could not apply to any target. ${p.length>0?`Skipped target attrs: ${p.join("; ")}`:"No matching supported attributes."}`)}cr.set(t,Ud({styleEffects:nt,matchedTargetCount:c.length+d.reduce((J,K)=>J+K.ranges.length,0),inlineRangeCount:d.reduce((J,K)=>J+K.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(J=>!x.has(me(J))),unmatchedSelectors:g,invalidSelectorErrors:u,skippedTargetErrors:p,exactCompatibilityMappings:w,approximateCompatibilityMappings:A,ignoredCompatibilityAttrs:P,unsupportedImageSpacing:T}));break}case"set_block_attribute":{const{id:a,attribute:l,operation:c,value:d}=t.arguments,g=Li("set_block_attribute",a),u=()=>{const b=Kt(s);return g.map(k=>W(b,k))},f=JSON.stringify(u());if(typeof l!="string"||l.trim().length===0)throw new Error("set_block_attribute requires a non-empty attribute name.");const h=l.trim();if(h==="id")throw new Error("set_block_attribute cannot modify the reserved 'id' attribute.");const p=bd(c),m=[],y=(b,k)=>{if(g.length<=1)throw new Error(k);return m.push(`${b}: ${k}`),!0};for(const b of g){const k=ot(s,b);if(!k){y(b,`Target block '${b}' not found in the document. Please only reference IDs you see inside <document_content>.`);continue}const{yBlock:S}=k,v=bt(S);if(h==="fontFamily"){const w=no(S);if(w){y(b,w);continue}}if(hd.has(h)){if(!v||S.nodeName!=="paragraph"&&S.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}let w;if(p==="remove")w=!1;else if(p==="toggle")w=!Ni(S,v,h);else if(d===void 0)w=!0;else if(typeof d=="boolean")w=d;else throw new Error(`set_block_attribute "${h}" expects a boolean value when operation is "set".`);if(v.length>0)at(v,0,v.length,{[h]:w?!0:null}),ne(o,b,v);else{pd(S,h,w);const A=`Text mark "${h}" ${w?"enabled":"removed"}.`;o.push({kind:"replace",paragraphId:b,text:A,oldText:A})}continue}if(h in Mi){if(!v||S.nodeName!=="paragraph"&&S.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}if(p==="toggle")throw new Error(`set_block_attribute "${h}" does not support toggle. Use operation "set" with a numeric value or "remove".`);const w=Mi[h],A=p==="remove"?null:md(h,d,w);if(v.length>0)at(v,0,v.length,{[h]:A===null?null:A}),ne(o,b,v);else{ur(S,h,A);const P=`Text mark "${h}" ${A===null?"removed":"set"}.`;o.push({kind:"replace",paragraphId:b,text:P,oldText:P})}continue}if(h==="indentLevel"&&S.nodeName==="paragraph"){Ri(S,p,d),v&&ne(o,b,v);continue}const x=Ei[h];if(!x){const w=Object.keys(Ei).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${w}.`)}if(!x.nodeNames.includes(S.nodeName)){y(b,`set_block_attribute "${h}" is not valid for ${S.nodeName} blocks.`);continue}if(p==="remove")et(S,h);else if(p==="toggle"){if(x.valueType!=="boolean")throw new Error(`set_block_attribute "${h}" only supports toggle for boolean attributes.`);const w=Fi(rt(S,h));S.setAttribute(h,String(!w))}else{if(d===void 0)throw new Error(`set_block_attribute "${h}" requires "value" when operation is "set".`);const w=Oi(h,d,x);S.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?fr(S,h,Number(w)):S.setAttribute(h,w)}if(v)ne(o,b,v);else{const w=`Updated ${h} on ${S.nodeName} block.`;o.push({kind:"replace",paragraphId:b,text:w,oldText:w})}}if(o.length===0&&m.length>0)throw new Error(`set_block_attribute could not apply to any target. Skipped targets: ${m.join("; ")}`);m.length===0&&f===JSON.stringify(u())&&wt(t,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=t.arguments,l=Li("clear_formatting",a),c=()=>{const g=Kt(s);return l.map(u=>W(g,u))},d=JSON.stringify(c());for(const g of l){const u=ot(s,g);if(!u)throw new Error(`Target block '${g}' not found in the document. Please only reference IDs you see inside <document_content>.`);const f=[];if(u.yBlock.nodeName==="list"){for(let h=0;h<u.yBlock.length;h++){const p=u.yBlock.get(h);if(p instanceof I.XmlElement&&p.nodeName==="list-item"){const m=p.getAttribute("id")||g;f.push({id:m,yBlock:p})}}if(f.length===0){const h=`Cleared formatting on list block ${g}.`;o.push({kind:"replace",paragraphId:g,text:h,oldText:h});continue}}else f.push({id:g,yBlock:u.yBlock});for(const h of f){if(h.yBlock.nodeName!=="paragraph"&&h.yBlock.nodeName!=="list-item")throw new Error("clear_formatting only supports paragraph, list, or list-item blocks.");const p=bt(h.yBlock);if(!p)throw new Error("clear_formatting only supports paragraph, list, or list-item text blocks.");if(h.yBlock.nodeName==="paragraph")for(const m of $s)et(h.yBlock,m);if(zd(h.yBlock),p.length>0){let m=0;for(const y of st(p)){const b=typeof y.insert=="string"?y.insert.length:1,k={...js};typeof y.attributes?.footnoteRef=="string"&&y.attributes.footnoteRef.length>0&&delete k.superscript,at(p,m,b,k),m+=b}ne(o,h.id,p)}else{const m="Formatting cleared.";o.push({kind:"replace",paragraphId:h.id,text:m,oldText:m})}}}d===JSON.stringify(c())&&wt(t,{verifiedUnchanged:!0});break}case"remove_block":{const{id:a,count:l=1}=t.arguments,c=ot(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const{yParent:d,index:g}=c;Le(d)&&Fe();const u=We(s),f=d===u;for(let h=0;h<l;h++){const p=g;if(p>=d.length)break;const m=d.get(p);if(!(m instanceof I.XmlElement))break;const y=m.getAttribute("id"),b=m.nodeName;if(f&&d.length===1){if(b==="paragraph"){const k=bt(m);if(k&&k.length>0){const S=st(k);let v="";for(const x of S)x.insert&&typeof x.insert=="string"&&(v+=x.insert);o.push({kind:"delete",paragraphId:y,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,v.length,0)),text:v}),k.delete(0,k.length)}}else{o.push({kind:"delete",paragraphId:y,text:b==="list"?"List removed":"Block removed"});const k=new I.XmlElement("paragraph");k.setAttribute("id",y);const S=new I.XmlText;k.insert(0,[S]),d.delete(p,1),d.insert(p,[k])}break}if(b==="list")o.push({kind:"delete",paragraphId:y,text:"List removed"});else{const k=bt(m);if(k){const S=st(k);let v="";for(const x of S)x.insert&&typeof x.insert=="string"&&(v+=x.insert);o.push({kind:"delete",paragraphId:y,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,v.length,0)),text:v})}else o.push({kind:"delete",paragraphId:y,text:"Block removed"})}d.delete(p,1)}break}case"append_to_paragraph":{const{id:a,content:l}=t.arguments,c=Z(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const d=bt(c);d||lr(c);const g=d.length,u=de(g>0?go(d,g-1,1):ye(c.getAttribute("_emptyTextMarks"))),f=it.fromAgentHtml(l);if(f.children.length>0){const h=[];for(const y of f.children)y.type==="paragraph"&&y.children.forEach(b=>{b.type==="text"&&h.push(b)});let p=g,m="";for(const y of h)if(y.text){const b=oe(d,p,y.text,{...u||{},...y.marks||{}});m+=y.text,p=b}m&&o.push({kind:"insert",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,g,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,p,0)),text:m})}break}case"break_paragraph":{const{id:a,substring:l}=t.arguments,c=typeof l=="string"?l:String(l??"");if(c.trim().length===0)throw new Error("break_paragraph requires a non-empty substring to split on.");const d=n?.document??mt(s),g=W(d,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);if(g.type!=="paragraph")throw new Error(`break_paragraph only works on paragraphs. Block '${a}' is type '${g.type}'.`);const u=Mc(g,c);if(u.length===0){const j=g.children.filter(z=>z.type==="text").map(z=>z.text).join(""),U=Os(j.length>100?j.slice(0,100)+"...":j);throw new Error(`No match found for "${c}" in block '${a}'. The block contains: "${U}".`)}const f=u[0].offset,h=ot(s,a);if(!h)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:p,yParent:m,index:y}=h;if(Le(m)&&Fe(),!(p instanceof I.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const b=bt(p);if(!b)throw new Error(`break_paragraph only works on text paragraphs. Block '${a}' has no text content.`);const{beforeOps:k,afterOps:S,formatAtSplit:v,originalText:x,beforeText:w,afterText:A}=sg(b,f);b.delete(0,b.length);let P=0;for(const j of k)lt(b,P,j.insert,j.attributes??{}),P+=j.insert.length;const T=G(),E=new I.XmlElement("paragraph");E.setAttribute("id",T);const B=p.getAttribute("heading");B&&E.setAttribute("heading",B);const N=rt(p,"align");N&&E.setAttribute("align",N);const R=rt(p,"lineSpacing");R!=null&&E.setAttribute("lineSpacing",R);const M=rt(p,"pagination");M!=null&&E.setAttribute("pagination",M);const O=p.getAttribute("styleId");O!=null&&E.setAttribute("styleId",O);const $=rt(p,"direction");$!=null&&E.setAttribute("direction",$);const L=rt(p,"borders");L!=null&&E.setAttribute("borders",L);const D=rt(p,"shading");D!=null&&E.setAttribute("shading",D);const H=rt(p,"tabStops");H!=null&&E.setAttribute("tabStops",H);const F=p.getAttribute("oxmlPPr");F!=null&&E.setAttribute("oxmlPPr",F);const X=new I.XmlText;let C=0;for(const j of S)X.insert(C,j.insert,j.attributes??{}),C+=j.insert.length;if(S.length===0){const j=ye(p.getAttribute("_emptyTextMarks")),U=de({...j,...v??{}});U&&Object.keys(U).length>0&&E.setAttribute("_emptyTextMarks",JSON.stringify(U))}E.insert(0,[X]),m.insert(y+1,[E]),w!==x&&o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(b,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(b,P,0)),text:w,oldText:x}),o.push({kind:"insert",paragraphId:T,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(X,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(X,C,0)),text:A||"Paragraph split"});break}case"join_paragraphs":{const{firstId:a,secondId:l,separator:c}=t.arguments;if(!a||!l||a===l)throw new Error("join_paragraphs requires two different paragraph IDs: firstId and secondId.");const d=ot(s,a),g=ot(s,l);if(!d)throw new Error(`Target block '${a}' not found in the document.`);if(!g)throw new Error(`Target block '${l}' not found in the document.`);if((Le(d.yParent)||Le(g.yParent))&&Fe(),d.yBlock.nodeName!=="paragraph"||g.yBlock.nodeName!=="paragraph")throw new Error("join_paragraphs only works on two paragraph blocks.");if(d.yParent!==g.yParent||g.index!==d.index+1)throw new Error(`join_paragraphs requires adjacent sibling paragraphs with secondId immediately after firstId. '${l}' does not immediately follow '${a}'.`);const u=bt(d.yBlock),f=bt(g.yBlock);if(!u||!f)throw new Error("join_paragraphs only works on text paragraph blocks.");const h=u.toString(),p=f.toString(),m=c!==void 0?String(c):/\S/.test(h)&&/\S/.test(p)?" ":"",y=h.match(/\s+$/)?.[0].length??0,b=p.match(/^\s+/)?.[0].length??0,k=m.length>0,S=k?h.slice(0,h.length-y):h,v=k?p.slice(b):p;k&&y>0&&u.delete(u.length-y,y);const x=st(u),w=st(f),A=x.length>0?x[x.length-1].attributes??{}:{},P=w.length>0?w[0].attributes??{}:{};let T=u.length;m.length>0&&(lt(u,T,m,Object.keys(A).length>0?A:P),T+=m.length);let E=k?b:0;for(const N of w){if(typeof N.insert!="string"||N.insert.length===0)continue;const R=N.insert.slice(E);E=Math.max(0,E-N.insert.length),R.length!==0&&(lt(u,T,R,N.attributes??{}),T+=R.length)}const B=`${S}${m}${v}`;o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,u.length,0)),text:B||"Paragraphs joined",oldText:h}),o.push({kind:"delete",paragraphId:l,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,f.length,0)),text:p||"Empty paragraph removed"}),g.yParent.delete(g.index,1);break}case"insert_table_row":{const a=mt(s),l=it.createParsingContext(a),{tableId:c,referenceIndex:d,referenceRowId:g,position:u,content:f}=t.arguments,h=W(a,c);if(h?.type!=="table")throw new Error(`Table ${c} not found`);let p=d;if(g!==void 0){if(p=h.children.findIndex(k=>k.id===g),p<0)throw new Error(`Row ${g} not found in table ${c}. Read the table and use a current row ID.`);if(d!==void 0&&d!==p)throw new Error(`Row ${g} is at index ${p}, not ${d}. Use referenceRowId alone or reread the table.`)}if(p===void 0||!Number.isInteger(p)||p<0||p>=h.children.length)throw new Error("Invalid reference row index. Supply a current referenceRowId or a valid 0-based referenceIndex.");const m=h.children[p],y=f?.map(k=>{if(k==="")return;const S=it.fromAgentHtml(k,{existingDocument:a,parsingContext:l});return S.children.length>0?S.children:void 0}),b=sd(s,c,u,p,y);if(!b.success)throw new Error(b.error||"Failed to insert table row");o.push({kind:"insert",paragraphId:c,text:`Row inserted ${u} row ${m.id} (reference index ${p}; new row index ${p+(u==="after"?1:0)})`});break}case"remove_table_row":{const a=t.arguments,l=String(a.tableId??""),c=W(mt(s),l);if(c?.type!=="table"||c.id!==l)throw new Error(`Table ${l} not found`);const d=xi(c,a);if("error"in d)throw new Error(d.error);const{rowIndices:g,rowIds:u}=d,f=nd(s,l,g);if(!f.success)throw new Error(f.error||"Failed to remove table rows");g.forEach((h,p)=>o.push({kind:"delete",paragraphId:l,text:`Row ${u[p]} (index ${h}) removed`}));break}case"insert_table_column":{const a=mt(s),l=it.createParsingContext(a),{tableId:c,referenceIndex:d,position:g,content:u}=t.arguments,f=u?.map(p=>{if(p==="")return;const m=it.fromAgentHtml(p,{existingDocument:a,parsingContext:l});return m.children.length>0?m.children:void 0}),h=od(s,c,g,d,f);if(!h.success)throw new Error(h.error||"Failed to insert table column");o.push({kind:"insert",paragraphId:c,text:`Column inserted ${g} column ${d}`});break}case"remove_table_column":{const{tableId:a,columnIndex:l}=t.arguments,c=td(s,a,l);if(!c.success)throw new Error(c.error||"Failed to remove table column");o.push({kind:"delete",paragraphId:a,text:`Column ${l} removed`});break}}return n?.refreshDocumentIncrementally&&(n.document=Kt(s)),o}function ye(s){if(!s)return{};try{const t=JSON.parse(s);if(t&&typeof t=="object")return t}catch{}return{}}function sg(s,t){const e=[],n=[];let o={},r="",i="",a="",l=0;const c=st(s);for(const d of c){if(!d.insert||typeof d.insert!="string")continue;const g=d.insert,u=d.attributes||{},f=l+g.length;if(r+=g,f<=t)e.push({insert:g,attributes:u}),i+=g,f===t&&(o=u);else if(l>=t)n.push({insert:g,attributes:u}),a+=g;else{const h=t-l,p=g.slice(0,h),m=g.slice(h);p.length>0&&(e.push({insert:p,attributes:u}),i+=p),m.length>0&&(n.push({insert:m,attributes:u}),a+=m),o=u}l=f}return{beforeOps:e,afterOps:n,formatAtSplit:o,originalText:r,beforeText:i,afterText:a}}function go(s,t,e){const n=t+e;let o=0,r=null;for(const i of st(s)){if(typeof i.insert!="string")continue;const a=o+i.insert.length;if(a>t&&o<n){const l=i.attributes||{},c={};for(const d of ps){const g=l[d];g!=null&&g!==!1&&(c[d]=g)}if(r===null)r=c;else for(const d of Object.keys(r))r[d]!==c[d]&&delete r[d]}if(o=a,o>=n)break}return r??{}}function vr(s){const t=new Set;if(!s.includes("<")||!s.includes(">"))return t;try{const e=it.fromAgentHtml(s),n=o=>{if(o.type==="text"){for(const r of xn)o.marks?.[r]!==void 0&&t.add(r);return}if("children"in o&&Array.isArray(o.children))for(const r of o.children)n(r)};for(const o of e.children)n(o)}catch{}return t}function na(s,t,e,n,o){if(o.includes("<")&&o.includes(">")||vr(n).size>0)return!1;const r=go(s,t,e),i=si(o,r);return s.toString().slice(t,t+e)===i}function xr(s,t,e,n,o,r,i,a={}){if(!na(s,t,e,n,o))if(o.includes("<")&&o.includes(">")){const l={...a,...go(s,t,e)};for(const f of vr(n))delete l[f];const c=o.trim(),d=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(c)?c:`<p>${o}</p>`,g=it.fromAgentHtml(d,{preserveExplicitMarkResets:!0}),u=g.children.length>0?g.children[0]:null;if(u&&u.type==="paragraph"&&u.children.length>0){s.delete(t,e);const f=[];for(const b of u.children)if(b.type==="text"){const k=b,S={...l,...k.marks||{}};f.push({text:k.text,marks:S})}const h=s.doc;let p=t;const m=[];for(const b of f){const k=m[m.length-1],S=JSON.stringify(b.marks||{}),v=k?JSON.stringify(k.marks||{}):null;k&&S===v?k.text+=b.text:m.push({text:b.text,marks:b.marks||{}})}const y=m.map(b=>b.text).join("");h.transact(()=>{lt(s,t,y);let b=t;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&at(s,b,k.text.length,k.marks),b+=k.text.length;p=t+y.length},"performReplacement"),Vi(s,t,p),i.push({kind:"replace",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,p,0)),text:o.replace(/<[^>]*>/g,""),oldText:n.replace(/<[^>]*>/g,"")})}}else{const l={...a,...go(s,t,e)},c=si(o,l);for(const d of vr(n))delete l[d];s.delete(t,e),c.length>0&&lt(s,t,c,l),Vi(s,t,t+c.length),i.push({kind:"replace",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t+c.length,0)),text:c,oldText:n.replace(/<[^>]*>/g,"")})}}function ig(s,t,e,n,o={}){if(!t.length)return{anchorsByAction:[],failures:[],alreadySatisfied:!1};const r=t.every(h=>h.name==="insert_block"),i=r?n:o.canonicalDocument?.()??n;r||Rn(s,i);let a;const l={document:r?{...n,children:[...n.children]}:i,get htmlParsingContext(){return a??(a=it.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!r},c=[],d=[],g=new Set,u=[],f=(h,p,m,y)=>{const b=Rt(h);d.push({actionIndex:p,actionName:h.name,error:m,failure:y,sourceEditIndex:b?.sourceEditIndex,sourceEditType:b?.sourceEditType})};for(let h=0;h<t.length;h++){const p=t[h];try{const m=()=>Wt(s,p,`${e}_${h}`,!o.skipContextForFirstAction||r||h>0?l:void 0),y=o.measure?o.measure(m):m();o.skipContextForFirstAction&&!r&&h===0&&t.length>1&&(l.document=Kt(s)),c.push(y);const b=Rt(p);if(y.length&&b?.splitReplacementGroup&&g.add(b.splitReplacementGroup),!y.length&&o.rejectUnchangedAction&&!b?.verifiedUnchanged)if(wc(p)&&b?.splitReplacementGroup)u.push({action:p,index:h,group:b.splitReplacementGroup});else{f(p,h,dr(p)??`${JSON.stringify(p.arguments)} - no change made`);break}}catch(m){if(o.throwOnError)throw m;if(f(p,h,String(m),Be(m)),!o.continueAfterError)break}}for(const{action:h,index:p,group:m}of u)g.has(m)||f(h,p,"Split replacement made no verified change");return{anchorsByAction:c,failures:d,alreadySatisfied:d.length===0&&t.every(h=>Rt(h)?.verifiedUnchanged)}}const wr=()=>{},ag={count:wr,gauge:wr,distribution:wr},oa=new WeakSet;function Ar(s,t){try{ag.count("frontend.editor.yjs_observer_failure",1,{event:t})}catch{}console.error(`Yjs ${t} observer failed`,s)}function ra(s,t=Ar){if(oa.has(s))return;oa.add(s);const e=s.emit;let n=Number.NEGATIVE_INFINITY;s.emit=function(o,r){if(!["update","updateV2","afterTransactionCleanup"].includes(o))return e.call(this,o,r);const i=Array.from(this._observers.get(o)??[]);for(const a of i)try{a(...r)}catch(l){const c=Date.now();if(c-n>=3e4){n=c;try{t(l,o)}catch{}}}}}const sa="suggestion-id-repair";function lg(s){if(s.deleteSet.clients.size>0)return!0;for(const[t,e]of s.afterState){const n=s.beforeState.get(t)??0;if(n===e)continue;const o=s.doc.store.clients.get(t);for(let r=I.findIndexSS(o,n);r<o.length&&o[r].id.clock<e;r++){const i=o[r];if(i instanceof I.Item&&i.content instanceof I.ContentFormat&&["insertion","deletion","suggestionId","proposalId"].includes(i.content.key))return!0}}return!1}function cg(s,t,e="recover"){const n=new Set(["content","chrome","notes"].filter(l=>s.share.has(l)).map(l=>s.getXmlFragment(l))),o=new Set,r=l=>{l._item?.deleted||(l instanceof I.XmlText?o.add(l):l instanceof I.XmlFragment&&l.toArray().forEach(r))};if(t){const l=lg(t);for(const[c,d]of t.changed)c instanceof I.XmlText?l&&o.add(c):c instanceof I.XmlFragment&&(d.has("structuralSuggestionId")||d.has("suggestionId"))&&r(c);vl(t,c=>{c.deleted||c.content instanceof I.ContentType&&r(c.content.type)})}else n.forEach(r);const i=l=>typeof l=="string"&&l.trim().length>0,a=[];for(const l of o){if(l._item?.deleted)continue;let c=l,d=!1;for(;c.parent;){c=c.parent;const h=c;if(h instanceof I.XmlElement&&["structuralSuggestionId","suggestionId","proposalId"].some(p=>i(h.getAttribute(p)))){d=!0;break}}if(d||!n.has(c))continue;let g=0,u,f;for(const h of st(l)){const p=typeof h.insert=="string"?h.insert.length:1,m=h.attributes??{};if(typeof h.insert!="string"||p===0||!(m.insertion||m.deletion)||i(m.suggestionId)||i(m.proposalId)){u=void 0,f=void 0,g+=p;continue}const y=JSON.stringify(Object.entries(m).filter(([b])=>b==="insertion"||b==="deletion"||b==="layeredInsertion"||b.startsWith("suggestion")).sort(([b],[k])=>b.localeCompare(k)));if(f&&u===y)f.length+=p;else{const b=I.createRelativePositionFromTypeIndex(l,g).item;if(!b){g+=p;continue}f={text:l,start:g,length:p,id:`recovered-inline-${b.client.toString(36)}-${b.clock.toString(36)}`},u=y,a.push(f)}g+=p}}return a.length&&s.transact(()=>{for(const l of a)at(l.text,l.start,l.length,e==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:l.id})},sa),a.length}function uo(s,t){if(Array.isArray(s))return s.map(o=>uo(o,t));if(!s||typeof s!="object")return s;const e={};for(const[o,r]of Object.entries(s))if(!(t.regenerateIds&&o==="id")){if(t.regenerateIds&&o==="marks"&&r&&typeof r=="object"&&!Array.isArray(r)&&"comment"in r){const{comment:i,...a}=r;Object.keys(a).length>0&&(e[o]=uo(a,t));continue}e[o]=uo(r,t)}const n=e.type;return t.regenerateIds&&typeof n=="string"&&n!=="doc"&&n!=="text"&&(e.id=G()),e}function dg(s){return s.map(t=>uo(t,{regenerateIds:!0}))}const gg=["borders","align","styleId","direction","_emptyTextMarks"],ug=["id","heading","oxmlAttrs",...wl],hg=["pagination"],fg=[...xl("paragraph"),...hg].filter(s=>!gg.includes(s)&&!ug.includes(s));function ia(s,t){for(const e of fg){const n=rt(s,e);n!=null&&t.setAttribute(e,n)}}const ho=new Set(["aiGenerated","insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove","proposalId","toolCallId","toolType","diffSegmentIndex","__htmlClassName"]),pg=["insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove"];function aa(s,t){if(!s)return[];const e=!!s.footnoteRef,n=[];for(const[o,r]of Object.entries(s))r===void 0||r===!1||r===null||ho.has(o)||o==="link"&&t.excludeLink||o==="comment"&&t.excludeComment||o!=="footnoteRef"&&(o==="superscript"&&e||n.push([o,r]));return n}function Tr(s){const{explicitMarks:t,inheritedMarks:e,emptyParagraphMarks:n,exitingLink:o=!1,exitingComment:r=!1,noteBodyFontSize:i,suggestionMarks:a}=s,l={},c=[],d=f=>{c.includes(f)||c.push(f)},g=f=>l[f]!==void 0,u=f=>c.includes(f);if(t){for(const[f,h]of Object.entries(t))h===!1?d(f):h!=null&&(l[f]=h);l.footnoteRef&&(delete l.footnoteRef,e?.footnoteRef&&delete l.superscript)}for(const[f,h]of aa(e,{excludeLink:o,excludeComment:r}))!g(f)&&!u(f)&&(l[f]=h);e?.footnoteRef&&!l.footnoteRef&&(d("footnoteRef"),l.superscript||d("superscript"));for(const[f,h]of aa(n,{excludeLink:o,excludeComment:r}))!g(f)&&!u(f)&&(l[f]=h);if(i!=null&&l.fontSize===void 0&&!u("fontSize")&&(l.fontSize=i),o&&!l.link&&d("link"),r&&!l.comment&&d("comment"),a)Object.assign(l,a);else if(e){const f=e;for(const h of pg)f[h]!==void 0&&f[h]!==null&&d(h)}return{marksToApply:l,marksToRemove:c}}function la(s,t,e,n){if(lt(s,t,e),Object.keys(n.marksToApply).length>0&&at(s,t,e.length,n.marksToApply),n.marksToRemove.length>0){const o={};for(const r of n.marksToRemove)o[r]=null;at(s,t,e.length,o)}}function Cr(s,t,e){const n=vs(t,e,Qt(s.getDocument().children));s.transact(()=>{const o=s.getYChromeFragment();Pr(o,i=>i.getAttribute("sectionIndex")===void 0);for(const i of n)o.push([s.blockToYjsElement(i)]);const r=s.ydoc.getMap("metadata");r.delete("headers"),r.delete("footers")})}function ca(s){return hs(s.getDocument().chrome??[])}function Pr(s,t){for(let e=s.length-1;e>=0;e--){const n=s.get(e);n instanceof I.XmlElement&&t(n)&&s.delete(e,1)}}function mg(s,t,e,n){const o=Qt(s.getDocument().children),r=vs(e,n,o).map(i=>({...i,sectionIndex:t}));s.transact(()=>{const i=s.getYChromeFragment();Pr(i,a=>a.getAttribute("sectionIndex")===String(t));for(const a of r)i.push([s.blockToYjsElement(a)])})}function bg(s,t){return Tl(s.getDocument().chrome??[],t)}function Mr(s,t,e,n){const o=(s.getDocument().chrome??[]).find(i=>i.type==="header-footer"&&i.side===t&&i.slot===e&&i.sectionIndex===n);if(o)return o;const r=xs(t,e,void 0,Qt(s.getDocument().children),n);return s.transact(()=>{s.getYChromeFragment().push([s.blockToYjsElement(r)])}),r}function yg(s){const t=s.getYContentFragment(),e=[];for(const r of t.toArray())r instanceof I.XmlElement&&r.nodeName==="header-footer"&&e.push(r);const n=s.getYChromeFragment();if(e.length===0&&n.length<=3){da(s);return}const o=s.getYChromeFragment();s.transact(()=>{for(const i of e){const a=s.getDocument().children.find(l=>l.type==="header-footer"&&l.id===i.getAttribute("id"));a&&o.push([s.blockToYjsElement(a)])}const r=t.toArray();for(let i=r.length-1;i>=0;i--){const a=r[i];a instanceof I.XmlElement&&a.nodeName==="header-footer"&&t.delete(i,1)}}),da(s)}function da(s){const t=s.getYChromeFragment(),e=new Map,n=[],o=t.toArray(),r=s.getDocument().chrome??[],i=a=>{const l=r.find(c=>c.id===a);return!!(l&&As(l))};o.forEach((a,l)=>{if(!(a instanceof I.XmlElement)||a.nodeName!=="header-footer")return;const c=`${a.getAttribute("side")}:${a.getAttribute("slot")}:${a.getAttribute("sectionIndex")??""}`,d=e.get(c);if(d===void 0){e.set(c,l);return}const g=o[d];!i(g.getAttribute("id"))&&i(a.getAttribute("id"))?(n.push(d),e.set(c,l)):n.push(l)}),n.length!==0&&s.transact(()=>{for(const a of n.sort((l,c)=>c-l))t.delete(a,1)})}function kg(s){const t=s.ydoc.getMap("metadata"),e=t.get("headers"),n=t.get("footers");!e&&!n||((s.getDocument().chrome?.length??0)>0?s.transact(()=>{t.delete("headers"),t.delete("footers")}):Cr(s,e,n))}function Sg(s,t,e="bottom-right"){const n=(s.getDocument().chrome??[]).filter(c=>c.type==="header-footer"&&c.slot==="default"&&c.sectionIndex===void 0),o=c=>{const d=Pl(c);return!d||d.children.every(g=>g.type==="text"&&(g.marks?.field==="page"||g.text.trim()===""))},r=new Set(n.filter(o).map(c=>c.side)),i=t?ws(e):void 0,a=i?.side==="headers"?"header":"footer",l=!!i&&!n.some(c=>c.side===a&&!o(c));!r.size&&!l||s.transact(()=>{const c=s.getYChromeFragment();Pr(c,d=>d.nodeName==="header-footer"&&d.getAttribute("slot")==="default"&&Br(d)===void 0&&r.has(d.getAttribute("side"))),i&&l&&c.push([s.blockToYjsElement(xs(a,"default",Cl([i.paragraph]),Qt(s.getDocument().children)))])})}function Ig(s){const t=s.ydoc.getMap("metadata");if(t.get(Gt.showPageNumbers)!==!0)return;const e=t.get(Gt.pageNumberPosition)??"bottom-right",{headers:n={},footers:o={}}=ca(s),r=ws(e),i=r.side==="headers"?n:o;if(s.transact(()=>{t.set(Gt.showPageNumbers,!1)}),!i.default){const a={...i,default:[r.paragraph]};Cr(s,r.side==="headers"?a:n,r.side==="footers"?a:o)}}function vg(s,t){const e=t?{fontFamily:t}:{},n=[];for(const o of s.split(/(\{PAGE\}|\{PAGES\})/))o&&(o==="{PAGE}"?n.push({type:"text",text:"1",marks:{field:"page",...e}}):o==="{PAGES}"?n.push({type:"text",text:"1",marks:{field:"numPages",...e}}):n.push({type:"text",text:o,...t?{marks:{...e}}:{}}));return n.length===0&&n.push({type:"text",text:"",...t?{marks:{...e}}:{}}),n}function xg(s){return s.toArray().every(t=>t instanceof I.XmlText?t.length===0:t instanceof I.XmlElement?t.toArray().every(e=>e instanceof I.XmlText?e.toDelta().every(n=>typeof n.insert=="string"&&n.insert.length===0):!1):!0)}function Br(s){const t=s.getAttribute("sectionIndex");if(t==null||t==="")return;const e=Number(t);return Number.isFinite(e)?e:void 0}function ga(s){return JSON.stringify((s.getDocument().chrome??[]).map(t=>t.type==="header-footer"?{side:t.side,slot:t.slot,sectionIndex:t.sectionIndex,children:t.children.map(e=>({align:e.align,children:e.children}))}:t.type))}function wg(s,t){const{side:e,sectionIndex:n}=t,o=s.getYChromeFragment();if(t.clear){const h=[];o.toArray().forEach((m,y)=>{m instanceof I.XmlElement&&m.nodeName==="header-footer"&&m.getAttribute("side")===e&&(t.slot===void 0||m.getAttribute("slot")===t.slot)&&(n===void 0||Br(m)===n)&&h.push(y)});const p=(t.slot!==void 0&&t.slot!=="default"||n!==void 0)&&o.toArray().some((m,y)=>m instanceof I.XmlElement&&m.nodeName==="header-footer"&&m.getAttribute("side")===e&&!h.includes(y));return p&&h.length>0&&h.every(m=>{const y=o.get(m);return y instanceof I.XmlElement&&xg(y)})?{changed:!1,removedCount:0}:h.length===0?p?(Mr(s,e,t.slot??"default",n),{changed:!0,removedCount:0,createdEmpty:!0}):{changed:!1,removedCount:0}:(s.transact(()=>{for(const m of h.reverse())o.delete(m,1)}),{changed:!0,removedCount:h.length})}const r=t.slot??"default",i=t.zones??{},a=[];if(typeof i.left=="string"&&a.push([0,i.left]),typeof i.center=="string"&&a.push([1,i.center]),typeof i.right=="string"&&a.push([2,i.right]),a.length===0)return{changed:!1,removedCount:0};const l=ga(s),c=()=>{for(const h of o.toArray())if(h instanceof I.XmlElement&&h.nodeName==="header-footer"&&h.getAttribute("side")===e&&h.getAttribute("slot")===r&&Br(h)===n)return h;return null},d=a.every(([,h])=>h==="");let g=!1;if(!c()&&d){if(!((r!=="default"||n!==void 0)&&o.toArray().some(h=>h instanceof I.XmlElement&&h.nodeName==="header-footer"&&h.getAttribute("side")===e)))return{changed:!1,removedCount:0};g=!0}Mr(s,e,r,n);const u=c();if(!u)return{changed:!1,removedCount:0};if(g)return{changed:!0,removedCount:0,createdEmpty:g};const f=Qt(s.getDocument().children);return s.transact(()=>{for(const[h,p]of a){const m=(s.getDocument().chrome??[]).find(k=>k.type==="header-footer"&&k.side===e&&k.slot===r&&k.sectionIndex===n)?.children[h],y=Al[h],b={type:"paragraph",id:m?.id??G(),children:vg(p,f),...m?.align??y?{align:m?.align??y}:{}};u.get(h)&&u.delete(h,1),u.insert(h,[s.blockToYjsElement(b)])}}),{changed:ga(s)!==l,removedCount:0}}function Ag(s,t,e){const n=e!==void 0?[e]:["default","first","even"];let o=0;return s.transact(()=>{for(const r of n){const i=Ss(s.ydoc,t,r);i.length!==0&&(o+=i.length,Is(s.ydoc,t,r,[]))}}),o}function Tg(s,t){const e=Ss(s.ydoc,t.side,t.slot);return JSON.stringify(e)===JSON.stringify([t])?!1:(s.transact(()=>{Is(s.ydoc,t.side,t.slot,[t])}),!0)}function se(s){return s.ydoc?s.ydoc.getMap("comments"):null}function Cg(s){const t=se(s);if(!t)return[];const e=[];return t.forEach(n=>{n&&typeof n=="object"&&e.push(n)}),e.sort((n,o)=>(n.createdAt??"").localeCompare(o.createdAt??"")),e}function ua(s){const t=s.getAttribute("structuralSuggestionKind")==="insert"?s.getAttribute("structuralSuggestionId"):s.getAttribute("diffState")==="insert"?s.getAttribute("suggestionId"):void 0;return typeof t=="string"?t:void 0}function Pg(s,t){if(!s.ydoc||t.length===0)return[];const e=new Set(t),n=[],o=(r,i)=>{for(const a of r.toArray()){if(a instanceof I.XmlElement){const g=ua(a);o(a,typeof g=="string"&&e.has(g)?g:i);continue}if(!(a instanceof I.XmlText)||!(r instanceof I.XmlElement))continue;const l=r.getAttribute("id");if(typeof l!="string")continue;let c=0,d=0;for(const g of st(a)){if(typeof g.insert!="string")continue;const u=g.insert.length,f=d+(g.attributes?.deletion?0:u),h=g.attributes?.suggestionId??i,p=!g.attributes?.suggestionId&&!!i;if(u>0&&typeof h=="string"&&e.has(h)){const m=n[n.length-1];m?.blockId===l&&m.suggestionId===h&&!!m.structural===p&&m.end===c?(m.end+=u,m.projectedEnd=f):n.push({blockId:l,suggestionId:h,start:c,end:c+u,projectedStart:d,projectedEnd:f,...p?{structural:!0}:{}})}c+=u,d=f}c===0&&i&&n.push({blockId:l,suggestionId:i,start:0,end:0,projectedStart:0,projectedEnd:0,structural:!0})}};return o(s.getYContentFragment()),o(s.ydoc.getXmlFragment("notes")),o(s.ydoc.getXmlFragment("chrome")),n}function Er(s,t,e,n){return{id:gt(),author:e?.author??"Anonymous",...e?.initials?{initials:e.initials}:{},...e?.authorId?{authorId:e.authorId}:{},...e?.authorImageUrl?{authorImageUrl:e.authorImageUrl}:{},...e?.authorType?{authorType:e.authorType}:{},...e?.agentName?{agentName:e.agentName}:{},...e?.agentModel?{agentModel:e.agentModel}:{},...e?.suggestionId?{suggestionId:e.suggestionId}:{},...e?.mentions?.length?{mentions:e.mentions}:{},...e?.citations?.length?{citations:e.citations.map(o=>({...o}))}:{},...e?.anchorBlockId?{anchorBlockId:e.anchorBlockId}:{},...e?.agentRequestId?{agentRequestId:e.agentRequestId}:{},...e?.agentConversationId?{agentConversationId:e.agentConversationId}:{},...e?.agentTriggerIds?.length?{agentTriggerIds:[...e.agentTriggerIds]}:{},...e?.relatedSuggestionIds?.length?{relatedSuggestionIds:[...e.relatedSuggestionIds]}:{},createdAt:new Date().toISOString(),bodyMd:t,...n?{parentId:n}:{}}}function ha(s,t,e,n){const o=se(s);if(!o||!Z(s.ydoc,t))return null;const r=Er(s,e,{...n,anchorBlockId:t});return s.transact(()=>{o.set(r.id,r)}),r.id}function Mg(s,t,e,n,o){const r=Z(s.ydoc,t),i=r?ct(r):null;if(!i||n<=e||e>=i.length)return!1;const a=Math.min(n,i.length),l=st(i);let c=0,d=!1;for(const g of l){if(typeof g.insert!="string")continue;const u=c,f=c+g.insert.length;c=f;const h=Math.max(u,e),p=Math.min(f,a);if(p<=h)continue;const m=g.attributes?.comment,y=m?m.split(","):[];y.includes(o)||y.push(o),at(i,h,p-h,{comment:y.join(",")}),d=!0}return d}function Bg(s,t,e,n,o,r){return Nr(s,[{blockId:t,start:e,end:n}],o,r)}function Nr(s,t,e,n){const o=se(s);if(!o||t.length===0)return null;const r=Er(s,e,n),i=r.id;let a=!1;return s.transact(()=>{for(const l of t)a=Mg(s,l.blockId,l.start,l.end,i)||a;a&&o.set(i,r)}),a?i:null}function Eg(s,t,e,n){const o=se(s);if(!o||!o.has(t))return null;const r=Er(s,e,n,t);return s.transact(()=>{o.set(r.id,r)}),r.id}function Ng(s,t,e){const n=se(s),o=n?.get(t);return!n||!o?!1:(s.transact(()=>{n.set(t,{...o,resolved:e})}),!0)}function Lg(s,t,e){const n=se(s);if(!n)return 0;const o=new Set(t);if(o.size===0)return 0;const r=[];return n.forEach(i=>{const a=i;if(!a||typeof a!="object"||a.parentId||a.resolved)return;const l=[];typeof a.suggestionId=="string"&&a.suggestionId.length>0&&l.push(a.suggestionId);for(const c of a.relatedSuggestionIds??[])l.includes(c)||l.push(c);l.length!==0&&l.some(c=>o.has(c))&&(l.some(c=>e(c))||r.push(a))}),r.length===0?0:(s.transact(()=>{for(const i of r)n.set(i.id,{...i,resolved:!0})}),r.length)}function Fg(s,t){const e=se(s);if(!e)return 0;const n=[];if(e.forEach(l=>{const c=l;c&&typeof c=="object"&&!c.parentId&&!c.resolved&&typeof c.suggestionId=="string"&&c.suggestionId.length>0&&(!t(c.suggestionId)||c.relatedSuggestionIds?.some(d=>!t(d)))&&n.push(c)}),n.length===0)return 0;const o=new Map,r=(l,c)=>{for(const d of l.toArray()){if(d instanceof I.XmlElement){const g=ua(d);r(d,g&&t(g)?g:c);continue}if(d instanceof I.XmlText)for(const g of st(d)){const u=g.attributes?.comment,f=g.attributes?.suggestionId??c;if(!(!u||!f))for(const h of u.split(",")){const p=o.get(h)??[];p.includes(f)||p.push(f),o.set(h,p)}}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}const i=l=>{const c=Array.from(new Set([...l.suggestionId?[l.suggestionId]:[],...o.get(l.id)??[],...l.relatedSuggestionIds??[]])).filter(t);if(c.length>0)return c;if(l.anchorBlockId){let d=Z(s.ydoc,l.anchorBlockId)??null;for(;d;){if(d instanceof I.XmlElement){const g=d.getAttribute("structuralSuggestionId");if(typeof g=="string"&&t(g))return[g];for(const u of["structuralSuggestionRecord","structuralSuggestionRecords"]){const f=d.getAttribute(u);if(typeof f=="string")try{const h=JSON.parse(f),p=(Array.isArray(h)?h:[h]).find(m=>typeof m?.id=="string"&&t(m.id));if(p)return[p.id]}catch{}}}d=d.parent}}return[]};let a=0;return s.transact(()=>{for(const l of n){const c=i(l);if(c.length===0)continue;const d={...l,suggestionId:c[0]};c.length>1?d.relatedSuggestionIds=c:delete d.relatedSuggestionIds,e.set(l.id,d),a+=1}}),a}function Og(s,t){const e=se(s);if(!e||!e.has(t))return!1;const n=new Set([t]);let o=!0;for(;o;)o=!1,e.forEach((r,i)=>{const a=r;a?.parentId&&n.has(a.parentId)&&!n.has(i)&&(n.add(i),o=!0)});return s.transact(()=>{for(const i of n)e.delete(i);const r=i=>{for(const a of i.toArray()){if(a instanceof I.XmlElement){r(a);continue}if(!(a instanceof I.XmlText))continue;let l=0;for(const c of st(a)){if(typeof c.insert!="string")continue;const d=c.insert.length,g=c.attributes?.comment;if(g){const u=g.split(",").filter(f=>!n.has(f));u.length!==g.split(",").length&&at(a,l,d,{comment:u.length>0?u.join(","):null})}l+=d}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function fa(s,t){const e=d=>d.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&");if(!s.includes("<")||!s.includes(">"))return[{type:"text",text:e(s),marks:{...t}}];const n=[],o={},r=d=>{d&&n.push({type:"text",text:e(d),marks:{...o,...t}})},i=/<(\/?)(i|em|b|strong|u|a)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;let a=0,l;for(;(l=i.exec(s))!==null;){r(s.slice(a,l.index)),a=i.lastIndex;const d=l[1]==="/",g=l[2].toLowerCase();if(g==="i"||g==="em")d?delete o.italic:o.italic=!0;else if(g==="b"||g==="strong")d?delete o.bold:o.bold=!0;else if(g==="u")d?delete o.underline:o.underline=!0;else if(g==="a")if(d)delete o.link;else{const u=/href="([^"]*)"/.exec(l[3]??"");u?.[1]&&(o.link=e(u[1]))}}r(s.slice(a));const c=n.map(d=>({...d,text:d.text.replace(/<[^>]{1,80}>/g,"")})).filter(d=>d.text.length>0);return c.length>0?c:[{type:"text",text:e(s),marks:{...t}}]}function $e(s){const t=[],e=n=>{for(const o of n.toArray()){if(o instanceof I.XmlElement){if(o.nodeName==="footnote")continue;e(o);continue}if(!(o instanceof I.XmlText))continue;let r=0;for(const i of st(o)){if(typeof i.insert!="string")continue;const a=i.attributes??{};typeof a.footnoteRef=="string"&&a.footnoteRef&&t.push({yText:o,start:r,length:i.insert.length,text:i.insert,attributes:a,footnoteId:a.footnoteRef}),r+=i.insert.length}}};try{e(s.getYContentFragment())}catch{}return t}function ke(s){const t=new Map,e=n=>{for(const o of n.toArray())if(o instanceof I.XmlElement&&o.nodeName==="footnote"){const r=o.getAttribute("id");typeof r=="string"&&r&&t.set(r,o)}};try{e(s.getYNotesFragment()),e(s.getYContentFragment())}catch{}return t}function Rg(s,t){const e=[...s.notes??[],...s.children.filter(n=>n.type==="footnote")];for(const n of e)if(n.id===t||W(n,t))return!0;return!1}function Lr(s){const t=new Map;for(const[e,n]of ke(s))t.set(e,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return t}function Dg(s){const t=[];for(const a of $e(s))t.includes(a.footnoteId)||t.push(a.footnoteId);const e=Lr(s),n=new Map,o=s.getDocument();for(const a of[...o.notes??[],...o.children.filter(l=>l.type==="footnote")])n.set(a.id,a);const r={footnote:0,endnote:0},i=[];for(const a of t){const l=n.get(a);if(!l)continue;const c=e.get(a)??"footnote";r[c]+=1,i.push({footnote:l,number:r[c],display:Mo(r[c],c),kind:c})}return i}function Se(s){const t=$e(s);if(t.length===0)return!1;const e=Lr(s),n=new Map,o={footnote:0,endnote:0};for(const i of t)if(!n.has(i.footnoteId)){const a=e.get(i.footnoteId)??"footnote";o[a]+=1,n.set(i.footnoteId,Mo(o[a],a))}const r=t.filter(i=>i.text!==n.get(i.footnoteId));return r.length===0?!1:(s.transact(()=>{for(const i of[...r].sort((a,l)=>l.start-a.start)){const a=n.get(i.footnoteId)??"";i.yText.delete(i.start,i.length),lt(i.yText,i.start,a,i.attributes)}}),!0)}function $g(s){pa(s);const t=$e(s),e=ke(s);if(t.length===0&&e.size===0)return;const n=new Set(t.map(o=>o.footnoteId));s.transact(()=>{for(const[o,r]of e)if(!n.has(o)&&!r.getAttribute("structuralSuggestionId")){const i=r.parent;if(i){const a=i.toArray().indexOf(r);a>=0&&i.delete(a,1)}}for(const o of[...t].sort((r,i)=>i.start-r.start))e.has(o.footnoteId)||o.yText.delete(o.start,o.length)}),Se(s)}function pa(s){let t;try{t=s.getYContentFragment()}catch{return!1}const e=[],n=d=>{for(const g of d.toArray()){if(g instanceof I.XmlElement){n(g);continue}if(!(g instanceof I.XmlText))continue;let u=0;for(const f of st(g)){if(typeof f.insert!="string")continue;const h=f.attributes??{};typeof h.footnotePendingBody=="string"&&e.push({yText:g,start:u,length:f.insert.length,footnoteId:typeof h.footnoteRef=="string"&&h.footnoteRef?h.footnoteRef:G(),body:h.footnotePendingBody,kind:h.footnotePendingKind==="endnote"?"endnote":"footnote",fontFamily:typeof h.fontFamily=="string"?h.fontFamily:void 0,suggestionId:typeof h.suggestionId=="string"?h.suggestionId:void 0,suggested:h.insertion===!0}),u+=f.insert.length}}};if(n(t),e.length===0)return!1;const o=ke(s),r=new Set($e(s).map(d=>d.footnoteId)),i=s.getDocument(),a=new Map;for(const d of[...i.notes??[],...i.children.filter(g=>g.type==="footnote")])a.set(d.id,d.children.flatMap(g=>g.type==="paragraph"?g.children:[]).map(g=>g.type==="text"?g.text:"").join(""));const l=new Set;for(const d of e)if(!o.has(d.footnoteId)){for(const[g,u]of a)if(u===d.body&&!r.has(g)&&!l.has(g)&&o.has(g)){d.footnoteId=g,l.add(g);break}}const c=Qt(s.getDocument().children);return s.transact(()=>{for(const d of e){if(at(d.yText,d.start,d.length,{footnotePendingBody:null,footnotePendingKind:null,footnoteRef:d.footnoteId,superscript:!0}),o.has(d.footnoteId)){if(a.get(d.footnoteId)!==d.body){const p=o.get(d.footnoteId);let m=null;for(const b of p.toArray())if(b instanceof I.XmlElement&&b.nodeName==="paragraph"){m=b;break}const y=m?ct(m):null;if(y){const b=d.fontFamily??c;y.length>0&&y.delete(0,y.length);let k=0;for(const S of fa(d.body,{fontSize:ge,...b?{fontFamily:b}:{}}))lt(y,k,S.text,S.marks),k+=S.text.length}}continue}const g=d.fontFamily??c,u={fontSize:ge,...g?{fontFamily:g}:{}},f={type:"footnote",id:d.footnoteId,...d.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:G(),children:fa(d.body,u)}]},h=s.blockToYjsElement(f);h.setAttribute("id",d.footnoteId),d.kind==="endnote"&&h.setAttribute("noteKind","endnote"),d.suggested&&d.suggestionId&&s.suggestions.setElementStructuralSuggestion(h,"insert",void 0,d.suggestionId,"Insert footnote"),s.getYNotesFragment().push([h]),o.set(d.footnoteId,h)}}),Se(s),!0}function jg(s){let t;try{t=s.getYContentFragment()}catch{return}const e=[];for(const i of t.toArray())i instanceof I.XmlElement&&i.nodeName==="footnote"&&e.push(i);if(e.length===0)return;const n=s.getYNotesFragment(),o=s.getDocument(),r=new Map([...o.notes??[],...o.children.filter(i=>i.type==="footnote")].map(i=>[i.id,i]));s.transact(()=>{for(const a of e){const l=a.getAttribute("id"),c=typeof l=="string"?r.get(l):void 0;c&&n.push([s.blockToYjsElement(c)])}const i=t.toArray();for(let a=i.length-1;a>=0;a--){const l=i[a];l instanceof I.XmlElement&&l.nodeName==="footnote"&&t.delete(a,1)}}),Se(s)}function _g(s,t,e,n,o="footnote"){if(!s.ydoc)return null;const r=G(),i=s.suggestions.isSuggesting(),a=i?gt():void 0,l=Lr(s),c=new Set($e(s).map(m=>m.footnoteId).filter(m=>(l.get(m)??"footnote")===o)).size,d=Mo(c+1,o);let g,u;{const m=W(s.getDocument(),t.block);if(m&&m.type==="paragraph"){u=m.direction;let y=0;for(const b of m.children){if(b.type!=="text")continue;const k=y+b.text.length;if(t.offset<=k&&b.marks?.fontFamily){g=b.marks.fontFamily;break}y=k}}}const f={footnoteRef:r,superscript:!0,...g?{fontFamily:g}:{},...i&&a?{insertion:!0,...s.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!s.insertTextNodes(t,[{type:"text",text:d,marks:f}],n))return null;const h=g??Qt(s.getDocument().children),p={fontSize:ge,...h?{fontFamily:h}:{}};return s.transact(()=>{const m={type:"footnote",id:r,...o==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:G(),...u?{direction:u}:{},children:[{type:"text",text:e||"",marks:p}]}]},y=s.blockToYjsElement(m);if(y.setAttribute("id",r),o==="endnote"&&y.setAttribute("noteKind","endnote"),i&&a&&s.suggestions.setElementStructuralSuggestion(y,"insert",void 0,a,"Insert footnote"),s.getYNotesFragment().push([y]),!e){const b=y.toArray()[0];b instanceof I.XmlElement&&b.setAttribute("_emptyTextMarks",JSON.stringify(p))}}),Se(s),{footnoteId:r,...a?{suggestionId:a}:{}}}function Xg(s,t,e){const n=ke(s).get(t);if(!n)return!1;let o=null;for(const c of n.toArray())if(c instanceof I.XmlElement&&c.nodeName==="paragraph"){o=c;break}if(!o)return!1;const r=ct(o);if(!r)return!1;const i=s.getDocument(),a=[...i.notes??[],...i.children.filter(c=>c.type==="footnote")].find(c=>c.id===t)?.children.flatMap(c=>c.type==="paragraph"?c.children:[]).find(c=>c.type==="text"&&c.marks?.fontFamily)?.marks?.fontFamily??Qt(s.getDocument().children),l={fontSize:ge,...a?{fontFamily:a}:{}};return s.transact(()=>{r.length>0&&r.delete(0,r.length),e.length>0?lt(r,0,e,l):o.setAttribute("_emptyTextMarks",JSON.stringify(l))}),!0}function Ug(s,t,e,n,o=!1){if(!e)return{success:!1,replacements:0,error:"The text to find must not be empty."};let r=null;const i=b=>{if(!r){for(const k of b.toArray())if(k instanceof I.XmlElement){if(k.getAttribute("id")===t){r=k;return}i(k)}}};for(const b of ke(s).values()){if(b.getAttribute("id")===t){r=b;break}if(i(b),r)break}if(!r)return{success:!1,replacements:0,error:`Note block '${t}' was not found.`};const a=ct(r);if(!a)return{success:!1,replacements:0,error:`Note block '${t}' does not contain editable text.`};let l="";const c=[];let d=0;for(const b of st(a))if(typeof b.insert=="string"){if(!b.attributes?.deletion){for(let k=0;k<b.insert.length;k+=1)c.push(d+k);l+=b.insert}d+=b.insert.length}const g=[];let u=0;for(;u<=l.length-e.length;){const b=l.indexOf(e,u);if(b<0)break;const k=c[b];if(c[b+e.length-1]-k!==e.length-1)return{success:!1,replacements:0,error:`${JSON.stringify(e)} in note block '${t}' runs across a pending tracked deletion. Replace a smaller piece that doesn't span it, or settle that change first.`};g.push(k),u=b+e.length}if(g.length===0)return{success:!1,replacements:0,error:`No match found for ${JSON.stringify(e)} in note block '${t}'.`};if(!o&&g.length>1)return{success:!1,replacements:0,error:`Found ${g.length} matches for ${JSON.stringify(e)} in note block '${t}'. Include more surrounding context so it matches exactly one location, or use replace_all.`};const f=o?g:g.slice(0,1),h=s.suggestions.isSuggesting()?gt():null,p=h?s.suggestions.buildInlineMetadataMarks(h,"Replace footnote text"):null,m=b=>{let k=0;for(const S of st(a)){if(typeof S.insert!="string")continue;const v=k+S.insert.length;if(b<v){const x={...S.attributes??{}};return delete x.insertion,delete x.deletion,delete x.suggestionId,delete x.suggestionLabel,delete x.suggestionCreatedAt,x}k=v}return{fontSize:ge}},y=new Map(f.map(b=>[b,m(b)]));return s.transact(()=>{for(const b of[...f].reverse()){const k=y.get(b)??{fontSize:ge};h&&p?(at(a,b,e.length,{deletion:!0,...p}),n&&lt(a,b,n,{...k,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(b,e.length),n&&lt(a,b,n,k))}}),{success:!0,replacements:f.length,...h?{suggestionId:h}:{}}}function zg(s,t){const e=ke(s);return e.size===0?!1:(s.transact(()=>{for(const n of e.values())t==="endnote"?n.setAttribute("noteKind","endnote"):n.removeAttribute("noteKind")}),Se(s),!0)}function Wg(s,t){const e=$e(s).filter(o=>o.footnoteId===t),n=ke(s).get(t);if(e.length===0&&!n)return!1;if(s.suggestions.isSuggesting()){const o=gt();return s.transact(()=>{for(const r of e)at(r.yText,r.start,r.length,{deletion:!0,...s.suggestions.buildInlineMetadataMarks(o,"Delete footnote")});n&&s.suggestions.setElementStructuralSuggestion(n,"delete",void 0,o,"Delete footnote")}),!0}return s.transact(()=>{for(const o of[...e].sort((r,i)=>i.start-r.start))o.yText.delete(o.start,o.length);if(n){const o=n.parent;if(o){const r=o.toArray().indexOf(n);r>=0&&o.delete(r,1)}}}),Se(s),!0}function ma(s,t,e){const n=a=>{const l=new Map;for(const c of a)c.id&&l.set(c.id,(l.get(c.id)??0)+1);return l},o=n(s),r=n(t),i=a=>a.id&&o.get(a.id)===1&&r.get(a.id)===1?`id:${a.id}`:`content:${e(a)}`;return{beforeKeys:s.map(i),afterKeys:t.map(i)}}function Fr(s,t){const e=s.length,n=t.length,o=Array.from({length:e+1},()=>Array(n+1).fill(0));for(let l=1;l<=e;l++)for(let c=1;c<=n;c++)s[l-1]===t[c-1]?o[l][c]=o[l-1][c-1]+1:o[l][c]=Math.max(o[l-1][c],o[l][c-1]);const r=[];let i=e,a=n;for(;i>0&&a>0;)s[i-1]===t[a-1]?(r.unshift(s[i-1]),i-=1,a-=1):o[i-1][a]>o[i][a-1]?i-=1:a-=1;return r}function ba(s){let t=s,e=null;for(;t;){if(t instanceof I.XmlElement){const n=t.nodeName,o=t.getAttribute("id");if(n==="paragraph"&&o)return{blockId:o,offset:0};if(n==="list-item"&&(e=t),n==="list"&&o&&e){let r=0;for(let i=0;i<t.length;i++){const a=t.get(i);if(a===e)return{blockId:o,offset:r};if(a instanceof I.XmlElement&&a.nodeName==="list-item"){for(let l=0;l<a.length;l++){const c=a.get(l);if(c instanceof I.XmlText){r+=c.length;break}}r+=1}}return{blockId:o,offset:0}}}t=t.parent}return null}function Jg(s,t,e,n){const o=s.getArray("paragraphs"),r=o.toArray().findIndex(a=>a?.get("id")===t);if(r<0)return null;const i=o.get(r);if(!i)return null;if(e==="paragraph")return i.get("content");if(e==="list"&&n!==void 0){const a=i.get("items");return!a||n>=a.length?null:a.get(n)?.get("content")}return null}function Hg(s,t,e,n){const o=Z(s,t);if(!o)return null;if(e==="paragraph"||e==="list-item")return ct(o);if(e==="list"&&n!==void 0){let r=0;for(let i=0;i<o.length;i++){const a=o.get(i);if(a instanceof I.XmlElement&&a.nodeName==="list-item"){if(r===n)return ct(a);r++}}}return null}function ya(s,t,e,n){return Hg(s,t,e,n)||(Te(s)?Jg(s,t,e,n):null)}function ie(s,t,e){const n=W(e,s.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const o=n,r=ya(t,n.id,"paragraph");if(!r)return null;const i=o.children.filter(c=>c.type==="text").reduce((c,d)=>c+d.text.length,0),a=Math.max(0,Math.min(s.offset,i)),l=I.createRelativePositionFromTypeIndex(r,a);return{blockId:n.id,textOffset:l}}if(n.type==="list"){const o=n;let r=-1,i=s.offset;if(s.offset,s.block!==n.id){let d=0;for(let g=0;g<o.children.length;g++){if(o.children[g].id===s.block){r=g,d+s.offset;break}d+=Fn(o.children[g]),g<o.children.length-1&&(d+=1)}}if(r===-1){let d=s.offset;for(let g=0;g<o.children.length;g++){const u=Fn(o.children[g]),f=g<o.children.length-1?1:0;if(d<=u){r=g,i=d;break}d-=u+f,g===o.children.length-1&&(r=g,i=u)}}r===-1&&(r=0,i=0);const a=ya(t,n.id,"list",r);if(!a)return null;const l=Math.max(0,Math.min(i,a.length)),c=I.createRelativePositionFromTypeIndex(a,l);return{blockId:n.id,textOffset:c}}return null}function qg(s,t,e){const n=s.getArray("paragraphs");for(let o=0;o<n.length;o++){const r=n.get(o);if(!r)continue;const i=r.get("id");if(!i)continue;const a=r.get("type");if(a==="paragraph"&&r.get("content")===t)return{blockId:i,offset:0,yTextOffset:0};if(a==="list"){const l=r.get("items");if(!l)continue;const c=W(e,i);if(!c||c.type!=="list")continue;const d=c;let g=0;for(let u=0;u<l.length;u++){if(l.get(u)?.get("content")===t)return{blockId:i,offset:g,yTextOffset:0};u<d.children.length&&(g+=Fn(d.children[u]),u<d.children.length-1&&(g+=1))}}}return null}function on(s,t){const e=I.createAbsolutePositionFromRelativePosition(s.textOffset,t);if(!e||!(e.type instanceof I.XmlText))return Z(t,s.blockId)?{block:s.blockId,offset:0}:null;const n=e.index,o=e.type,r=ba(o);if(r)return{block:r.blockId,offset:r.offset+n};if(Te(t)){const i=mt(t),a=qg(t,o,i);if(a)return{block:a.blockId,offset:a.offset+n}}return Z(t,s.blockId)?{block:s.blockId,offset:n}:null}function Y(s,t,e){return{anchor:s.anchor?ie(s.anchor,t,e):null,focus:s.focus?ie(s.focus,t,e):null}}function Or(s,t){return{anchor:s.anchor?on(s.anchor,t):null,focus:s.focus?on(s.focus,t):null}}function Ie(s){if(typeof window>"u")return null;try{return window.localStorage??null}catch(t){return console.warn(`[${s}] localStorage unavailable:`,t),null}}function Yg(s,t){if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return!1;return!0}class Rr{constructor(t,e,n=!1,o){this.destroyed=!1,this.handleDocumentUpdate=()=>{this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null},this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.conversationId=null,this.ydoc=t,this.ydoc.on("update",this.handleDocumentUpdate),this.documentId=e||"default",this.conversationId=o||null,this.disableLocalStorage=n,this.storageKey=this.computeStorageKey();const r=t.getXmlFragment("content");this.undoManager=new I.UndoManager(r,{trackedOrigins:new Set}),this.documentId,this.conversationId,this.storageKey,n?this.clearDocumentProposalCacheIfRemote():this.loadFromLocalStorage(),Kg(this.documentId,this)}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=I.encodeStateAsUpdate(this.ydoc)),this.cachedBaseUpdate}seedForkFromBase(t){return this.cachedBaseUpdateV2||(this.cachedBaseUpdateV2=I.encodeStateAsUpdateV2(this.ydoc)),I.applyUpdateV2(t,this.cachedBaseUpdateV2),t}computeStorageKey(){return this.conversationId?`proposals_${this.documentId}_${this.conversationId}`:`proposals_${this.documentId}`}clearDocumentProposalCacheIfRemote(){if(!this.isLikelyRemoteDocumentId())return;const t=Ie("DetachedSuggestionStore");if(!t)return;const e=`proposals_${this.documentId}`,n=[];for(let o=0;o<t.length;o++){const r=t.key(o);r&&(r===e||r.startsWith(`${e}_`))&&n.push(r)}for(const o of n)t.removeItem(o)}isLikelyRemoteDocumentId(){const t=this.documentId.replace(/-/g,"");return/^[a-z0-9]{16}$/i.test(t)?!0:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.documentId)}getYDoc(){return this.ydoc}getDocumentId(){return this.documentId}getConversationId(){return this.conversationId}setOnSuggestionsChanged(t){this.onProposalsChanged=t}setConversation(t,e){this.conversationId!==t&&(this.conversationId,this.conversationId=t,this.storageKey=this.computeStorageKey(),this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),e&&(Object.keys(e.proposals||{}).length>0||Object.keys(e.metadata||{}).length>0)?(Object.keys(e.proposals||{}).length,this.loadFromServerData(e)):this.disableLocalStorage||this.loadFromLocalStorage(),this.notifyListeners())}serializeForServer(){const t={proposals:{},metadata:{},paragraphSuggestions:{}},e=new Set;for(const[n,o]of this.suggestionMeta)o.status==="pending"&&e.add(n);for(const[n,o]of this.proposals)e.has(n)&&(t.proposals[n]=btoa(String.fromCharCode(...o)));for(const[n,o]of this.suggestionMeta){if(!e.has(n))continue;const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?btoa(String.fromCharCode(...i.from)):i.from,to:i.to?btoa(String.fromCharCode(...i.to)):i.to}))),t.metadata[n]=r}for(const[n,o]of this.paragraphSuggestions){const r=o.filter(i=>e.has(i));r.length>0&&(t.paragraphSuggestions[n]=r)}return t}loadFromServerData(t,e){if(this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),!!t){if(Object.keys(t.proposals||{}).length,Object.keys(t.metadata||{}).length,e?.persistAndNotify,t.proposals)for(const[n,o]of Object.entries(t.proposals)){const r=Uint8Array.from(atob(o),i=>i.charCodeAt(0));this.proposals.set(n,r)}if(t.metadata)for(const[n,o]of Object.entries(t.metadata)){const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?Uint8Array.from(atob(i.from),a=>a.charCodeAt(0)):i.from,to:i.to?Uint8Array.from(atob(i.to),a=>a.charCodeAt(0)):i.to}))),this.suggestionMeta.set(n,r)}if(t.paragraphSuggestions)for(const[n,o]of Object.entries(t.paragraphSuggestions))this.paragraphSuggestions.set(n,o);e?.persistAndNotify&&(this.saveToLocalStorage(),this.notifyListeners())}}static getOldFormatProposals(t){const e=Ie("DetachedSuggestionStore");if(!e)return null;const n=`proposals_${t}`;try{const o=e.getItem(n);if(!o)return null;const r=JSON.parse(o);return!r.proposals||Object.keys(r.proposals).length===0?null:{proposals:r.proposals||{},metadata:r.metadata||{},paragraphSuggestions:r.paragraphSuggestions||{}}}catch(o){return console.error("[DetachedSuggestionStore] Failed to read old format proposals:",o),null}}static clearOldFormatProposals(t){const e=Ie("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`;try{e.removeItem(n)}catch(o){console.error("[DetachedSuggestionStore] Failed to clear old format proposals:",o)}}static clearAllStoredSuggestions(t){const e=Ie("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`,o=[];for(let r=0;r<e.length;r++){const i=e.key(r);i&&(i===n||i.startsWith(`${n}_`))&&o.push(i)}try{for(const r of o)e.removeItem(r)}catch(r){console.error("[DetachedSuggestionStore] Failed to clear stored proposals for document:",t,r)}}loadFromLocalStorage(){const t=Ie("DetachedSuggestionStore");if(t)try{const e=t.getItem(this.storageKey);if(e){const n=JSON.parse(e);if(Object.keys(n.proposals||{}).length,Object.keys(n.metadata||{}).length,n.proposals)for(const[o,r]of Object.entries(n.proposals)){const i=Uint8Array.from(atob(r),a=>a.charCodeAt(0));this.proposals.set(o,i)}if(n.metadata)for(const[o,r]of Object.entries(n.metadata)){const i=r;i.anchors&&(i.anchors=i.anchors.map(a=>({...a,from:a.from?Uint8Array.from(atob(a.from),l=>l.charCodeAt(0)):a.from,to:a.to?Uint8Array.from(atob(a.to),l=>l.charCodeAt(0)):a.to}))),this.suggestionMeta.set(o,i)}if(n.paragraphSuggestions)for(const[o,r]of Object.entries(n.paragraphSuggestions))this.paragraphSuggestions.set(o,r);Array.from(this.proposals.keys()),Array.from(this.suggestionMeta.keys()),Array.from(this.suggestionMeta.values()).filter(o=>o.status==="pending").length,Array.from(this.suggestionMeta.values()).filter(o=>o.status==="accepted").length,Array.from(this.suggestionMeta.values()).filter(o=>o.status==="rejected").length,Array.from(this.suggestionMeta.values()).map(o=>({id:o.id,status:o.status}))}else this.storageKey}catch(e){console.error("[DetachedSuggestionStore] Failed to load from localStorage:",e)}}saveToLocalStorage(){if(this.disableLocalStorage){this.onProposalsChanged&&this.onProposalsChanged();return}const t=Ie("DetachedSuggestionStore");if(!t){this.onProposalsChanged&&this.onProposalsChanged();return}try{const e={proposals:{},metadata:{},paragraphSuggestions:{}};for(const[n,o]of this.proposals)e.proposals[n]=btoa(String.fromCharCode(...o));for(const[n,o]of this.suggestionMeta){const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?btoa(String.fromCharCode(...i.from)):i.from,to:i.to?btoa(String.fromCharCode(...i.to)):i.to}))),e.metadata[n]=r}for(const[n,o]of this.paragraphSuggestions)e.paragraphSuggestions[n]=o;t.setItem(this.storageKey,JSON.stringify(e)),this.storageKey,Object.keys(e.proposals).length,Object.keys(e.metadata).length,Object.values(e.metadata).filter(n=>n.status==="pending").length,Object.values(e.metadata).filter(n=>n.status==="accepted").length,Object.values(e.metadata).filter(n=>n.status==="rejected").length,Object.keys(e.metadata),this.onProposalsChanged&&this.onProposalsChanged()}catch(e){console.error("[DetachedSuggestionStore] Failed to save to localStorage:",e)}}cleanupOldProposals(){const t=Date.now(),e=24*60*60*1e3;for(const[n,o]of this.suggestionMeta)t-o.createdAt>e&&(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n));this.saveToLocalStorage()}createSuggestion(t,e,n={}){const o=this.seedForkFromBase(new I.Doc),r=I.encodeStateVector(o);let i=[];o.transact(()=>{i=e(o)},"proposal-edit");const a=I.encodeStateAsUpdate(o,r);return this.proposals.set(t,a),this.suggestionMeta.set(t,{id:t,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:i,...n}),this.saveToLocalStorage(),this.notifyListeners(),i.length,t}createSuggestionFromToolCall(t,e){return this.createSuggestion(this.generateId(),n=>e(n,t),{authorType:"ai",toolCallAction:t,description:`AI: ${t.name}`})}createTextDeletion(t,e,n,o,r,i={}){return this.createSuggestion(t,a=>{const l=Z(a,e);if(!l)return console.warn(`Paragraph ${e} not found for text deletion`),[];const c=ct(l);return c?(c.delete(n,o),[{kind:"delete",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(c,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(c,n+o,0)),text:r}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...i,id:t})}createTextInsertion(t,e,n,o,r={},i={}){const a={...r,proposalId:t};return this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return console.warn(`Paragraph ${e} not found for text insertion`),[];const d=ct(c);return d?(lt(d,n,o,a),[{kind:"insert",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...i,id:t})}createTextReplacement(t,e,n,o,r,i={},a,l={}){const c={...i,proposalId:t};return this.createSuggestion(t,d=>{const g=Z(d,e);if(!g)return console.warn(`Paragraph ${e} not found for text replacement`),[];const u=ct(g);return u?(u.delete(n,o),lt(u,n,r,c),[{kind:"replace",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,n+r.length,0)),text:r,oldText:a}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...l,id:t})}createPositionAwareInsertion(t,e,n,o,r={}){const i=this.generateId();return this.suggestionMeta.set(i,{id:i,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...r}),this.saveToLocalStorage(),this.notifyListeners(),n.length,o.length,i}materializeWithSuggestion(t){const e=this.proposals.get(t);if(!e)return null;const n=new I.Doc;return this.seedForkFromBase(n),I.applyUpdate(n,e),n}withMaterializedSuggestion(t,e){const n=this.materializeWithSuggestion(t);return n?e(n):null}expandPositionAwarePredecessors(t){const e=new Map;for(const r of this.suggestionMeta.values()){const i=r.insertionContext;i&&e.set(i.paragraphId,i)}const n=new Set,o=[...t.mustBeAfter];for(;o.length>0;){const r=o.pop();if(n.has(r))continue;n.add(r);const i=e.get(r);i&&o.push(...i.mustBeAfter)}return n}applyPositionAwareInsertionToDoc(t,e,n){const o=n.insertionContext;if(!o)return;const r=this.expandPositionAwarePredecessors(o),i=t.getXmlFragment("content");let a=0;for(let c=i.length-1;c>=0;c--){const d=i.get(c);if(!(d instanceof I.XmlElement))continue;const g=d.getAttribute("id");if(g&&r.has(g)){a=c+1;break}}const l=ka(o.content,o.paragraphId,e);i.insert(a,[l])}materializeWithSuggestions(t){const e=new I.Doc;this.seedForkFromBase(e);for(const n of t){const o=this.suggestionMeta.get(n);if(!(o&&o.status==="accepted"))if(o?.insertionContext)this.applyPositionAwareInsertionToDoc(e,n,o);else{const r=this.proposals.get(n);if(r){const i=I.encodeStateAsUpdate(e);mt(e),I.applyUpdate(e,r);const a=I.encodeStateAsUpdate(e);if(mt(e),!!Yg(i,a)&&o&&o.status==="pending")if(o.toolCallAction?.name==="remove_block"){const l=o.toolCallAction.arguments.id,c=ot(e,l);if(c){const{yParent:d,index:g}=c;d.delete(g,1)}}else o.anchors&&o.anchors.length>0?console.warn("[DetachedSuggestionStore] Anchor-based regeneration not yet implemented for:",n):console.warn("[DetachedSuggestionStore] Cannot regenerate proposal without sufficient metadata:",n)}}}return e}acceptProposal(t){const e=this.suggestionMeta.get(t);if(!e)return!1;if(e.insertionContext){const n=this.acceptPositionAwareInsertion(t,e);return n&&this.recordAction({type:"accept",suggestionId:t,timestamp:Date.now()}),this.notifyListeners(),n}else{const n=this.proposals.get(t);if(!n)return!1;const o=`proposal-${t}`;this.undoManager.trackedOrigins.add(o);const r=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{I.applyUpdate(this.ydoc,n),this.ensureTrailingParagraphInTransaction(r)},o),this.undoManager.stopCapturing(),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage();const i={type:"accept",suggestionId:t,timestamp:Date.now()};return i.suggestionId,this.undoStack.length,this.recordAction(i),this.notifyListeners(),!0}}acceptPositionAwareInsertion(t,e){const n=e.insertionContext,o=this.ydoc.getXmlFragment("content"),r=this.expandPositionAwarePredecessors(n);let i=0;const a=new Set;for(let c=0;c<o.length;c++){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");g&&a.add(g)}}for(let c=o.length-1;c>=0;c--){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");if(g&&r.has(g)){i=c+1;break}}}for(let c=0;c<o.length;c++){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");if(g&&n.mustBeBefore.includes(g)){c<i&&(i=c);break}}}const l=`proposal-${t}`;return this.undoManager.trackedOrigins.add(l),this.ydoc.transact(()=>{const c=ka(n.content,n.paragraphId,t);o.insert(i,[c]),this.ensureTrailingParagraphInTransaction(o)},l),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.notifyListeners(),!0}ensureTrailingParagraph(){const t=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{this.ensureTrailingParagraphInTransaction(t)})}ensureTrailingParagraphInTransaction(t){if(t.length===0)return;const e=t.get(t.length-1);if(!(e instanceof I.XmlElement)||e.nodeName==="paragraph")return;const n=new I.XmlElement("paragraph");n.setAttribute("id",G());const o=new I.XmlText;n.insert(0,[o]),t.insert(t.length,[n])}acceptSuggestions(t){let e=!0;const n=[],o=()=>{if(n.length===0)return;const r=[...n];n.length=0;const i=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{for(const a of r){const l=this.proposals.get(a);l?I.applyUpdate(this.ydoc,l):e=!1}this.ensureTrailingParagraphInTransaction(i)},"accept-proposals");for(const a of r){const l=this.suggestionMeta.get(a);l&&(l.status="accepted",this.suggestionMeta.set(a,l))}};for(const r of t)this.suggestionMeta.get(r)?.insertionContext?(o(),this.acceptProposal(r)||(e=!1)):n.push(r);return o(),this.saveToLocalStorage(),this.notifyListeners(),e}deleteSuggestion(t){this.proposals.delete(t),this.suggestionMeta.delete(t),this.removeProposalFromParagraphs(t),this.saveToLocalStorage()}rejectProposal(t){const e=this.suggestionMeta.get(t);return e?(e.status="rejected",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.notifyListeners(),this.recordAction({type:"reject",suggestionId:t,timestamp:Date.now()}),!0):!1}unrejectProposal(t){const e=this.suggestionMeta.get(t);return!e||e.status!=="rejected"?!1:(e.status="pending",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.recordAction({type:"unreject",suggestionId:t,timestamp:Date.now()}),this.notifyListeners(),!0)}rejectSuggestions(t){let e=!0;for(const n of t)this.suggestionMeta.has(n)?(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n)):e=!1;return this.saveToLocalStorage(),this.notifyListeners(),e}resolveAnchors(t){return this.resolveAnchorsAgainstDoc(t,this.ydoc)}resolveAnchorsAgainstDoc(t,e){const n=this.suggestionMeta.get(t);if(!n||!n.anchors)return[];const o=[];for(const r of n.anchors){const i=r.from?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(r.from),e):null,a=r.to?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(r.to),e):null;o.push({kind:r.kind,paragraphId:r.paragraphId,fromIndex:i?.index??null,toIndex:a?.index??null,text:r.text})}return o}checkConflicts(t){const e=this.suggestionMeta.get(t);if(!e)return"stale";if(e.anchors&&e.anchors.length>0){const n=this.resolveAnchors(t);for(let o=0;o<e.anchors.length;o++){const r=e.anchors[o],i=n[o];if(r.paragraphId&&i.fromIndex===null)return"conflicted"}}try{const n=this.materializeWithSuggestion(t);if(!n)return"stale";const o=wn(this.ydoc),r=wn(n),i=e.anchors?.filter(a=>a.kind==="insert"&&!a.paragraphId).length||0;return Math.abs(r-o)>i+1?"conflicted":"clean"}catch{return"conflicted"}}getAllSuggestions(){return new Map(this.suggestionMeta)}getSuggestion(t){return this.suggestionMeta.get(t)}getSuggestionCount(){return this.suggestionMeta.size}getPendingSuggestions(){const t=new Map;for(const[e,n]of this.suggestionMeta)n.status==="pending"&&t.set(e,n);return t}getParagraphIdsWithPendingProposals(){const t=new Set;for(const[n,o]of this.suggestionMeta)o.status==="pending"&&t.add(n);if(t.size===0)return[];const e=[];for(const[n,o]of this.paragraphSuggestions)!n||o.length===0||o.some(r=>t.has(r))&&e.push(n);return e}clearAllProposals(){this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.disableLocalStorage||Ie("DetachedSuggestionStore")?.removeItem(this.storageKey),this.notifyListeners()}destroy(){this.destroyed||(this.destroyed=!0,this.ydoc.off("update",this.handleDocumentUpdate),this.undoManager.destroy(),this.listeners.clear(),this.onProposalsChanged=void 0,this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),this.undoStack.length=0,this.redoStack.length=0,$r.get(this.documentId)===this&&$r.delete(this.documentId))}setSuggestionsForParagraph(t,e){this.paragraphSuggestions.set(t,e),this.saveToLocalStorage(),`${e.length}${t}`}getSuggestionsForParagraph(t){return this.paragraphSuggestions.get(t)||[]}setTableCellSuggestionMap(t,e){this.tableCellSuggestions.set(t,e),`${t}`,e.size}getProposalForTableCell(t,e){return this.tableCellSuggestions.get(t)?.get(e)}getTableCellSuggestionMap(t){return this.tableCellSuggestions.get(t)}async recomputeProposalsForParagraph(t){const e=this.getSuggestionsForParagraph(t).filter(d=>this.suggestionMeta.get(d)?.status==="pending");if(e.length===0)return;const{createGranularSuggestionsForParagraph:n}=await Promise.resolve().then(()=>fu),{findBlockById:o}=await import("./CanvasRenderer-Bqsj1S0p.js").then(d=>d.E),r=mt(this.ydoc),i=o(r,t);if(!i){console.warn(`[DetachedSuggestionStore] Paragraph ${t} not found in document`);return}if(i.type!=="paragraph")return;const a=new I.Doc;this.seedForkFromBase(a);for(const d of e){const g=this.proposals.get(d);g&&I.applyUpdate(a,g)}const l=mt(a),c=o(l,t);if(c&&c.type==="paragraph")for(const d of e)this.deleteSuggestion(d)}findParagraphForProposal(t){for(const[e,n]of this.paragraphSuggestions)if(n.includes(t))return e;return null}removeProposalFromParagraphs(t){for(const[e,n]of this.paragraphSuggestions){const o=n.filter(r=>r!==t);o.length!==n.length&&(o.length===0?this.paragraphSuggestions.delete(e):this.paragraphSuggestions.set(e,o))}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async regenerateProposalFromDiff(t,e,n){const o=this.suggestionMeta.get(t);if(!o){console.warn("[DetachedSuggestionStore] Cannot regenerate - no metadata for proposal:",t);return}if(o.insertionContext)return;if(o.toolCallAction?.name==="remove_block"){const d=o.toolCallAction.arguments.id;Z(this.ydoc,d);const g=new I.Doc;this.seedForkFromBase(g);const u=I.encodeStateVector(g);wn(g),g.transact(()=>{if(Te(g)){const h=g.getArray("paragraphs");for(let p=0;p<h.length;p++)if(h.get(p).get("id")===d){h.delete(p,1);break}}else{const h=ot(g,d);if(h){const{yParent:p,index:m}=h;p.delete(m,1)}}}),wn(g);const f=I.encodeStateAsUpdate(g,u);this.proposals.set(t,f),f.length;return}const r=new I.Doc;I.applyUpdate(r,e);const i=new I.Doc;I.applyUpdate(i,n);const a=mt(r),l=mt(i);if(a.children.length===l.children.length)for(let d=0;d<a.children.length;d++){const g=a.children[d],u=l.children[d];if(g.type!=="paragraph"||u.type!=="paragraph")continue;const f=g,h=u,p=c(f),m=c(h);if(p!==m&&f.id===h.id){f.id;const y=new I.Doc;this.seedForkFromBase(y);const b=I.encodeStateVector(y),{analyzeParagraphDiff:k}=await import("./ParagraphDiffAnalysis-DrmStvmz.js").then(x=>x.P),S=k(p,m).diffs;y.transact(()=>{let x=null;if(Te(y)){const w=y.getArray("paragraphs");for(let A=0;A<w.length;A++){const P=w.get(A);if(P.get("id")===f.id){x=P.get("content");break}}}else{const w=Z(y,f.id);w&&(x=ct(w))}if(x){const w=[];for(const T of h.children)if(T.type==="text")for(let E=0;E<T.text.length;E++)w.push({node:T,indexInNode:E,marks:T.marks||{}});let A=0,P=0;for(const[T,E]of S)if(T===0)A+=E.length,P+=E.length;else if(T===-1)x.delete(A,E.length);else if(T===1){for(let B=0;B<E.length;B++){const N=w[P+B];if(N){const R={...N.marks,proposalId:t};lt(x,A+B,E[B],R)}}A+=E.length,P+=E.length}}});const v=I.encodeStateAsUpdate(y,b);this.proposals.set(t,v),this.saveToLocalStorage(),this.notifyListeners();return}}function c(d){return d.children.filter(g=>g.type==="text").map(g=>g.text).join("")}}recordAction(t){this.undoStack.push(t),t.type,t.suggestionId,this.undoStack.length,this.undoStack.map(e=>e.suggestionId),this.redoStack=[]}clearHistory(){this.undoStack=[],this.redoStack=[]}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}async undoLastAction(){if(this.undoStack.length===0)return!1;const t=this.undoStack.pop();switch(this.redoStack.push(t),t.type){case"accept":{if(this.undoManager.canUndo()){const e=this.getBaseUpdate();this.undoManager.undo();const n=this.getBaseUpdate();await this.regenerateProposalFromDiff(t.suggestionId,n,e);const o=this.suggestionMeta.get(t.suggestionId);return o&&(o.status="pending",this.suggestionMeta.set(t.suggestionId,o),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="pending",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="rejected",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}redoLastAction(){if(this.redoStack.length===0)return!1;const t=this.redoStack.pop();switch(this.undoStack.push(t),t.type){case"accept":{if(this.undoManager.canRedo()){this.undoManager.redo();const e=this.suggestionMeta.get(t.suggestionId);return e&&(e.status="accepted",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="rejected",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="pending",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notifyListeners(){this.listeners.forEach(t=>t())}}function ka(s,t,e,n){if(s.type==="list"){const l=new I.XmlElement("list");return l.setAttribute("id",t),l.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&l.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&l.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(c=>{const d=new I.XmlElement("list-item");Ce(d,c),d.setAttribute("id",c.id||G()),c.checked!==void 0&&d.setAttribute("checked",String(c.checked)),typeof c.indentLevel=="number"&&c.indentLevel>0&&d.setAttribute("indentLevel",String(c.indentLevel)),c.direction!==void 0&&d.setAttribute("direction",c.direction);const g=new I.XmlText;let u=0;c.children.forEach(f=>{if(f.type==="text"){const h=f,p=Dr(h.marks,e);g.insert(u,h.text,p),u+=h.text.length}}),d.insert(0,[g]),l.push([d])}),l}if(s.type==="table"){const l=s,c=new I.XmlElement("table");c.setAttribute("id",t),l.columnWidths&&c.setAttribute("columnWidths",JSON.stringify(l.columnWidths)),l.hasHeader&&c.setAttribute("hasHeader","true"),l.tableWidth!==void 0&&c.setAttribute("tableWidth",String(l.tableWidth)),l.align&&c.setAttribute("align",l.align),l.borderColor&&c.setAttribute("borderColor",l.borderColor),l.borderWidth!==void 0&&c.setAttribute("borderWidth",String(l.borderWidth)),l.cellPadding!==void 0&&c.setAttribute("cellPadding",String(l.cellPadding));for(const d of l.children){const g=new I.XmlElement("table-row");g.setAttribute("id",d.id||G());for(const u of d.children){const f=new I.XmlElement("table-cell");f.setAttribute("id",u.id||G()),u.verticalAlign&&f.setAttribute("verticalAlign",u.verticalAlign),u.backgroundColor&&f.setAttribute("backgroundColor",u.backgroundColor);for(const h of u.children)if(h.type==="paragraph"){const p=h,m=new I.XmlElement("paragraph");m.setAttribute("id",p.id||G()),p.heading&&m.setAttribute("heading",String(p.heading)),p.align&&m.setAttribute("align",p.align);const y=new I.XmlText;let b=0;for(const k of p.children)if(k.type==="text"){const S=k,v=Dr(S.marks,e);lt(y,b,S.text,v),b+=S.text.length}m.insert(0,[y]),f.push([m])}g.push([f])}c.push([g])}return c}if(s.type==="code"){const l=s,c=new I.XmlElement("code");c.setAttribute("id",t),l.language&&c.setAttribute("language",l.language),l.renderDiagram!==void 0&&c.setAttribute("renderDiagram",String(l.renderDiagram)),l.showDiagramSource!==void 0&&c.setAttribute("showDiagramSource",String(l.showDiagramSource));const d=new I.XmlText;return c.insert(0,[d]),lt(d,0,l.content||""),c}if(s.type==="math"){const l=s,c=new I.XmlElement("math");c.setAttribute("id",t),l.displayMode&&c.setAttribute("displayMode",l.displayMode),l.align&&c.setAttribute("align",l.align);const d=new I.XmlText;return c.insert(0,[d]),lt(d,0,l.content||""),c}if(s.type==="image"){const l=s,c=new I.XmlElement("image");return c.setAttribute("id",t),c.setAttribute("src",l.src),l.sourceUrl&&c.setAttribute("sourceUrl",l.sourceUrl),c.setAttribute("width",String(l.width)),c.setAttribute("height",String(l.height)),l.alt&&c.setAttribute("alt",l.alt),l.align&&c.setAttribute("align",l.align),c}if(s.type==="page-break"){const l=new I.XmlElement("page-break");return l.setAttribute("id",t),l}if(s.type==="toc")return It({...s,id:t});if(s.type==="section-break"){const l=new I.XmlElement("section-break");return l.setAttribute("id",t),s.layout&&l.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&l.setAttribute("breakType",s.breakType),l}const o=new I.XmlElement("paragraph"),r=s;o.setAttribute("id",t),r.heading&&o.setAttribute("heading",String(r.heading)),r.align&&o.setAttribute("align",r.align);const i=new I.XmlText;let a=0;return r.children.forEach(l=>{if(l.type==="text"){const c=l,d=Dr(c.marks,e);lt(i,a,c.text,d),a+=c.text.length}}),o.insert(0,[i]),o}function Dr(s,t,e){return{...s||{},proposalId:t}}const $r=new Map;function Kg(s,t){$r.set(s,t)}const Vg=new Set(["Arial","Arial, sans-serif"]);function jr(s){if(typeof s!="string")return;const t=s.trim();if(!(!t||Vg.has(t)))return t}function fo(s){const t={};for(const e of xn)if(s[e]!==void 0)if(e==="fontFamily"){const n=jr(s[e]);n&&(t[e]=n)}else(e==="color"||e==="backgroundColor")&&typeof s[e]=="string"&&/^#[0-9a-fA-F]{6}$/.test(s[e])?t[e]=s[e].toLowerCase():t[e]=s[e];return t}const Sa=ps.filter(s=>!xn.includes(s));function je(s){const t=fo(s);for(const e of Sa)s[e]!==void 0&&(t[e]=s[e]);return t}function Gg(s){const t=Ia(s);for(const e of Sa)s[e]!==void 0&&(t[e]=s[e]);return t}function _r(s,t){return JSON.stringify(je(s||{}))===JSON.stringify(je(t||{}))}function Ia(s){const t=fo(s);t.docxRunPropertyResets=s.docxRunPropertyResets??null;for(const e of xn)e in t||(t[e]=null);return t}function Xr(s,t){const e=fo(s||{}),n=fo(t||{});return JSON.stringify(e)===JSON.stringify(n)}function va(s,t){for(const e of Tn){const n=s[e],o=t[e];if(e==="link"||e==="backgroundColor"||e==="color"){const r=l=>typeof l=="string"&&/^#[0-9a-fA-F]{6}$/.test(l),i=r(n)?n.toLowerCase():n,a=r(o)?o.toLowerCase():o;if(i!==a)return!1}else if(e==="fontFamily"){if(jr(n)!==jr(o))return!1}else if(e==="fontSize"){if((typeof n=="number"?n:void 0)!==(typeof o=="number"?o:void 0))return!1}else if(!!n!=!!o)return!1}return!0}class xa{constructor(){this.toolCalls=[]}addToolCalls(t,e){const n=Date.now();if(t.actions)for(const o of t.actions)this.toolCalls.push({toolCall:o,toolCallId:e,timestamp:n})}getAllToolCalls(){return this.toolCalls}clear(){this.toolCalls=[]}}function ae(s,t){return{...s,id:t}}function Qg(s,t,e){const n=new Set(s),o=r=>{if(r){if(r.block.type==="table"&&r.block.id){n.add(r.block.id);return}for(let i=r.containerPath.length-1;i>=0;i--){const a=r.containerPath[i];if((e.get(a)?.block??t.get(a)?.block)?.type==="table"){n.add(a);break}}}};for(const r of s)o(e.get(r)),o(t.get(r));return n}function wa(s){return JSON.stringify(s.children.map(t=>[t.id,t.children.map(e=>[e.id,e.rowSpan??1,e.colSpan??1])]))}function rn(s,t){return wa(s)!==wa(t)||He(s,t)}function Aa(s){return JSON.stringify({...s,children:s.children.map(t=>({...t,children:t.children.map(e=>({...e,children:[]}))}))})}function Zg(s,t){return{...t,children:t.children.map((e,n)=>({...e,children:e.children.map((o,r)=>({...o,children:s.children[n].children[r].children}))}))}}function Ur(s,t,e){const n=e?.affectedBlockIds?new Set(Array.from(e.affectedBlockIds).filter(M=>typeof M=="string"&&M.length>0)):null,o=t.getYDoc(),r=Array.from(t.getPendingSuggestions().keys()),i=r.length>0?t.materializeWithSuggestions(r):o,a=e?.precomputedLiveDocSchema??mt(o),l=e?.precomputedCurrentDocSchema??(i===o?a:mt(i)),c=e?.precomputedFinalDocSchema??mt(s),d=Ct(a),g=Ct(l),u=Ct(c),f=n?Qg(n,g,u):null,h=new Set;for(const M of new Set([...d.keys(),...u.keys()])){const O=d.get(M)?.block,$=u.get(M)?.block;O?.type!=="table"&&$?.type!=="table"||(O?.type!=="table"||$?.type!=="table"||rn(O,$))&&h.add(M)}if(f){const M=e?.precomputedVisibleBeforeDocSchema?Ct(e.precomputedVisibleBeforeDocSchema):null,O=D=>!Ut(M?.get(D)?.block??null,u.get(D)?.block??null),$=new Set,L=new Set;for(const D of f){const H=d.get(D)?.block,F=u.get(D)?.block;if(M&&H?.type==="table-cell"&&F?.type==="table-cell"){L.add(D);continue}H?.type!=="table"||F?.type!=="table"||h.has(D)||!M&&n?.has(D)?$.add(D):L.add(D)}for(const[D,H]of new Map([...d,...u]))(H.containerPath.some(F=>$.has(F))||M&&H.containerPath.some(F=>L.has(F))&&O(D))&&f.add(D)}const p=new Set(Array.from(e?.atomicReplaceBlockIds??[]).filter(M=>typeof M=="string"&&M.length>0)),m=new Map;for(const M of e?.replacementBlockMatches??[])typeof M?.currentBlockId!="string"||M.currentBlockId.length===0||typeof M?.finalBlockId!="string"||M.finalBlockId.length===0||m.set(M.finalBlockId,M.currentBlockId);const y=M=>{const O=m.get(M);return O&&d.has(O)?O:M},b=!!f&&f.size>0,k=t.getPendingSuggestions();if(b){const M=new Set;for(const O of f){const $=t.getSuggestionsForParagraph(O);for(const L of $)k.has(L)&&M.add(L)}for(const O of M)t.deleteSuggestion(O)}else for(const[M]of k)t.deleteSuggestion(M);const S=[],v=new Set,x=new Set,w=g;for(const[M,O]of d){const $=O.block;if($.type!=="list"||u.has(M)||$.children.length===0||b&&!f.has(M)||O.containerPath.some(U=>h.has(U)))continue;const L=w.get(M)?.block,D=(e?.listUnwrapMemberIds?.get(M)??(L?.type==="list"?L.children:$.children).map(U=>U.id)).map(U=>u.get(U)).filter(U=>!!U),H=D[0];if(!H||D.some((U,z)=>U.containerPath.join("/")!==O.containerPath.join("/")||z>0&&U.indexInParent<=D[z-1].indexInParent))continue;const F=H.containerPath.at(-1),X=F?u.get(F)?.block:null,C=(X&&"children"in X?X.children:c.children).slice(H.indexInParent,D.at(-1).indexInParent+1);if(C.some(U=>!U.id||d.has(U.id)))continue;const j=`prop_${G()}`;t.createSuggestion(j,U=>{const z=ot(U,M);return z?(z.yParent.delete(z.index,1),z.yParent.insert(z.index,C.map(tt=>It(tt))),[{kind:"replace",paragraphId:M,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:M,blocks:C},description:"AI: remove list markers"}),S.push(j),v.add(M),t.setSuggestionsForParagraph(M,[j]);for(const U of C)x.add(U.id),t.setSuggestionsForParagraph(U.id,[j])}const A=[],P=b?Array.from(f).filter(M=>u.has(M)):Array.from(u.keys());for(const M of P){const O=u.get(M);if(!O||x.has(M)||O.containerPath.some(F=>x.has(F)))continue;const $=O.block,L=m.get(M);if($.type==="container"||$.type==="table-cell"||O.containerPath.some(F=>h.has(F)))continue;const D=L?d.get(L)??d.get(M):d.get(M),H=L&&D?.block.id===L&&L!==M?L:null;if(D?.block.id&&v.add(D.block.id),$.type==="paragraph"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="paragraph"){const X=D.block,C=Hr(X),j=Hr(F);if(C!==j||hu(X,F)){if(p.has(M)){const z=zr(t,F);z&&(S.push(z),F.id&&t.setSuggestionsForParagraph(F.id,[z]));continue}const U=Ta(t,X,F);S.push(...U)}}else{const X=zr(t,F);X&&(S.push(X),F.id&&t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="list"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="list"){const X=D.block;if(Bo(X,F)){if(!au(X,F)){const C=tu(t,X,F);C.length>0&&X.id&&(S.push(...C),t.setSuggestionsForParagraph(X.id,C))}}else{const C=Jr(t,F);C&&X.id&&(S.push(C),t.setSuggestionsForParagraph(X.id,[C]))}}else{const X=Jr(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="table"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="table"){const X=D.block,C=h.has(F.id);if(C||Aa(X)!==Aa(F)){const j=Ca(t,C?F:Zg(X,F));j&&(S.push(j),t.setSuggestionsForParagraph(F.id,[j]))}}else{const X=Ca(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="code"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="code"){const X=D.block;if(X.content!==F.content||X.language!==F.language){const C=Pa(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Pa(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="math"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="math"){const X=D.block;if(X.content!==F.content||X.displayMode!==F.displayMode||X.align!==F.align){const C=Ma(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Ma(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="image"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="image"){const X=D.block;if(X.src!==F.src||X.width!==F.width||X.height!==F.height||X.alt!==F.alt||X.align!==F.align){const C=Ba(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Ba(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="page-break"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type!=="page-break"){const X=su(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="toc"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type!=="toc"||D.block.levels!==F.levels||D.block.instr!==F.instr||D.block.fontFamily!==F.fontFamily||D.block.fontSize!==F.fontSize||D.block.color!==F.color||D.block.direction!==F.direction||D.block.align!==F.align){const X=iu(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}}A.sort((M,O)=>{const $=M.location.containerPath,L=O.location.containerPath,D=Math.min($.length,L.length);for(let H=0;H<D;H++)if($[H]!==L[H])return $[H].localeCompare(L[H]);return $.length!==L.length?$.length-L.length:M.location.indexInParent-O.location.indexInParent});const T=M=>{const O=M.containerPath.at(-1),$=O?u.get(O)?.block:null;return $&&"children"in $?$.children:c.children},E=M=>{const O=T(M);for(let $=M.indexInParent-1;$>=0;$--){const L=O[$];if(L.id)return y(L.id)}return null},B=M=>{const O=T(M),$=(()=>{for(let D=M.indexInParent-1;D>=0;D--)if(O[D]?.id)return y(O[D].id);return null})(),L=(()=>{for(let D=M.indexInParent-1;D>=0;D--){const H=O[D]?.id;if(!H)continue;const F=y(H);if(d.has(F))return F}return null})();return Array.from(new Set([L,$].filter(D=>typeof D=="string"&&D.length>0)))},N=[];for(const M of A){const O=M.location,$=E(O),L=N[N.length-1];if(L&&L.afterId===$&&L.containerPath.join("/")===O.containerPath.join("/")&&L.blocks[L.blocks.length-1].location.indexInParent===O.indexInParent-1){L.blocks.push(M);continue}N.push({afterId:$,containerPath:O.containerPath,blocks:[M]})}for(const M of N){const O=M.afterId&&d.has(M.afterId);if(M.blocks.length===1&&O){const{location:$}=M.blocks[0],L=$.block,D=du(t,L,M.afterId,a);D&&(S.push(D),L.id&&t.setSuggestionsForParagraph(L.id,[D]))}else for(let $=0;$<M.blocks.length;$++){const{location:L}=M.blocks[$],D=L.block;if(D.type!=="paragraph"&&D.type!=="list"&&D.type!=="table"&&D.type!=="code"&&D.type!=="math"&&D.type!=="image"&&D.type!=="page-break"&&D.type!=="toc"){console.warn("[SuggestionPlanner] Skipping unsupported block type for position-aware insertion:",D.type);continue}const H=B(L),F=t.createPositionAwareInsertion(D.id,D,H,T(L).slice(L.indexInParent+1).map(X=>X.id).filter(X=>!!X&&d.has(X)).slice(0,1),{authorType:"ai",description:`AI: insert_${D.type} (position-aware)`});F&&(S.push(F),t.setSuggestionsForParagraph(D.id,[F]))}}const R=b?Array.from(f).filter(M=>d.has(M)):Array.from(d.keys());for(const M of R){const O=d.get(M);if(!O||v.has(M))continue;const $=O.block,L=$.type==="container"&&b&&!!f?.has(M);if(!($.type==="container"&&!L)&&$.type!=="table-cell"&&!O.containerPath.some(D=>h.has(D))&&($.type==="paragraph"||$.type==="list"||$.type==="table"||$.type==="code"||$.type==="math"||$.type==="image"||$.type==="docx-raw"||$.type==="page-break"||$.type==="section-break"||$.type==="toc"||L)){const D=cu(t,$);D&&(S.push(D),t.setSuggestionsForParagraph(M,[D]))}}return S}function Ta(s,t,e){const n=[];if(!Je(t,e)){const u=zr(s,e);if(u)return s.setSuggestionsForParagraph(e.id,[u]),[u]}const o=u=>{const f=[];return u.children.forEach((h,p)=>{if(h.type==="text"){const m=h;for(let y=0;y<m.text.length;y++)f.push({char:m.text[y],marks:m.marks||{},nodeIndex:p,charIndexInNode:y})}}),f},r=o(t),i=o(e),a=r.map(u=>u.char).join(""),l=i.map(u=>u.char).join(""),c=En(a,l).diffs;let d=0,g=0;for(let u=0;u<c.length;u++){const[f,h]=c[u];if(f===0){const p=h.length;for(let m=0;m<p;m++){const y=r[d+m],b=i[g+m],k=y?.marks||{},S=b?.marks||{};if(!va(k,S)){const v=m;let x=m+1;for(;x<p;){const E=r[d+x]?.marks||{},B=i[g+x]?.marks||{};if(va(E,B)||!_r(B,S))break;x++}const w=h.substring(v,x),A=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,P=Gg(S),T=s.createTextReplacement(A,e.id,d+v,x-v,w,P,w,{authorType:"ai",description:"AI: apply formatting"});T&&n.push(T),m=x-1}}d+=h.length,g+=h.length}else if(f===-1){const p=h.length,m=u+1<c.length?c[u+1]:null;if(m&&m[0]===1){const y=m[1];let b=!0;if(y.length>1){const k=g<i.length?i[g].marks:{};for(let S=1;S<y.length;S++){const v=g+S<i.length?i[g+S].marks:{};if(!Xr(k,v)){b=!1;break}}}if(b){const k=g<i.length?i[g].marks:{},{...S}=k,v=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,x=s.createTextReplacement(v,e.id,d,p,y,S,h,{authorType:"ai",description:"AI: replace text"});x&&n.push(x)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createSuggestion(k,v=>{const x=Z(v,e.id);let w=null;if(x)for(let T=0;T<x.length;T++){const E=x.get(T);if(E instanceof I.XmlText){w=E;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting replacement`),[];w.delete(d,p);let A=d,P=0;for(;P<y.length;){const T=P,E=g+P,B=E<i.length?je(i[E].marks):{};let N=P+1;for(;N<y.length;){const M=g+N,O=M<i.length?je(i[M].marks):{};if(!_r(B,O))break;N++}const R=y.substring(T,N);lt(w,A,R,{...B,suggestionId:k}),A+=R.length,P=N}return[{kind:"replace",paragraphId:e.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d+y.length,0)),text:y,oldText:h}]},{authorType:"ai",description:"AI: replace text"});S&&n.push(S)}u++,d+=p,g+=y.length}else{const y=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,b=s.createTextDeletion(y,e.id,d,p,h,{authorType:"ai",description:"AI: delete text"});b&&n.push(b),d+=p}}else if(f===1){const p=h,m=u>0?c[u-1]:null;if(m&&m[0]===-1)continue;const y=[];let b=0;for(;b<p.length;){const k=b,S=g+b,v=S<i.length?i[S].marks:{},x=je(v);let w=b+1;for(;w<p.length;){const P=g+w,T=P<i.length?i[P].marks:{};if(!_r(x,T))break;w++}const A=p.substring(k,w);y.push({text:A,marks:x}),b=w}if(y.length===1&&Object.keys(y[0].marks).length===0){const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createTextInsertion(k,e.id,d,p,{},{authorType:"ai",description:"AI: insert text"});S&&n.push(S)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createSuggestion(k,v=>{const x=Z(v,e.id);let w=null;if(x)for(let P=0;P<x.length;P++){const T=x.get(P);if(T instanceof I.XmlText){w=T;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting insertion`),[];let A=d;for(const P of y){const T={...P.marks,suggestionId:k};lt(w,A,P.text,T),A+=P.text.length}return[{kind:"insert",paragraphId:e.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d+p.length,0)),text:p}]},{authorType:"ai",description:"AI: insert text"});S&&n.push(S)}g+=p.length}}return e.id&&n.length>0&&s.setSuggestionsForParagraph(e.id,n),n}function zr(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};if(s.createBlockReplacementSuggestion){const n=s.createBlockReplacementSuggestion(t,e);if(n)return n}return s.createSuggestionFromToolCall(e,(n,o)=>{const r=ot(n,t.id);if(!r||r.yBlock.nodeName!=="paragraph")return Wt(n,o);const i=ct(r.yBlock)?.toDelta().map(c=>typeof c.insert=="string"?c.insert:"").join("")??"";r.yParent.delete(r.index,1);const a=It(t);r.yParent.insert(r.index,[a]);const l=ct(a);return[{kind:"replace",paragraphId:t.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(l,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(l,l.length,0)),text:Hr(t),oldText:i}]})}function tu(s,t,e){const n=[],o=t.children.map(b=>({item:b,text:ve(b),signature:Wr(b)})),r=e.children.map(b=>({item:b,text:ve(b),signature:Wr(b)})),{beforeKeys:i,afterKeys:a}=ma(t.children,e.children,Wr),l=Fr(i,a),c=[],d=(b,k,S)=>{const v=Math.min(b.length,k.length);for(let x=0;x<v;x++)c.push({kind:"replace",index:S+x,currentItem:b[x],finalItem:k[x]});for(let x=v;x<b.length;x++)c.push({kind:"delete",index:S+x,currentItem:b[x]});for(let x=k.length-1;x>=v;x--)c.push({kind:"insert",index:S+v,finalItem:k[x]})};let g=0,u=0;for(const b of l){let k=g;for(;k<o.length&&i[k]!==b;)k+=1;let S=u;for(;S<r.length&&a[S]!==b;)S+=1;d(o.slice(g,k),r.slice(u,S),g),g=k+1,u=S+1;const v=o[k],x=r[S];v&&x&&(v.signature!==x.signature||!Ea(v.item,x.item))&&c.push({kind:"replace",index:k,currentItem:v,finalItem:x})}d(o.slice(g),r.slice(u),g);const f=c.some(b=>b.kind!=="replace"?!0:b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text);if(c.length>0&&!f){const b=eu(s,e);return b?[b]:[]}for(const b of c){if(b.kind==="insert"){const S=nu(s,t.id,b.finalItem.item,b.index,t.variant);S&&n.push(S);continue}if(b.kind==="delete"){const S=ou(s,t.id,b.index,b.currentItem.text);S&&n.push(S);continue}const k=ru(s,t.id,b.index,b.currentItem.item,b.finalItem.item,t.variant);k&&n.push(k)}const h=c.filter(b=>b.kind==="replace").length,p=c.some(b=>b.kind!=="replace"?b.kind==="insert"||b.kind==="delete":b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text),m=Math.max(o.length,r.length),y=m>0?n.length/m:0;if(h>0&&y>.7&&p){const b=Jr(s,e);return b?[b]:[]}return n}function eu(s,t){if(!t.id)return null;const e=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(e,n=>{const o=Z(n,t.id);if(!o||o.nodeName!=="list")return[];for(let r=0;r<t.children.length;r++){const i=o.get(r),a=t.children[r];if(!(i instanceof I.XmlElement)||!a)continue;const l=ct(i);if(!l)continue;let c=0;for(const d of a.children)d.type!=="text"||d.text.length===0||(at(l,c,d.text.length,Ia(d.marks||{})),c+=d.text.length)}return[{kind:"replace",paragraphId:t.id,text:t.children.map(ve).join(`
5
+ `)});break}if(u.type==="paragraph"){const x=A=>A.children.filter(P=>!P.marks?.footnoteRef),w=it.extractUniformTextFontFamily(x(u));if(w){for(const A of v.children)if(A.type==="paragraph"&&it.extractUniformTextFontFamily(x(A)))for(const P of x(A))P.marks={...P.marks,fontFamily:w}}}if(v.children.length>0)if(v.children.length===1){const x=v.children[0];if(d===1&&(u.type==="paragraph"||u.type==="list")&&x.type===u.type){if(u.type==="paragraph"&&x.type==="paragraph")x.children=Vn(u.children,x.children);else if(u.type==="list"&&x.type==="list"){const O=new Map(u.children.map(L=>[L.id,L])),$=u.children.length===x.children.length&&x.children.every((L,D)=>L.children.map(H=>H.text).join("")===u.children[D].children.map(H=>H.text).join(""));x.children=x.children.map((L,D)=>({...L,children:Vn((O.get(L.id)??($?u.children[D]:void 0))?.children??[],L.children)}))}const N=O=>Array.isArray(O)?O.map(N):O&&typeof O=="object"?Object.fromEntries(Object.entries(O).filter(([$,L])=>$!=="id"&&L!==void 0&&!($==="marks"&&Object.keys(L).length===0)).sort(([$],[L])=>$.localeCompare(L)).map(([$,L])=>[$,N(L)])):O,R=O=>JSON.stringify(N(O)),M=O=>it.toInternalHtml({type:"doc",children:[N(O)]});if(R(u)===R(x)||M(u)===M(x)){wt(t,{verifiedUnchanged:!0});break}}if(!(h instanceof I.XmlElement))break;if(x.type==="list"){p.delete(m,1);const N=io({...x,id:a});p.insert(m,[N]);const R=u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:R});break}if(x.type==="table"){const N=x;p.delete(m,1);const R=io({...N,id:a});p.insert(m,[R]);const M=u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:M});break}if(x.type==="code"){const N=x;p.delete(m,1);const R=new I.XmlElement("code");R.setAttribute("id",a),N.language&&R.setAttribute("language",N.language),N.renderDiagram!==void 0&&R.setAttribute("renderDiagram",String(N.renderDiagram)),N.showDiagramSource!==void 0&&R.setAttribute("showDiagramSource",String(N.showDiagramSource));const M=new I.XmlText;R.insert(0,[M]),lt(M,0,N.content||""),p.insert(m,[R]);const O=u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Code block replaced",oldText:O});break}if(x.type==="math"){const N=x;p.delete(m,1);const R=new I.XmlElement("math");R.setAttribute("id",a),N.displayMode&&R.setAttribute("displayMode",N.displayMode),N.align&&R.setAttribute("align",N.align);const M=new I.XmlText;R.insert(0,[M]),lt(M,0,N.content||""),p.insert(m,[R]);const O=u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Math block replaced",oldText:O});break}if(x.type==="page-break"){p.delete(m,1);const N=new I.XmlElement("page-break");N.setAttribute("id",a),p.insert(m,[N]);const R=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Page break replaced",oldText:R});break}if(x.type==="toc"){p.delete(m,1);const N=It({...x,id:a});p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(x.type==="image"){const N=x;p.delete(m,1);const R=new I.XmlElement("image");R.setAttribute("id",a),R.setAttribute("src",N.src),N.sourceUrl&&R.setAttribute("sourceUrl",N.sourceUrl),R.setAttribute("width",String(N.width)),R.setAttribute("height",String(N.height)),N.alt&&R.setAttribute("alt",N.alt),N.align&&R.setAttribute("align",N.align),p.insert(m,[R]);const M=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Image replaced",oldText:M});break}if((u.type==="math"||u.type==="code")&&x.type==="paragraph"){p.delete(m,1);const N=new I.XmlElement("paragraph");N.setAttribute("id",a),ao(N,x);const R=new I.XmlText;let M=0;for(const O of x.children)O.type==="text"&&(M=oe(R,M,O.text,O.marks||{}));to(N,x,M),N.insert(0,[R]),p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:x.children.filter(O=>O.type==="text").map(O=>O.text).join(""),oldText:u.type==="code"?"Code block":"Math block"});break}if((u.type==="list"||u.type==="table")&&x.type==="paragraph"){p.delete(m,1);const N=new I.XmlElement("paragraph");N.setAttribute("id",a),ao(N,x);const R=new I.XmlText;let M=0;for(const O of x.children)O.type==="text"&&(M=oe(R,M,O.text,O.marks||{}));to(N,x,M),N.insert(0,[R]),p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:x.children.filter(O=>O.type==="text").map(O=>O.text).join(""),oldText:u.type==="table"?"Table":"List"});break}const w=bt(h);w||lr(h);const A=u.type==="paragraph"?u:null,P=w.length,T=v.children[0],E=A!==null&&Sr(A,T);let B=0;if(!E){if(P>0&&w.delete(0,P),T.children.length>0){for(const N of T.children)if(N.type==="text"){const R=N;B=oe(w,B,R.text,R.marks||{})}}ao(h,T)}if(!E){const N=u.type==="paragraph"?u.children.filter(R=>R.type==="text").map(R=>R.text).join(""):"";o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,B,0)),text:T.children.filter(R=>R.type==="text").map(R=>R.text).join(""),oldText:N})}}else{if(!(h instanceof I.XmlElement))throw new St("target_type_mismatch","Target is not an editable block. Read the current document and target a paragraph ID.","target_resolution");const x=bt(h);x||lr(h);const w=u.type==="paragraph"?u:null,A=x.length,P=u.type==="paragraph"?u.children.filter(R=>R.type==="text").map(R=>R.text).join(""):"",T=v.children[0],E=w!==null&&Sr(w,T);let B=0;if(!E){if(A>0&&x.delete(0,A),T.children.length>0){for(const R of T.children)if(R.type==="text"){const M=R;B=oe(x,B,M.text,M.marks||{})}}T.heading&&h.setAttribute("heading",String(T.heading)),T.align&&h.setAttribute("align",T.align)}E||o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,B,0)),text:T.children.filter(R=>R.type==="text").map(R=>R.text).join(""),oldText:P});let N=m+1;for(let R=1;R<v.children.length;R++){const M=v.children[R],O=new I.XmlElement("paragraph"),$=M.id||G();O.setAttribute("id",$),M.heading&&O.setAttribute("heading",String(M.heading)),M.align&&O.setAttribute("align",M.align);const L=new I.XmlText;let D=0;M.children.forEach(F=>{if(F.type==="text"){const X=F;D=oe(L,D,X.text,X.marks||{})}}),to(O,M,D),O.insert(0,[L]),p.insert(N,[O]),N++;const H=M.children.filter(F=>F.type==="text").map(F=>F.text).join("");o.push({kind:"insert",paragraphId:$,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(L,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(L,H.length,0)),text:H})}}}break}case"style_blocks":{const{selectors:a,attrs:l}=t.arguments,{targets:c,inlineTargets:d,unmatchedSelectors:g,invalidSelectorErrors:u}=Nd(s,a),f=Ld(l),h=Fd(f);if(c.length===0&&d.length===0)throw new Error(`style_blocks matched no blocks. Unmatched selectors: ${g.length>0?g.join(", "):"all"}. ${u.length>0?`Invalid selectors: ${u.join("; ")}.`:""}`);const p=[],m=new Map,y=(J,K,q)=>{const Q=me(J);let ut=m.get(Q);ut||(ut={name:J,applied:new Set,skipped:new Map},m.set(Q,ut)),q?ut.skipped.set(`${K}\0${q}`,{blockId:K,reason:q}):ut.applied.add(K)},b=o.length,k=new Set,S=new Set,v=new Set(c),x=new Set,w=[],A=[],P=[],T=[],E=Kt(s),B=new Set([...c,...d.map(J=>J.yBlock)].map(Bt)),N=J=>"id"in J&&B.has(String(J.id))||"children"in J&&J.children.some(K=>N(K)),R=J=>[...J.children,...J.notes??[],...J.chrome??[]],M=new Set(R(E).filter(N).map(J=>J.id)),O=J=>Pt({order:J.children.map(K=>K.id),noteOrder:(J.notes??[]).map(K=>K.id),chromeOrder:(J.chrome??[]).map(K=>K.id),targets:R(J).filter(K=>M.has(K.id))}),$=O(E),L=new Set,D=new Set,H=ro(f,"width");if(H&&!(c.some(J=>J.nodeName==="image")&&en(H.value)===void 0)){const J=new Map;for(const q of c){if(q.nodeName!=="table-cell")continue;let Q=q.parent;for(;Q instanceof I.XmlElement&&Q.nodeName!=="table";)Q=Q.parent;if(!(Q instanceof I.XmlElement))continue;const ut=W(E,Bt(Q));if(!ut||ut.type!=="table")continue;const yt=en(H.value),Lt=Oe("width",H.value),dt=ut.tableWidth??kr(E,Q),ht=yt??(typeof Lt=="number"&&Number.isFinite(Lt)?Lt/dt*100:NaN);J.has(Q)||J.set(Q,[]),J.get(Q).push({cellId:Bt(q),percent:ht}),L.add(q)}const K=[...J].map(([q,Q])=>({table:q,requests:Q,widths:Vc(W(E,Bt(q)),Q)}));for(const q of K){const Q=String(q.table.getAttribute("columnWidths")??""),ut=JSON.stringify(q.widths),yt=W(E,Bt(q.table)),Lt=Mn(yt);for(const dt of q.requests){const ht=Lt.byId.get(dt.cellId),vt=Tt=>Tt.slice(ht.col,ht.col+ht.colSpan).reduce((ce,Sn)=>ce+Sn,0);Math.abs(vt(yt.columnWidths)-vt(q.widths))>.001&&D.add(dt.cellId)}Q!==ut&&(q.table.setAttribute("columnWidths",ut),Ft(o,q.table,null,"columnWidths"),k.add(Bt(q.table))),x.add(H.canonicalName),S.add("columnWidths")}}for(const J of c){const K=Bt(J);let q=!1;const Q=Xd({doc:E,yBlock:J,rawAttrs:f,anchors:o});L.has(J)&&H&&(Q.handledRawNames.add(H.canonicalName),Q.appliedAttrs.push("cell width -> table columns"));for(const dt of Q.handledRawNames){const ht=f.find(Tt=>Tt.canonicalName===dt),vt=Q.issuesByRawName.get(dt)??[];y(ht?.rawName??dt,K,vt.length?vt.join("; "):void 0),x.add(dt)}for(const dt of Q.appliedAttrs)S.add(dt),k.add(K);w.push(...Q.exactMappings),A.push(...Q.approximateMappings),P.push(...Q.ignoredAttrs),T.push(...Q.unsupportedImageSpacing),p.push(...Q.errors);const ut=Wi(h,J,!1);A.push(...Ji(ut));const yt=ut.some(({rawName:dt,value:ht})=>["liststyletype","list-style-type"].includes(dt.toLowerCase())&&typeof ht=="string"&&ht.toLowerCase()==="none"),Lt=[];for(const{rawName:dt,entry:ht,value:vt}of ut){if(yt&&J.nodeName==="list"&&ht.kind!=="textMark"&&ht.nodeNames.includes("paragraph")&&!ht.nodeNames.includes("list-item")){Lt.push({rawName:dt,entry:ht,value:vt});continue}if(!Q.handledRawNames.has(me(dt)))try{if(ht.attr==="variant"&&typeof vt=="string"&&vt.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(dt.trim().toLowerCase())){if(J.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');q=!0;continue}if(ht.kind==="textMark"){const Tt=Di(dt,ht.attr,vt);kd({toolName:"style_blocks",yBlock:J,attribute:ht.attr,operation:Tt===null?"remove":"set",value:Tt,config:ht,anchors:o,independentlySelectedTargets:v}),k.add(K),S.add(`${dt} -> ${ht.attr}`),y(dt,K);continue}vd({toolName:"style_blocks",yBlock:J,attribute:ht.attr,operation:vt===null?"remove":"set",value:vt,config:{nodeNames:ht.nodeNames,valueType:ht.valueType,integer:ht.integer,min:ht.min,max:ht.max,enumValues:ht.enumValues},anchors:o,independentlySelectedTargets:v}),k.add(K),S.add(`${dt} -> ${ht.attr}`),y(dt,K)}catch(Tt){y(dt,K,Tt instanceof Error?Tt.message:String(Tt)),p.push(`${K}.${ht.attr}: ${Tt instanceof Error?Tt.message:String(Tt)}`)}}if(q){const dt=Hd(J,o);if(dt){for(const{rawName:ht,entry:vt,value:Tt}of Lt)if(vt.kind!=="textMark")try{for(const ce of dt)oo({toolName:"style_blocks",yBlock:ce,attribute:vt.attr,operation:Tt===null?"remove":"set",value:Tt,config:vt,anchors:o});S.add(`${ht} -> ${vt.attr}`),y(ht,K)}catch(ce){const Sn=ce instanceof Error?ce.message:String(ce);y(ht,K,Sn),p.push(`${K}.${vt.attr}: ${Sn}`)}k.add(K),S.add("listStyleType -> plain paragraphs"),y("listStyleType",K)}else p.push(`${K}.variant: could not convert the list to plain paragraphs.`)}}for(const{yBlock:J,ranges:K}of d){const q=Bt(J),Q=Wi(h,J,!0);A.push(...Ji(Q));for(const{rawName:ut,entry:yt,value:Lt}of Q){if(yt.kind!=="textMark"){const dt="Block attributes cannot apply to an inline range; select its block instead.";y(ut,q,dt),p.push(`${q}.${yt.attr}: ${dt}`);continue}try{const dt=Di(ut,yt.attr,Lt);Sd({toolName:"style_blocks",yBlock:J,ranges:K,attribute:yt.attr,operation:dt===null?"remove":"set",value:dt,config:yt,anchors:o}),k.add(q),S.add(`${ut} -> ${yt.attr}`),y(ut,q)}catch(dt){y(ut,q,dt instanceof Error?dt.message:String(dt)),p.push(`${q}.${yt.attr}: ${dt instanceof Error?dt.message:String(dt)}`)}}}for(const J of h.unsupportedAttrs??[]){const K=m.get(me(J)),q=new Set([...K?.skipped.values()??[]].map(Q=>Q.blockId));for(const Q of B)!K?.applied.has(Q)&&!q.has(Q)&&y(J,Q,"Unsupported attribute for this target.")}const F=Kt(s),X=J=>{const K=new Map,q=Q=>{"id"in Q&&Q.id&&K.set(Q.id,Q),"children"in Q&&Q.children.forEach(ut=>q(ut))};return R(J).forEach(q),K},C=X(E),j=X(F),U=J=>Pt(C.get(J)??null)!==Pt(j.get(J)??null),z=[...new Set([...B,...o.slice(b).map(J=>J.paragraphId).filter(J=>!!J)])].filter(U),tt=[...B].filter(J=>U(J)||D.has(J)),_=[...m.values()].map(J=>({name:J.name,appliedBlockIds:[...J.applied],skipped:[...J.skipped.values()]})),V=_.every(J=>J.skipped.length===0)&&S.size>0&&p.length===0&&g.length===0&&u.length===0&&P.length===0&&T.length===0&&(h.unsupportedAttrs??[]).every(J=>x.has(me(J))),nt={outcome:V?tt.length?"complete":"unchanged":"partial",targetBlockIds:[...B],changedBlockIds:tt,affectedBlockIds:z,attributes:_};if(wt(t,{styleEffects:nt}),V&&$===O(F)&&wt(t,{verifiedUnchanged:!0}),o.length===b&&!Rt(t)?.verifiedUnchanged){if(T.length||P.length)throw new St("attribute_unsupported","These image layout attributes cannot be represented. Use width/height or align for image sizing/placement, and document blockGap or surrounding paragraph spacing for separation.","validation");if(h.length===0){const J=h.unsupportedAttrs??[];throw new Error(J.length>0?`style_blocks has no supported attrs. Unsupported attrs: ${J.join(", ")}.`:"style_blocks requires at least one attr.")}throw new Error(`style_blocks could not apply to any target. ${p.length>0?`Skipped target attrs: ${p.join("; ")}`:"No matching supported attributes."}`)}cr.set(t,Ud({styleEffects:nt,matchedTargetCount:c.length+d.reduce((J,K)=>J+K.ranges.length,0),inlineRangeCount:d.reduce((J,K)=>J+K.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(J=>!x.has(me(J))),unmatchedSelectors:g,invalidSelectorErrors:u,skippedTargetErrors:p,exactCompatibilityMappings:w,approximateCompatibilityMappings:A,ignoredCompatibilityAttrs:P,unsupportedImageSpacing:T}));break}case"set_block_attribute":{const{id:a,attribute:l,operation:c,value:d}=t.arguments,g=Li("set_block_attribute",a),u=()=>{const b=Kt(s);return g.map(k=>W(b,k))},f=JSON.stringify(u());if(typeof l!="string"||l.trim().length===0)throw new Error("set_block_attribute requires a non-empty attribute name.");const h=l.trim();if(h==="id")throw new Error("set_block_attribute cannot modify the reserved 'id' attribute.");const p=bd(c),m=[],y=(b,k)=>{if(g.length<=1)throw new Error(k);return m.push(`${b}: ${k}`),!0};for(const b of g){const k=ot(s,b);if(!k){y(b,`Target block '${b}' not found in the document. Please only reference IDs you see inside <document_content>.`);continue}const{yBlock:S}=k,v=bt(S);if(h==="fontFamily"){const w=no(S);if(w){y(b,w);continue}}if(hd.has(h)){if(!v||S.nodeName!=="paragraph"&&S.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}let w;if(p==="remove")w=!1;else if(p==="toggle")w=!Ni(S,v,h);else if(d===void 0)w=!0;else if(typeof d=="boolean")w=d;else throw new Error(`set_block_attribute "${h}" expects a boolean value when operation is "set".`);if(v.length>0)at(v,0,v.length,{[h]:w?!0:null}),ne(o,b,v);else{pd(S,h,w);const A=`Text mark "${h}" ${w?"enabled":"removed"}.`;o.push({kind:"replace",paragraphId:b,text:A,oldText:A})}continue}if(h in Mi){if(!v||S.nodeName!=="paragraph"&&S.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}if(p==="toggle")throw new Error(`set_block_attribute "${h}" does not support toggle. Use operation "set" with a numeric value or "remove".`);const w=Mi[h],A=p==="remove"?null:md(h,d,w);if(v.length>0)at(v,0,v.length,{[h]:A===null?null:A}),ne(o,b,v);else{ur(S,h,A);const P=`Text mark "${h}" ${A===null?"removed":"set"}.`;o.push({kind:"replace",paragraphId:b,text:P,oldText:P})}continue}if(h==="indentLevel"&&S.nodeName==="paragraph"){Ri(S,p,d),v&&ne(o,b,v);continue}const x=Ei[h];if(!x){const w=Object.keys(Ei).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${w}.`)}if(!x.nodeNames.includes(S.nodeName)){y(b,`set_block_attribute "${h}" is not valid for ${S.nodeName} blocks.`);continue}if(p==="remove")et(S,h);else if(p==="toggle"){if(x.valueType!=="boolean")throw new Error(`set_block_attribute "${h}" only supports toggle for boolean attributes.`);const w=Fi(rt(S,h));S.setAttribute(h,String(!w))}else{if(d===void 0)throw new Error(`set_block_attribute "${h}" requires "value" when operation is "set".`);const w=Oi(h,d,x);S.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?fr(S,h,Number(w)):S.setAttribute(h,w)}if(v)ne(o,b,v);else{const w=`Updated ${h} on ${S.nodeName} block.`;o.push({kind:"replace",paragraphId:b,text:w,oldText:w})}}if(o.length===0&&m.length>0)throw new Error(`set_block_attribute could not apply to any target. Skipped targets: ${m.join("; ")}`);m.length===0&&f===JSON.stringify(u())&&wt(t,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=t.arguments,l=Li("clear_formatting",a),c=()=>{const g=Kt(s);return l.map(u=>W(g,u))},d=JSON.stringify(c());for(const g of l){const u=ot(s,g);if(!u)throw new Error(`Target block '${g}' not found in the document. Please only reference IDs you see inside <document_content>.`);const f=[];if(u.yBlock.nodeName==="list"){for(let h=0;h<u.yBlock.length;h++){const p=u.yBlock.get(h);if(p instanceof I.XmlElement&&p.nodeName==="list-item"){const m=p.getAttribute("id")||g;f.push({id:m,yBlock:p})}}if(f.length===0){const h=`Cleared formatting on list block ${g}.`;o.push({kind:"replace",paragraphId:g,text:h,oldText:h});continue}}else f.push({id:g,yBlock:u.yBlock});for(const h of f){if(h.yBlock.nodeName!=="paragraph"&&h.yBlock.nodeName!=="list-item")throw new Error("clear_formatting only supports paragraph, list, or list-item blocks.");const p=bt(h.yBlock);if(!p)throw new Error("clear_formatting only supports paragraph, list, or list-item text blocks.");if(h.yBlock.nodeName==="paragraph")for(const m of $s)et(h.yBlock,m);if(zd(h.yBlock),p.length>0){let m=0;for(const y of st(p)){const b=typeof y.insert=="string"?y.insert.length:1,k={...js};typeof y.attributes?.footnoteRef=="string"&&y.attributes.footnoteRef.length>0&&delete k.superscript,at(p,m,b,k),m+=b}ne(o,h.id,p)}else{const m="Formatting cleared.";o.push({kind:"replace",paragraphId:h.id,text:m,oldText:m})}}}d===JSON.stringify(c())&&wt(t,{verifiedUnchanged:!0});break}case"remove_block":{const{id:a,count:l=1}=t.arguments,c=ot(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const{yParent:d,index:g}=c;Le(d)&&Fe();const u=We(s),f=d===u;for(let h=0;h<l;h++){const p=g;if(p>=d.length)break;const m=d.get(p);if(!(m instanceof I.XmlElement))break;const y=m.getAttribute("id"),b=m.nodeName;if(f&&d.length===1){if(b==="paragraph"){const k=bt(m);if(k&&k.length>0){const S=st(k);let v="";for(const x of S)x.insert&&typeof x.insert=="string"&&(v+=x.insert);o.push({kind:"delete",paragraphId:y,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,v.length,0)),text:v}),k.delete(0,k.length)}}else{o.push({kind:"delete",paragraphId:y,text:b==="list"?"List removed":"Block removed"});const k=new I.XmlElement("paragraph");k.setAttribute("id",y);const S=new I.XmlText;k.insert(0,[S]),d.delete(p,1),d.insert(p,[k])}break}if(b==="list")o.push({kind:"delete",paragraphId:y,text:"List removed"});else{const k=bt(m);if(k){const S=st(k);let v="";for(const x of S)x.insert&&typeof x.insert=="string"&&(v+=x.insert);o.push({kind:"delete",paragraphId:y,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,v.length,0)),text:v})}else o.push({kind:"delete",paragraphId:y,text:"Block removed"})}d.delete(p,1)}break}case"append_to_paragraph":{const{id:a,content:l}=t.arguments,c=Z(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const d=bt(c);d||lr(c);const g=d.length,u=de(g>0?go(d,g-1,1):ye(c.getAttribute("_emptyTextMarks"))),f=it.fromAgentHtml(l);if(f.children.length>0){const h=[];for(const y of f.children)y.type==="paragraph"&&y.children.forEach(b=>{b.type==="text"&&h.push(b)});let p=g,m="";for(const y of h)if(y.text){const b=oe(d,p,y.text,{...u||{},...y.marks||{}});m+=y.text,p=b}m&&o.push({kind:"insert",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,g,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,p,0)),text:m})}break}case"break_paragraph":{const{id:a,substring:l}=t.arguments,c=typeof l=="string"?l:String(l??"");if(c.trim().length===0)throw new Error("break_paragraph requires a non-empty substring to split on.");const d=n?.document??mt(s),g=W(d,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);if(g.type!=="paragraph")throw new Error(`break_paragraph only works on paragraphs. Block '${a}' is type '${g.type}'.`);const u=Mc(g,c);if(u.length===0){const j=g.children.filter(z=>z.type==="text").map(z=>z.text).join(""),U=Os(j.length>100?j.slice(0,100)+"...":j);throw new Error(`No match found for "${c}" in block '${a}'. The block contains: "${U}".`)}const f=u[0].offset,h=ot(s,a);if(!h)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:p,yParent:m,index:y}=h;if(Le(m)&&Fe(),!(p instanceof I.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const b=bt(p);if(!b)throw new Error(`break_paragraph only works on text paragraphs. Block '${a}' has no text content.`);const{beforeOps:k,afterOps:S,formatAtSplit:v,originalText:x,beforeText:w,afterText:A}=sg(b,f);b.delete(0,b.length);let P=0;for(const j of k)lt(b,P,j.insert,j.attributes??{}),P+=j.insert.length;const T=G(),E=new I.XmlElement("paragraph");E.setAttribute("id",T);const B=p.getAttribute("heading");B&&E.setAttribute("heading",B);const N=rt(p,"align");N&&E.setAttribute("align",N);const R=rt(p,"lineSpacing");R!=null&&E.setAttribute("lineSpacing",R);const M=rt(p,"pagination");M!=null&&E.setAttribute("pagination",M);const O=p.getAttribute("styleId");O!=null&&E.setAttribute("styleId",O);const $=rt(p,"direction");$!=null&&E.setAttribute("direction",$);const L=rt(p,"borders");L!=null&&E.setAttribute("borders",L);const D=rt(p,"shading");D!=null&&E.setAttribute("shading",D);const H=rt(p,"tabStops");H!=null&&E.setAttribute("tabStops",H);const F=p.getAttribute("oxmlPPr");F!=null&&E.setAttribute("oxmlPPr",F);const X=new I.XmlText;let C=0;for(const j of S)X.insert(C,j.insert,j.attributes??{}),C+=j.insert.length;if(S.length===0){const j=ye(p.getAttribute("_emptyTextMarks")),U=de({...j,...v??{}});U&&Object.keys(U).length>0&&E.setAttribute("_emptyTextMarks",JSON.stringify(U))}E.insert(0,[X]),m.insert(y+1,[E]),w!==x&&o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(b,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(b,P,0)),text:w,oldText:x}),o.push({kind:"insert",paragraphId:T,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(X,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(X,C,0)),text:A||"Paragraph split"});break}case"join_paragraphs":{const{firstId:a,secondId:l,separator:c}=t.arguments;if(!a||!l||a===l)throw new Error("join_paragraphs requires two different paragraph IDs: firstId and secondId.");const d=ot(s,a),g=ot(s,l);if(!d)throw new Error(`Target block '${a}' not found in the document.`);if(!g)throw new Error(`Target block '${l}' not found in the document.`);if((Le(d.yParent)||Le(g.yParent))&&Fe(),d.yBlock.nodeName!=="paragraph"||g.yBlock.nodeName!=="paragraph")throw new Error("join_paragraphs only works on two paragraph blocks.");if(d.yParent!==g.yParent||g.index!==d.index+1)throw new Error(`join_paragraphs requires adjacent sibling paragraphs with secondId immediately after firstId. '${l}' does not immediately follow '${a}'.`);const u=bt(d.yBlock),f=bt(g.yBlock);if(!u||!f)throw new Error("join_paragraphs only works on text paragraph blocks.");const h=u.toString(),p=f.toString(),m=c!==void 0?String(c):/\S/.test(h)&&/\S/.test(p)?" ":"",y=h.match(/\s+$/)?.[0].length??0,b=p.match(/^\s+/)?.[0].length??0,k=m.length>0,S=k?h.slice(0,h.length-y):h,v=k?p.slice(b):p;k&&y>0&&u.delete(u.length-y,y);const x=st(u),w=st(f),A=x.length>0?x[x.length-1].attributes??{}:{},P=w.length>0?w[0].attributes??{}:{};let T=u.length;m.length>0&&(lt(u,T,m,Object.keys(A).length>0?A:P),T+=m.length);let E=k?b:0;for(const N of w){if(typeof N.insert!="string"||N.insert.length===0)continue;const R=N.insert.slice(E);E=Math.max(0,E-N.insert.length),R.length!==0&&(lt(u,T,R,N.attributes??{}),T+=R.length)}const B=`${S}${m}${v}`;o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,u.length,0)),text:B||"Paragraphs joined",oldText:h}),o.push({kind:"delete",paragraphId:l,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,f.length,0)),text:p||"Empty paragraph removed"}),g.yParent.delete(g.index,1);break}case"insert_table_row":{const a=mt(s),l=it.createParsingContext(a),{tableId:c,referenceIndex:d,referenceRowId:g,position:u,content:f}=t.arguments,h=W(a,c);if(h?.type!=="table")throw new Error(`Table ${c} not found`);let p=d;if(g!==void 0){if(p=h.children.findIndex(k=>k.id===g),p<0)throw new Error(`Row ${g} not found in table ${c}. Read the table and use a current row ID.`);if(d!==void 0&&d!==p)throw new Error(`Row ${g} is at index ${p}, not ${d}. Use referenceRowId alone or reread the table.`)}if(p===void 0||!Number.isInteger(p)||p<0||p>=h.children.length)throw new Error("Invalid reference row index. Supply a current referenceRowId or a valid 0-based referenceIndex.");const m=h.children[p],y=f?.map(k=>{if(k==="")return;const S=it.fromAgentHtml(k,{existingDocument:a,parsingContext:l});return S.children.length>0?S.children:void 0}),b=sd(s,c,u,p,y);if(!b.success)throw new Error(b.error||"Failed to insert table row");o.push({kind:"insert",paragraphId:c,text:`Row inserted ${u} row ${m.id} (reference index ${p}; new row index ${p+(u==="after"?1:0)})`});break}case"remove_table_row":{const a=t.arguments,l=String(a.tableId??""),c=W(mt(s),l);if(c?.type!=="table"||c.id!==l)throw new Error(`Table ${l} not found`);const d=xi(c,a);if("error"in d)throw new Error(d.error);const{rowIndices:g,rowIds:u}=d,f=nd(s,l,g);if(!f.success)throw new Error(f.error||"Failed to remove table rows");g.forEach((h,p)=>o.push({kind:"delete",paragraphId:l,text:`Row ${u[p]} (index ${h}) removed`}));break}case"insert_table_column":{const a=mt(s),l=it.createParsingContext(a),{tableId:c,referenceIndex:d,position:g,content:u}=t.arguments,f=u?.map(p=>{if(p==="")return;const m=it.fromAgentHtml(p,{existingDocument:a,parsingContext:l});return m.children.length>0?m.children:void 0}),h=od(s,c,g,d,f);if(!h.success)throw new Error(h.error||"Failed to insert table column");o.push({kind:"insert",paragraphId:c,text:`Column inserted ${g} column ${d}`});break}case"remove_table_column":{const{tableId:a,columnIndex:l}=t.arguments,c=td(s,a,l);if(!c.success)throw new Error(c.error||"Failed to remove table column");o.push({kind:"delete",paragraphId:a,text:`Column ${l} removed`});break}}return n?.refreshDocumentIncrementally&&(n.document=Kt(s)),o}function ye(s){if(!s)return{};try{const t=JSON.parse(s);if(t&&typeof t=="object")return t}catch{}return{}}function sg(s,t){const e=[],n=[];let o={},r="",i="",a="",l=0;const c=st(s);for(const d of c){if(!d.insert||typeof d.insert!="string")continue;const g=d.insert,u=d.attributes||{},f=l+g.length;if(r+=g,f<=t)e.push({insert:g,attributes:u}),i+=g,f===t&&(o=u);else if(l>=t)n.push({insert:g,attributes:u}),a+=g;else{const h=t-l,p=g.slice(0,h),m=g.slice(h);p.length>0&&(e.push({insert:p,attributes:u}),i+=p),m.length>0&&(n.push({insert:m,attributes:u}),a+=m),o=u}l=f}return{beforeOps:e,afterOps:n,formatAtSplit:o,originalText:r,beforeText:i,afterText:a}}function go(s,t,e){const n=t+e;let o=0,r=null;for(const i of st(s)){if(typeof i.insert!="string")continue;const a=o+i.insert.length;if(a>t&&o<n){const l=i.attributes||{},c={};for(const d of ps){const g=l[d];g!=null&&g!==!1&&(c[d]=g)}if(r===null)r=c;else for(const d of Object.keys(r))r[d]!==c[d]&&delete r[d]}if(o=a,o>=n)break}return r??{}}function vr(s){const t=new Set;if(!s.includes("<")||!s.includes(">"))return t;try{const e=it.fromAgentHtml(s),n=o=>{if(o.type==="text"){for(const r of xn)o.marks?.[r]!==void 0&&t.add(r);return}if("children"in o&&Array.isArray(o.children))for(const r of o.children)n(r)};for(const o of e.children)n(o)}catch{}return t}function na(s,t,e,n,o){if(o.includes("<")&&o.includes(">")||vr(n).size>0)return!1;const r=go(s,t,e),i=si(o,r);return s.toString().slice(t,t+e)===i}function xr(s,t,e,n,o,r,i,a={}){if(!na(s,t,e,n,o))if(o.includes("<")&&o.includes(">")){const l={...a,...go(s,t,e)};for(const f of vr(n))delete l[f];const c=o.trim(),d=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(c)?c:`<p>${o}</p>`,g=it.fromAgentHtml(d,{preserveExplicitMarkResets:!0}),u=g.children.length>0?g.children[0]:null;if(u&&u.type==="paragraph"&&u.children.length>0){s.delete(t,e);const f=[];for(const b of u.children)if(b.type==="text"){const k=b,S={...l,...k.marks||{}};f.push({text:k.text,marks:S})}const h=s.doc;let p=t;const m=[];for(const b of f){const k=m[m.length-1],S=JSON.stringify(b.marks||{}),v=k?JSON.stringify(k.marks||{}):null;k&&S===v?k.text+=b.text:m.push({text:b.text,marks:b.marks||{}})}const y=m.map(b=>b.text).join("");h.transact(()=>{lt(s,t,y);let b=t;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&at(s,b,k.text.length,k.marks),b+=k.text.length;p=t+y.length},"performReplacement"),Vi(s,t,p),i.push({kind:"replace",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,p,0)),text:o.replace(/<[^>]*>/g,""),oldText:n.replace(/<[^>]*>/g,"")})}}else{const l={...a,...go(s,t,e)},c=si(o,l);for(const d of vr(n))delete l[d];s.delete(t,e),c.length>0&&lt(s,t,c,l),Vi(s,t,t+c.length),i.push({kind:"replace",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t+c.length,0)),text:c,oldText:n.replace(/<[^>]*>/g,"")})}}function ig(s,t,e,n,o={}){if(!t.length)return{anchorsByAction:[],failures:[],alreadySatisfied:!1};const r=t.every(h=>h.name==="insert_block"),i=r?n:o.canonicalDocument?.()??n;r||Rn(s,i);let a;const l={document:r?{...n,children:[...n.children]}:i,get htmlParsingContext(){return a??(a=it.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!r},c=[],d=[],g=new Set,u=[],f=(h,p,m,y)=>{const b=Rt(h);d.push({actionIndex:p,actionName:h.name,error:m,failure:y,sourceEditIndex:b?.sourceEditIndex,sourceEditType:b?.sourceEditType})};for(let h=0;h<t.length;h++){const p=t[h];try{const m=()=>Wt(s,p,`${e}_${h}`,!o.skipContextForFirstAction||r||h>0?l:void 0),y=o.measure?o.measure(m):m();o.skipContextForFirstAction&&!r&&h===0&&t.length>1&&(l.document=Kt(s)),c.push(y);const b=Rt(p);if(y.length&&b?.splitReplacementGroup&&g.add(b.splitReplacementGroup),!y.length&&o.rejectUnchangedAction&&!b?.verifiedUnchanged)if(wc(p)&&b?.splitReplacementGroup)u.push({action:p,index:h,group:b.splitReplacementGroup});else{f(p,h,dr(p)??`${JSON.stringify(p.arguments)} - no change made`);break}}catch(m){if(o.throwOnError)throw m;if(f(p,h,String(m),Be(m)),!o.continueAfterError)break}}for(const{action:h,index:p,group:m}of u)g.has(m)||f(h,p,"Split replacement made no verified change");return{anchorsByAction:c,failures:d,alreadySatisfied:d.length===0&&t.every(h=>Rt(h)?.verifiedUnchanged)}}const wr=()=>{},ag={count:wr,gauge:wr,distribution:wr},oa=new WeakSet;function Ar(s,t){try{ag.count("frontend.editor.yjs_observer_failure",1,{event:t})}catch{}console.error(`Yjs ${t} observer failed`,s)}function ra(s,t=Ar){if(oa.has(s))return;oa.add(s);const e=s.emit;let n=Number.NEGATIVE_INFINITY;s.emit=function(o,r){if(!["update","updateV2","afterTransactionCleanup"].includes(o))return e.call(this,o,r);const i=Array.from(this._observers.get(o)??[]);for(const a of i)try{a(...r)}catch(l){const c=Date.now();if(c-n>=3e4){n=c;try{t(l,o)}catch{}}}}}const sa="suggestion-id-repair";function lg(s){if(s.deleteSet.clients.size>0)return!0;for(const[t,e]of s.afterState){const n=s.beforeState.get(t)??0;if(n===e)continue;const o=s.doc.store.clients.get(t);for(let r=I.findIndexSS(o,n);r<o.length&&o[r].id.clock<e;r++){const i=o[r];if(i instanceof I.Item&&i.content instanceof I.ContentFormat&&["insertion","deletion","suggestionId","proposalId"].includes(i.content.key))return!0}}return!1}function cg(s,t,e="recover"){const n=new Set(["content","chrome","notes"].filter(l=>s.share.has(l)).map(l=>s.getXmlFragment(l))),o=new Set,r=l=>{l._item?.deleted||(l instanceof I.XmlText?o.add(l):l instanceof I.XmlFragment&&l.toArray().forEach(r))};if(t){const l=lg(t);for(const[c,d]of t.changed)c instanceof I.XmlText?l&&o.add(c):c instanceof I.XmlFragment&&(d.has("structuralSuggestionId")||d.has("suggestionId"))&&r(c);vl(t,c=>{c.deleted||c.content instanceof I.ContentType&&r(c.content.type)})}else n.forEach(r);const i=l=>typeof l=="string"&&l.trim().length>0,a=[];for(const l of o){if(l._item?.deleted)continue;let c=l,d=!1;for(;c.parent;){c=c.parent;const h=c;if(h instanceof I.XmlElement&&["structuralSuggestionId","suggestionId","proposalId"].some(p=>i(h.getAttribute(p)))){d=!0;break}}if(d||!n.has(c))continue;let g=0,u,f;for(const h of st(l)){const p=typeof h.insert=="string"?h.insert.length:1,m=h.attributes??{};if(typeof h.insert!="string"||p===0||!(m.insertion||m.deletion)||i(m.suggestionId)||i(m.proposalId)){u=void 0,f=void 0,g+=p;continue}const y=JSON.stringify(Object.entries(m).filter(([b])=>b==="insertion"||b==="deletion"||b==="layeredInsertion"||b.startsWith("suggestion")).sort(([b],[k])=>b.localeCompare(k)));if(f&&u===y)f.length+=p;else{const b=I.createRelativePositionFromTypeIndex(l,g).item;if(!b){g+=p;continue}f={text:l,start:g,length:p,id:`recovered-inline-${b.client.toString(36)}-${b.clock.toString(36)}`},u=y,a.push(f)}g+=p}}return a.length&&s.transact(()=>{for(const l of a)at(l.text,l.start,l.length,e==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:l.id})},sa),a.length}function uo(s,t){if(Array.isArray(s))return s.map(o=>uo(o,t));if(!s||typeof s!="object")return s;const e={};for(const[o,r]of Object.entries(s))if(!(t.regenerateIds&&o==="id")){if(t.regenerateIds&&o==="marks"&&r&&typeof r=="object"&&!Array.isArray(r)&&"comment"in r){const{comment:i,...a}=r;Object.keys(a).length>0&&(e[o]=uo(a,t));continue}e[o]=uo(r,t)}const n=e.type;return t.regenerateIds&&typeof n=="string"&&n!=="doc"&&n!=="text"&&(e.id=G()),e}function dg(s){return s.map(t=>uo(t,{regenerateIds:!0}))}const gg=["borders","align","styleId","direction","_emptyTextMarks"],ug=["id","heading","oxmlAttrs",...wl],hg=["pagination"],fg=[...xl("paragraph"),...hg].filter(s=>!gg.includes(s)&&!ug.includes(s));function ia(s,t){for(const e of fg){const n=rt(s,e);n!=null&&t.setAttribute(e,n)}}const ho=new Set(["aiGenerated","insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove","proposalId","toolCallId","toolType","diffSegmentIndex","__htmlClassName"]),pg=["insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove"];function aa(s,t){if(!s)return[];const e=!!s.footnoteRef,n=[];for(const[o,r]of Object.entries(s))r===void 0||r===!1||r===null||ho.has(o)||o==="link"&&t.excludeLink||o==="comment"&&t.excludeComment||o!=="footnoteRef"&&(o==="superscript"&&e||n.push([o,r]));return n}function Tr(s){const{explicitMarks:t,inheritedMarks:e,emptyParagraphMarks:n,exitingLink:o=!1,exitingComment:r=!1,noteBodyFontSize:i,suggestionMarks:a}=s,l={},c=[],d=f=>{c.includes(f)||c.push(f)},g=f=>l[f]!==void 0,u=f=>c.includes(f);if(t){for(const[f,h]of Object.entries(t))h===!1?d(f):h!=null&&(l[f]=h);l.footnoteRef&&(delete l.footnoteRef,e?.footnoteRef&&delete l.superscript)}for(const[f,h]of aa(e,{excludeLink:o,excludeComment:r}))!g(f)&&!u(f)&&(l[f]=h);e?.footnoteRef&&!l.footnoteRef&&(d("footnoteRef"),l.superscript||d("superscript"));for(const[f,h]of aa(n,{excludeLink:o,excludeComment:r}))!g(f)&&!u(f)&&(l[f]=h);if(i!=null&&l.fontSize===void 0&&!u("fontSize")&&(l.fontSize=i),o&&!l.link&&d("link"),r&&!l.comment&&d("comment"),a)Object.assign(l,a);else if(e){const f=e;for(const h of pg)f[h]!==void 0&&f[h]!==null&&d(h)}return{marksToApply:l,marksToRemove:c}}function la(s,t,e,n){if(lt(s,t,e),Object.keys(n.marksToApply).length>0&&at(s,t,e.length,n.marksToApply),n.marksToRemove.length>0){const o={};for(const r of n.marksToRemove)o[r]=null;at(s,t,e.length,o)}}function Cr(s,t,e){const n=vs(t,e,Qt(s.getDocument().children));s.transact(()=>{const o=s.getYChromeFragment();Pr(o,i=>i.getAttribute("sectionIndex")===void 0);for(const i of n)o.push([s.blockToYjsElement(i)]);const r=s.ydoc.getMap("metadata");r.delete("headers"),r.delete("footers")})}function ca(s){return hs(s.getDocument().chrome??[])}function Pr(s,t){for(let e=s.length-1;e>=0;e--){const n=s.get(e);n instanceof I.XmlElement&&t(n)&&s.delete(e,1)}}function mg(s,t,e,n){const o=Qt(s.getDocument().children),r=vs(e,n,o).map(i=>({...i,sectionIndex:t}));s.transact(()=>{const i=s.getYChromeFragment();Pr(i,a=>a.getAttribute("sectionIndex")===String(t));for(const a of r)i.push([s.blockToYjsElement(a)])})}function bg(s,t){return Tl(s.getDocument().chrome??[],t)}function Mr(s,t,e,n){const o=(s.getDocument().chrome??[]).find(i=>i.type==="header-footer"&&i.side===t&&i.slot===e&&i.sectionIndex===n);if(o)return o;const r=xs(t,e,void 0,Qt(s.getDocument().children),n);return s.transact(()=>{s.getYChromeFragment().push([s.blockToYjsElement(r)])}),r}function yg(s){const t=s.getYContentFragment(),e=[];for(const r of t.toArray())r instanceof I.XmlElement&&r.nodeName==="header-footer"&&e.push(r);const n=s.getYChromeFragment();if(e.length===0&&n.length<=3){da(s);return}const o=s.getYChromeFragment();s.transact(()=>{for(const i of e){const a=s.getDocument().children.find(l=>l.type==="header-footer"&&l.id===i.getAttribute("id"));a&&o.push([s.blockToYjsElement(a)])}const r=t.toArray();for(let i=r.length-1;i>=0;i--){const a=r[i];a instanceof I.XmlElement&&a.nodeName==="header-footer"&&t.delete(i,1)}}),da(s)}function da(s){const t=s.getYChromeFragment(),e=new Map,n=[],o=t.toArray(),r=s.getDocument().chrome??[],i=a=>{const l=r.find(c=>c.id===a);return!!(l&&As(l))};o.forEach((a,l)=>{if(!(a instanceof I.XmlElement)||a.nodeName!=="header-footer")return;const c=`${a.getAttribute("side")}:${a.getAttribute("slot")}:${a.getAttribute("sectionIndex")??""}`,d=e.get(c);if(d===void 0){e.set(c,l);return}const g=o[d];!i(g.getAttribute("id"))&&i(a.getAttribute("id"))?(n.push(d),e.set(c,l)):n.push(l)}),n.length!==0&&s.transact(()=>{for(const a of n.sort((l,c)=>c-l))t.delete(a,1)})}function kg(s){const t=s.ydoc.getMap("metadata"),e=t.get("headers"),n=t.get("footers");!e&&!n||((s.getDocument().chrome?.length??0)>0?s.transact(()=>{t.delete("headers"),t.delete("footers")}):Cr(s,e,n))}function Sg(s,t,e="bottom-right"){const n=(s.getDocument().chrome??[]).filter(c=>c.type==="header-footer"&&c.slot==="default"&&c.sectionIndex===void 0),o=c=>{const d=Pl(c);return!d||d.children.every(g=>g.type==="text"&&(g.marks?.field==="page"||g.text.trim()===""))},r=new Set(n.filter(o).map(c=>c.side)),i=t?ws(e):void 0,a=i?.side==="headers"?"header":"footer",l=!!i&&!n.some(c=>c.side===a&&!o(c));!r.size&&!l||s.transact(()=>{const c=s.getYChromeFragment();Pr(c,d=>d.nodeName==="header-footer"&&d.getAttribute("slot")==="default"&&Br(d)===void 0&&r.has(d.getAttribute("side"))),i&&l&&c.push([s.blockToYjsElement(xs(a,"default",Cl([i.paragraph]),Qt(s.getDocument().children)))])})}function Ig(s){const t=s.ydoc.getMap("metadata");if(t.get(Gt.showPageNumbers)!==!0)return;const e=t.get(Gt.pageNumberPosition)??"bottom-right",{headers:n={},footers:o={}}=ca(s),r=ws(e),i=r.side==="headers"?n:o;if(s.transact(()=>{t.set(Gt.showPageNumbers,!1)}),!i.default){const a={...i,default:[r.paragraph]};Cr(s,r.side==="headers"?a:n,r.side==="footers"?a:o)}}function vg(s,t){const e=t?{fontFamily:t}:{},n=[];for(const o of s.split(/(\{PAGE\}|\{PAGES\})/))o&&(o==="{PAGE}"?n.push({type:"text",text:"1",marks:{field:"page",...e}}):o==="{PAGES}"?n.push({type:"text",text:"1",marks:{field:"numPages",...e}}):n.push({type:"text",text:o,...t?{marks:{...e}}:{}}));return n.length===0&&n.push({type:"text",text:"",...t?{marks:{...e}}:{}}),n}function xg(s){return s.toArray().every(t=>t instanceof I.XmlText?t.length===0:t instanceof I.XmlElement?t.toArray().every(e=>e instanceof I.XmlText?e.toDelta().every(n=>typeof n.insert=="string"&&n.insert.length===0):!1):!0)}function Br(s){const t=s.getAttribute("sectionIndex");if(t==null||t==="")return;const e=Number(t);return Number.isFinite(e)?e:void 0}function ga(s){return JSON.stringify((s.getDocument().chrome??[]).map(t=>t.type==="header-footer"?{side:t.side,slot:t.slot,sectionIndex:t.sectionIndex,children:t.children.map(e=>({align:e.align,children:e.children}))}:t.type))}function wg(s,t){const{side:e,sectionIndex:n}=t,o=s.getYChromeFragment();if(t.clear){const h=[];o.toArray().forEach((m,y)=>{m instanceof I.XmlElement&&m.nodeName==="header-footer"&&m.getAttribute("side")===e&&(t.slot===void 0||m.getAttribute("slot")===t.slot)&&(n===void 0||Br(m)===n)&&h.push(y)});const p=(t.slot!==void 0&&t.slot!=="default"||n!==void 0)&&o.toArray().some((m,y)=>m instanceof I.XmlElement&&m.nodeName==="header-footer"&&m.getAttribute("side")===e&&!h.includes(y));return p&&h.length>0&&h.every(m=>{const y=o.get(m);return y instanceof I.XmlElement&&xg(y)})?{changed:!1,removedCount:0}:h.length===0?p?(Mr(s,e,t.slot??"default",n),{changed:!0,removedCount:0,createdEmpty:!0}):{changed:!1,removedCount:0}:(s.transact(()=>{for(const m of h.reverse())o.delete(m,1)}),{changed:!0,removedCount:h.length})}const r=t.slot??"default",i=t.zones??{},a=[];if(typeof i.left=="string"&&a.push([0,i.left]),typeof i.center=="string"&&a.push([1,i.center]),typeof i.right=="string"&&a.push([2,i.right]),a.length===0)return{changed:!1,removedCount:0};const l=ga(s),c=()=>{for(const h of o.toArray())if(h instanceof I.XmlElement&&h.nodeName==="header-footer"&&h.getAttribute("side")===e&&h.getAttribute("slot")===r&&Br(h)===n)return h;return null},d=a.every(([,h])=>h==="");let g=!1;if(!c()&&d){if(!((r!=="default"||n!==void 0)&&o.toArray().some(h=>h instanceof I.XmlElement&&h.nodeName==="header-footer"&&h.getAttribute("side")===e)))return{changed:!1,removedCount:0};g=!0}Mr(s,e,r,n);const u=c();if(!u)return{changed:!1,removedCount:0};if(g)return{changed:!0,removedCount:0,createdEmpty:g};const f=Qt(s.getDocument().children);return s.transact(()=>{for(const[h,p]of a){const m=(s.getDocument().chrome??[]).find(k=>k.type==="header-footer"&&k.side===e&&k.slot===r&&k.sectionIndex===n)?.children[h],y=Al[h],b={type:"paragraph",id:m?.id??G(),children:vg(p,f),...m?.align??y?{align:m?.align??y}:{}};u.get(h)&&u.delete(h,1),u.insert(h,[s.blockToYjsElement(b)])}}),{changed:ga(s)!==l,removedCount:0}}function Ag(s,t,e){const n=e!==void 0?[e]:["default","first","even"];let o=0;return s.transact(()=>{for(const r of n){const i=Ss(s.ydoc,t,r);i.length!==0&&(o+=i.length,Is(s.ydoc,t,r,[]))}}),o}function Tg(s,t){const e=Ss(s.ydoc,t.side,t.slot);return JSON.stringify(e)===JSON.stringify([t])?!1:(s.transact(()=>{Is(s.ydoc,t.side,t.slot,[t])}),!0)}function se(s){return s.ydoc?s.ydoc.getMap("comments"):null}function Cg(s){const t=se(s);if(!t)return[];const e=[];return t.forEach(n=>{n&&typeof n=="object"&&e.push(n)}),e.sort((n,o)=>(n.createdAt??"").localeCompare(o.createdAt??"")),e}function ua(s){const t=s.getAttribute("structuralSuggestionKind")==="insert"?s.getAttribute("structuralSuggestionId"):s.getAttribute("diffState")==="insert"?s.getAttribute("suggestionId"):void 0;return typeof t=="string"?t:void 0}function Pg(s,t){if(!s.ydoc||t.length===0)return[];const e=new Set(t),n=[],o=(r,i)=>{for(const a of r.toArray()){if(a instanceof I.XmlElement){const g=ua(a);o(a,typeof g=="string"&&e.has(g)?g:i);continue}if(!(a instanceof I.XmlText)||!(r instanceof I.XmlElement))continue;const l=r.getAttribute("id");if(typeof l!="string")continue;let c=0,d=0;for(const g of st(a)){if(typeof g.insert!="string")continue;const u=g.insert.length,f=d+(g.attributes?.deletion?0:u),h=g.attributes?.suggestionId??i,p=!g.attributes?.suggestionId&&!!i;if(u>0&&typeof h=="string"&&e.has(h)){const m=n[n.length-1];m?.blockId===l&&m.suggestionId===h&&!!m.structural===p&&m.end===c?(m.end+=u,m.projectedEnd=f):n.push({blockId:l,suggestionId:h,start:c,end:c+u,projectedStart:d,projectedEnd:f,...p?{structural:!0}:{}})}c+=u,d=f}c===0&&i&&n.push({blockId:l,suggestionId:i,start:0,end:0,projectedStart:0,projectedEnd:0,structural:!0})}};return o(s.getYContentFragment()),o(s.ydoc.getXmlFragment("notes")),o(s.ydoc.getXmlFragment("chrome")),n}function Er(s,t,e,n){return{id:gt(),author:e?.author??"Anonymous",...e?.initials?{initials:e.initials}:{},...e?.authorId?{authorId:e.authorId}:{},...e?.authorImageUrl?{authorImageUrl:e.authorImageUrl}:{},...e?.authorType?{authorType:e.authorType}:{},...e?.agentName?{agentName:e.agentName}:{},...e?.agentModel?{agentModel:e.agentModel}:{},...e?.suggestionId?{suggestionId:e.suggestionId}:{},...e?.mentions?.length?{mentions:e.mentions}:{},...e?.citations?.length?{citations:e.citations.map(o=>({...o}))}:{},...e?.anchorBlockId?{anchorBlockId:e.anchorBlockId}:{},...e?.agentRequestId?{agentRequestId:e.agentRequestId}:{},...e?.agentConversationId?{agentConversationId:e.agentConversationId}:{},...e?.agentTriggerIds?.length?{agentTriggerIds:[...e.agentTriggerIds]}:{},...e?.relatedSuggestionIds?.length?{relatedSuggestionIds:[...e.relatedSuggestionIds]}:{},createdAt:new Date().toISOString(),bodyMd:t,...n?{parentId:n}:{}}}function ha(s,t,e,n){const o=se(s);if(!o||!Z(s.ydoc,t))return null;const r=Er(s,e,{...n,anchorBlockId:t});return s.transact(()=>{o.set(r.id,r)}),r.id}function Mg(s,t,e,n,o){const r=Z(s.ydoc,t),i=r?ct(r):null;if(!i||n<=e||e>=i.length)return!1;const a=Math.min(n,i.length),l=st(i);let c=0,d=!1;for(const g of l){if(typeof g.insert!="string")continue;const u=c,f=c+g.insert.length;c=f;const h=Math.max(u,e),p=Math.min(f,a);if(p<=h)continue;const m=g.attributes?.comment,y=m?m.split(","):[];y.includes(o)||y.push(o),at(i,h,p-h,{comment:y.join(",")}),d=!0}return d}function Bg(s,t,e,n,o,r){return Nr(s,[{blockId:t,start:e,end:n}],o,r)}function Nr(s,t,e,n){const o=se(s);if(!o||t.length===0)return null;const r=Er(s,e,n),i=r.id;let a=!1;return s.transact(()=>{for(const l of t)a=Mg(s,l.blockId,l.start,l.end,i)||a;a&&o.set(i,r)}),a?i:null}function Eg(s,t,e,n){const o=se(s);if(!o||!o.has(t))return null;const r=Er(s,e,n,t);return s.transact(()=>{o.set(r.id,r)}),r.id}function Ng(s,t,e){const n=se(s),o=n?.get(t);return!n||!o?!1:(s.transact(()=>{n.set(t,{...o,resolved:e})}),!0)}function Lg(s,t,e){const n=se(s);if(!n)return 0;const o=new Set(t);if(o.size===0)return 0;const r=[];return n.forEach(i=>{const a=i;if(!a||typeof a!="object"||a.parentId||a.resolved)return;const l=[];typeof a.suggestionId=="string"&&a.suggestionId.length>0&&l.push(a.suggestionId);for(const c of a.relatedSuggestionIds??[])l.includes(c)||l.push(c);l.length!==0&&l.some(c=>o.has(c))&&(l.some(c=>e(c))||r.push(a))}),r.length===0?0:(s.transact(()=>{for(const i of r)n.set(i.id,{...i,resolved:!0})}),r.length)}function Fg(s,t){const e=se(s);if(!e)return 0;const n=[];if(e.forEach(l=>{const c=l;c&&typeof c=="object"&&!c.parentId&&!c.resolved&&typeof c.suggestionId=="string"&&c.suggestionId.length>0&&(!t(c.suggestionId)||c.relatedSuggestionIds?.some(d=>!t(d)))&&n.push(c)}),n.length===0)return 0;const o=new Map,r=(l,c)=>{for(const d of l.toArray()){if(d instanceof I.XmlElement){const g=ua(d);r(d,g&&t(g)?g:c);continue}if(d instanceof I.XmlText)for(const g of st(d)){const u=g.attributes?.comment,f=g.attributes?.suggestionId??c;if(!(!u||!f))for(const h of u.split(",")){const p=o.get(h)??[];p.includes(f)||p.push(f),o.set(h,p)}}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}const i=l=>{const c=Array.from(new Set([...l.suggestionId?[l.suggestionId]:[],...o.get(l.id)??[],...l.relatedSuggestionIds??[]])).filter(t);if(c.length>0)return c;if(l.anchorBlockId){let d=Z(s.ydoc,l.anchorBlockId)??null;for(;d;){if(d instanceof I.XmlElement){const g=d.getAttribute("structuralSuggestionId");if(typeof g=="string"&&t(g))return[g];for(const u of["structuralSuggestionRecord","structuralSuggestionRecords"]){const f=d.getAttribute(u);if(typeof f=="string")try{const h=JSON.parse(f),p=(Array.isArray(h)?h:[h]).find(m=>typeof m?.id=="string"&&t(m.id));if(p)return[p.id]}catch{}}}d=d.parent}}return[]};let a=0;return s.transact(()=>{for(const l of n){const c=i(l);if(c.length===0)continue;const d={...l,suggestionId:c[0]};c.length>1?d.relatedSuggestionIds=c:delete d.relatedSuggestionIds,e.set(l.id,d),a+=1}}),a}function Og(s,t){const e=se(s);if(!e||!e.has(t))return!1;const n=new Set([t]);let o=!0;for(;o;)o=!1,e.forEach((r,i)=>{const a=r;a?.parentId&&n.has(a.parentId)&&!n.has(i)&&(n.add(i),o=!0)});return s.transact(()=>{for(const i of n)e.delete(i);const r=i=>{for(const a of i.toArray()){if(a instanceof I.XmlElement){r(a);continue}if(!(a instanceof I.XmlText))continue;let l=0;for(const c of st(a)){if(typeof c.insert!="string")continue;const d=c.insert.length,g=c.attributes?.comment;if(g){const u=g.split(",").filter(f=>!n.has(f));u.length!==g.split(",").length&&at(a,l,d,{comment:u.length>0?u.join(","):null})}l+=d}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function fa(s,t){const e=d=>d.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&");if(!s.includes("<")||!s.includes(">"))return[{type:"text",text:e(s),marks:{...t}}];const n=[],o={},r=d=>{d&&n.push({type:"text",text:e(d),marks:{...o,...t}})},i=/<(\/?)(i|em|b|strong|u|a)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;let a=0,l;for(;(l=i.exec(s))!==null;){r(s.slice(a,l.index)),a=i.lastIndex;const d=l[1]==="/",g=l[2].toLowerCase();if(g==="i"||g==="em")d?delete o.italic:o.italic=!0;else if(g==="b"||g==="strong")d?delete o.bold:o.bold=!0;else if(g==="u")d?delete o.underline:o.underline=!0;else if(g==="a")if(d)delete o.link;else{const u=/href="([^"]*)"/.exec(l[3]??"");u?.[1]&&(o.link=e(u[1]))}}r(s.slice(a));const c=n.map(d=>({...d,text:d.text.replace(/<[^>]{1,80}>/g,"")})).filter(d=>d.text.length>0);return c.length>0?c:[{type:"text",text:e(s),marks:{...t}}]}function $e(s){const t=[],e=n=>{for(const o of n.toArray()){if(o instanceof I.XmlElement){if(o.nodeName==="footnote")continue;e(o);continue}if(!(o instanceof I.XmlText))continue;let r=0;for(const i of st(o)){if(typeof i.insert!="string")continue;const a=i.attributes??{};typeof a.footnoteRef=="string"&&a.footnoteRef&&t.push({yText:o,start:r,length:i.insert.length,text:i.insert,attributes:a,footnoteId:a.footnoteRef}),r+=i.insert.length}}};try{e(s.getYContentFragment())}catch{}return t}function ke(s){const t=new Map,e=n=>{for(const o of n.toArray())if(o instanceof I.XmlElement&&o.nodeName==="footnote"){const r=o.getAttribute("id");typeof r=="string"&&r&&t.set(r,o)}};try{e(s.getYNotesFragment()),e(s.getYContentFragment())}catch{}return t}function Rg(s,t){const e=[...s.notes??[],...s.children.filter(n=>n.type==="footnote")];for(const n of e)if(n.id===t||W(n,t))return!0;return!1}function Lr(s){const t=new Map;for(const[e,n]of ke(s))t.set(e,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return t}function Dg(s){const t=[];for(const a of $e(s))t.includes(a.footnoteId)||t.push(a.footnoteId);const e=Lr(s),n=new Map,o=s.getDocument();for(const a of[...o.notes??[],...o.children.filter(l=>l.type==="footnote")])n.set(a.id,a);const r={footnote:0,endnote:0},i=[];for(const a of t){const l=n.get(a);if(!l)continue;const c=e.get(a)??"footnote";r[c]+=1,i.push({footnote:l,number:r[c],display:Mo(r[c],c),kind:c})}return i}function Se(s){const t=$e(s);if(t.length===0)return!1;const e=Lr(s),n=new Map,o={footnote:0,endnote:0};for(const i of t)if(!n.has(i.footnoteId)){const a=e.get(i.footnoteId)??"footnote";o[a]+=1,n.set(i.footnoteId,Mo(o[a],a))}const r=t.filter(i=>i.text!==n.get(i.footnoteId));return r.length===0?!1:(s.transact(()=>{for(const i of[...r].sort((a,l)=>l.start-a.start)){const a=n.get(i.footnoteId)??"";i.yText.delete(i.start,i.length),lt(i.yText,i.start,a,i.attributes)}}),!0)}function $g(s){pa(s);const t=$e(s),e=ke(s);if(t.length===0&&e.size===0)return;const n=new Set(t.map(o=>o.footnoteId));s.transact(()=>{for(const[o,r]of e)if(!n.has(o)&&!r.getAttribute("structuralSuggestionId")){const i=r.parent;if(i){const a=i.toArray().indexOf(r);a>=0&&i.delete(a,1)}}for(const o of[...t].sort((r,i)=>i.start-r.start))e.has(o.footnoteId)||o.yText.delete(o.start,o.length)}),Se(s)}function pa(s){let t;try{t=s.getYContentFragment()}catch{return!1}const e=[],n=d=>{for(const g of d.toArray()){if(g instanceof I.XmlElement){n(g);continue}if(!(g instanceof I.XmlText))continue;let u=0;for(const f of st(g)){if(typeof f.insert!="string")continue;const h=f.attributes??{};typeof h.footnotePendingBody=="string"&&e.push({yText:g,start:u,length:f.insert.length,footnoteId:typeof h.footnoteRef=="string"&&h.footnoteRef?h.footnoteRef:G(),body:h.footnotePendingBody,kind:h.footnotePendingKind==="endnote"?"endnote":"footnote",fontFamily:typeof h.fontFamily=="string"?h.fontFamily:void 0,suggestionId:typeof h.suggestionId=="string"?h.suggestionId:void 0,suggested:h.insertion===!0}),u+=f.insert.length}}};if(n(t),e.length===0)return!1;const o=ke(s),r=new Set($e(s).map(d=>d.footnoteId)),i=s.getDocument(),a=new Map;for(const d of[...i.notes??[],...i.children.filter(g=>g.type==="footnote")])a.set(d.id,d.children.flatMap(g=>g.type==="paragraph"?g.children:[]).map(g=>g.type==="text"?g.text:"").join(""));const l=new Set;for(const d of e)if(!o.has(d.footnoteId)){for(const[g,u]of a)if(u===d.body&&!r.has(g)&&!l.has(g)&&o.has(g)){d.footnoteId=g,l.add(g);break}}const c=Qt(s.getDocument().children);return s.transact(()=>{for(const d of e){if(at(d.yText,d.start,d.length,{footnotePendingBody:null,footnotePendingKind:null,footnoteRef:d.footnoteId,superscript:!0}),o.has(d.footnoteId)){if(a.get(d.footnoteId)!==d.body){const p=o.get(d.footnoteId);let m=null;for(const b of p.toArray())if(b instanceof I.XmlElement&&b.nodeName==="paragraph"){m=b;break}const y=m?ct(m):null;if(y){const b=d.fontFamily??c;y.length>0&&y.delete(0,y.length);let k=0;for(const S of fa(d.body,{fontSize:ge,...b?{fontFamily:b}:{}}))lt(y,k,S.text,S.marks),k+=S.text.length}}continue}const g=d.fontFamily??c,u={fontSize:ge,...g?{fontFamily:g}:{}},f={type:"footnote",id:d.footnoteId,...d.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:G(),children:fa(d.body,u)}]},h=s.blockToYjsElement(f);h.setAttribute("id",d.footnoteId),d.kind==="endnote"&&h.setAttribute("noteKind","endnote"),d.suggested&&d.suggestionId&&s.suggestions.setElementStructuralSuggestion(h,"insert",void 0,d.suggestionId,"Insert footnote"),s.getYNotesFragment().push([h]),o.set(d.footnoteId,h)}}),Se(s),!0}function jg(s){let t;try{t=s.getYContentFragment()}catch{return}const e=[];for(const i of t.toArray())i instanceof I.XmlElement&&i.nodeName==="footnote"&&e.push(i);if(e.length===0)return;const n=s.getYNotesFragment(),o=s.getDocument(),r=new Map([...o.notes??[],...o.children.filter(i=>i.type==="footnote")].map(i=>[i.id,i]));s.transact(()=>{for(const a of e){const l=a.getAttribute("id"),c=typeof l=="string"?r.get(l):void 0;c&&n.push([s.blockToYjsElement(c)])}const i=t.toArray();for(let a=i.length-1;a>=0;a--){const l=i[a];l instanceof I.XmlElement&&l.nodeName==="footnote"&&t.delete(a,1)}}),Se(s)}function _g(s,t,e,n,o="footnote"){if(!s.ydoc)return null;const r=G(),i=s.suggestions.isSuggesting(),a=i?gt():void 0,l=Lr(s),c=new Set($e(s).map(m=>m.footnoteId).filter(m=>(l.get(m)??"footnote")===o)).size,d=Mo(c+1,o);let g,u;{const m=W(s.getDocument(),t.block);if(m&&m.type==="paragraph"){u=m.direction;let y=0;for(const b of m.children){if(b.type!=="text")continue;const k=y+b.text.length;if(t.offset<=k&&b.marks?.fontFamily){g=b.marks.fontFamily;break}y=k}}}const f={footnoteRef:r,superscript:!0,...g?{fontFamily:g}:{},...i&&a?{insertion:!0,...s.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!s.insertTextNodes(t,[{type:"text",text:d,marks:f}],n))return null;const h=g??Qt(s.getDocument().children),p={fontSize:ge,...h?{fontFamily:h}:{}};return s.transact(()=>{const m={type:"footnote",id:r,...o==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:G(),...u?{direction:u}:{},children:[{type:"text",text:e||"",marks:p}]}]},y=s.blockToYjsElement(m);if(y.setAttribute("id",r),o==="endnote"&&y.setAttribute("noteKind","endnote"),i&&a&&s.suggestions.setElementStructuralSuggestion(y,"insert",void 0,a,"Insert footnote"),s.getYNotesFragment().push([y]),!e){const b=y.toArray()[0];b instanceof I.XmlElement&&b.setAttribute("_emptyTextMarks",JSON.stringify(p))}}),Se(s),{footnoteId:r,...a?{suggestionId:a}:{}}}function Xg(s,t,e){const n=ke(s).get(t);if(!n)return!1;let o=null;for(const c of n.toArray())if(c instanceof I.XmlElement&&c.nodeName==="paragraph"){o=c;break}if(!o)return!1;const r=ct(o);if(!r)return!1;const i=s.getDocument(),a=[...i.notes??[],...i.children.filter(c=>c.type==="footnote")].find(c=>c.id===t)?.children.flatMap(c=>c.type==="paragraph"?c.children:[]).find(c=>c.type==="text"&&c.marks?.fontFamily)?.marks?.fontFamily??Qt(s.getDocument().children),l={fontSize:ge,...a?{fontFamily:a}:{}};return s.transact(()=>{r.length>0&&r.delete(0,r.length),e.length>0?lt(r,0,e,l):o.setAttribute("_emptyTextMarks",JSON.stringify(l))}),!0}function Ug(s,t,e,n,o=!1){if(!e)return{success:!1,replacements:0,error:"The text to find must not be empty."};let r=null;const i=b=>{if(!r){for(const k of b.toArray())if(k instanceof I.XmlElement){if(k.getAttribute("id")===t){r=k;return}i(k)}}};for(const b of ke(s).values()){if(b.getAttribute("id")===t){r=b;break}if(i(b),r)break}if(!r)return{success:!1,replacements:0,error:`Note block '${t}' was not found.`};const a=ct(r);if(!a)return{success:!1,replacements:0,error:`Note block '${t}' does not contain editable text.`};let l="";const c=[];let d=0;for(const b of st(a))if(typeof b.insert=="string"){if(!b.attributes?.deletion){for(let k=0;k<b.insert.length;k+=1)c.push(d+k);l+=b.insert}d+=b.insert.length}const g=[];let u=0;for(;u<=l.length-e.length;){const b=l.indexOf(e,u);if(b<0)break;const k=c[b];if(c[b+e.length-1]-k!==e.length-1)return{success:!1,replacements:0,error:`${JSON.stringify(e)} in note block '${t}' runs across a pending tracked deletion. Replace a smaller piece that doesn't span it, or settle that change first.`};g.push(k),u=b+e.length}if(g.length===0)return{success:!1,replacements:0,error:`No match found for ${JSON.stringify(e)} in note block '${t}'.`};if(!o&&g.length>1)return{success:!1,replacements:0,error:`Found ${g.length} matches for ${JSON.stringify(e)} in note block '${t}'. Include more surrounding context so it matches exactly one location, or use replace_all.`};const f=o?g:g.slice(0,1),h=s.suggestions.isSuggesting()?gt():null,p=h?s.suggestions.buildInlineMetadataMarks(h,"Replace footnote text"):null,m=b=>{let k=0;for(const S of st(a)){if(typeof S.insert!="string")continue;const v=k+S.insert.length;if(b<v){const x={...S.attributes??{}};return delete x.insertion,delete x.deletion,delete x.suggestionId,delete x.suggestionLabel,delete x.suggestionCreatedAt,x}k=v}return{fontSize:ge}},y=new Map(f.map(b=>[b,m(b)]));return s.transact(()=>{for(const b of[...f].reverse()){const k=y.get(b)??{fontSize:ge};h&&p?(at(a,b,e.length,{deletion:!0,...p}),n&&lt(a,b,n,{...k,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(b,e.length),n&&lt(a,b,n,k))}}),{success:!0,replacements:f.length,...h?{suggestionId:h}:{}}}function zg(s,t){const e=ke(s);return e.size===0?!1:(s.transact(()=>{for(const n of e.values())t==="endnote"?n.setAttribute("noteKind","endnote"):n.removeAttribute("noteKind")}),Se(s),!0)}function Wg(s,t){const e=$e(s).filter(o=>o.footnoteId===t),n=ke(s).get(t);if(e.length===0&&!n)return!1;if(s.suggestions.isSuggesting()){const o=gt();return s.transact(()=>{for(const r of e)at(r.yText,r.start,r.length,{deletion:!0,...s.suggestions.buildInlineMetadataMarks(o,"Delete footnote")});n&&s.suggestions.setElementStructuralSuggestion(n,"delete",void 0,o,"Delete footnote")}),!0}return s.transact(()=>{for(const o of[...e].sort((r,i)=>i.start-r.start))o.yText.delete(o.start,o.length);if(n){const o=n.parent;if(o){const r=o.toArray().indexOf(n);r>=0&&o.delete(r,1)}}}),Se(s),!0}function ma(s,t,e){const n=a=>{const l=new Map;for(const c of a)c.id&&l.set(c.id,(l.get(c.id)??0)+1);return l},o=n(s),r=n(t),i=a=>a.id&&o.get(a.id)===1&&r.get(a.id)===1?`id:${a.id}`:`content:${e(a)}`;return{beforeKeys:s.map(i),afterKeys:t.map(i)}}function Fr(s,t){const e=s.length,n=t.length,o=Array.from({length:e+1},()=>Array(n+1).fill(0));for(let l=1;l<=e;l++)for(let c=1;c<=n;c++)s[l-1]===t[c-1]?o[l][c]=o[l-1][c-1]+1:o[l][c]=Math.max(o[l-1][c],o[l][c-1]);const r=[];let i=e,a=n;for(;i>0&&a>0;)s[i-1]===t[a-1]?(r.unshift(s[i-1]),i-=1,a-=1):o[i-1][a]>o[i][a-1]?i-=1:a-=1;return r}function ba(s){let t=s,e=null;for(;t;){if(t instanceof I.XmlElement){const n=t.nodeName,o=t.getAttribute("id");if(n==="paragraph"&&o)return{blockId:o,offset:0};if(n==="list-item"&&(e=t),n==="list"&&o&&e){let r=0;for(let i=0;i<t.length;i++){const a=t.get(i);if(a===e)return{blockId:o,offset:r};if(a instanceof I.XmlElement&&a.nodeName==="list-item"){for(let l=0;l<a.length;l++){const c=a.get(l);if(c instanceof I.XmlText){r+=c.length;break}}r+=1}}return{blockId:o,offset:0}}}t=t.parent}return null}function Jg(s,t,e,n){const o=s.getArray("paragraphs"),r=o.toArray().findIndex(a=>a?.get("id")===t);if(r<0)return null;const i=o.get(r);if(!i)return null;if(e==="paragraph")return i.get("content");if(e==="list"&&n!==void 0){const a=i.get("items");return!a||n>=a.length?null:a.get(n)?.get("content")}return null}function Hg(s,t,e,n){const o=Z(s,t);if(!o)return null;if(e==="paragraph"||e==="list-item")return ct(o);if(e==="list"&&n!==void 0){let r=0;for(let i=0;i<o.length;i++){const a=o.get(i);if(a instanceof I.XmlElement&&a.nodeName==="list-item"){if(r===n)return ct(a);r++}}}return null}function ya(s,t,e,n){return Hg(s,t,e,n)||(Te(s)?Jg(s,t,e,n):null)}function ie(s,t,e){const n=W(e,s.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const o=n,r=ya(t,n.id,"paragraph");if(!r)return null;const i=o.children.filter(c=>c.type==="text").reduce((c,d)=>c+d.text.length,0),a=Math.max(0,Math.min(s.offset,i)),l=I.createRelativePositionFromTypeIndex(r,a);return{blockId:n.id,textOffset:l}}if(n.type==="list"){const o=n;let r=-1,i=s.offset;if(s.offset,s.block!==n.id){let d=0;for(let g=0;g<o.children.length;g++){if(o.children[g].id===s.block){r=g,d+s.offset;break}d+=Fn(o.children[g]),g<o.children.length-1&&(d+=1)}}if(r===-1){let d=s.offset;for(let g=0;g<o.children.length;g++){const u=Fn(o.children[g]),f=g<o.children.length-1?1:0;if(d<=u){r=g,i=d;break}d-=u+f,g===o.children.length-1&&(r=g,i=u)}}r===-1&&(r=0,i=0);const a=ya(t,n.id,"list",r);if(!a)return null;const l=Math.max(0,Math.min(i,a.length)),c=I.createRelativePositionFromTypeIndex(a,l);return{blockId:n.id,textOffset:c}}return null}function qg(s,t,e){const n=s.getArray("paragraphs");for(let o=0;o<n.length;o++){const r=n.get(o);if(!r)continue;const i=r.get("id");if(!i)continue;const a=r.get("type");if(a==="paragraph"&&r.get("content")===t)return{blockId:i,offset:0,yTextOffset:0};if(a==="list"){const l=r.get("items");if(!l)continue;const c=W(e,i);if(!c||c.type!=="list")continue;const d=c;let g=0;for(let u=0;u<l.length;u++){if(l.get(u)?.get("content")===t)return{blockId:i,offset:g,yTextOffset:0};u<d.children.length&&(g+=Fn(d.children[u]),u<d.children.length-1&&(g+=1))}}}return null}function on(s,t){const e=I.createAbsolutePositionFromRelativePosition(s.textOffset,t);if(!e||!(e.type instanceof I.XmlText))return Z(t,s.blockId)?{block:s.blockId,offset:0}:null;const n=e.index,o=e.type,r=ba(o);if(r)return{block:r.blockId,offset:r.offset+n};if(Te(t)){const i=mt(t),a=qg(t,o,i);if(a)return{block:a.blockId,offset:a.offset+n}}return Z(t,s.blockId)?{block:s.blockId,offset:n}:null}function Y(s,t,e){return{anchor:s.anchor?ie(s.anchor,t,e):null,focus:s.focus?ie(s.focus,t,e):null}}function Or(s,t){return{anchor:s.anchor?on(s.anchor,t):null,focus:s.focus?on(s.focus,t):null}}function Ie(s){if(typeof window>"u")return null;try{return window.localStorage??null}catch(t){return console.warn(`[${s}] localStorage unavailable:`,t),null}}function Yg(s,t){if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return!1;return!0}class Rr{constructor(t,e,n=!1,o){this.destroyed=!1,this.handleDocumentUpdate=()=>{this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null},this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.conversationId=null,this.ydoc=t,this.ydoc.on("update",this.handleDocumentUpdate),this.documentId=e||"default",this.conversationId=o||null,this.disableLocalStorage=n,this.storageKey=this.computeStorageKey();const r=t.getXmlFragment("content");this.undoManager=new I.UndoManager(r,{trackedOrigins:new Set}),this.documentId,this.conversationId,this.storageKey,n?this.clearDocumentProposalCacheIfRemote():this.loadFromLocalStorage(),Kg(this.documentId,this)}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=I.encodeStateAsUpdate(this.ydoc)),this.cachedBaseUpdate}seedForkFromBase(t){return this.cachedBaseUpdateV2||(this.cachedBaseUpdateV2=I.encodeStateAsUpdateV2(this.ydoc)),I.applyUpdateV2(t,this.cachedBaseUpdateV2),t}computeStorageKey(){return this.conversationId?`proposals_${this.documentId}_${this.conversationId}`:`proposals_${this.documentId}`}clearDocumentProposalCacheIfRemote(){if(!this.isLikelyRemoteDocumentId())return;const t=Ie("DetachedSuggestionStore");if(!t)return;const e=`proposals_${this.documentId}`,n=[];for(let o=0;o<t.length;o++){const r=t.key(o);r&&(r===e||r.startsWith(`${e}_`))&&n.push(r)}for(const o of n)t.removeItem(o)}isLikelyRemoteDocumentId(){const t=this.documentId.replace(/-/g,"");return/^[a-z0-9]{16}$/i.test(t)?!0:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.documentId)}getYDoc(){return this.ydoc}getDocumentId(){return this.documentId}getConversationId(){return this.conversationId}setOnSuggestionsChanged(t){this.onProposalsChanged=t}setConversation(t,e){this.conversationId!==t&&(this.conversationId,this.conversationId=t,this.storageKey=this.computeStorageKey(),this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),e&&(Object.keys(e.proposals||{}).length>0||Object.keys(e.metadata||{}).length>0)?(Object.keys(e.proposals||{}).length,this.loadFromServerData(e)):this.disableLocalStorage||this.loadFromLocalStorage(),this.notifyListeners())}serializeForServer(){const t={proposals:{},metadata:{},paragraphSuggestions:{}},e=new Set;for(const[n,o]of this.suggestionMeta)o.status==="pending"&&e.add(n);for(const[n,o]of this.proposals)e.has(n)&&(t.proposals[n]=btoa(String.fromCharCode(...o)));for(const[n,o]of this.suggestionMeta){if(!e.has(n))continue;const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?btoa(String.fromCharCode(...i.from)):i.from,to:i.to?btoa(String.fromCharCode(...i.to)):i.to}))),t.metadata[n]=r}for(const[n,o]of this.paragraphSuggestions){const r=o.filter(i=>e.has(i));r.length>0&&(t.paragraphSuggestions[n]=r)}return t}loadFromServerData(t,e){if(this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),!!t){if(Object.keys(t.proposals||{}).length,Object.keys(t.metadata||{}).length,e?.persistAndNotify,t.proposals)for(const[n,o]of Object.entries(t.proposals)){const r=Uint8Array.from(atob(o),i=>i.charCodeAt(0));this.proposals.set(n,r)}if(t.metadata)for(const[n,o]of Object.entries(t.metadata)){const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?Uint8Array.from(atob(i.from),a=>a.charCodeAt(0)):i.from,to:i.to?Uint8Array.from(atob(i.to),a=>a.charCodeAt(0)):i.to}))),this.suggestionMeta.set(n,r)}if(t.paragraphSuggestions)for(const[n,o]of Object.entries(t.paragraphSuggestions))this.paragraphSuggestions.set(n,o);e?.persistAndNotify&&(this.saveToLocalStorage(),this.notifyListeners())}}static getOldFormatProposals(t){const e=Ie("DetachedSuggestionStore");if(!e)return null;const n=`proposals_${t}`;try{const o=e.getItem(n);if(!o)return null;const r=JSON.parse(o);return!r.proposals||Object.keys(r.proposals).length===0?null:{proposals:r.proposals||{},metadata:r.metadata||{},paragraphSuggestions:r.paragraphSuggestions||{}}}catch(o){return console.error("[DetachedSuggestionStore] Failed to read old format proposals:",o),null}}static clearOldFormatProposals(t){const e=Ie("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`;try{e.removeItem(n)}catch(o){console.error("[DetachedSuggestionStore] Failed to clear old format proposals:",o)}}static clearAllStoredSuggestions(t){const e=Ie("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`,o=[];for(let r=0;r<e.length;r++){const i=e.key(r);i&&(i===n||i.startsWith(`${n}_`))&&o.push(i)}try{for(const r of o)e.removeItem(r)}catch(r){console.error("[DetachedSuggestionStore] Failed to clear stored proposals for document:",t,r)}}loadFromLocalStorage(){const t=Ie("DetachedSuggestionStore");if(t)try{const e=t.getItem(this.storageKey);if(e){const n=JSON.parse(e);if(Object.keys(n.proposals||{}).length,Object.keys(n.metadata||{}).length,n.proposals)for(const[o,r]of Object.entries(n.proposals)){const i=Uint8Array.from(atob(r),a=>a.charCodeAt(0));this.proposals.set(o,i)}if(n.metadata)for(const[o,r]of Object.entries(n.metadata)){const i=r;i.anchors&&(i.anchors=i.anchors.map(a=>({...a,from:a.from?Uint8Array.from(atob(a.from),l=>l.charCodeAt(0)):a.from,to:a.to?Uint8Array.from(atob(a.to),l=>l.charCodeAt(0)):a.to}))),this.suggestionMeta.set(o,i)}if(n.paragraphSuggestions)for(const[o,r]of Object.entries(n.paragraphSuggestions))this.paragraphSuggestions.set(o,r);Array.from(this.proposals.keys()),Array.from(this.suggestionMeta.keys()),Array.from(this.suggestionMeta.values()).filter(o=>o.status==="pending").length,Array.from(this.suggestionMeta.values()).filter(o=>o.status==="accepted").length,Array.from(this.suggestionMeta.values()).filter(o=>o.status==="rejected").length,Array.from(this.suggestionMeta.values()).map(o=>({id:o.id,status:o.status}))}else this.storageKey}catch(e){console.error("[DetachedSuggestionStore] Failed to load from localStorage:",e)}}saveToLocalStorage(){if(this.disableLocalStorage){this.onProposalsChanged&&this.onProposalsChanged();return}const t=Ie("DetachedSuggestionStore");if(!t){this.onProposalsChanged&&this.onProposalsChanged();return}try{const e={proposals:{},metadata:{},paragraphSuggestions:{}};for(const[n,o]of this.proposals)e.proposals[n]=btoa(String.fromCharCode(...o));for(const[n,o]of this.suggestionMeta){const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?btoa(String.fromCharCode(...i.from)):i.from,to:i.to?btoa(String.fromCharCode(...i.to)):i.to}))),e.metadata[n]=r}for(const[n,o]of this.paragraphSuggestions)e.paragraphSuggestions[n]=o;t.setItem(this.storageKey,JSON.stringify(e)),this.storageKey,Object.keys(e.proposals).length,Object.keys(e.metadata).length,Object.values(e.metadata).filter(n=>n.status==="pending").length,Object.values(e.metadata).filter(n=>n.status==="accepted").length,Object.values(e.metadata).filter(n=>n.status==="rejected").length,Object.keys(e.metadata),this.onProposalsChanged&&this.onProposalsChanged()}catch(e){console.error("[DetachedSuggestionStore] Failed to save to localStorage:",e)}}cleanupOldProposals(){const t=Date.now(),e=24*60*60*1e3;for(const[n,o]of this.suggestionMeta)t-o.createdAt>e&&(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n));this.saveToLocalStorage()}createSuggestion(t,e,n={}){const o=this.seedForkFromBase(new I.Doc),r=I.encodeStateVector(o);let i=[];o.transact(()=>{i=e(o)},"proposal-edit");const a=I.encodeStateAsUpdate(o,r);return this.proposals.set(t,a),this.suggestionMeta.set(t,{id:t,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:i,...n}),this.saveToLocalStorage(),this.notifyListeners(),i.length,t}createSuggestionFromToolCall(t,e){return this.createSuggestion(this.generateId(),n=>e(n,t),{authorType:"ai",toolCallAction:t,description:`AI: ${t.name}`})}createTextDeletion(t,e,n,o,r,i={}){return this.createSuggestion(t,a=>{const l=Z(a,e);if(!l)return console.warn(`Paragraph ${e} not found for text deletion`),[];const c=ct(l);return c?(c.delete(n,o),[{kind:"delete",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(c,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(c,n+o,0)),text:r}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...i,id:t})}createTextInsertion(t,e,n,o,r={},i={}){const a={...r,proposalId:t};return this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return console.warn(`Paragraph ${e} not found for text insertion`),[];const d=ct(c);return d?(lt(d,n,o,a),[{kind:"insert",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...i,id:t})}createTextReplacement(t,e,n,o,r,i={},a,l={}){const c={...i,proposalId:t};return this.createSuggestion(t,d=>{const g=Z(d,e);if(!g)return console.warn(`Paragraph ${e} not found for text replacement`),[];const u=ct(g);return u?(u.delete(n,o),lt(u,n,r,c),[{kind:"replace",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,n+r.length,0)),text:r,oldText:a}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...l,id:t})}createPositionAwareInsertion(t,e,n,o,r={}){const i=this.generateId();return this.suggestionMeta.set(i,{id:i,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...r}),this.saveToLocalStorage(),this.notifyListeners(),n.length,o.length,i}materializeWithSuggestion(t){const e=this.proposals.get(t);if(!e)return null;const n=new I.Doc;return this.seedForkFromBase(n),I.applyUpdate(n,e),n}withMaterializedSuggestion(t,e){const n=this.materializeWithSuggestion(t);return n?e(n):null}expandPositionAwarePredecessors(t){const e=new Map;for(const r of this.suggestionMeta.values()){const i=r.insertionContext;i&&e.set(i.paragraphId,i)}const n=new Set,o=[...t.mustBeAfter];for(;o.length>0;){const r=o.pop();if(n.has(r))continue;n.add(r);const i=e.get(r);i&&o.push(...i.mustBeAfter)}return n}applyPositionAwareInsertionToDoc(t,e,n){const o=n.insertionContext;if(!o)return;const r=this.expandPositionAwarePredecessors(o),i=t.getXmlFragment("content");let a=0;for(let c=i.length-1;c>=0;c--){const d=i.get(c);if(!(d instanceof I.XmlElement))continue;const g=d.getAttribute("id");if(g&&r.has(g)){a=c+1;break}}const l=ka(o.content,o.paragraphId,e);i.insert(a,[l])}materializeWithSuggestions(t){const e=new I.Doc;this.seedForkFromBase(e);for(const n of t){const o=this.suggestionMeta.get(n);if(!(o&&o.status==="accepted"))if(o?.insertionContext)this.applyPositionAwareInsertionToDoc(e,n,o);else{const r=this.proposals.get(n);if(r){const i=I.encodeStateAsUpdate(e);mt(e),I.applyUpdate(e,r);const a=I.encodeStateAsUpdate(e);if(mt(e),!!Yg(i,a)&&o&&o.status==="pending")if(o.toolCallAction?.name==="remove_block"){const l=o.toolCallAction.arguments.id,c=ot(e,l);if(c){const{yParent:d,index:g}=c;d.delete(g,1)}}else o.anchors&&o.anchors.length>0?console.warn("[DetachedSuggestionStore] Anchor-based regeneration not yet implemented for:",n):console.warn("[DetachedSuggestionStore] Cannot regenerate proposal without sufficient metadata:",n)}}}return e}acceptProposal(t){const e=this.suggestionMeta.get(t);if(!e)return!1;if(e.insertionContext){const n=this.acceptPositionAwareInsertion(t,e);return n&&this.recordAction({type:"accept",suggestionId:t,timestamp:Date.now()}),this.notifyListeners(),n}else{const n=this.proposals.get(t);if(!n)return!1;const o=`proposal-${t}`;this.undoManager.trackedOrigins.add(o);const r=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{I.applyUpdate(this.ydoc,n),this.ensureTrailingParagraphInTransaction(r)},o),this.undoManager.stopCapturing(),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage();const i={type:"accept",suggestionId:t,timestamp:Date.now()};return i.suggestionId,this.undoStack.length,this.recordAction(i),this.notifyListeners(),!0}}acceptPositionAwareInsertion(t,e){const n=e.insertionContext,o=this.ydoc.getXmlFragment("content"),r=this.expandPositionAwarePredecessors(n);let i=0;const a=new Set;for(let c=0;c<o.length;c++){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");g&&a.add(g)}}for(let c=o.length-1;c>=0;c--){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");if(g&&r.has(g)){i=c+1;break}}}for(let c=0;c<o.length;c++){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");if(g&&n.mustBeBefore.includes(g)){c<i&&(i=c);break}}}const l=`proposal-${t}`;return this.undoManager.trackedOrigins.add(l),this.ydoc.transact(()=>{const c=ka(n.content,n.paragraphId,t);o.insert(i,[c]),this.ensureTrailingParagraphInTransaction(o)},l),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.notifyListeners(),!0}ensureTrailingParagraph(){const t=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{this.ensureTrailingParagraphInTransaction(t)})}ensureTrailingParagraphInTransaction(t){if(t.length===0)return;const e=t.get(t.length-1);if(!(e instanceof I.XmlElement)||e.nodeName==="paragraph")return;const n=new I.XmlElement("paragraph");n.setAttribute("id",G());const o=new I.XmlText;n.insert(0,[o]),t.insert(t.length,[n])}acceptSuggestions(t){let e=!0;const n=[],o=()=>{if(n.length===0)return;const r=[...n];n.length=0;const i=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{for(const a of r){const l=this.proposals.get(a);l?I.applyUpdate(this.ydoc,l):e=!1}this.ensureTrailingParagraphInTransaction(i)},"accept-proposals");for(const a of r){const l=this.suggestionMeta.get(a);l&&(l.status="accepted",this.suggestionMeta.set(a,l))}};for(const r of t)this.suggestionMeta.get(r)?.insertionContext?(o(),this.acceptProposal(r)||(e=!1)):n.push(r);return o(),this.saveToLocalStorage(),this.notifyListeners(),e}deleteSuggestion(t){this.proposals.delete(t),this.suggestionMeta.delete(t),this.removeProposalFromParagraphs(t),this.saveToLocalStorage()}rejectProposal(t){const e=this.suggestionMeta.get(t);return e?(e.status="rejected",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.notifyListeners(),this.recordAction({type:"reject",suggestionId:t,timestamp:Date.now()}),!0):!1}unrejectProposal(t){const e=this.suggestionMeta.get(t);return!e||e.status!=="rejected"?!1:(e.status="pending",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.recordAction({type:"unreject",suggestionId:t,timestamp:Date.now()}),this.notifyListeners(),!0)}rejectSuggestions(t){let e=!0;for(const n of t)this.suggestionMeta.has(n)?(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n)):e=!1;return this.saveToLocalStorage(),this.notifyListeners(),e}resolveAnchors(t){return this.resolveAnchorsAgainstDoc(t,this.ydoc)}resolveAnchorsAgainstDoc(t,e){const n=this.suggestionMeta.get(t);if(!n||!n.anchors)return[];const o=[];for(const r of n.anchors){const i=r.from?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(r.from),e):null,a=r.to?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(r.to),e):null;o.push({kind:r.kind,paragraphId:r.paragraphId,fromIndex:i?.index??null,toIndex:a?.index??null,text:r.text})}return o}checkConflicts(t){const e=this.suggestionMeta.get(t);if(!e)return"stale";if(e.anchors&&e.anchors.length>0){const n=this.resolveAnchors(t);for(let o=0;o<e.anchors.length;o++){const r=e.anchors[o],i=n[o];if(r.paragraphId&&i.fromIndex===null)return"conflicted"}}try{const n=this.materializeWithSuggestion(t);if(!n)return"stale";const o=wn(this.ydoc),r=wn(n),i=e.anchors?.filter(a=>a.kind==="insert"&&!a.paragraphId).length||0;return Math.abs(r-o)>i+1?"conflicted":"clean"}catch{return"conflicted"}}getAllSuggestions(){return new Map(this.suggestionMeta)}getSuggestion(t){return this.suggestionMeta.get(t)}getSuggestionCount(){return this.suggestionMeta.size}getPendingSuggestions(){const t=new Map;for(const[e,n]of this.suggestionMeta)n.status==="pending"&&t.set(e,n);return t}getParagraphIdsWithPendingProposals(){const t=new Set;for(const[n,o]of this.suggestionMeta)o.status==="pending"&&t.add(n);if(t.size===0)return[];const e=[];for(const[n,o]of this.paragraphSuggestions)!n||o.length===0||o.some(r=>t.has(r))&&e.push(n);return e}clearAllProposals(){this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.disableLocalStorage||Ie("DetachedSuggestionStore")?.removeItem(this.storageKey),this.notifyListeners()}destroy(){this.destroyed||(this.destroyed=!0,this.ydoc.off("update",this.handleDocumentUpdate),this.undoManager.destroy(),this.listeners.clear(),this.onProposalsChanged=void 0,this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),this.undoStack.length=0,this.redoStack.length=0,$r.get(this.documentId)===this&&$r.delete(this.documentId))}setSuggestionsForParagraph(t,e){this.paragraphSuggestions.set(t,e),this.saveToLocalStorage(),`${e.length}${t}`}getSuggestionsForParagraph(t){return this.paragraphSuggestions.get(t)||[]}setTableCellSuggestionMap(t,e){this.tableCellSuggestions.set(t,e),`${t}`,e.size}getProposalForTableCell(t,e){return this.tableCellSuggestions.get(t)?.get(e)}getTableCellSuggestionMap(t){return this.tableCellSuggestions.get(t)}async recomputeProposalsForParagraph(t){const e=this.getSuggestionsForParagraph(t).filter(d=>this.suggestionMeta.get(d)?.status==="pending");if(e.length===0)return;const{createGranularSuggestionsForParagraph:n}=await Promise.resolve().then(()=>fu),{findBlockById:o}=await import("./CanvasRenderer-C1Vegx9Y.js").then(d=>d.E),r=mt(this.ydoc),i=o(r,t);if(!i){console.warn(`[DetachedSuggestionStore] Paragraph ${t} not found in document`);return}if(i.type!=="paragraph")return;const a=new I.Doc;this.seedForkFromBase(a);for(const d of e){const g=this.proposals.get(d);g&&I.applyUpdate(a,g)}const l=mt(a),c=o(l,t);if(c&&c.type==="paragraph")for(const d of e)this.deleteSuggestion(d)}findParagraphForProposal(t){for(const[e,n]of this.paragraphSuggestions)if(n.includes(t))return e;return null}removeProposalFromParagraphs(t){for(const[e,n]of this.paragraphSuggestions){const o=n.filter(r=>r!==t);o.length!==n.length&&(o.length===0?this.paragraphSuggestions.delete(e):this.paragraphSuggestions.set(e,o))}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async regenerateProposalFromDiff(t,e,n){const o=this.suggestionMeta.get(t);if(!o){console.warn("[DetachedSuggestionStore] Cannot regenerate - no metadata for proposal:",t);return}if(o.insertionContext)return;if(o.toolCallAction?.name==="remove_block"){const d=o.toolCallAction.arguments.id;Z(this.ydoc,d);const g=new I.Doc;this.seedForkFromBase(g);const u=I.encodeStateVector(g);wn(g),g.transact(()=>{if(Te(g)){const h=g.getArray("paragraphs");for(let p=0;p<h.length;p++)if(h.get(p).get("id")===d){h.delete(p,1);break}}else{const h=ot(g,d);if(h){const{yParent:p,index:m}=h;p.delete(m,1)}}}),wn(g);const f=I.encodeStateAsUpdate(g,u);this.proposals.set(t,f),f.length;return}const r=new I.Doc;I.applyUpdate(r,e);const i=new I.Doc;I.applyUpdate(i,n);const a=mt(r),l=mt(i);if(a.children.length===l.children.length)for(let d=0;d<a.children.length;d++){const g=a.children[d],u=l.children[d];if(g.type!=="paragraph"||u.type!=="paragraph")continue;const f=g,h=u,p=c(f),m=c(h);if(p!==m&&f.id===h.id){f.id;const y=new I.Doc;this.seedForkFromBase(y);const b=I.encodeStateVector(y),{analyzeParagraphDiff:k}=await import("./ParagraphDiffAnalysis-DrmStvmz.js").then(x=>x.P),S=k(p,m).diffs;y.transact(()=>{let x=null;if(Te(y)){const w=y.getArray("paragraphs");for(let A=0;A<w.length;A++){const P=w.get(A);if(P.get("id")===f.id){x=P.get("content");break}}}else{const w=Z(y,f.id);w&&(x=ct(w))}if(x){const w=[];for(const T of h.children)if(T.type==="text")for(let E=0;E<T.text.length;E++)w.push({node:T,indexInNode:E,marks:T.marks||{}});let A=0,P=0;for(const[T,E]of S)if(T===0)A+=E.length,P+=E.length;else if(T===-1)x.delete(A,E.length);else if(T===1){for(let B=0;B<E.length;B++){const N=w[P+B];if(N){const R={...N.marks,proposalId:t};lt(x,A+B,E[B],R)}}A+=E.length,P+=E.length}}});const v=I.encodeStateAsUpdate(y,b);this.proposals.set(t,v),this.saveToLocalStorage(),this.notifyListeners();return}}function c(d){return d.children.filter(g=>g.type==="text").map(g=>g.text).join("")}}recordAction(t){this.undoStack.push(t),t.type,t.suggestionId,this.undoStack.length,this.undoStack.map(e=>e.suggestionId),this.redoStack=[]}clearHistory(){this.undoStack=[],this.redoStack=[]}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}async undoLastAction(){if(this.undoStack.length===0)return!1;const t=this.undoStack.pop();switch(this.redoStack.push(t),t.type){case"accept":{if(this.undoManager.canUndo()){const e=this.getBaseUpdate();this.undoManager.undo();const n=this.getBaseUpdate();await this.regenerateProposalFromDiff(t.suggestionId,n,e);const o=this.suggestionMeta.get(t.suggestionId);return o&&(o.status="pending",this.suggestionMeta.set(t.suggestionId,o),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="pending",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="rejected",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}redoLastAction(){if(this.redoStack.length===0)return!1;const t=this.redoStack.pop();switch(this.undoStack.push(t),t.type){case"accept":{if(this.undoManager.canRedo()){this.undoManager.redo();const e=this.suggestionMeta.get(t.suggestionId);return e&&(e.status="accepted",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="rejected",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="pending",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notifyListeners(){this.listeners.forEach(t=>t())}}function ka(s,t,e,n){if(s.type==="list"){const l=new I.XmlElement("list");return l.setAttribute("id",t),l.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&l.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&l.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(c=>{const d=new I.XmlElement("list-item");Ce(d,c),d.setAttribute("id",c.id||G()),c.checked!==void 0&&d.setAttribute("checked",String(c.checked)),typeof c.indentLevel=="number"&&c.indentLevel>0&&d.setAttribute("indentLevel",String(c.indentLevel)),c.direction!==void 0&&d.setAttribute("direction",c.direction);const g=new I.XmlText;let u=0;c.children.forEach(f=>{if(f.type==="text"){const h=f,p=Dr(h.marks,e);g.insert(u,h.text,p),u+=h.text.length}}),d.insert(0,[g]),l.push([d])}),l}if(s.type==="table"){const l=s,c=new I.XmlElement("table");c.setAttribute("id",t),l.columnWidths&&c.setAttribute("columnWidths",JSON.stringify(l.columnWidths)),l.hasHeader&&c.setAttribute("hasHeader","true"),l.tableWidth!==void 0&&c.setAttribute("tableWidth",String(l.tableWidth)),l.align&&c.setAttribute("align",l.align),l.borderColor&&c.setAttribute("borderColor",l.borderColor),l.borderWidth!==void 0&&c.setAttribute("borderWidth",String(l.borderWidth)),l.cellPadding!==void 0&&c.setAttribute("cellPadding",String(l.cellPadding));for(const d of l.children){const g=new I.XmlElement("table-row");g.setAttribute("id",d.id||G());for(const u of d.children){const f=new I.XmlElement("table-cell");f.setAttribute("id",u.id||G()),u.verticalAlign&&f.setAttribute("verticalAlign",u.verticalAlign),u.backgroundColor&&f.setAttribute("backgroundColor",u.backgroundColor);for(const h of u.children)if(h.type==="paragraph"){const p=h,m=new I.XmlElement("paragraph");m.setAttribute("id",p.id||G()),p.heading&&m.setAttribute("heading",String(p.heading)),p.align&&m.setAttribute("align",p.align);const y=new I.XmlText;let b=0;for(const k of p.children)if(k.type==="text"){const S=k,v=Dr(S.marks,e);lt(y,b,S.text,v),b+=S.text.length}m.insert(0,[y]),f.push([m])}g.push([f])}c.push([g])}return c}if(s.type==="code"){const l=s,c=new I.XmlElement("code");c.setAttribute("id",t),l.language&&c.setAttribute("language",l.language),l.renderDiagram!==void 0&&c.setAttribute("renderDiagram",String(l.renderDiagram)),l.showDiagramSource!==void 0&&c.setAttribute("showDiagramSource",String(l.showDiagramSource));const d=new I.XmlText;return c.insert(0,[d]),lt(d,0,l.content||""),c}if(s.type==="math"){const l=s,c=new I.XmlElement("math");c.setAttribute("id",t),l.displayMode&&c.setAttribute("displayMode",l.displayMode),l.align&&c.setAttribute("align",l.align);const d=new I.XmlText;return c.insert(0,[d]),lt(d,0,l.content||""),c}if(s.type==="image"){const l=s,c=new I.XmlElement("image");return c.setAttribute("id",t),c.setAttribute("src",l.src),l.sourceUrl&&c.setAttribute("sourceUrl",l.sourceUrl),c.setAttribute("width",String(l.width)),c.setAttribute("height",String(l.height)),l.alt&&c.setAttribute("alt",l.alt),l.align&&c.setAttribute("align",l.align),c}if(s.type==="page-break"){const l=new I.XmlElement("page-break");return l.setAttribute("id",t),l}if(s.type==="toc")return It({...s,id:t});if(s.type==="section-break"){const l=new I.XmlElement("section-break");return l.setAttribute("id",t),s.layout&&l.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&l.setAttribute("breakType",s.breakType),l}const o=new I.XmlElement("paragraph"),r=s;o.setAttribute("id",t),r.heading&&o.setAttribute("heading",String(r.heading)),r.align&&o.setAttribute("align",r.align);const i=new I.XmlText;let a=0;return r.children.forEach(l=>{if(l.type==="text"){const c=l,d=Dr(c.marks,e);lt(i,a,c.text,d),a+=c.text.length}}),o.insert(0,[i]),o}function Dr(s,t,e){return{...s||{},proposalId:t}}const $r=new Map;function Kg(s,t){$r.set(s,t)}const Vg=new Set(["Arial","Arial, sans-serif"]);function jr(s){if(typeof s!="string")return;const t=s.trim();if(!(!t||Vg.has(t)))return t}function fo(s){const t={};for(const e of xn)if(s[e]!==void 0)if(e==="fontFamily"){const n=jr(s[e]);n&&(t[e]=n)}else(e==="color"||e==="backgroundColor")&&typeof s[e]=="string"&&/^#[0-9a-fA-F]{6}$/.test(s[e])?t[e]=s[e].toLowerCase():t[e]=s[e];return t}const Sa=ps.filter(s=>!xn.includes(s));function je(s){const t=fo(s);for(const e of Sa)s[e]!==void 0&&(t[e]=s[e]);return t}function Gg(s){const t=Ia(s);for(const e of Sa)s[e]!==void 0&&(t[e]=s[e]);return t}function _r(s,t){return JSON.stringify(je(s||{}))===JSON.stringify(je(t||{}))}function Ia(s){const t=fo(s);t.docxRunPropertyResets=s.docxRunPropertyResets??null;for(const e of xn)e in t||(t[e]=null);return t}function Xr(s,t){const e=fo(s||{}),n=fo(t||{});return JSON.stringify(e)===JSON.stringify(n)}function va(s,t){for(const e of Tn){const n=s[e],o=t[e];if(e==="link"||e==="backgroundColor"||e==="color"){const r=l=>typeof l=="string"&&/^#[0-9a-fA-F]{6}$/.test(l),i=r(n)?n.toLowerCase():n,a=r(o)?o.toLowerCase():o;if(i!==a)return!1}else if(e==="fontFamily"){if(jr(n)!==jr(o))return!1}else if(e==="fontSize"){if((typeof n=="number"?n:void 0)!==(typeof o=="number"?o:void 0))return!1}else if(!!n!=!!o)return!1}return!0}class xa{constructor(){this.toolCalls=[]}addToolCalls(t,e){const n=Date.now();if(t.actions)for(const o of t.actions)this.toolCalls.push({toolCall:o,toolCallId:e,timestamp:n})}getAllToolCalls(){return this.toolCalls}clear(){this.toolCalls=[]}}function ae(s,t){return{...s,id:t}}function Qg(s,t,e){const n=new Set(s),o=r=>{if(r){if(r.block.type==="table"&&r.block.id){n.add(r.block.id);return}for(let i=r.containerPath.length-1;i>=0;i--){const a=r.containerPath[i];if((e.get(a)?.block??t.get(a)?.block)?.type==="table"){n.add(a);break}}}};for(const r of s)o(e.get(r)),o(t.get(r));return n}function wa(s){return JSON.stringify(s.children.map(t=>[t.id,t.children.map(e=>[e.id,e.rowSpan??1,e.colSpan??1])]))}function rn(s,t){return wa(s)!==wa(t)||He(s,t)}function Aa(s){return JSON.stringify({...s,children:s.children.map(t=>({...t,children:t.children.map(e=>({...e,children:[]}))}))})}function Zg(s,t){return{...t,children:t.children.map((e,n)=>({...e,children:e.children.map((o,r)=>({...o,children:s.children[n].children[r].children}))}))}}function Ur(s,t,e){const n=e?.affectedBlockIds?new Set(Array.from(e.affectedBlockIds).filter(M=>typeof M=="string"&&M.length>0)):null,o=t.getYDoc(),r=Array.from(t.getPendingSuggestions().keys()),i=r.length>0?t.materializeWithSuggestions(r):o,a=e?.precomputedLiveDocSchema??mt(o),l=e?.precomputedCurrentDocSchema??(i===o?a:mt(i)),c=e?.precomputedFinalDocSchema??mt(s),d=Ct(a),g=Ct(l),u=Ct(c),f=n?Qg(n,g,u):null,h=new Set;for(const M of new Set([...d.keys(),...u.keys()])){const O=d.get(M)?.block,$=u.get(M)?.block;O?.type!=="table"&&$?.type!=="table"||(O?.type!=="table"||$?.type!=="table"||rn(O,$))&&h.add(M)}if(f){const M=e?.precomputedVisibleBeforeDocSchema?Ct(e.precomputedVisibleBeforeDocSchema):null,O=D=>!Ut(M?.get(D)?.block??null,u.get(D)?.block??null),$=new Set,L=new Set;for(const D of f){const H=d.get(D)?.block,F=u.get(D)?.block;if(M&&H?.type==="table-cell"&&F?.type==="table-cell"){L.add(D);continue}H?.type!=="table"||F?.type!=="table"||h.has(D)||!M&&n?.has(D)?$.add(D):L.add(D)}for(const[D,H]of new Map([...d,...u]))(H.containerPath.some(F=>$.has(F))||M&&H.containerPath.some(F=>L.has(F))&&O(D))&&f.add(D)}const p=new Set(Array.from(e?.atomicReplaceBlockIds??[]).filter(M=>typeof M=="string"&&M.length>0)),m=new Map;for(const M of e?.replacementBlockMatches??[])typeof M?.currentBlockId!="string"||M.currentBlockId.length===0||typeof M?.finalBlockId!="string"||M.finalBlockId.length===0||m.set(M.finalBlockId,M.currentBlockId);const y=M=>{const O=m.get(M);return O&&d.has(O)?O:M},b=!!f&&f.size>0,k=t.getPendingSuggestions();if(b){const M=new Set;for(const O of f){const $=t.getSuggestionsForParagraph(O);for(const L of $)k.has(L)&&M.add(L)}for(const O of M)t.deleteSuggestion(O)}else for(const[M]of k)t.deleteSuggestion(M);const S=[],v=new Set,x=new Set,w=g;for(const[M,O]of d){const $=O.block;if($.type!=="list"||u.has(M)||$.children.length===0||b&&!f.has(M)||O.containerPath.some(U=>h.has(U)))continue;const L=w.get(M)?.block,D=(e?.listUnwrapMemberIds?.get(M)??(L?.type==="list"?L.children:$.children).map(U=>U.id)).map(U=>u.get(U)).filter(U=>!!U),H=D[0];if(!H||D.some((U,z)=>U.containerPath.join("/")!==O.containerPath.join("/")||z>0&&U.indexInParent<=D[z-1].indexInParent))continue;const F=H.containerPath.at(-1),X=F?u.get(F)?.block:null,C=(X&&"children"in X?X.children:c.children).slice(H.indexInParent,D.at(-1).indexInParent+1);if(C.some(U=>!U.id||d.has(U.id)))continue;const j=`prop_${G()}`;t.createSuggestion(j,U=>{const z=ot(U,M);return z?(z.yParent.delete(z.index,1),z.yParent.insert(z.index,C.map(tt=>It(tt))),[{kind:"replace",paragraphId:M,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:M,blocks:C},description:"AI: remove list markers"}),S.push(j),v.add(M),t.setSuggestionsForParagraph(M,[j]);for(const U of C)x.add(U.id),t.setSuggestionsForParagraph(U.id,[j])}const A=[],P=b?Array.from(f).filter(M=>u.has(M)):Array.from(u.keys());for(const M of P){const O=u.get(M);if(!O||x.has(M)||O.containerPath.some(F=>x.has(F)))continue;const $=O.block,L=m.get(M);if($.type==="container"||$.type==="table-cell"||O.containerPath.some(F=>h.has(F)))continue;const D=L?d.get(L)??d.get(M):d.get(M),H=L&&D?.block.id===L&&L!==M?L:null;if(D?.block.id&&v.add(D.block.id),$.type==="paragraph"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="paragraph"){const X=D.block,C=Hr(X),j=Hr(F);if(C!==j||hu(X,F)){if(p.has(M)){const z=zr(t,F);z&&(S.push(z),F.id&&t.setSuggestionsForParagraph(F.id,[z]));continue}const U=Ta(t,X,F);S.push(...U)}}else{const X=zr(t,F);X&&(S.push(X),F.id&&t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="list"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="list"){const X=D.block;if(Bo(X,F)){if(!au(X,F)){const C=tu(t,X,F);C.length>0&&X.id&&(S.push(...C),t.setSuggestionsForParagraph(X.id,C))}}else{const C=Jr(t,F);C&&X.id&&(S.push(C),t.setSuggestionsForParagraph(X.id,[C]))}}else{const X=Jr(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="table"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="table"){const X=D.block,C=h.has(F.id);if(C||Aa(X)!==Aa(F)){const j=Ca(t,C?F:Zg(X,F));j&&(S.push(j),t.setSuggestionsForParagraph(F.id,[j]))}}else{const X=Ca(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="code"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="code"){const X=D.block;if(X.content!==F.content||X.language!==F.language){const C=Pa(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Pa(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="math"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="math"){const X=D.block;if(X.content!==F.content||X.displayMode!==F.displayMode||X.align!==F.align){const C=Ma(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Ma(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="image"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="image"){const X=D.block;if(X.src!==F.src||X.width!==F.width||X.height!==F.height||X.alt!==F.alt||X.align!==F.align){const C=Ba(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Ba(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="page-break"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type!=="page-break"){const X=su(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="toc"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type!=="toc"||D.block.levels!==F.levels||D.block.instr!==F.instr||D.block.fontFamily!==F.fontFamily||D.block.fontSize!==F.fontSize||D.block.color!==F.color||D.block.direction!==F.direction||D.block.align!==F.align){const X=iu(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}}A.sort((M,O)=>{const $=M.location.containerPath,L=O.location.containerPath,D=Math.min($.length,L.length);for(let H=0;H<D;H++)if($[H]!==L[H])return $[H].localeCompare(L[H]);return $.length!==L.length?$.length-L.length:M.location.indexInParent-O.location.indexInParent});const T=M=>{const O=M.containerPath.at(-1),$=O?u.get(O)?.block:null;return $&&"children"in $?$.children:c.children},E=M=>{const O=T(M);for(let $=M.indexInParent-1;$>=0;$--){const L=O[$];if(L.id)return y(L.id)}return null},B=M=>{const O=T(M),$=(()=>{for(let D=M.indexInParent-1;D>=0;D--)if(O[D]?.id)return y(O[D].id);return null})(),L=(()=>{for(let D=M.indexInParent-1;D>=0;D--){const H=O[D]?.id;if(!H)continue;const F=y(H);if(d.has(F))return F}return null})();return Array.from(new Set([L,$].filter(D=>typeof D=="string"&&D.length>0)))},N=[];for(const M of A){const O=M.location,$=E(O),L=N[N.length-1];if(L&&L.afterId===$&&L.containerPath.join("/")===O.containerPath.join("/")&&L.blocks[L.blocks.length-1].location.indexInParent===O.indexInParent-1){L.blocks.push(M);continue}N.push({afterId:$,containerPath:O.containerPath,blocks:[M]})}for(const M of N){const O=M.afterId&&d.has(M.afterId);if(M.blocks.length===1&&O){const{location:$}=M.blocks[0],L=$.block,D=du(t,L,M.afterId,a);D&&(S.push(D),L.id&&t.setSuggestionsForParagraph(L.id,[D]))}else for(let $=0;$<M.blocks.length;$++){const{location:L}=M.blocks[$],D=L.block;if(D.type!=="paragraph"&&D.type!=="list"&&D.type!=="table"&&D.type!=="code"&&D.type!=="math"&&D.type!=="image"&&D.type!=="page-break"&&D.type!=="toc"){console.warn("[SuggestionPlanner] Skipping unsupported block type for position-aware insertion:",D.type);continue}const H=B(L),F=t.createPositionAwareInsertion(D.id,D,H,T(L).slice(L.indexInParent+1).map(X=>X.id).filter(X=>!!X&&d.has(X)).slice(0,1),{authorType:"ai",description:`AI: insert_${D.type} (position-aware)`});F&&(S.push(F),t.setSuggestionsForParagraph(D.id,[F]))}}const R=b?Array.from(f).filter(M=>d.has(M)):Array.from(d.keys());for(const M of R){const O=d.get(M);if(!O||v.has(M))continue;const $=O.block,L=$.type==="container"&&b&&!!f?.has(M);if(!($.type==="container"&&!L)&&$.type!=="table-cell"&&!O.containerPath.some(D=>h.has(D))&&($.type==="paragraph"||$.type==="list"||$.type==="table"||$.type==="code"||$.type==="math"||$.type==="image"||$.type==="docx-raw"||$.type==="page-break"||$.type==="section-break"||$.type==="toc"||L)){const D=cu(t,$);D&&(S.push(D),t.setSuggestionsForParagraph(M,[D]))}}return S}function Ta(s,t,e){const n=[];if(!Je(t,e)){const u=zr(s,e);if(u)return s.setSuggestionsForParagraph(e.id,[u]),[u]}const o=u=>{const f=[];return u.children.forEach((h,p)=>{if(h.type==="text"){const m=h;for(let y=0;y<m.text.length;y++)f.push({char:m.text[y],marks:m.marks||{},nodeIndex:p,charIndexInNode:y})}}),f},r=o(t),i=o(e),a=r.map(u=>u.char).join(""),l=i.map(u=>u.char).join(""),c=En(a,l).diffs;let d=0,g=0;for(let u=0;u<c.length;u++){const[f,h]=c[u];if(f===0){const p=h.length;for(let m=0;m<p;m++){const y=r[d+m],b=i[g+m],k=y?.marks||{},S=b?.marks||{};if(!va(k,S)){const v=m;let x=m+1;for(;x<p;){const E=r[d+x]?.marks||{},B=i[g+x]?.marks||{};if(va(E,B)||!_r(B,S))break;x++}const w=h.substring(v,x),A=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,P=Gg(S),T=s.createTextReplacement(A,e.id,d+v,x-v,w,P,w,{authorType:"ai",description:"AI: apply formatting"});T&&n.push(T),m=x-1}}d+=h.length,g+=h.length}else if(f===-1){const p=h.length,m=u+1<c.length?c[u+1]:null;if(m&&m[0]===1){const y=m[1];let b=!0;if(y.length>1){const k=g<i.length?i[g].marks:{};for(let S=1;S<y.length;S++){const v=g+S<i.length?i[g+S].marks:{};if(!Xr(k,v)){b=!1;break}}}if(b){const k=g<i.length?i[g].marks:{},{...S}=k,v=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,x=s.createTextReplacement(v,e.id,d,p,y,S,h,{authorType:"ai",description:"AI: replace text"});x&&n.push(x)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createSuggestion(k,v=>{const x=Z(v,e.id);let w=null;if(x)for(let T=0;T<x.length;T++){const E=x.get(T);if(E instanceof I.XmlText){w=E;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting replacement`),[];w.delete(d,p);let A=d,P=0;for(;P<y.length;){const T=P,E=g+P,B=E<i.length?je(i[E].marks):{};let N=P+1;for(;N<y.length;){const M=g+N,O=M<i.length?je(i[M].marks):{};if(!_r(B,O))break;N++}const R=y.substring(T,N);lt(w,A,R,{...B,suggestionId:k}),A+=R.length,P=N}return[{kind:"replace",paragraphId:e.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d+y.length,0)),text:y,oldText:h}]},{authorType:"ai",description:"AI: replace text"});S&&n.push(S)}u++,d+=p,g+=y.length}else{const y=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,b=s.createTextDeletion(y,e.id,d,p,h,{authorType:"ai",description:"AI: delete text"});b&&n.push(b),d+=p}}else if(f===1){const p=h,m=u>0?c[u-1]:null;if(m&&m[0]===-1)continue;const y=[];let b=0;for(;b<p.length;){const k=b,S=g+b,v=S<i.length?i[S].marks:{},x=je(v);let w=b+1;for(;w<p.length;){const P=g+w,T=P<i.length?i[P].marks:{};if(!_r(x,T))break;w++}const A=p.substring(k,w);y.push({text:A,marks:x}),b=w}if(y.length===1&&Object.keys(y[0].marks).length===0){const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createTextInsertion(k,e.id,d,p,{},{authorType:"ai",description:"AI: insert text"});S&&n.push(S)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createSuggestion(k,v=>{const x=Z(v,e.id);let w=null;if(x)for(let P=0;P<x.length;P++){const T=x.get(P);if(T instanceof I.XmlText){w=T;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting insertion`),[];let A=d;for(const P of y){const T={...P.marks,suggestionId:k};lt(w,A,P.text,T),A+=P.text.length}return[{kind:"insert",paragraphId:e.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d+p.length,0)),text:p}]},{authorType:"ai",description:"AI: insert text"});S&&n.push(S)}g+=p.length}}return e.id&&n.length>0&&s.setSuggestionsForParagraph(e.id,n),n}function zr(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};if(s.createBlockReplacementSuggestion){const n=s.createBlockReplacementSuggestion(t,e);if(n)return n}return s.createSuggestionFromToolCall(e,(n,o)=>{const r=ot(n,t.id);if(!r||r.yBlock.nodeName!=="paragraph")return Wt(n,o);const i=ct(r.yBlock)?.toDelta().map(c=>typeof c.insert=="string"?c.insert:"").join("")??"";r.yParent.delete(r.index,1);const a=It(t);r.yParent.insert(r.index,[a]);const l=ct(a);return[{kind:"replace",paragraphId:t.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(l,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(l,l.length,0)),text:Hr(t),oldText:i}]})}function tu(s,t,e){const n=[],o=t.children.map(b=>({item:b,text:ve(b),signature:Wr(b)})),r=e.children.map(b=>({item:b,text:ve(b),signature:Wr(b)})),{beforeKeys:i,afterKeys:a}=ma(t.children,e.children,Wr),l=Fr(i,a),c=[],d=(b,k,S)=>{const v=Math.min(b.length,k.length);for(let x=0;x<v;x++)c.push({kind:"replace",index:S+x,currentItem:b[x],finalItem:k[x]});for(let x=v;x<b.length;x++)c.push({kind:"delete",index:S+x,currentItem:b[x]});for(let x=k.length-1;x>=v;x--)c.push({kind:"insert",index:S+v,finalItem:k[x]})};let g=0,u=0;for(const b of l){let k=g;for(;k<o.length&&i[k]!==b;)k+=1;let S=u;for(;S<r.length&&a[S]!==b;)S+=1;d(o.slice(g,k),r.slice(u,S),g),g=k+1,u=S+1;const v=o[k],x=r[S];v&&x&&(v.signature!==x.signature||!Ea(v.item,x.item))&&c.push({kind:"replace",index:k,currentItem:v,finalItem:x})}d(o.slice(g),r.slice(u),g);const f=c.some(b=>b.kind!=="replace"?!0:b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text);if(c.length>0&&!f){const b=eu(s,e);return b?[b]:[]}for(const b of c){if(b.kind==="insert"){const S=nu(s,t.id,b.finalItem.item,b.index,t.variant);S&&n.push(S);continue}if(b.kind==="delete"){const S=ou(s,t.id,b.index,b.currentItem.text);S&&n.push(S);continue}const k=ru(s,t.id,b.index,b.currentItem.item,b.finalItem.item,t.variant);k&&n.push(k)}const h=c.filter(b=>b.kind==="replace").length,p=c.some(b=>b.kind!=="replace"?b.kind==="insert"||b.kind==="delete":b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text),m=Math.max(o.length,r.length),y=m>0?n.length/m:0;if(h>0&&y>.7&&p){const b=Jr(s,e);return b?[b]:[]}return n}function eu(s,t){if(!t.id)return null;const e=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(e,n=>{const o=Z(n,t.id);if(!o||o.nodeName!=="list")return[];for(let r=0;r<t.children.length;r++){const i=o.get(r),a=t.children[r];if(!(i instanceof I.XmlElement)||!a)continue;const l=ct(i);if(!l)continue;let c=0;for(const d of a.children)d.type!=="text"||d.text.length===0||(at(l,c,d.text.length,Ia(d.marks||{})),c+=d.text.length)}return[{kind:"replace",paragraphId:t.id,text:t.children.map(ve).join(`
6
6
  `),oldText:t.children.map(ve).join(`
7
7
  `)}]},{authorType:"ai",description:"AI: apply list formatting"})}function nu(s,t,e,n,o){const r=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(r,i=>{const a=Z(i,t);if(!a||a.nodeName!=="list")return console.warn(`List ${t} not found for item insertion`),[];const l=new I.XmlElement("list-item");Ce(l,e),l.setAttribute("id",e.id||G()),e.checked!==void 0&&l.setAttribute("checked",String(e.checked)),e.indentLevel&&l.setAttribute("indentLevel",String(e.indentLevel)),e.direction!==void 0&&l.setAttribute("direction",e.direction);const c=new I.XmlText;let d=0;e.children.forEach(u=>{if(u.type==="text"){const f=u,h={...f.marks||{},suggestionId:r,toolType:"list_item_insert"};c.insert(d,f.text,h),d+=f.text.length}}),l.insert(0,[c]);const g=Math.min(n,a.length);return a.insert(g,[l]),[{kind:"insert",paragraphId:t,text:ve(e)}]},{authorType:"ai",description:"AI: insert list item"})}function ou(s,t,e,n){const o=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(o,r=>{const i=Z(r,t);return!i||i.nodeName!=="list"?(console.warn(`List ${t} not found for item deletion`),[]):e>=i.length?(console.warn(`Item index ${e} out of bounds for list ${t}`),[]):(i.delete(e,1),[{kind:"delete",paragraphId:t,text:n}])},{authorType:"ai",description:"AI: delete list item"})}function ru(s,t,e,n,o,r){const i=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(i,a=>{const l=Z(a,t);if(!l||l.nodeName!=="list")return console.warn(`List ${t} not found for item replacement`),[];if(e>=l.length)return console.warn(`Item index ${e} out of bounds for list ${t}`),[];const c=l.get(e);if(!(c instanceof I.XmlElement))return console.warn(`Item at index ${e} is not an XmlElement`),[];Ce(c,o),o.direction!==n.direction&&(o.direction!==void 0?c.setAttribute("direction",o.direction):c.removeAttribute("direction")),o.checked!==n.checked&&(o.checked!==void 0?c.setAttribute("checked",String(o.checked)):c.removeAttribute("checked")),o.indentLevel!==n.indentLevel&&(o.indentLevel?c.setAttribute("indentLevel",String(o.indentLevel)):c.removeAttribute("indentLevel"));let d=null;for(let f=0;f<c.length;f++){const h=c.get(f);if(h instanceof I.XmlText){d=h;break}}if(!d)return console.warn(`No content found in list item at index ${e}`),[];const g=d.length;g>0&&d.delete(0,g);let u=0;return o.children.forEach(f=>{if(f.type==="text"){const h=f,p={...je(h.marks||{}),suggestionId:i,toolType:"list_item_replace"};d.insert(u,h.text,p),u+=h.text.length}}),[{kind:"replace",paragraphId:t,text:ve(o),oldText:ve(n)}]},{authorType:"ai",description:"AI: replace list item"})}function ve(s){return s.children.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wr(s){return JSON.stringify({...Object.fromEntries(An.map(t=>[t,s[t]])),direction:s.direction,checked:s.checked??!1,indentLevel:s.indentLevel??0,children:s.children.map(t=>t.type==="text"?{type:"text",text:t.text}:{type:t.type})})}function Jr(s,t){const e={name:"replace_block",arguments:{id:t.id,content:lu(t)}};return s.createSuggestionFromToolCall(e,n=>{const o=ot(n,t.id);return o?(o.yParent.delete(o.index,1),o.yParent.insert(o.index,[It(t)]),[{kind:"replace",paragraphId:t.id,text:"List replaced",oldText:o.yBlock.nodeName==="list"?"List":"Paragraph"}]):[]})}function Ca(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toInternalHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function Pa(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function Ma(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function Ba(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toInternalImageHtml(t)}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function su(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function iu(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function au(s,t){if(s.children.length!==t.children.length)return!1;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(An.some(a=>n[a]!==o[a])||n.direction!==o.direction||n.checked!==o.checked||n.indentLevel!==o.indentLevel)return!1;const r=n.children.filter(a=>a.type==="text").map(a=>a.text).join(""),i=o.children.filter(a=>a.type==="text").map(a=>a.text).join("");if(r!==i||!Ea(n,o))return!1}return!0}function Ea(s,t){if(s.children.length!==t.children.length)return!1;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(n.type!==o.type||n.type==="text"&&o.type==="text"&&(n.text!==o.text||!Xr(n.marks||{},o.marks||{})))return!1}return!0}function lu(s){return it.toInternalHtml({type:"doc",children:[s]})}function cu(s,t){if(!t.id)return console.warn("[SuggestionPlanner] Cannot create remove_block proposal for block without id:",t.type),null;const e=t.id,n={name:"remove_block",arguments:{id:e,count:1}},o=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(o,r=>{const i=ot(r,e);if(!i)return console.warn(`[SuggestionPlanner] Block ${e} not found for removal`),[];const{yBlock:a,yParent:l,index:c}=i,d=a.nodeName;let g;if(d==="list")g={kind:"delete",paragraphId:e,text:"List removed"};else{let u="";for(let f=0;f<a.length;f++){const h=a.get(f);if(h instanceof I.XmlText){const p=st(h);for(const m of p)m.insert&&typeof m.insert=="string"&&(u+=m.insert)}}g={kind:"delete",paragraphId:e,text:u||"Block removed"}}return l.delete(c,1),[g]},{authorType:"ai",toolCallAction:n,description:"AI: remove_block"})}function du(s,t,e,n){let o,r;e===null?n.children.length>0?(o=n.children[0].id,r="before"):(o=Ve,r="after"):(o=e,r="after");const i={name:"insert_block",arguments:{referenceId:o,position:r,content:[gu(t)]}};return wt(i,{stableId:t.id||G()}),s.createSuggestionFromToolCall(i,(a,l)=>Wt(a,l))}function gu(s){return s.type==="paragraph"?uu(s):s.type==="image"?it.toInternalImageHtml(s):s.type==="list"||s.type==="table"||s.type==="code"||s.type==="math"||s.type==="page-break"||s.type==="toc"?it.toInternalHtml({type:"doc",children:[s]}):""}function Dt(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function uu(s,t){const e=s.heading?`h${s.heading}`:"p",n=[];s.align&&n.push(`text-align: ${s.align}`);const o=n.length>0?` style="${n.join("; ")}"`:"";let r=`<${e}${o}>`;for(const i of s.children)if(i.type==="text"){let a=i.text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");if(i.marks?.bold&&(a=`<b>${a}</b>`),i.marks?.italic&&(a=`<i>${a}</i>`),i.marks?.underline&&(a=`<u>${a}</u>`),i.marks?.strikethrough&&(a=`<s>${a}</s>`),i.marks?.code&&(a=`<code>${a}</code>`),i.marks?.latex&&(a=`<latex-inline>${a}</latex-inline>`),i.marks?.superscript||i.marks?.footnoteRef){const g=i.marks?.footnotePendingBody!==void 0?` data-footnote="${Dt(i.marks.footnotePendingBody)}"${i.marks?.footnotePendingKind==="endnote"?' data-note-kind="endnote"':""}`:"";a=i.marks?.footnoteRef?`<sup data-footnote-ref="${Dt(i.marks.footnoteRef)}"${g}>${a}</sup>`:`<sup>${a}</sup>`}else i.marks?.subscript&&(a=`<sub>${a}</sub>`);const l=i.marks?.fontFamily,c=i.marks?.fontSize;if(l||c||i.marks?.color||i.marks?.doubleStrikethrough||i.marks?.smallCaps||i.marks?.allCaps||i.marks?.letterSpacing){const g=[];l&&g.push(`font-family: ${Dt(l)}`),c&&g.push(`font-size: ${c}px`),i.marks?.color&&g.push(`color: ${Dt(i.marks.color)}`),i.marks?.doubleStrikethrough&&g.push("text-decoration: line-through double"),i.marks?.smallCaps&&g.push("font-variant: small-caps"),i.marks?.allCaps&&g.push("text-transform: uppercase"),typeof i.marks?.letterSpacing=="number"&&Number.isFinite(i.marks.letterSpacing)&&i.marks.letterSpacing!==0&&g.push(`letter-spacing: ${i.marks.letterSpacing}px`),a=`<span style="${g.join("; ")}">${a}</span>`}i.marks?.hidden&&(a=`<span data-word-hidden="true">${a}</span>`),i.marks?.lang&&(a=`<span data-word-lang="${Dt(i.marks.lang)}">${a}</span>`),i.marks?.bookmark&&(a=`<span data-bookmark="${Dt(i.marks.bookmark)}">${a}</span>`),i.marks?.fieldInstr&&(a=`<span data-field-instr="${Dt(i.marks.fieldInstr)}">${a}</span>`),i.marks?.field&&(a=`<span data-dynamic-field="${Dt(i.marks.field)}">${a}</span>`),i.marks?.sdtInline&&(a=`<span data-sdt-inline="${Dt(i.marks.sdtInline)}">${a}</span>`),i.marks?.aiGenerated&&(a=`<span data-ai-generated="true">${a}</span>`),i.marks?.__htmlClassName&&(a=`<span data-html-class="${Dt(i.marks.__htmlClassName)}">${a}</span>`);const d=Ke(i.marks?.backgroundColor);if(d&&(a=`<mark color="${Dt(d)}">${a}</mark>`),i.marks?.link&&(a=`<a href="${Dt(i.marks.link)}">${a}</a>`),i.marks?.comment)for(const g of i.marks.comment.split(",").map(u=>u.trim()).filter(Boolean).reverse())a=`<comment-thread id="${Dt(g)}">${a}</comment-thread>`;r+=a}return r+=`</${e}>`,r}function Hr(s){return s.children.filter(t=>t.type==="text").map(t=>t.type==="text"?t.text:"").join("")}function hu(s,t){if(!Je(s,t)||s.children.length!==t.children.length)return!0;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(n.type!==o.type||n.type==="text"&&o.type==="text"&&(n.text!==o.text||!Xr(n.marks||{},o.marks||{})))return!0}return!1}const fu=Object.freeze(Object.defineProperty({__proto__:null,ToolCallHistory:xa,createFlattenedSuggestions:Ur,createGranularSuggestionsForParagraph:Ta,isStructuralTableChange:rn},Symbol.toStringTag,{value:"Module"}));class qr{constructor(t,e=!1){this.allowDirectBlockReplacementPreviews=e,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.cachedBaseUpdate=null,this.invalidateBaseUpdate=()=>{this.cachedBaseUpdate=null,this.ydoc.off("update",this.invalidateBaseUpdate)},this.ydoc=t}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=I.encodeStateAsUpdateV2(this.ydoc),this.ydoc.on("update",this.invalidateBaseUpdate)),this.cachedBaseUpdate}seedFork(){const t=new I.Doc;return I.applyUpdateV2(t,this.getBaseUpdate()),t}createForklessTextSuggestion(t){const e=Z(this.ydoc,t.paragraphId),n=e?ct(e):null;if(!n||t.startOffset+t.deleteLength>n.length)return null;const o=t.kind==="delete"?t.startOffset+t.deleteLength:t.startOffset,r=I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(n,o,0)),i=I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(n,t.kind==="delete"?o:t.startOffset+t.deleteLength,0));return this.proposals.set(t.id,new Uint8Array(0)),this.suggestionMeta.set(t.id,{id:t.id,authorId:t.metadata.authorId||"system",authorType:t.metadata.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:[{kind:t.kind,paragraphId:t.paragraphId,from:r,to:i,text:t.anchorText,...t.oldText!==void 0?{oldText:t.oldText}:{}}],...t.metadata,inlinePreview:{startOffset:t.startOffset,newText:t.newText,marks:t.marks}}),t.id}getYDoc(){return this.ydoc}createSuggestion(t,e,n={}){const o=this.seedFork(),r=I.encodeStateVector(o);let i=[];o.transact(()=>{i=e(o)},"proposal-edit");const a=I.encodeStateAsUpdate(o,r);return this.proposals.set(t,a),this.suggestionMeta.set(t,{id:t,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:i,...n}),t}createSuggestionFromToolCall(t,e){return this.createSuggestion(this.generateId(),n=>e(n,t),{authorType:"ai",toolCallAction:t,description:`AI: ${t.name}`})}createBlockReplacementSuggestion(t,e){if(!this.allowDirectBlockReplacementPreviews)return null;const n=t.id?Z(this.ydoc,t.id):null;if(!n||n.nodeName!=="paragraph")return null;const o=this.generateId();return this.suggestionMeta.set(o,{id:o,authorId:"system",authorType:"ai",createdAt:Date.now(),status:"pending",anchors:[{kind:"replace",paragraphId:t.id}],toolCallAction:e,description:`AI: ${e.name}`,blockPreview:t}),o}createTextDeletion(t,e,n,o,r,i={}){return this.createForklessTextSuggestion({id:t,kind:"delete",paragraphId:e,startOffset:n,deleteLength:o,newText:"",marks:{},anchorText:r,metadata:{...i,id:t}})||this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return[];const d=ct(c);return d?(d.delete(n,o),[{kind:"delete",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o,0)),text:r}]):[]},{...i,id:t,inlinePreview:{startOffset:n,newText:"",marks:{}}})}createTextInsertion(t,e,n,o,r={},i={}){const a={...r,suggestionId:t};return this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return[];const d=ct(c);return d?(lt(d,n,o,a),[{kind:"insert",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):[]},{...i,id:t})}createTextReplacement(t,e,n,o,r,i={},a,l={}){const c={...i,suggestionId:t};return this.createForklessTextSuggestion({id:t,kind:"replace",paragraphId:e,startOffset:n,deleteLength:o,newText:r,marks:c,anchorText:r,oldText:a,metadata:{...l,id:t}})||this.createSuggestion(t,g=>{const u=Z(g,e);if(!u)return[];const f=ct(u);return f?(f.delete(n,o),lt(f,n,r,c),[{kind:"replace",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,n+r.length,0)),text:r,oldText:a}]):[]},{...l,id:t,inlinePreview:{startOffset:n,newText:r,marks:c}})}createPositionAwareInsertion(t,e,n,o,r={}){const i=this.generateId();return this.suggestionMeta.set(i,{id:i,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...r}),i}materializeWithSuggestion(t){const e=this.suggestionMeta.get(t);if(!e||e.status==="accepted")return null;const n=this.seedFork();if(e.blockPreview?.id){const r=ot(n,e.blockPreview.id);return r?(r.yParent.delete(r.index,1),r.yParent.insert(r.index,[It(e.blockPreview)]),n):null}if(e.insertionContext)return this.applyPositionAwareInsertion(n,t,e),n;const o=this.proposals.get(t);return o?(I.applyUpdate(n,o),n):null}withMaterializedSuggestion(t,e){const n=this.materializeWithSuggestion(t);return n?e(n):null}materializeWithSuggestions(t){const e=this.seedFork();for(const n of t){const o=this.suggestionMeta.get(n);if(!o||o.status==="accepted")continue;if(o.insertionContext){this.applyPositionAwareInsertion(e,n,o);continue}if(o.blockPreview?.id){const i=ot(e,o.blockPreview.id);i&&(i.yParent.delete(i.index,1),i.yParent.insert(i.index,[It(o.blockPreview)]));continue}const r=this.proposals.get(n);r&&I.applyUpdate(e,r)}return e}getSuggestion(t){return this.suggestionMeta.get(t)}getPendingSuggestions(){const t=new Map;for(const[e,n]of this.suggestionMeta)n.status==="pending"&&t.set(e,n);return t}deleteSuggestion(t){this.proposals.delete(t),this.suggestionMeta.delete(t),this.removeProposalFromParagraphs(t),this.removeProposalFromTableCellMaps(t)}resolveAnchorsAgainstDoc(t,e){const n=this.suggestionMeta.get(t);return n?.anchors?n.anchors.map(o=>{const r=o.from?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(o.from),e):null,i=o.to?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(o.to),e):null;return{kind:o.kind,paragraphId:o.paragraphId,fromIndex:r?.index??null,toIndex:i?.index??null,text:o.text}}):[]}setSuggestionsForParagraph(t,e){this.paragraphSuggestions.set(t,e)}getSuggestionsForParagraph(t){return this.paragraphSuggestions.get(t)||[]}setTableCellSuggestionMap(t,e){this.tableCellSuggestions.set(t,e)}applyPositionAwareInsertion(t,e,n){const o=n.insertionContext;if(!o)return;const r=t.getXmlFragment("content");let i=0;for(let l=r.length-1;l>=0;l--){const c=r.get(l);if(!(c instanceof I.XmlElement))continue;const d=c.getAttribute("id");if(d&&o.mustBeAfter.includes(d)){i=l+1;break}}const a=pu(o.content,o.paragraphId,e);r.insert(i,[a])}removeProposalFromParagraphs(t){for(const[e,n]of this.paragraphSuggestions){const o=n.filter(r=>r!==t);o.length!==n.length&&(o.length===0?this.paragraphSuggestions.delete(e):this.paragraphSuggestions.set(e,o))}}removeProposalFromTableCellMaps(t){for(const[e,n]of this.tableCellSuggestions){let o=!1;for(const[r,i]of n)i===t&&(n.delete(r),o=!0);o&&n.size===0&&this.tableCellSuggestions.delete(e)}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function pu(s,t,e,n){if(s.type==="list"){const a=new I.XmlElement("list");return a.setAttribute("id",t),a.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&a.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&a.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(l=>{const c=new I.XmlElement("list-item");Ce(c,l),c.setAttribute("id",l.id||G()),l.checked!==void 0&&c.setAttribute("checked",String(l.checked)),typeof l.indentLevel=="number"&&l.indentLevel>0&&c.setAttribute("indentLevel",String(l.indentLevel)),l.direction!==void 0&&c.setAttribute("direction",l.direction);const d=new I.XmlText;let g=0;l.children.forEach(u=>{if(u.type!=="text")return;const f=Yr(u.marks,e);d.insert(g,u.text,f),g+=u.text.length}),c.insert(0,[d]),a.push([c])}),a}if(s.type==="table")return It(ys({...s,id:t},a=>({...a,marks:Yr(a.marks,e)})));if(s.type==="code"){const a=new I.XmlElement("code");a.setAttribute("id",t),s.language&&a.setAttribute("language",s.language),s.renderDiagram!==void 0&&a.setAttribute("renderDiagram",String(s.renderDiagram)),s.showDiagramSource!==void 0&&a.setAttribute("showDiagramSource",String(s.showDiagramSource));const l=new I.XmlText;return a.insert(0,[l]),lt(l,0,s.content||""),a}if(s.type==="math"){const a=new I.XmlElement("math");a.setAttribute("id",t),s.displayMode&&a.setAttribute("displayMode",s.displayMode),s.align&&a.setAttribute("align",s.align);const l=new I.XmlText;return a.insert(0,[l]),lt(l,0,s.content||""),a}if(s.type==="image"){const a=new I.XmlElement("image");return a.setAttribute("id",t),a.setAttribute("src",s.src),s.sourceUrl&&a.setAttribute("sourceUrl",s.sourceUrl),a.setAttribute("width",String(s.width)),a.setAttribute("height",String(s.height)),s.alt&&a.setAttribute("alt",s.alt),s.align&&a.setAttribute("align",s.align),a}if(s.type==="page-break"){const a=new I.XmlElement("page-break");return a.setAttribute("id",t),a}if(s.type==="toc")return It({...s,id:t});if(s.type==="section-break"){const a=new I.XmlElement("section-break");return a.setAttribute("id",t),s.layout&&a.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&a.setAttribute("breakType",s.breakType),a}const o=new I.XmlElement("paragraph");o.setAttribute("id",t),s.heading&&o.setAttribute("heading",String(s.heading)),s.align&&o.setAttribute("align",s.align);const r=new I.XmlText;let i=0;return s.children.forEach(a=>{if(a.type!=="text")return;const l=Yr(a.marks,e);lt(r,i,a.text,l),i+=a.text.length}),o.insert(0,[r]),o}function Yr(s,t,e){return{...s||{},suggestionId:t}}const mu={pending_table_changes:{code:"pending_table_changes",summary:"A table edit that would rebuild a table whose cells hold pending changes the call must keep.",message:({subject:s,reason:t})=>`Table '${s}' has ${t??"a pending row or column change"} and pending edits in its cells, so this change would have to rebuild the whole table and would lose or re-author those pending edits. Nothing was changed. Resolve (accept or reject) the table's pending changes first, or edit its cell text with replace/edit_table_cells.`,why:"A table that already has a pending row/column revision, a horizontally merged cell, or blocks moved between cells is replanned as one whole-table proposal from its rejected and accepted views. That would re-create (tracked) or accept (direct) every pending change in its cells. Row/column revisions record grid widths and indexes as snapshots that only resolve in creation order, so a new one cannot be layered over a pending one.",realFix:"Stacked table revision markers: row/column insert/delete markers that compose with pending ones (grid widths derived from the live grid at decision time instead of snapshots), merged-cell (gridSpan) aware column operations, and cell-content moves expressed as text revisions, so the live table can be edited in place like the other structure edits (graftTableStructureChange).",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"a table edit that would rebuild a table holding pending cell changes"}]},pending_list_changes:{code:"pending_list_changes",summary:"A list-level change, reorder, conversion, or edit over an item's own pending revision, in a list whose items hold pending changes the call must keep.",message:({subject:s})=>`List '${s}' holds pending edits in its items, and this change (a list type or list-level change, reordering, or converting the list) would have to rebuild the whole list, losing or re-authoring those pending edits. Nothing was changed. Resolve (accept or reject) the list's pending changes first, or edit item text and item formatting directly.`,why:"Item text, item formatting, item fields, and item insertions/removals are applied in place on the live list (planPendingListEdit). Anything else replans the list as one whole-list proposal from its rejected and accepted views, which re-creates (tracked) or accepts (direct) the items' pending changes.",realFix:"List-level property revisions (Word w:pPrChange with prior w:numPr on every item, plus numbering-definition revisions), item moves (Word move revisions: w:moveFrom/w:moveTo), and item-level revisions that stack on an item's own pending revision.",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"a list edit that cannot keep the items' pending changes is refused"}]},list_reorder_unsupported:{code:"list_reorder_unsupported",summary:"A tracked reorder of a clean list's items.",message:({subject:s})=>`This change reorders the items of list '${s}'. Moving list items is not a tracked change Revise can suggest, so nothing was changed. Apply it as a direct edit, or remove the items and insert them again where they belong (each is then reviewable).`,why:"The list suggestion bridge has no item-move operation: a reorder reported success, accepting kept the old order, and rejecting after a .docx reopen duplicated an item. Direct mode rewrites a clean list in its new order.",realFix:"Item move suggestions: a move record (source and destination positions) that renders as a move, resolves either way, and exports as Word move revisions (w:moveFrom/w:moveTo with w:moveFromRangeStart/w:moveToRangeStart) on the list paragraphs.",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"reordering the items of a clean list"}]},list_numbering_tracked_unsupported:{code:"list_numbering_tracked_unsupported",summary:"A tracked numbering restart, list-type change, or numbering-format change, where a .docx is the source of truth (the revise library and CLI).",message:({subject:s})=>`This change restarts the numbering of list '${s}' or changes its list type. Revise cannot track that as a suggestion (Word stores it as a new numbering definition), so nothing was changed. Apply it as a direct edit.`,why:"In Word a restart or type change is a new numbering definition (a new w:numId, with w:lvlOverride/w:startOverride for a restart); a whole-list suggestion has no such representation, so it exported with no revision and could not be rejected after a reopen. Only sessions that require a .docx round trip (docxRoundTripRequired, set by the revise library) refuse it; the web editor keeps it as an in-app suggestion, and its .docx export writes the list as it now reads and reports a warning with this code.",realFix:"Numbering-definition revisions: export a new w:num (abstract numbering plus start override) for the changed list and a w:pPrChange holding each item's prior w:numPr (old w:numId and w:ilvl), and import that pair back as a list-level suggestion that restores the old numbering on reject.",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"tracked list numbering changes refuse only when a .docx round trip is required"},{file:"src/editor/converters/DocxConverter.redlines.roundtrip.test.ts",name:"warns when it exports a pending list numbering change Word cannot track"}]},footnote_in_note_unsupported:{code:"footnote_in_note_unsupported",summary:"A footnote or endnote inserted inside a footnote or endnote.",message:({subject:s})=>`Block '${s}' is inside a footnote or endnote, and a note cannot hold another note. Nothing was changed. Put the reference in the body text the note annotates, or write the extra remark into the note's own text.`,why:'Word has no note inside a note: a w:footnoteReference is only valid in the main story. The insertion reported success, but after a .docx round trip the nested reference read back as a superscript "0" and its body was gone.',realFix:"None in .docx. A note-in-note could only exist as a Revise-only structure, which a .docx export would have to flatten (for example into the note's text); until then the tool refuses it in every session.",tests:[{file:"src/embed-sdk/__tests__/serverDocumentSession.node.test.ts",name:"refuses a footnote inside a footnote and changes nothing"}]}};function sn(s,t,e){return{success:!1,error:mu[s].message(t),failure:{code:s,phase:"validation",retryable:!1,mutationOutcome:"unchanged",details:e}}}const bu=new Set(["footnoteRef","footnotePendingBody","footnotePendingKind","comment","bookmark","field","fieldInstr","oxmlRange","sdtInline","latex"]);class ft{constructor(t){this.host=t,this.batchYBlockLocationsById=null,this.stampedIdRecorder=null}recordStampedSuggestionIds(t){const e=this.stampedIdRecorder,n={deletionIds:new Set,insertionIds:new Set,structuralInsertIds:new Set,structuralDeleteIds:new Set};this.stampedIdRecorder=n;try{return{result:t(),stamped:n}}finally{this.stampedIdRecorder=e}}recordStampedId(t,e){this.stampedIdRecorder&&e&&this.stampedIdRecorder[t].add(e)}buildInlinePreviewTextNodes(t){return t.newText?[{type:"text",text:t.newText,marks:{...t.marks}}]:[]}setSuggestingMode(t){this.host.suggestingMode=t}isSuggestingMode(){return this.host.suggestingMode}cloneSuggestionSnapshot(t){return JSON.parse(JSON.stringify(t))}getLiveSuggestionStore(){return this.host.ydoc.getMap("liveSuggestions")}setDefaultSuggestionAuthorName(t){const e=t?.trim();this.host.defaultHumanAuthorName=e||null}resolveSuggestionAuthorName(t,e){return e?.trim()||(t==="ai"?Nt:this.host.defaultHumanAuthorName??Ws)}isOwnPendingSuggestionSpan(t){const e=typeof t.suggestionAuthorName=="string"?t.suggestionAuthorName.trim():"";if(!e)return!0;const n=this.host.liveSuggestionMetadataContext,o=this.resolveSuggestionAuthorName(n?.authorType??"human",n?.agentName);return e===o}withSuggestionMetadata(t,e){const n=this.host.liveSuggestionMetadataContext,o=new Set(this.getLiveSuggestionIds()),r={source:t.source,authorType:t.authorType,createdAt:t.createdAt??Date.now(),label:t.label,commentThreadId:t.commentThreadId,agentName:t.agentName,agentModel:t.agentModel,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn},i=()=>{this.host.liveSuggestionMetadataContext=r;try{return e()}finally{this.host.liveSuggestionMetadataContext=n}},a=t.batchHistory===!1?i():this.host.runWithUndoGroup(t.historyOrigin??`live-suggestions:${r.createdAt}`,i),l=this.getLiveSuggestionIds().filter(c=>!o.has(c));return{result:a,suggestionIds:l}}normalizeLiveSuggestionRecord(t){const e=this.host.liveSuggestionMetadataContext,n=t.source??e?.source??"manual",o=t.authorType??e?.authorType??(n==="agent"?"ai":"human"),r=t.createdAt??e?.createdAt??Date.now(),i=t.label??e?.label,a=this.resolveSuggestionAuthorName(o,t.agentName??e?.agentName),l=t.agentModel??e?.agentModel,c=t.commentThreadId??e?.commentThreadId,d=t.agentConversationId??e?.agentConversationId,g=t.agentRequestId??e?.agentRequestId,u=t.agentTurn??e?.agentTurn;return{...t,source:n,authorType:o,createdAt:r,label:i,...c?{commentThreadId:c}:{},agentName:a,...l?{agentModel:l}:{},...d?{agentConversationId:d}:{},...g!==void 0?{agentRequestId:g}:{},...u!==void 0?{agentTurn:u}:{}}}saveLiveSuggestion(t,e){const n=this.normalizeLiveSuggestionRecord(t);this.getLiveSuggestionStore().set(n.id,this.cloneSuggestionSnapshot(n)),this.embedLiveSuggestionRecordInTree(n,e)}liveSuggestionRecordAnchorBlockId(t){switch(t.type){case"block-change":return t.sequenceBlockIds?this.getSequenceReplacementMembers(t)[0]?.yBlock.getAttribute("id")??null:t.blockId;case"block-insert":case"block-delete":case"paragraph-split":return t.blockId;case"table-change":return t.tableId;case"paragraph-merge":return t.firstBlockId;case"inline-text":return t.anchorBlockId??null;default:return null}}embedLiveSuggestionRecordInTree(t,e){const n=this.liveSuggestionRecordAnchorBlockId(t);if(!n||!this.host.ydoc)return;const o=e??Z(this.host.ydoc,n);if(o instanceof I.XmlElement)try{if(t.type==="table-change"){let r=[];const i=o.getAttribute("structuralSuggestionRecords");if(typeof i=="string")try{const a=JSON.parse(i);Array.isArray(a)&&(r=a)}catch{}r=r.filter(a=>a?.id!==t.id),r.push(t),o.setAttribute("structuralSuggestionRecords",JSON.stringify(r))}else o.setAttribute("structuralSuggestionRecord",JSON.stringify(t));this.host.liveSuggestionTreeRecordCache.delete(t.id)}catch{}}backfillLiveSuggestionTreeRecords(){if(!this.host.ydoc)return;const t=[];try{for(const[,e]of this.getLiveSuggestionStore()){const n=this.liveSuggestionRecordAnchorBlockId(e);if(!n)continue;const o=Z(this.host.ydoc,n);o instanceof I.XmlElement&&!o.getAttribute("structuralSuggestionRecord")&&t.push(e)}}catch{return}t.length!==0&&this.host.transact(()=>{for(const e of t)this.embedLiveSuggestionRecordInTree(this.normalizeLiveSuggestionRecord(e))})}findLiveSuggestionRecordInTree(t){if(this.host.liveSuggestionTreeRecordCacheReady)return this.host.liveSuggestionTreeRecordCache.get(t)??null;const e=this.host.liveSuggestionTreeRecordCache,n=r=>{r&&r.id&&r.type&&!e.has(r.id)&&e.set(r.id,r)},o=r=>{for(const i of r.toArray()){if(!(i instanceof I.XmlElement))continue;const a=i.getAttribute("structuralSuggestionRecord");if(typeof a=="string"&&a.length>0)try{n(JSON.parse(a))}catch{}const l=i.getAttribute("structuralSuggestionRecords");if(typeof l=="string"&&l.length>0)try{const c=JSON.parse(l);Array.isArray(c)&&c.forEach(n)}catch{}o(i)}};try{o(this.host.getYContentFragment()),o(this.host.getYNotesFragment())}catch{}return this.host.liveSuggestionTreeRecordCacheReady=!0,e.get(t)??null}getLiveSuggestion(t){const e=this.getLiveSuggestionStore().get(t);return e?this.cloneSuggestionSnapshot(e):this.findLiveSuggestionRecordInTree(t)??void 0}findInlineSuggestionMetadataInValue(t,e){if(!t||typeof t!="object")return null;if(Array.isArray(t)){for(const r of t){const i=this.findInlineSuggestionMetadataInValue(r,e);if(i)return i}return null}const n=t;if(n.marks?.suggestionId===e)return{id:e,source:n.marks.suggestionSource,authorType:n.marks.suggestionAuthorType,createdAt:n.marks.suggestionCreatedAt,label:n.marks.suggestionLabel,commentThreadId:n.marks.suggestionCommentThreadId,agentName:n.marks.suggestionAuthorName,agentModel:n.marks.suggestionAgentModel,agentConversationId:n.marks.suggestionAgentConversationId,agentRequestId:n.marks.suggestionAgentRequestId,agentTurn:n.marks.suggestionAgentTurn};const o=mn(n.marks?.layeredInsertion);return o&&o.id===e?{id:e,source:o.source,authorType:o.authorType,createdAt:o.createdAt,label:o.label,commentThreadId:o.commentThreadId,agentName:o.authorName,agentModel:o.agentModel,agentConversationId:o.agentConversationId,agentRequestId:o.agentRequestId,agentTurn:o.agentTurn}:n.children?this.findInlineSuggestionMetadataInValue(n.children,e):null}getInlineSuggestionMetadataFromDocument(t){return this.host.inlineSuggestionMetadataCache.has(t)?this.host.inlineSuggestionMetadataCache.get(t)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionMetadataCache.has(t)?this.host.inlineSuggestionMetadataCache.get(t)??null:(this.host.inlineSuggestionMetadataCache.set(t,null),null))}getLiveSuggestionTooltipDescription(t){const e=this.getLiveSuggestion(t);if(!e)return null;switch(e.type){case"inline-text":return null;case"inline-format":return this.host.getInlineFormatDescription(e);case"paragraph-split":return"Split Paragraph";case"paragraph-merge":return"Join Paragraphs";case"block-insert":{const n=W(this.host.getDocument(),e.blockId)??void 0,o=this.host.getBlockDescription(n);return o?`Insert ${o}`:n?.type==="paragraph"?"Insert Paragraph":n?.type==="list"?"Insert List":null}case"block-delete":{const n=this.host.getBlockDescription(e.beforeBlock);return n?`Delete ${n}`:e.beforeBlock.type==="paragraph"?"Delete Paragraph":e.beforeBlock.type==="list"?"Delete List":e.label??null}case"table-change":return e.label??"Table change";case"block-change":{const n=e.acceptedBlock??W(this.host.getDocument(),e.blockId)??void 0,o=this.host.getTableDimensionDescription(e.label,e.beforeBlock,n);if(o)return o;if(e.label==="Format")return this.host.getBlockFormatDescription(e.beforeBlock,n);if(e.label==="Paragraph")return"Convert to Paragraph";if(e.beforeBlock.type==="list"&&n?.type==="list"&&(e.label==="Insert"||e.label==="Delete"||e.label==="Change"))return e.label==="Insert"?"Insert List Item":e.label==="Delete"?"Delete List Item":"Change List Item";if(e.label==="List")return e.beforeBlock.type==="paragraph"?"Convert to List":"List Change";if(e.label==="Indent"||e.label==="Outdent")return e.label;if(e.label==="Join")return"Join List Items";const r=this.host.getBlockDescription(n)??this.host.getBlockDescription(e.beforeBlock);if(r&&e.label)return`${e.label} ${r}`;if(e.label){if(e.beforeBlock.type==="paragraph")return`${e.label} Paragraph`;if(e.beforeBlock.type==="list")return`${e.label} List`}return e.label??null}default:return null}}deleteLiveSuggestion(t){this.getLiveSuggestionStore().delete(t),this.host.liveSuggestionTreeRecordCache.delete(t)}getLiveSuggestionIds(){if(this.host.liveSuggestionIdsCache)return this.host.liveSuggestionIdsCache.slice();const t=Array.from(new Set([...Array.from(this.getLiveSuggestionStore().keys()),...this.getResolvableSuggestionIdsFromDocument()]));return this.host.liveSuggestionIdsCache=t,t.slice()}getLiveSuggestionIdsBySource(t){const e=this.host.liveSuggestionIdsBySourceCache.get(t);if(e)return e.slice();const n=this.getLiveSuggestionIds().filter(o=>{const r=this.getInlineSuggestionMetadataFromDocument(o);if(r?.source)return r.source===t;if(t==="agent"&&r?.authorType==="ai")return!0;const i=this.getLiveSuggestion(o);return i?.source?i.source===t:t==="agent"&&i?.authorType==="ai"});return this.host.liveSuggestionIdsBySourceCache.set(t,n),n.slice()}getLiveSuggestionIdsByCommentThread(t){return t?this.getLiveSuggestionIds().filter(e=>{const n=this.getInlineSuggestionMetadataFromDocument(e);return n?.commentThreadId?n.commentThreadId===t:this.getLiveSuggestion(e)?.commentThreadId===t}):[]}getResolvableLiveSuggestionIdsBySource(t){return this.getLiveSuggestionIdsBySource(t).filter(e=>this.canResolveLiveSuggestion(e))}normalizeLiveSuggestionIds(t){return Array.from(new Set(t)).filter(e=>typeof e=="string"&&e.length>0)}getLiveSuggestionAuthorName(t){const e=this.getInlineSuggestionMetadataFromDocument(t),n=e?void 0:this.getLiveSuggestion(t),o=e?.agentName??n?.agentName;return o?.trim()?o.trim():(e?.authorType??n?.authorType)==="ai"?Nt:Ws}getLiveSuggestionKind(t){const e=this.getLiveSuggestion(t);if(e)switch(e.type){case"inline-format":return"format";case"block-change":return"format";case"table-change":return e.tableRevision.suggestionKind;case"block-insert":case"paragraph-split":return"insert";case"block-delete":case"paragraph-merge":return"delete"}return this.getInlineSuggestionKindFromDocument(t)}getInlineSuggestionKindFromDocument(t){return this.host.inlineSuggestionKindCache.has(t)?this.host.inlineSuggestionKindCache.get(t)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionKindCache.has(t)?this.host.inlineSuggestionKindCache.get(t)??null:(this.host.inlineSuggestionKindCache.set(t,null),null))}getResolvableSuggestionIdsForScope(t){switch(t.kind){case"source":return this.getResolvableLiveSuggestionIdsBySource(t.source);case"author":{const e=t.authorName.trim();return this.getLiveSuggestionIds().filter(n=>this.getLiveSuggestionAuthorName(n)===e).filter(n=>this.canResolveLiveSuggestion(n))}case"suggestion-kind":return this.getLiveSuggestionIds().filter(e=>this.getLiveSuggestionKind(e)===t.suggestionKind).filter(e=>this.canResolveLiveSuggestion(e))}}getInitialSuggestionIdsForDecisionScope(t){return t.kind==="ids"?this.normalizeLiveSuggestionIds(t.suggestionIds):this.getResolvableSuggestionIdsForScope(t)}getNextSuggestionIdsForDecisionScope(t,e){return t.kind==="ids"?e===0?this.normalizeLiveSuggestionIds(t.suggestionIds):[]:this.getResolvableSuggestionIdsForScope(t)}getResolvableSuggestionIdsFromDocument(){return this.getSuggestionIdsFromDocument()}getSuggestionIdsFromDocument(){return this.getDocumentSuggestionIdsCache().ids.slice()}documentContainsSuggestionId(t){return this.getDocumentSuggestionIdsCache().idSet.has(t)}getDocumentSuggestionIdsCache(){return this.host.documentSuggestionIdsCache&&this.host.documentSuggestionIdsCache.revision===this.host.derivedDocumentRevision?this.host.documentSuggestionIdsCache:(this.host.documentSuggestionIdsCache=this.createDocumentSuggestionIdsCache(this.host.getDocument()),this.host.documentSuggestionIdsCache)}createDocumentSuggestionIdsCache(t){const e=new Set;for(const o of this.blocksWithNotesAndChrome(t)){for(const r of this.getSuggestionIdsForBlock(o))e.add(r);this.indexInlineSuggestionFacts(o)}const n=Array.from(e);return{revision:this.host.derivedDocumentRevision,ids:n,idSet:new Set(n)}}indexInlineSuggestionFacts(t){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const r of t)this.indexInlineSuggestionFacts(r);return}const e=t,n=e.marks?.suggestionId;if(typeof n=="string"&&n.length>0){this.host.inlineSuggestionMetadataCache.has(n)||this.host.inlineSuggestionMetadataCache.set(n,{id:n,source:e.marks?.suggestionSource,authorType:e.marks?.suggestionAuthorType,createdAt:e.marks?.suggestionCreatedAt,label:e.marks?.suggestionLabel,commentThreadId:e.marks?.suggestionCommentThreadId,agentName:e.marks?.suggestionAuthorName,agentModel:e.marks?.suggestionAgentModel,agentConversationId:e.marks?.suggestionAgentConversationId,agentRequestId:e.marks?.suggestionAgentRequestId,agentTurn:e.marks?.suggestionAgentTurn});const r=e.marks?.deletion?"delete":e.marks?.insertion?"insert":e.marks?.formatChange?"format":null;r&&!this.host.inlineSuggestionKindCache.has(n)&&this.host.inlineSuggestionKindCache.set(n,r)}const o=mn(e.marks?.layeredInsertion);if(o&&(this.host.inlineSuggestionMetadataCache.has(o.id)||this.host.inlineSuggestionMetadataCache.set(o.id,{id:o.id,source:o.source,authorType:o.authorType,createdAt:o.createdAt,label:o.label,commentThreadId:o.commentThreadId,agentName:o.authorName,agentModel:o.agentModel,agentConversationId:o.agentConversationId,agentRequestId:o.agentRequestId,agentTurn:o.agentTurn}),this.host.inlineSuggestionKindCache.set(o.id,"insert")),typeof e.structuralSuggestionId=="string"&&e.structuralSuggestionId.length>0){const r=e.structuralSuggestionKind==="insert"||e.structuralSuggestionKind==="split"?"insert":e.structuralSuggestionKind==="delete"||e.structuralSuggestionKind==="merge"?"delete":e.structuralSuggestionKind==="change"?"format":null;r&&this.host.inlineSuggestionKindCache.set(e.structuralSuggestionId,r)}if(typeof e.suggestionId=="string"&&e.suggestionId.length>0&&!this.host.inlineSuggestionKindCache.has(e.suggestionId)){const r=e.diffState==="insert"?"insert":e.diffState==="delete"?"delete":null;r&&this.host.inlineSuggestionKindCache.set(e.suggestionId,r)}e.children&&this.indexInlineSuggestionFacts(e.children)}getLiveSuggestionIdsForBlock(t){return this.getSuggestionIdsForBlock(t)}getSuggestionIdsForBlock(t){const e=this.host.suggestionIdsByBlockCache.get(t);if(e)return e;const n=new Set;this.collectSuggestionIdsFromBlockValue(t,n);const o=Array.from(n);return this.host.suggestionIdsByBlockCache.set(t,o),o}canResolveLiveSuggestion(t){if(this.host.canResolveLiveSuggestionCache.has(t))return this.host.canResolveLiveSuggestionCache.get(t)??!1;const e=this.computeCanResolveLiveSuggestion(t);return this.host.canResolveLiveSuggestionCache.set(t,e),e}computeCanResolveLiveSuggestion(t){const e=this.getLiveSuggestion(t);if(!e)return this.documentContainsSuggestionId(t);const n=this.host.getDocument();switch(e.type){case"inline-text":return this.documentContainsSuggestionId(e.id);case"inline-format":return this.host.inlineFormatRecordHasLiveMarker(e);case"block-change":{if(e.sequenceBlockIds)return this.getSequenceReplacementMembers(e).length>0;const o=W(n,e.blockId);return o?this.host.isListItemBlockChangeRecord(e)?o.type==="list"&&o.children.some(r=>r.structuralSuggestionId===e.id):e.acceptedBlock?this.blockChangeTargetIsOwned(e):this.blockContainsSuggestionMarker(o,e.id):!1}case"table-change":{const o=W(n,e.tableId);return o?.type!=="table"||!this.blockContainsSuggestionMarker(o,e.id)?!1:e.tableRevision.operations.some(r=>r.kind==="row"?o.children.some(i=>i.id===r.rowId):r.kind==="cell"?o.children.some(i=>i.id===r.rowId&&i.children.some(a=>a.id===r.cellId)):r.kind==="geometry"?r.pendingRows.some(i=>o.children.some(a=>a.id===i.id)):r.kind==="grid"||r.target==="table"?!0:r.target==="row"||r.target==="row-exception"?o.children.some(i=>i.id===r.rowId):o.children.some(i=>i.children.some(a=>a.id===r.cellId)))}case"block-insert":{const o=W(n,e.blockId);return o&&this.blockContainsSuggestionMarker(o,e.id)?!0:this.host.collectStructuralInsertBlockIds(n,e.id).length>0}case"block-delete":{const o=W(n,e.blockId);return!!(o&&this.blockContainsSuggestionMarker(o,e.id))}case"paragraph-split":{const o=W(n,e.blockId),r=W(n,e.insertedBlockId);return!!(o&&r&&(this.blockContainsSuggestionMarker(o,e.id)||this.blockContainsSuggestionMarker(r,e.id)))}case"paragraph-merge":{const o=W(n,e.firstBlockId),r=W(n,e.secondBlockId);return!r||r.type!=="paragraph"?!1:o&&o.type==="paragraph"?this.blockContainsSuggestionMarker(o,e.id)||this.blockContainsSuggestionMarker(r,e.id):this.blockContainsSuggestionMarker(r,e.id)}}}getUnresolvableLiveSuggestionRecords(){const t=[];for(const e of this.getLiveSuggestionIds()){if(this.canResolveLiveSuggestion(e))continue;const n=this.getLiveSuggestion(e);t.push({id:e,type:n?.type??"unknown",source:n?.source??"unknown",label:n?.label})}return t}pruneUnresolvableLiveSuggestionsInternal(){const t=this.getUnresolvableLiveSuggestionRecords();return t.length===0?[]:(this.host.transact(()=>{for(const e of t)this.deleteLiveSuggestion(e.id)}),t)}pruneUnresolvableLiveSuggestions(){const t=this.pruneUnresolvableLiveSuggestionsInternal();return this.host.lastPrunedUnresolvableLiveSuggestions=t,t}takeLastPrunedUnresolvableLiveSuggestions(){const t=this.host.lastPrunedUnresolvableLiveSuggestions;return this.host.lastPrunedUnresolvableLiveSuggestions=[],t}getDocumentWithAcceptedSuggestions(){return this.createLiveSuggestionProjection("accept").doc}getDocumentWithRejectedSuggestions(){return this.createLiveSuggestionProjection("reject").doc}getSelectionInRejectedSuggestionProjection(t){if(!t.anchor||!t.focus||this.getLiveSuggestionIds().length===0)return null;const e=this.host.getDocument(),n=Y(t,this.host.ydoc,e),o=this.createLiveSuggestionProjection("reject"),r=Or(n,o.ydoc);if(!r.anchor||!r.focus)return null;const i=xt(o.doc,r.anchor,r.focus)<=0;return{doc:o.doc,start:i?r.anchor:r.focus,end:i?r.focus:r.anchor}}createLiveSuggestionProjection(t){const e=this.getLiveSuggestionIds(),n=this.host.liveSuggestionProjectionCache.get(t);if(n&&n.revision===this.host.derivedDocumentRevision)return n.projection;const o=Co.createSuggestionProjectionFromYDoc(this.host.ydoc,t,e);return this.host.liveSuggestionProjectionCache.set(t,{revision:this.host.derivedDocumentRevision,projection:o}),o}mapAcceptedSuggestionRangeToLiveRange(t,e,n){if(e<0||n<=e)return null;if(this.getLiveSuggestionIds().length===0)return{start:e,end:n};const o=this.createLiveSuggestionProjection("accept"),r=Z(o.ydoc,t),i=r?ct(r):null,a=Z(this.host.ydoc,t),l=a?ct(a):null;if(!i||!l||n>i.length)return null;const c=I.createRelativePositionFromTypeIndex(i,e,0),d=I.createRelativePositionFromTypeIndex(i,n,-1),g=I.createAbsolutePositionFromRelativePosition(c,this.host.ydoc),u=I.createAbsolutePositionFromRelativePosition(d,this.host.ydoc);return!g||!u||g.type!==l||u.type!==l||u.index<=g.index?null:{start:g.index,end:u.index}}blocksWithNotesAndChrome(t){return[...t.children,...t.notes??[],...t.chrome??[]]}collectSuggestionIdsFromBlockValue(t,e){ft.collectSuggestionIdsFromBlockValue(t,e)}static collectSuggestionIdsFromBlockValue(t,e){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const r of t)ft.collectSuggestionIdsFromBlockValue(r,e);return}const n=t;typeof n.suggestionId=="string"&&n.suggestionId.length&&e.add(n.suggestionId);const o=mn(n.marks?.layeredInsertion);if(o&&e.add(o.id),typeof n.structuralSuggestionId=="string"&&n.structuralSuggestionId.length&&e.add(n.structuralSuggestionId),typeof n.structuralSuggestionRecords=="string"&&n.structuralSuggestionRecords.length)try{const r=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(r))for(const i of r)i&&typeof i.id=="string"&&i.id&&e.add(i.id)}catch{}n.marks&&typeof n.marks.suggestionId=="string"&&n.marks.suggestionId.length&&e.add(n.marks.suggestionId);for(const r of Object.values(n))r&&typeof r=="object"&&ft.collectSuggestionIdsFromBlockValue(r,e)}getSequenceReplacementMembers(t){const e=[],n=o=>{o.toArray().forEach((r,i)=>{r instanceof I.XmlElement&&(r.getAttribute("structuralSuggestionId")===t.id?e.push({yBlock:r,yParent:o,index:i}):n(r))})};for(const o of["content","notes"])this.host.ydoc.share.has(o)&&n(this.host.ydoc.getXmlFragment(o));return e}preserveSequenceAfterParagraphSplit(t,e){for(const r of e)this.setParagraphStructuralSuggestion(r,"change",void 0,t.id,"Paragraph");const n=this.getSequenceReplacementMembers(t),o={...t,blockId:n[0].yBlock.getAttribute("id"),sequenceBlockIds:n.map(({yBlock:r})=>r.getAttribute("id"))};this.saveLiveSuggestion(o,n[0].yBlock);for(const r of n.slice(1))this.embedLiveSuggestionRecordInTree(o,r.yBlock)}expandPendingSequenceBlockIds(t){for(const e of this.getLiveSuggestionIds()){const n=this.getLiveSuggestion(e);if(!(n?.type!=="block-change"||!n.sequenceBlockIds||!this.liveSuggestionRecordTouchesAnyBlock(n,t))){n.beforeBlock.id&&t.add(n.beforeBlock.id);for(const{yBlock:o}of this.getSequenceReplacementMembers(n)){const r=o.getAttribute("id");r&&t.add(r)}}}}resetTablePropertyRevisions(t,e,n,o){let r=null,i=null,a=null;for(const l of[...t]){if(r??(r=Ct(e)),i??(i=Ct(n)),!a){a=new Set;for(const{block:g}of r.values())if(g.type==="table")for(const u of g.children)a.add(u.id)}const c=r.get(l)?.block,d=i.get(l)?.block;if(c?.type==="table"&&d?.type==="table"){if(rn(c,d)){const g=o?W(o,l):null;if(g?.type==="table"&&!this.tableHasPendingStructure(l)&&this.buildTableStructureChange(g,d,"probe")){t.delete(l);for(const{block:u}of Ct({children:[g]}).values())t.delete(u.id)}continue}t.delete(l);for(const g of[...this.getLiveSuggestionStore().values()])if(!(g.type!=="table-change"||g.tableId!==l)){if(!this.applySuggestionRecordRejection(g))throw new Error("Could not restore the pending table formatting for replanning.");this.deleteLiveSuggestion(g.id)}}else(c?.type==="table-cell"||a.has(l))&&t.delete(l)}}resetLiveSuggestionsForBlocks(t,e){const n=new Set(t);this.expandPendingSequenceBlockIds(n);for(const g of this.getLiveSuggestionStore().values())if(g.type==="block-change"&&g.sequenceBlockIds&&this.liveSuggestionRecordTouchesAnyBlock(g,n)&&!this.applySuggestionRecordRejection(g))throw new Error("Could not restore the pending list conversion for replanning.");const o=this.host.collapseAffectedBlockIds(n,e);if(o.length===0)return;const r=new Set,i=this.host.getDocument(),a=Ct(i),l=Ct(e),c=new Set(o);for(const[g,u]of this.getLiveSuggestionStore())this.liveSuggestionRecordTouchesAnyBlock(u,c)&&r.add(g);for(const g of o){const u=a.get(g)?.block??W(i,g);u&&this.collectSuggestionIdsFromBlockValue(u,r)}const d=this.getSuggestionMutationSelection();for(const g of o){const u=a.get(g)?.block??W(i,g),f=l.get(g)?.block??W(e,g);if(f){if(!u||u.type==="paragraph"&&f.type==="paragraph"&&Ut(u,f))continue;this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(g,this.cloneSuggestionSnapshot(f),d,d));continue}u&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(g,d,d))}this.host.transact(()=>{for(const g of r)this.deleteLiveSuggestion(g)})}liveSuggestionRecordTouchesAnyBlock(t,e){const n=o=>e.has(o.getAttribute("id")??"")||o.toArray().some(r=>r instanceof I.XmlElement&&n(r));switch(t.type){case"block-change":return e.has(t.blockId)||!!t.sequenceBlockIds&&(!!t.beforeBlock.id&&e.has(t.beforeBlock.id)||this.getSequenceReplacementMembers(t).some(({yBlock:o})=>n(o)));case"block-insert":case"block-delete":case"paragraph-split":return e.has(t.blockId);case"table-change":return e.has(t.tableId);case"paragraph-merge":return e.has(t.firstBlockId)||e.has(t.secondBlockId);case"inline-format":return t.spans.some(o=>e.has(o.blockId));case"inline-text":return!1}}applyLiveSuggestionDecisionInternal(t,e){const n=this.normalizeLiveSuggestionIds(t);if(n.length===0)return 0;const o=n.filter(l=>{const c=this.getLiveSuggestion(l);return!c||c.type==="inline-text"||c.type==="inline-format"});if(o.length===n.length)return this.applyInlineSuggestionDecisions(new Set(o),e).size;let r=this.applyInlineSuggestionDecisions(new Set(o),e).size;const i=this.host.documentId==="live-suggestion-projection"?this.applySimpleProjectionBlockDecisions(n,e):new Set;r+=i.size;const a=new Set;for(const l of n){if(i.has(l))continue;const c=this.getLiveSuggestion(l);if(!c||c.type==="inline-text"||c.type==="inline-format")continue;const d=c?.type==="block-change"&&!this.host.isListItemBlockChangeRecord(c);if(d&&a.has(c.blockId)){this.deleteLiveSuggestion(l),r+=1;continue}(e==="accept"?this.acceptLiveSuggestionWithoutPruning(l):this.rejectLiveSuggestionWithoutPruning(l))&&(d&&a.add(c.blockId),r+=1)}return r}applySimpleProjectionBlockDecisions(t,e){const n=new Set,o=new Set,r=new Set,i=new Set;for(const l of t){const c=this.getLiveSuggestion(l);if(c){if(e==="accept"&&c.type==="block-delete"||e==="reject"&&c.type==="block-insert"){n.add(l),o.add(c.blockId),c.cleanupTrailingParagraphId&&o.add(c.cleanupTrailingParagraphId),i.add(l);continue}(e==="accept"&&(c.type==="block-insert"||c.type==="paragraph-split")||e==="reject"&&(c.type==="block-delete"||c.type==="paragraph-merge"))&&(r.add(l),i.add(l))}}if(i.size===0)return i;const a=l=>{const c=l.toArray();for(let d=c.length-1;d>=0;d-=1){const g=c[d];if(!(g instanceof I.XmlElement))continue;const u=g.getAttribute("id"),f=g.getAttribute("structuralSuggestionId"),h=g.getAttribute("suggestionId");if(typeof u=="string"&&o.has(u)||typeof f=="string"&&n.has(f)||typeof h=="string"&&n.has(h)){l.delete(d,1);continue}typeof f=="string"&&r.has(f)&&this.clearElementStructuralSuggestion(g),typeof h=="string"&&r.has(h)&&this.setDiffSuggestionAttributes(g,void 0,void 0),a(g)}};return this.host.transact(()=>{a(this.host.getYContentFragment()),a(this.host.getYNotesFragment());for(const l of i)this.deleteLiveSuggestion(l)}),i}applyLiveSuggestionDecisionScopeInternal(t){let e=0,n=[];const o=new Set,r=new Set,i=[];for(let a=0;a<tl;a+=1){const l=this.getNextSuggestionIdsForDecisionScope(t.scope,a);if(a===0&&(n=l),l.length===0)break;const c=l.join("\0");if(r.has(c))break;r.add(c);for(const g of l)o.add(g);const d=this.applyLiveSuggestionDecisionInternal(l,t.decision);if(i.push(...this.pruneUnresolvableLiveSuggestionsInternal()),d<=0)break;e+=d}return{decision:t.decision,scope:t.scope,resolvedCount:e,initialSuggestionIds:n,attemptedSuggestionIds:Array.from(o),attemptedSuggestionIdCount:o.size,prunedSuggestions:i}}decideLiveSuggestions(t){this.host.lastPrunedUnresolvableLiveSuggestions=[];const e=this.getInitialSuggestionIdsForDecisionScope(t.scope),n={decision:t.decision,scope:t.scope,resolvedCount:0,initialSuggestionIds:e,attemptedSuggestionIds:[],attemptedSuggestionIdCount:0,prunedSuggestions:[]};if(e.length===0)return n;let o=n;const r=t.historyOrigin??this.getLiveSuggestionDecisionHistoryOrigin(t);return this.host.runWithUndoGroup(r,()=>{let i=this.applyLiveSuggestionDecisionScopeInternal(t);for(let l=0;l<e.length&&i.resolvedCount>0;l++){const c=new Set(this.getInitialSuggestionIdsForDecisionScope(t.scope)),d=e.filter(f=>c.has(f));if(d.length===0)break;const g=this.applyLiveSuggestionDecisionScopeInternal({...t,scope:{kind:"ids",suggestionIds:d}});if(g.resolvedCount===0)break;const u=[...new Set([...i.attemptedSuggestionIds,...g.attemptedSuggestionIds])];i={...i,resolvedCount:i.resolvedCount+g.resolvedCount,attemptedSuggestionIds:u,attemptedSuggestionIdCount:u.length,prunedSuggestions:i.prunedSuggestions.concat(g.prunedSuggestions)}}const a=i.prunedSuggestions.concat(this.pruneUnresolvableLiveSuggestionsInternal());o={...i,prunedSuggestions:a},this.host.lastPrunedUnresolvableLiveSuggestions=a,this.host.reconcileFootnotes(),this.host.resolveCommentsForSettledSuggestions(o.attemptedSuggestionIds)}),o}getLiveSuggestionDecisionHistoryOrigin(t){if(t.scope.kind==="source")return`live-suggestion-${t.decision}-source:${t.scope.source}`;if(t.scope.kind==="author")return`live-suggestion-${t.decision}-author:${t.scope.authorName}`;if(t.scope.kind==="suggestion-kind")return`live-suggestion-${t.decision}-kind:${t.scope.suggestionKind}`;const e=this.normalizeLiveSuggestionIds(t.scope.suggestionIds);return`live-suggestion-${t.decision}-individual:${e.join(",")}`}acceptLiveSuggestions(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}acceptLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"source",source:t}})}acceptLiveSuggestionsByAuthor(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"author",authorName:t}})}rejectLiveSuggestionsByAuthor(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"author",authorName:t}})}acceptLiveSuggestionsByKind(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"suggestion-kind",suggestionKind:t}})}rejectLiveSuggestionsByKind(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"suggestion-kind",suggestionKind:t}})}rejectLiveSuggestions(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}rejectLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"source",source:t}})}runWithoutSuggesting(t){const e=this.host.suggestingMode;this.host.suggestingMode=!1;try{return t()}finally{this.host.suggestingMode=e}}getSuggestionIdFromInheritedMarks(t){return t?.insertion&&t.suggestionId&&this.isOwnPendingSuggestionSpan(t)?t.suggestionId:gt()}getSuggestionIdForSuggestedSelectionOverwrite(t,e,n){if(!this.host.suggestingMode||!n?.anchor||!n.focus||xt(t,n.anchor,n.focus)===0)return null;const[o,r]=xt(t,n.anchor,n.focus)<=0?[n.anchor,n.focus]:[n.focus,n.anchor];if(o.block!==e.block||r.block!==e.block)return null;const i=W(t,e.block);if(!i)return null;if(i.type==="paragraph")return r.offset>o.offset?gt():null;if(i.type!=="list")return null;const a=this.host.getListCursorInfo(i,o),l=this.host.getListCursorInfo(i,r);return!a||!l||a.itemIndex!==l.itemIndex?null:(i.children[a.itemIndex],l.offsetInItem>a.offsetInItem?gt():null)}getInlineInsertionSuggestionNodeInTextChildren(t,e){let n=0,o=null;for(const r of t){if(r.type!=="text")continue;const i=r.text.length,a=n+i,l=!!(r.marks?.insertion&&r.marks.suggestionId&&this.isOwnPendingSuggestionSpan(r.marks));if(e>=n&&e<=a&&l)return r;e===a&&l&&(o=r),n=a}return o}getInlineInsertionSuggestionIdInTextChildren(t,e){return this.getInlineInsertionSuggestionNodeInTextChildren(t,e)?.marks?.suggestionId??null}getInlineInsertionSuggestionNodeAtPosition(t,e){const n=W(t,e.block);if(!n)return null;if(n.type==="paragraph")return this.getInlineInsertionSuggestionNodeInTextChildren(n.children,e.offset);if(n.type!=="list")return null;const o=this.host.getListCursorInfo(n,e);if(!o)return null;const r=n.children[o.itemIndex];return r?this.getInlineInsertionSuggestionNodeInTextChildren(r.children,o.offsetInItem):null}getInlineInsertionSuggestionIdAtPosition(t,e){return this.getInlineInsertionSuggestionNodeAtPosition(t,e)?.marks?.suggestionId??null}getStructuralInsertSuggestionIdAtPosition(t,e){const n=W(t,e.block);if(!n)return null;if("structuralSuggestionKind"in n&&n.structuralSuggestionKind==="insert"&&"structuralSuggestionId"in n&&typeof n.structuralSuggestionId=="string")return n.structuralSuggestionId;if(n.type!=="list")return null;const o=this.host.getListCursorInfo(n,e);if(!o)return null;const r=n.children[o.itemIndex];return r?.structuralSuggestionKind==="insert"&&r.structuralSuggestionId?r.structuralSuggestionId:null}getBlockInsertSuggestionIdForBlock(t){return t?(t.type==="paragraph"||t.type==="list")&&t.structuralSuggestionKind==="insert"&&typeof t.structuralSuggestionId=="string"&&t.structuralSuggestionId.length>0?t.structuralSuggestionId:"diffState"in t&&t.diffState==="insert"&&"suggestionId"in t&&typeof t.suggestionId=="string"&&t.suggestionId.length>0?t.suggestionId:null:null}getEnclosingBlockInsertSuggestionIdForBlockId(t,e){let n=W(t,e);for(;n;){const o=this.getBlockInsertSuggestionIdForBlock(n);if(o)return o;if(typeof n.id!="string")break;const r=Xt(t,n.id);if(!r||!("id"in r)||typeof r.id!="string")break;n=r}return null}stripSuggestionMarksFromTextMark(t){if(!t)return;const e={...t};return delete e.insertion,delete e.deletion,delete e.suggestionId,delete e.formatChange,delete e.suggestionSource,delete e.suggestionAuthorType,delete e.suggestionCreatedAt,delete e.suggestionLabel,delete e.suggestionCommentThreadId,delete e.suggestionAuthorName,delete e.suggestionAgentModel,delete e.suggestionAgentConversationId,delete e.suggestionAgentRequestId,delete e.suggestionAgentTurn,delete e.suggestionPriorAttributes,delete e.layeredInsertion,delete e.docxMove,Object.keys(e).length>0?e:void 0}buildInlineSuggestionMetadataMarks(t,e,n){const o=this.host.liveSuggestionMetadataContext,r=o?.source??"manual",i=o?.authorType??(r==="agent"?"ai":"human");return{suggestionId:t,suggestionSource:r,suggestionAuthorType:i,suggestionCreatedAt:n??o?.createdAt??Date.now(),suggestionLabel:e??o?.label,...o?.commentThreadId?{suggestionCommentThreadId:o.commentThreadId}:{},suggestionAuthorName:this.resolveSuggestionAuthorName(i,o?.agentName),...o?.agentModel?{suggestionAgentModel:o.agentModel}:{},...o?.agentConversationId?{suggestionAgentConversationId:o.agentConversationId}:{},...o?.agentRequestId!==void 0?{suggestionAgentRequestId:o.agentRequestId}:{},...o?.agentTurn!==void 0?{suggestionAgentTurn:o.agentTurn}:{}}}buildSuggestionInsertionMarks(t,e,n="Insert",o,r){const i=t?.suggestionId===e?t:r?.suggestionId===e?r:null;return this.recordStampedId("insertionIds",e),{...t||{},insertion:!0,...this.buildInlineSuggestionMetadataMarks(e,n,o),...this.pickInlineSuggestionMetadataMarks(i)}}pickInlineSuggestionMetadataMarks(t){return t?Object.fromEntries(Object.entries({suggestionSource:t.suggestionSource,suggestionAuthorType:t.suggestionAuthorType,suggestionCreatedAt:t.suggestionCreatedAt,suggestionLabel:t.suggestionLabel,suggestionCommentThreadId:t.suggestionCommentThreadId,suggestionAuthorName:t.suggestionAuthorName,suggestionAgentModel:t.suggestionAgentModel,suggestionAgentConversationId:t.suggestionAgentConversationId,suggestionAgentRequestId:t.suggestionAgentRequestId,suggestionAgentTurn:t.suggestionAgentTurn}).filter(([,e])=>e!==void 0)):{}}clearInheritedDeletionFromInsertedSuggestion(t,e,n){n<=0||at(t,e,n,{deletion:null})}findAdjacentDeletionSuggestionAttrs(t,e,n){if(n<=0)return null;const o=e+n,r=st(t);let i=0,a=null,l=null;for(const c of r){if(typeof c.insert!="string")continue;const d=i,g=i+c.insert.length,u=c.attributes||{},f=u.deletion&&typeof u.suggestionId=="string"&&this.isOwnPendingSuggestionSpan(u);if(f&&g===e&&(a=u),f&&d===o){l=u;break}if(i=g,i>o)break}return a??l}findAdjacentDeletionSuggestionId(t,e,n){return this.findAdjacentDeletionSuggestionAttrs(t,e,n)?.suggestionId??null}applySuggestedDeletionToTextRange(t,e,n,o){const r=this.host.collectOverlappingTextSpans(t,e,n);if(r.length===0)return{retainedLength:0,changed:!1};const i=o?null:this.findAdjacentDeletionSuggestionAttrs(t,e,n),a=o??i?.suggestionId??gt(),l={...this.buildInlineSuggestionMetadataMarks(a,"Delete"),...this.pickInlineSuggestionMetadataMarks(i?.suggestionId===a?i:null)};let c=0,d=!1;for(let g=r.length-1;g>=0;g--){const u=r[g],f=u.attributes||{};if(f.insertion){if(this.isOwnPendingSuggestionSpan(f)){t.delete(u.start,u.length),d=!0;continue}c+=u.length,this.recordStampedId("deletionIds",a),at(t,u.start,u.length,{deletion:!0,...l,layeredInsertion:JSON.stringify({id:f.suggestionId,source:f.suggestionSource,authorType:f.suggestionAuthorType,createdAt:f.suggestionCreatedAt,label:f.suggestionLabel,authorName:f.suggestionAuthorName,commentThreadId:f.suggestionCommentThreadId,agentModel:f.suggestionAgentModel,agentConversationId:f.suggestionAgentConversationId,agentRequestId:f.suggestionAgentRequestId,agentTurn:f.suggestionAgentTurn}),formatChange:null,suggestionPriorAttributes:null}),d=!0;continue}if(c+=u.length,f.deletion){o&&f.suggestionId!==o&&(this.recordStampedId("deletionIds",a),at(t,u.start,u.length,{...l,formatChange:null,suggestionPriorAttributes:null}),d=!0);continue}this.recordStampedId("deletionIds",a),at(t,u.start,u.length,{deletion:!0,...l,formatChange:null,suggestionPriorAttributes:null}),d=!0}return{retainedLength:c,changed:d}}clearElementStructuralSuggestion(t){t.removeAttribute("structuralSuggestionId"),t.removeAttribute("structuralSuggestionKind"),t.removeAttribute("structuralSuggestionRole"),t.removeAttribute("structuralSuggestionLabel"),t.removeAttribute("structuralSuggestionRecord")}clearParagraphStructuralSuggestion(t){this.clearElementStructuralSuggestion(t)}setElementStructuralSuggestion(t,e,n,o,r){this.recordStampedId(e==="insert"||e==="split"?"structuralInsertIds":"structuralDeleteIds",o),t.setAttribute("structuralSuggestionId",o),t.setAttribute("structuralSuggestionKind",e),n?t.setAttribute("structuralSuggestionRole",n):t.removeAttribute("structuralSuggestionRole"),r?t.setAttribute("structuralSuggestionLabel",r):t.removeAttribute("structuralSuggestionLabel")}setParagraphStructuralSuggestion(t,e,n,o,r){this.setElementStructuralSuggestion(t,e,n,o,r)}setDiffSuggestionAttributes(t,e,n){e?t.setAttribute("diffState",e):t.removeAttribute("diffState"),n?t.setAttribute("suggestionId",n):t.removeAttribute("suggestionId")}markInsertedBlockElement(t,e,n="Insert"){if(t.nodeName==="paragraph"||t.nodeName==="list"||t.nodeName==="list-item"){this.clearElementStructuralSuggestion(t),this.setElementStructuralSuggestion(t,"insert",void 0,e,n);return}this.setDiffSuggestionAttributes(t,"insert",e)}markDeletedBlockElement(t,e,n="Delete"){if(t.nodeName==="paragraph"||t.nodeName==="list"||t.nodeName==="list-item"){this.clearElementStructuralSuggestion(t),this.setElementStructuralSuggestion(t,"delete",void 0,e,n);return}this.setDiffSuggestionAttributes(t,"delete",e)}markTableSuggestionRows(t,e,n,o){const r=this.cloneSuggestionSnapshot(t);return r.children=r.children.map(i=>e.has(i.id)?{...i,diffState:n,suggestionId:o,children:i.children.map(a=>({...a,diffState:n,suggestionId:o}))}:i),r}markTableSuggestionColumn(t,e,n,o){const r=this.cloneSuggestionSnapshot(t);return r.children=r.children.map(i=>({...i,children:i.children.map((a,l)=>l===e?{...a,diffState:n,suggestionId:o}:a)})),r}buildMinimalParagraphEdit(t,e,n){if(t.children.some(f=>f.type!=="text")||e.children.some(f=>f.type!=="text"))return null;const o=t.children.map(f=>f.text).join(""),r=e.children.map(f=>f.text).join("");let i=0;for(;i<o.length&&i<r.length&&o[i]===r[i];)i++;let a=0;for(;a<o.length-i&&a<r.length-i&&o[o.length-1-a]===r[r.length-1-a];)a++;const l=/[\p{L}\p{N}_]/u;for(;i>0&&l.test(o[i-1]);)i--;for(;a>0&&l.test(o[o.length-a]);)a--;const c=gt(),d=this.buildInlineSuggestionMetadataMarks(c,n),g=(f,h)=>f.map(p=>{const m=this.sanitizePreviewMarks(p.marks)??{};return delete m.insertion,delete m.deletion,{...p,marks:{...m,...d,[h]:!0}}}),u=(f,h,p)=>h<p?this.host.extractTextNodesForRange(f,h,p):[];return{...e,children:[...u(e,0,i),...g(u(t,i,o.length-a),"deletion"),...g(u(e,i,r.length-a),"insertion"),...u(e,r.length-a,r.length)]}}blockChangeTarget(t,e){const n=i=>i&&"children"in i?Pt(Bn(JSON.parse(JSON.stringify(i.children),(a,l)=>a==="id"?void 0:l))):void 0,o=n(t.beforeBlock);if(!t.acceptedBlock||o===void 0||o!==n(t.acceptedBlock))return e;const r=W(this.host.getDocument(),t.blockId);return!r||r.type!==e.type||!("children"in r)?e:{...e,children:r.children}}buildTablePropertyOnlyChange(t,e,n,o,r){if(rn(n,o)||!this.hasSameTableGeometry(n,o)||!this.hasSameTableGeometry(e,o)||!n.children.every((d,g)=>d.children.every((u,f)=>Ut(u.children,o.children[g].children[f].children))))return null;const i=(d,g,u)=>{const f=d,h=g,p=u;for(const m of new Set([...Object.keys(h),...Object.keys(p)]))m==="children"||m==="id"||Ut(h[m],p[m])||(p[m]===void 0?delete f[m]:f[m]=structuredClone(p[m]))},a=d=>{const g=this.cloneSuggestionSnapshot(d);return i(g,n,o),g.children.forEach((u,f)=>{i(u,n.children[f],o.children[f]),u.children.forEach((h,p)=>i(h,n.children[f].children[p],o.children[f].children[p]))}),g},l=W(this.createLiveSuggestionProjection("accept").doc,t);if(l?.type!=="table"||!this.hasSameTableGeometry(l,o))return null;const c=this.buildSuggestedTableChange(l,a(l),r);return c?{liveBlock:a(e),record:c.record,label:c.label}:null}decomposeTableRowAndCellChanges(t,e,n,o){const r=new Map(t.children.map(f=>[f.id,f])),i=new Set(e.children.map(f=>f.id));if(t.children.some(f=>!i.has(f.id)))return null;const a=f=>Pt(Bn(JSON.parse(JSON.stringify(f),(h,p)=>h==="id"?void 0:p))),l=new Map;for(const f of e.children){const h=r.get(f.id);if(h){if(a({...h,children:[]})!==a({...f,children:[]})||h.children.length!==f.children.length)return null;for(let p=0;p<f.children.length;p++){const m=h.children[p],y=f.children[p];if(m.id!==y.id||a({...m,children:[]})!==a({...y,children:[]})||m.children.length!==y.children.length)return null;for(let b=0;b<y.children.length;b++){const k=m.children[b],S=y.children[b];if(k.id!==S.id)return null;if(a(k)===a(S))continue;if(k.type!=="paragraph"||S.type!=="paragraph")return null;const v=this.buildMinimalParagraphEdit(k,S,o);if(!v)return null;l.set(S.id,v)}}}}const c={...e,children:e.children.map(f=>r.get(f.id)??f)},d=e.children.length>t.children.length,g=d?this.buildSuggestedTableChange(t,c,n):null;if(d&&!g||!d&&l.size===0)return null;const u=g?.liveBlock??c;return{liveBlock:{...u,children:u.children.map(f=>r.has(f.id)?{...f,children:f.children.map((h,p)=>({...h,children:e.children.find(m=>m.id===f.id).children[p].children.map(m=>l.get(m.id)??m)}))}:f)},record:g?.record}}buildSuggestedTableChange(t,e,n){const o=(m,y,b)=>({id:n,type:"table-change",tableId:t.id,label:m,tableRevision:{version:1,suggestionKind:y,...b}}),r=t.children.map(m=>m.id),i=e.children.map(m=>m.id),a=(m,y)=>{const b=y==="accepted"?"deletion":"insertion";if(Array.isArray(m))return m.filter(S=>!(S&&typeof S=="object"&&S.type==="text"&&S.marks?.[b])).map(S=>a(S,y));if(!m||typeof m!="object")return m;const k={};for(const[S,v]of Object.entries(m))if(S!=="id"){if(S==="marks"&&v&&typeof v=="object"){const x={};for(const[w,A]of Object.entries(v))w==="insertion"||w==="deletion"||w.startsWith("suggestion")||w==="fontFamily"&&A===jt||(x[w]=A);Object.keys(x).length&&(k.marks=x);continue}k[S]=a(v,y)}return k},l=(m,y="accepted")=>Pt(Bn(a(JSON.parse(JSON.stringify(m??null)),y))),c=(m,y)=>l(m)===l(y)||l(m,"rejected")===l(y,"rejected"),d=c({...t,children:[]},{...e,children:[]}),g=(m,y)=>{let b=0;for(const k of y)k===m[b]&&b++;return b===m.length};if(e.children.length>t.children.length&&g(r,i)&&d&&t.children.every(m=>c(m,e.children.find(y=>y.id===m.id)))){const m=new Set(r),y=e.children.map((S,v)=>({row:S,rowIndex:v})).filter(({row:S})=>!m.has(S.id)),b=new Set(y.map(({row:S})=>S.id)),k=y.length===1?"Insert table row":"Insert table rows";return{liveBlock:this.markTableSuggestionRows(e,b,"insert",n),label:k,record:o(k,"insert",{markers:y.map(({row:S,rowIndex:v})=>({kind:"row-insert",rowId:S.id,rowIndex:v})),operations:y.map(({row:S,rowIndex:v})=>({kind:"row",action:"insert",rowId:S.id,rowIndex:v,row:this.cloneSuggestionSnapshot(S)}))})}}if(e.children.length<t.children.length&&g(i,r)&&d&&e.children.every(m=>c(m,t.children.find(y=>y.id===m.id)))){const m=new Set(i),y=t.children.map((x,w)=>({row:x,rowIndex:w})).filter(({row:x})=>!m.has(x.id)),b=new Set(y.map(({row:x})=>x.id)),k=new Map(e.children.map(x=>[x.id,x])),S=this.cloneSuggestionSnapshot(e);S.children=t.children.map(x=>k.get(x.id)??x);const v=y.length===1?"Delete table row":"Delete table rows";return{liveBlock:this.markTableSuggestionRows(S,b,"delete",n),label:v,record:o(v,"delete",{markers:y.map(({row:x,rowIndex:w})=>({kind:"row-delete",rowId:x.id,rowIndex:w})),operations:y.map(({row:x,rowIndex:w})=>({kind:"row",action:"delete",rowId:x.id,rowIndex:w,row:this.cloneSuggestionSnapshot(x)}))})}}const u=this.host.findSingleTableColumnDelta(t,e);if(u&&(!c({...t,children:[],columnWidths:[]},{...e,children:[],columnWidths:[]})||t.children.some((m,y)=>{const b=e.children[y];return c({...m,children:[]},{...b,children:[]})?m.children.some(k=>{const S=b.children.find(v=>v.id===k.id);return S&&!c(k,S)}):!0})))return null;if(u?.kind==="insert"){const m=[],y=[];for(let b=0;b<e.children.length;b++){const k=e.children[b],S=k.children[u.index];S&&(m.push({kind:"cell",action:"insert",rowId:k.id,cellId:S.id,cellIndex:u.index,cell:this.cloneSuggestionSnapshot(S)}),y.push({kind:"cell-insert",rowId:k.id,cellId:S.id,rowIndex:b,cellIndex:u.index,gridColumn:u.index}))}return m.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(e,u.index,"insert",n),label:"Insert table column",record:o("Insert table column","insert",{markers:y,operations:m})}}if(u?.kind==="delete"){const m=[],y=[];for(let b=0;b<t.children.length;b++){const k=t.children[b],S=k.children[u.index];S&&(m.push({kind:"cell",action:"delete",rowId:k.id,cellId:S.id,cellIndex:u.index,cell:this.cloneSuggestionSnapshot(S)}),y.push({kind:"cell-delete",rowId:k.id,cellId:S.id,rowIndex:b,cellIndex:u.index,gridColumn:u.index}))}return m.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(t,u.index,"delete",n),label:"Delete table column",record:o("Delete table column","delete",{markers:y,operations:m})}}const f=Mn(t),h=Mn(e);if(t.children.length===e.children.length&&f.rows===h.rows&&f.cols===h.cols&&t.children.every((m,y)=>m.id===e.children[y]?.id)){const m=f.cells.map(y=>{const b=h.byId.get(y.cell.id);return b?{before:y,after:b}:null}).filter(y=>!!y&&(y.before.rowSpan!==y.after.rowSpan||y.before.colSpan!==y.after.colSpan));if(m.length===1&&m[0].before.col===m[0].after.col&&m[0].before.row===m[0].after.row&&m[0].before.colSpan===m[0].after.colSpan&&m[0].before.rowSpan!==m[0].after.rowSpan){const y=m[0].before,b=m[0].after,k=b.rowSpan>y.rowSpan,S=k?y.row+y.rowSpan:b.row+b.rowSpan,v=k?b.row+b.rowSpan:y.row+y.rowSpan,x=[],w=new Set([t.children[y.row].id]);for(let E=S;E<v;E++){const B=e.children[E];B&&(w.add(B.id),x.push({kind:"cell-merge",rowId:B.id,rowIndex:E,gridColumn:b.col,...k?{vMerge:"cont"}:{vMergeOrig:"cont"}}))}const A=e.children.filter(E=>w.has(E.id)).map(E=>this.cloneSuggestionSnapshot(E)),P=t.children.filter(E=>w.has(E.id)).map(E=>this.cloneSuggestionSnapshot(E));if(!d||t.children.some(E=>!w.has(E.id)&&!c(E,e.children.find(B=>B.id===E.id))))return null;const T=k?"Merge table cells":"Split table cells";return{liveBlock:this.cloneSuggestionSnapshot(e),label:T,record:o(T,"format",{markers:x,operations:[{kind:"geometry",pendingRows:A,acceptedRows:this.cloneSuggestionSnapshot(A),rejectedRows:P}]})}}}const p=m=>Pt(JSON.parse(JSON.stringify(m.children,(y,b)=>{if(y!=="marks"||!b||typeof b!="object")return b;const k={...b};return k.fontFamily===jt&&delete k.fontFamily,Object.keys(k).length>0?k:void 0})));if(t.children.length===e.children.length&&t.children.every((m,y)=>{const b=e.children[y];return b?.id===m.id&&m.children.length===b.children.length&&m.children.every((k,S)=>{const v=b.children[S];return v?.id===k.id&&k.colSpan===v.colSpan&&k.rowSpan===v.rowSpan&&p(k)===p(v)})})){const m=[],y=[],b=(S,v,x)=>{const w={},A={};for(const P of x){const T=S[P],E=v[P];JSON.stringify(T)!==JSON.stringify(E)&&(E!==void 0&&(w[P]=E),T!==void 0&&(A[P]=T))}return{current:w,prior:A}};JSON.stringify(t.columnWidths)!==JSON.stringify(e.columnWidths)&&m.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""});const k=b(t,e,["tableWidth","align","borderColor","borderWidth","borders","cellPadding"]);(Object.keys(k.current).length>0||Object.keys(k.prior).length>0)&&(y.push({kind:"table-properties"}),m.push({kind:"properties",target:"table",currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:k.current,priorAttributes:k.prior})),t.hasHeader!==e.hasHeader&&e.children[0]&&(y.push({kind:"row-properties",rowId:e.children[0].id,rowIndex:0}),m.push({kind:"properties",target:"row",rowId:e.children[0].id,currentPropertiesXml:"",priorPropertiesXml:"",currentTableAttributes:e.hasHeader===void 0?{}:{hasHeader:e.hasHeader},priorTableAttributes:t.hasHeader===void 0?{}:{hasHeader:t.hasHeader}}));for(let S=0;S<e.children.length;S++){const v=t.children[S],x=e.children[S];for(let w=0;w<x.children.length;w++){const A=v.children[w],P=x.children[w],T=b(A,P,["verticalAlign","backgroundColor","borders","padding"]);if(Object.keys(T.current).length===0&&Object.keys(T.prior).length===0)continue;const E=h.byId.get(P.id);y.push({kind:"cell-properties",rowId:x.id,cellId:P.id,rowIndex:S,cellIndex:w,gridColumn:E?.col}),m.push({kind:"properties",target:"cell",rowId:x.id,cellId:P.id,currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:T.current,priorAttributes:T.prior})}}if(m.length>0)return{liveBlock:this.cloneSuggestionSnapshot(e),label:"Change table formatting",record:o("Change table formatting","format",{markers:y,operations:m})}}return null}buildTableStructureChange(t,e,n){const o=this.reconcileTableDescendantIds(t,e);if(He(t,o))return null;const r=this.buildSuggestedTableChange(t,o,n),i=r?.record.tableRevision.operations??[];return!r||!i.some(a=>a.kind==="row"||a.kind==="cell")||!i.every(a=>a.kind==="row"||a.kind==="cell"||a.kind==="grid")?null:{after:o,change:r}}graftTableStructureChange(t,e,n){const o=this.cloneSuggestionSnapshot(t),r=e.id,i=(l,c)=>{l.diffState=c,l.suggestionId=r},a=(l,c,d)=>{const g=c.findIndex(u=>u.id===d.id);for(let u=g-1;u>=0;u--){const f=l.findIndex(h=>h.id===c[u].id);if(f>=0){l.splice(f+1,0,d);return}}for(let u=g+1;u<c.length;u++){const f=l.findIndex(h=>h.id===c[u].id);if(f>=0){l.splice(f,0,d);return}}l.push(d)};for(const l of e.tableRevision.operations){if(l.kind==="grid"){e.tableRevision.suggestionKind==="insert"&&(o.columnWidths=[...l.currentColumnWidths]);continue}if(l.kind==="row"){const g=o.children.find(u=>u.id===l.rowId);if(l.action==="delete"){if(!g||g.diffState)return null;i(g,"delete"),g.children.forEach(u=>i(u,"delete"))}else{if(g)return null;const u=this.cloneSuggestionSnapshot(l.row);i(u,"insert"),u.children.forEach(f=>i(f,"insert")),a(o.children,n.children,u)}continue}if(l.kind!=="cell")return null;const c=o.children.find(g=>g.id===l.rowId);if(!c)return null;const d=c.children.find(g=>g.id===l.cellId);if(l.action==="delete"){if(!d||d.diffState)return null;i(d,"delete")}else{const g=n.children.find(f=>f.id===c.id);if(d||!g)return null;const u=this.cloneSuggestionSnapshot(l.cell);i(u,"insert"),a(c.children,g.children,u)}}return o}tableHasPendingStructure(t){for(const n of this.getLiveSuggestionStore().values())if(n.type==="table-change"&&n.tableId===t)return!0;const e=W(this.host.getDocument(),t);return e?.type==="table"&&e.children.some(n=>!!n.diffState||n.children.some(o=>!!o.diffState))}hasSameTableGeometry(t,e){return t.children.length===e.children.length&&t.children.every((n,o)=>{const r=e.children[o];return r?.id===n.id&&n.children.length===r.children.length&&n.children.every((i,a)=>{const l=r.children[a];return l?.id===i.id&&l.colSpan===i.colSpan&&l.rowSpan===i.rowSpan})})}reconcileTableDescendantIds(t,e){const n=this.cloneSuggestionSnapshot(e),o=new Set(["id","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),r=b=>Pt(JSON.parse(JSON.stringify(b,(k,S)=>o.has(k)?void 0:S))),i=t.children,a=n.children,l=new Set(i.map(b=>b.id)),c=new Set(a.map(b=>b.id)),d=new Set(i.flatMap(b=>b.children.map(k=>k.id))),g=new Set(a.flatMap(b=>b.children.map(k=>k.id))),u=new Map([...i,...a].map(b=>[b,r(b)])),f=(b,k)=>b.id===k.id?0:l.has(k.id)||c.has(b.id)?2.25:u.get(b)===u.get(k)?0:b.children.length===k.children.length&&b.children.every((S,v)=>{const x=k.children[v];return x?.colSpan===S.colSpan&&x?.rowSpan===S.rowSpan})?.75:2.25,h=Array.from({length:i.length+1},()=>Array(a.length+1).fill(0));for(let b=0;b<=i.length;b++)h[b][0]=b;for(let b=0;b<=a.length;b++)h[0][b]=b;for(let b=1;b<=i.length;b++)for(let k=1;k<=a.length;k++)h[b][k]=Math.min(h[b-1][k]+1,h[b][k-1]+1,h[b-1][k-1]+f(i[b-1],a[k-1]));const p=[];let m=i.length,y=a.length;for(;m>0&&y>0;){const b=f(i[m-1],a[y-1]);b<2&&Math.abs(h[m][y]-(h[m-1][y-1]+b))<1e-4?(p.push([i[m-1],a[y-1]]),m--,y--):h[m][y]===h[m-1][y]+1?m--:y--}for(const[b,k]of p)if(k.id=b.id,b.children.length===k.children.length)for(let S=0;S<b.children.length;S++){const v=b.children[S],x=k.children[S];v.colSpan!==x.colSpan||v.rowSpan!==x.rowSpan||v.id!==x.id&&(d.has(x.id)||g.has(v.id))||(x.id=v.id)}return n}mergePendingTableRevisionState(t,e){const n=this.cloneSuggestionSnapshot(e);t.structuralSuggestionRecords&&(n.structuralSuggestionRecords=t.structuralSuggestionRecords),t.docxTablePropertyOverrides&&(n.docxTablePropertyOverrides=t.docxTablePropertyOverrides);const o=(r,i)=>{!i.diffState&&r.diffState&&(i.diffState=r.diffState),!i.suggestionId&&r.suggestionId&&(i.suggestionId=r.suggestionId)};for(let r=0;r<t.children.length;r++){const i=t.children[r];let a=n.children.find(l=>l.id===i.id);if(!a&&i.diffState==="delete"){const l=t.children.slice(r+1).map(d=>d.id).find(d=>n.children.some(g=>g.id===d)),c=l?n.children.findIndex(d=>d.id===l):n.children.length;a=this.cloneSuggestionSnapshot(i),n.children.splice(c,0,a)}if(a){o(i,a);for(let l=0;l<i.children.length;l++){const c=i.children[l];let d=a.children.find(g=>g.id===c.id);if(!d&&c.diffState==="delete"){const g=i.children.slice(l+1).map(f=>f.id).find(f=>a.children.some(h=>h.id===f)),u=g?a.children.findIndex(f=>f.id===g):a.children.length;d=this.cloneSuggestionSnapshot(c),a.children.splice(u,0,d)}d&&o(c,d)}}}return n}getYTextForSuggestionSpan(t){const e=Z(this.host.ydoc,t.blockId);if(!(e instanceof I.XmlElement))return null;if(t.itemIndex===void 0)return ct(e);const n=[];for(let r=0;r<e.length;r++){const i=e.get(r);i instanceof I.XmlElement&&i.nodeName==="list-item"&&n.push(i)}const o=n[t.itemIndex];return o?ct(o):null}stripInlineSuggestionMarks(t,e,n){at(t,e,n,{insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null})}restoreInlineSuggestionFormatting(t,e,n,o){const r=this.host.collectOverlappingTextSpans(t,e,n),i=r.length>0?r:[{start:e,length:n,attributes:{}}];for(const a of i){const l={insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null},c=xo(a.attributes?.suggestionPriorAttributes)??o,d=new Set([...Object.keys(a.attributes||{}),...Object.keys(c||{})]);d.delete("insertion"),d.delete("deletion"),d.delete("suggestionId"),d.delete("formatChange"),d.delete("suggestionSource"),d.delete("suggestionAuthorType"),d.delete("suggestionCreatedAt"),d.delete("suggestionLabel"),d.delete("suggestionCommentThreadId"),d.delete("suggestionAuthorName"),d.delete("suggestionAgentModel"),d.delete("suggestionAgentConversationId"),d.delete("suggestionAgentRequestId"),d.delete("suggestionAgentTurn"),d.delete("suggestionPriorAttributes"),d.delete("layeredInsertion"),d.delete("docxMove");for(const g of d)Object.prototype.hasOwnProperty.call(c,g)?l[g]=c[g]:bu.has(g)||(l[g]=null);at(t,a.start,a.length,l)}}clearStructuralSuggestionById(t,e){for(const n of t.toArray()){if(!(n instanceof I.XmlElement))continue;n.getAttribute("structuralSuggestionId")===e&&this.clearElementStructuralSuggestion(n);const o=n.getAttribute("structuralSuggestionRecords");if(typeof o=="string"&&o.length>0)try{const r=JSON.parse(o);if(Array.isArray(r)){const i=r.filter(a=>a?.id!==e);i.length!==r.length&&(i.length>0?n.setAttribute("structuralSuggestionRecords",JSON.stringify(i)):n.removeAttribute("structuralSuggestionRecords"))}}catch{}n.getAttribute("suggestionId")===e&&this.setDiffSuggestionAttributes(n,void 0,void 0),this.clearStructuralSuggestionById(n,e)}}blockChangeTargetIsOwned(t){if(t.sequenceBlockIds)return this.getSequenceReplacementMembers(t).length>0;const e=W(this.host.getDocument(),t.blockId);return e?this.blockContainsSuggestionMarker(e,t.id)?!0:e.structuralSuggestionId?!1:Ml(this.host.ydoc,t.blockId)===1:!1}blockContainsSuggestionMarker(t,e){if(!t||typeof t!="object")return!1;if(t.suggestionId===e||t.structuralSuggestionId===e)return!0;const n=t.structuralSuggestionRecords;if(typeof n=="string"&&n.length>0)try{const o=JSON.parse(n);if(Array.isArray(o)&&o.some(r=>r?.id===e))return!0}catch{}return Array.isArray(t.children)?t.children.some(o=>this.blockContainsSuggestionMarker(o,e)):!1}getSuggestionMutationSelection(){return this.host.afterOperationSelection??this.host.beforeOperationSelection??{anchor:null,focus:null}}collectNestedSuggestionIdsForBlock(t,e){const n=W(this.host.getDocument(),t);if(!n)return[];const o=new Set;return this.collectSuggestionIdsFromBlockValue(n,o),e&&o.delete(e),Array.from(o)}clearSuggestionMarkerFromValue(t,e){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const o of t)this.clearSuggestionMarkerFromValue(o,e);return}const n=t;if(n.suggestionId===e&&(delete n.suggestionId,delete n.diffState),n.structuralSuggestionId===e&&(delete n.structuralSuggestionId,delete n.structuralSuggestionKind,delete n.structuralSuggestionRole,delete n.structuralSuggestionLabel,delete n.structuralSuggestionRecord),typeof n.structuralSuggestionRecords=="string")try{const o=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(o)){const r=o.filter(i=>i?.id!==e);r.length>0?n.structuralSuggestionRecords=JSON.stringify(r):delete n.structuralSuggestionRecords}}catch{}for(const o of Object.values(n))o&&typeof o=="object"&&this.clearSuggestionMarkerFromValue(o,e)}applyTableGeometryRows(t,e,n){const o=new Map(e.map(a=>[a.id,a])),r=new Map(n.map(a=>[a.id,a])),i=new Set([...o.keys(),...r.keys()]);for(const a of i){const l=t.children.find(f=>f.id===a),c=o.get(a),d=r.get(a);if(!l||!c||!d)continue;const g=new Set(c.children.map(f=>f.id)),u=new Set(d.children.map(f=>f.id));l.children=l.children.filter(f=>!g.has(f.id)||u.has(f.id));for(let f=0;f<d.children.length;f++){const h=d.children[f],p=c.children.find(y=>y.id===h.id);let m=l.children.find(y=>y.id===h.id);if(!m&&!p&&(m=this.cloneSuggestionSnapshot(h),l.children.splice(Math.min(f,l.children.length),0,m)),!(!m||!p)){JSON.stringify(p.children)!==JSON.stringify(h.children)&&JSON.stringify(m.children)===JSON.stringify(p.children)&&(m.children=this.cloneSuggestionSnapshot(h.children));for(const y of["rowSpan","colSpan"])p[y]!==h[y]&&(h[y]===void 0?delete m[y]:m[y]=h[y])}}}}applyTableRevisionDecision(t,e){const n=W(this.host.getDocument(),t.tableId);if(!n||n.type!=="table")return!1;const o=this.cloneSuggestionSnapshot(n);let r={version:1};if(o.docxTablePropertyOverrides)try{const l=JSON.parse(o.docxTablePropertyOverrides);l?.version===1&&(r=l)}catch{}for(const l of t.tableRevision.operations){if(l.kind==="row"){const p=l.action==="insert"?e==="accept":e==="reject",m=o.children.findIndex(y=>y.id===l.rowId);p&&m<0?o.children.splice(Math.min(l.rowIndex,o.children.length),0,this.cloneSuggestionSnapshot(l.row)):!p&&m>=0&&o.children.splice(m,1);continue}if(l.kind==="cell"){const p=o.children.find(b=>b.id===l.rowId);if(!p)continue;const m=l.action==="insert"?e==="accept":e==="reject",y=p.children.findIndex(b=>b.id===l.cellId);m&&y<0?p.children.splice(Math.min(l.cellIndex,p.children.length),0,this.cloneSuggestionSnapshot(l.cell)):!m&&y>=0&&p.children.splice(y,1);continue}if(l.kind==="geometry"){this.applyTableGeometryRows(o,l.pendingRows,e==="accept"?l.acceptedRows:l.rejectedRows);continue}if(l.kind==="grid"){const p=e==="accept"?l.currentColumnWidths:l.priorColumnWidths,m=e==="accept"?l.currentGridXml:l.priorGridXml;o.columnWidths=[...p],m&&(r.grid={xml:m,columnWidths:[...p]});continue}const c=e==="accept"?l.currentAttributes:l.priorAttributes,d=e==="accept"?l.priorAttributes:l.currentAttributes;let g;if(l.target==="table"?g=o:l.target==="row"||l.target==="row-exception"?g=o.children.find(p=>p.id===l.rowId):g=o.children.flatMap(p=>p.children).find(p=>p.id===l.cellId),g)for(const p of new Set([...Object.keys(d??{}),...Object.keys(c??{})]))c&&Object.prototype.hasOwnProperty.call(c,p)&&c[p]!==void 0?g[p]=this.cloneSuggestionSnapshot(c[p]):delete g[p];const u=e==="accept"?l.currentTableAttributes:l.priorTableAttributes,f=e==="accept"?l.priorTableAttributes:l.currentTableAttributes;for(const p of new Set([...Object.keys(f??{}),...Object.keys(u??{})]))u&&Object.prototype.hasOwnProperty.call(u,p)&&u[p]!==void 0?o[p]=this.cloneSuggestionSnapshot(u[p]):delete o[p];const h=e==="accept"?l.currentPropertiesXml:l.priorPropertiesXml;l.target==="table"?r.table=h:l.target==="row-exception"&&l.rowId?(r.rowExceptions=r.rowExceptions??{},r.rowExceptions[l.rowId]=h):l.target==="row"&&l.rowId?(r.rows=r.rows??{},r.rows[l.rowId]=h):l.target==="cell"&&l.cellId&&(r.cells=r.cells??{},r.cells[l.cellId]=h)}(r.table||r.grid||Object.keys(r.rows??{}).length>0||Object.keys(r.rowExceptions??{}).length>0||Object.keys(r.cells??{}).length>0)&&(o.docxTablePropertyOverrides=JSON.stringify(r)),this.clearSuggestionMarkerFromValue(o,t.id);const i=this.getSuggestionMutationSelection();if(n.children.length>0&&o.children.length===0){const l=this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.tableId,i,i));return l&&this.deleteLiveSuggestion(t.id),l}const a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.tableId,o,i,i));return a&&this.deleteLiveSuggestion(t.id),a}applySuggestionRecordAcceptance(t){const e=this.getSuggestionMutationSelection();switch(t.type){case"inline-text":return this.applyInlineSuggestionDecision(t.id,"accept");case"table-change":return this.applyTableRevisionDecision(t,"accept");case"block-change":{if(this.host.isListItemBlockChangeRecord(t)&&this.host.applyListItemBlockChangeDecision(t,"accept",e))return!0;if(t.acceptedBlock){if(!this.blockChangeTargetIsOwned(t))return!1;const o=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,this.blockChangeTarget(t,t.acceptedBlock),e,e));return o&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)),this.deleteLiveSuggestion(t.id)),o}const n=W(this.host.getDocument(),this.liveSuggestionRecordAnchorBlockId(t)??t.blockId);return n&&this.blockContainsSuggestionMarker(n,t.id)?(this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0):!1}case"block-insert":{const n=this.collectNestedSuggestionIdsForBlock(t.blockId,t.id);for(const o of n)this.acceptLiveSuggestionWithoutPruning(o);return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}case"block-delete":{const n=this.host.getDocument(),o=Xt(n,t.blockId),r=W(n,t.blockId);if(o?.type==="table-cell"&&o.children?.length===1&&r?.type==="paragraph"){const a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,{type:"paragraph",id:t.blockId,children:[]},e,e));return a&&this.deleteLiveSuggestion(t.id),a}const i=this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.blockId,e,e));return i&&(t.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.cleanupTrailingParagraphId,e,e)),this.deleteLiveSuggestion(t.id)),i}case"paragraph-split":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"paragraph-merge":{const n=this.host.getDocument(),o=W(n,t.secondBlockId);let r=W(n,t.firstBlockId),i=Xt(n,t.firstBlockId);if(!r||r.type!=="paragraph"){const d=Xt(n,t.secondBlockId),g=d?"children"in d?d.children:[]:n.children,u=g.findIndex(h=>h.id===t.secondBlockId),f=u>0?g[u-1]:null;f?.type==="paragraph"&&(r=f,i=d??n)}if(!r||!o||!i||r.type!=="paragraph"||o.type!=="paragraph")return!1;const a={block:r.id,offset:r.children.reduce((d,g)=>d+(g.type==="text"?g.text.length:0),0)},l={block:o.id,offset:0},c=this.runWithoutSuggesting(()=>this.host.mergeAdjacentParagraphs(r,o,a,l,i,e,e));return c&&this.deleteLiveSuggestion(t.id),c}case"inline-format":return this.host.transact(()=>{for(const n of t.spans){const o=this.getYTextForSuggestionSpan(n);o&&this.stripInlineSuggestionMarks(o,n.start,n.end-n.start)}}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}}applySuggestionRecordRejection(t){const e=this.getSuggestionMutationSelection();switch(t.type){case"inline-text":return this.applyInlineSuggestionDecision(t.id,"reject");case"table-change":return this.applyTableRevisionDecision(t,"reject");case"block-change":{if(this.host.isListItemBlockChangeRecord(t)&&this.host.applyListItemBlockChangeDecision(t,"reject",e))return!0;if(!this.blockChangeTargetIsOwned(t))return!1;if(t.sequenceBlockIds){const o=this.getSequenceReplacementMembers(t),r=o[0];return!r||o.some(i=>i.yParent!==r.yParent)?!1:(this.host.transact(()=>{for(const i of[...o].sort((a,l)=>l.index-a.index))i.yParent.delete(i.index,1);r.yParent.insert(r.index,[this.host.blockToYjsElement(this.cloneSuggestionSnapshot(t.beforeBlock))]),this.deleteLiveSuggestion(t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),!0)}const n=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,this.blockChangeTarget(t,t.beforeBlock),e,e));return n&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)),this.deleteLiveSuggestion(t.id)),n}case"block-insert":{const n=this.collectNestedSuggestionIdsForBlock(t.blockId,t.id),o=this.host.collectStructuralInsertBlockIds(this.host.getDocument(),t.id),r=o.length>0?Array.from(new Set(o)):[t.blockId];let i=!1;for(const a of[...r].reverse())i=this.runWithoutSuggesting(()=>this.host.deleteBlockById(a,e,e))||i;if(i){t.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.cleanupTrailingParagraphId,e,e)),this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id));for(const a of n)this.deleteLiveSuggestion(a);this.deleteLiveSuggestion(t.id)}return i}case"block-delete":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"paragraph-split":{const n=this.host.getDocument(),o=W(n,t.insertedBlockId);if(!o)return!1;const r=W(n,t.blockId);let i=t.beforeBlock,a;if(r&&r.type==="paragraph"&&o.type==="paragraph"){const{id:c,children:d,structuralSuggestionId:g,structuralSuggestionKind:u,structuralSuggestionRole:f,structuralSuggestionLabel:h,structuralSuggestionRecord:p,...m}=o;let y={};if(g&&g!==t.id){a=g;let b=p;if(p)try{const k=JSON.parse(p);k.blockId===t.insertedBlockId&&(k.blockId=t.blockId),b=JSON.stringify(k)}catch{}y={structuralSuggestionId:g,...u?{structuralSuggestionKind:u}:{},...f?{structuralSuggestionRole:f}:{},...h?{structuralSuggestionLabel:h}:{},...b?{structuralSuggestionRecord:b}:{}}}i={...m,...y,type:"paragraph",id:t.blockId,children:[...r.children,...d]}}if(!this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,i,e,e)))return!1;this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.insertedBlockId,e,e)),this.deleteLiveSuggestion(t.id);const l=new Set(a?[a]:[]);for(const[c,d]of this.getLiveSuggestionStore())c!==t.id&&d.blockId===t.insertedBlockId&&l.add(c);for(const c of l){const d=this.getLiveSuggestion(c);if(d&&d.blockId===t.insertedBlockId){const g=f=>{if(!f||typeof f!="object")return f;const h={...f};return h.structuralSuggestionId===t.id&&(delete h.structuralSuggestionId,delete h.structuralSuggestionKind,delete h.structuralSuggestionRole,delete h.structuralSuggestionLabel,delete h.structuralSuggestionRecord),"children"in h&&i.type==="paragraph"&&(h.children=i.children,h.id=t.blockId),h},u=d;this.saveLiveSuggestion({...u,blockId:t.blockId,...u.beforeBlock?{beforeBlock:g(u.beforeBlock)}:{},...u.acceptedBlock?{acceptedBlock:g(u.acceptedBlock)}:{}})}this.host.liveSuggestionTreeRecordCache.delete(c)}return!0}case"paragraph-merge":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"inline-format":return this.host.transact(()=>{for(const n of t.spans){const o=this.getYTextForSuggestionSpan(n);o&&this.restoreInlineSuggestionFormatting(o,n.start,n.end-n.start,n.attributes)}}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}}applyInlineSuggestionDecision(t,e){return this.applyInlineSuggestionDecisions(new Set([t]),e).has(t)}applyInlineSuggestionDecisions(t,e){const n=new Set;if(t.size===0)return n;const o=new Set,r=(l,c)=>l instanceof I.XmlText?st(l).some(d=>{if(d.attributes?.suggestionId!==c||!d.attributes.docxMove)return!1;try{return JSON.parse(d.attributes.docxMove).wholeBlocks===!0}catch{return!1}}):l.toArray().some(d=>(d instanceof I.XmlElement||d instanceof I.XmlText)&&r(d,c)),i=new Map;for(const l of this.host.getYContentFragment().toArray()){if(!(l instanceof I.XmlElement))continue;const c=l.getAttribute("structuralSuggestionId")??l.getAttribute("suggestionId");if(!c||!t.has(c)||o.has(c))continue;if(r(l,c)){o.add(c);continue}const d=l.getAttribute("structuralSuggestionKind")??l.getAttribute("diffState");if(d!=="insert"&&d!=="delete")continue;const g=i.get(c)??new Set;g.add(d),i.set(c,g)}for(const[l,c]of i){if(c.size!==2)continue;const d=this.getLiveSuggestion(l);(!d||d.type==="inline-text")&&o.add(l)}const a=(l,c,d)=>{if(l instanceof I.XmlText)return st(l).every(u=>u.insert===""||u.attributes?.suggestionId===c&&(d==="delete"?u.attributes?.deletion:u.attributes?.insertion));const g=l.getAttribute("structuralSuggestionId")??l.getAttribute("suggestionId");return g&&g!==c?!1:Ts(l.nodeName)?!0:l.toArray().every(u=>(u instanceof I.XmlElement||u instanceof I.XmlText)&&a(u,c,d))};if(this.host.transact(()=>{const l=c=>{for(const d of c.toArray()){if(d instanceof I.XmlElement){const h=d.getAttribute("structuralSuggestionId")??d.getAttribute("suggestionId"),p=d.getAttribute("structuralSuggestionKind")??d.getAttribute("diffState");if(c===this.host.getYContentFragment()&&typeof h=="string"&&typeof p=="string"&&o.has(h)&&a(d,h,p)&&(e==="accept"&&p==="delete"||e==="reject"&&p==="insert")){const b=c.toArray().indexOf(d);b>=0&&c.delete(b,1),n.add(h);continue}const m=d.getAttribute("structuralSuggestionId");typeof m=="string"&&t.has(m)&&(this.clearElementStructuralSuggestion(d),n.add(m));const y=d.getAttribute("suggestionId");if(typeof y=="string"&&t.has(y)){this.setDiffSuggestionAttributes(d,void 0,void 0);const b=d.getAttribute("structuralSuggestionRecord");let k;try{k=typeof b=="string"?JSON.parse(b)?.id:void 0}catch{k=void 0}k===y&&d.removeAttribute("structuralSuggestionRecord"),n.add(y)}l(d);continue}if(!(d instanceof I.XmlText))continue;const g=st(d),u=[];let f=0;for(const h of g)typeof h.insert=="string"&&(u.push({start:f,length:h.insert.length,attributes:h.attributes||{}}),f+=h.insert.length);for(let h=u.length-1;h>=0;h--){const p=u[h],m=typeof p.attributes.suggestionId=="string"?p.attributes.suggestionId:null,y=mn(p.attributes.layeredInsertion);if(m&&t.has(m)){e==="accept"?p.attributes.deletion?d.delete(p.start,p.length):this.stripInlineSuggestionMarks(d,p.start,p.length):p.attributes.deletion&&y?at(d,p.start,p.length,{deletion:null,layeredInsertion:null,insertion:!0,suggestionId:y.id,suggestionSource:y.source??null,suggestionAuthorType:y.authorType??null,suggestionCreatedAt:y.createdAt??null,suggestionLabel:y.label??"Insert",suggestionCommentThreadId:y.commentThreadId??null,suggestionAuthorName:y.authorName??null,suggestionAgentModel:y.agentModel??null,suggestionAgentConversationId:y.agentConversationId??null,suggestionAgentRequestId:y.agentRequestId??null,suggestionAgentTurn:y.agentTurn??null}):p.attributes.insertion?d.delete(p.start,p.length):p.attributes.formatChange&&xo(p.attributes.suggestionPriorAttributes)?this.restoreInlineSuggestionFormatting(d,p.start,p.length,xo(p.attributes.suggestionPriorAttributes)):this.stripInlineSuggestionMarks(d,p.start,p.length),n.add(m);continue}y&&t.has(y.id)&&(e==="accept"?at(d,p.start,p.length,{insertion:null,layeredInsertion:null}):d.delete(p.start,p.length),n.add(y.id))}}};l(this.host.getYContentFragment()),o.size>0&&this.host.ensureTrailingParagraph(),l(this.host.getYNotesFragment()),l(this.host.ydoc.getXmlFragment("chrome"))}),n.size>0){const l=this.getSuggestionMutationSelection();this.host.setSelectionAfterOperation(l),this.host.afterOperationRelativeSelection=Y(l,this.host.ydoc,this.host.getDocument());for(const c of n)this.deleteLiveSuggestion(c)}return n}acceptLiveSuggestionWithoutPruning(t){const e=this.getLiveSuggestion(t);return e?this.applySuggestionRecordAcceptance(e):this.applyInlineSuggestionDecision(t,"accept")}rejectLiveSuggestionWithoutPruning(t){const e=this.getLiveSuggestion(t);return e?this.applySuggestionRecordRejection(e):this.applyInlineSuggestionDecision(t,"reject")}acceptLiveSuggestion(t){this.host.lastPrunedUnresolvableLiveSuggestions=[];const e=this.acceptLiveSuggestionWithoutPruning(t);return this.host.lastPrunedUnresolvableLiveSuggestions=this.pruneUnresolvableLiveSuggestionsInternal(),e&&this.host.resolveCommentsForSettledSuggestions([t]),e}rejectLiveSuggestion(t){this.host.lastPrunedUnresolvableLiveSuggestions=[];const e=this.rejectLiveSuggestionWithoutPruning(t);return this.host.lastPrunedUnresolvableLiveSuggestions=this.pruneUnresolvableLiveSuggestionsInternal(),e&&this.host.resolveCommentsForSettledSuggestions([t]),e}deleteMultiParagraphSelectionAsSuggestion(t,e,n,o,r){const i=this.host.getDocument().children.slice(n,o+1);if(i.length<2||i.some(c=>c.type!=="paragraph"))return!1;const a=i.map((c,d)=>{const g=c,u=this.host.getParagraphTextLength(g),f=d===0?Math.min(t.offset,u):0,h=d===i.length-1?Math.min(e.offset,u):u;return{blockId:g.id,from:f,to:h}});if(!a.some(c=>c.to>c.from))return!1;const l=gt();return this.host.transact(()=>{for(const c of a){if(c.to<=c.from)continue;const d=Z(this.host.ydoc,c.blockId);if(!(d instanceof I.XmlElement))continue;const g=ct(d);g&&(this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),c.blockId)?g.delete(c.from,c.to-c.from):this.applySuggestedDeletionToTextRange(g,c.from,c.to-c.from,l).retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(g,c.from))}for(let c=0;c+1<i.length;c++){const d=i[c],g=i[c+1],u=Z(this.host.ydoc,d.id),f=Z(this.host.ydoc,g.id);if(!(u instanceof I.XmlElement)||!(f instanceof I.XmlElement)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),d.id)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),g.id))continue;const h=gt();this.setParagraphStructuralSuggestion(u,"merge","before",h),this.setParagraphStructuralSuggestion(f,"merge","after",h),this.saveLiveSuggestion({id:h,type:"paragraph-merge",firstBlockId:d.id,secondBlockId:g.id})}}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=Y(r,this.host.ydoc,this.host.getDocument()),!0}sanitizePreviewMarks(t){let e=el(t);for(const n of fs)t?.[n]===!1&&(e??(e={}),e[n]=!1);return t?.footnoteRef?{...e,footnoteRef:t.footnoteRef,...t.superscript?{superscript:!0}:{}}:e}sanitizePreviewBlock(t){const e=o=>({...o,marks:this.sanitizePreviewMarks(o.marks)}),n=o=>{const r={...o};return delete r.diffState,delete r.suggestionId,delete r.proposalId,delete r.toolCallId,delete r.toolType,delete r.diffSegmentIndex,delete r.structuralSuggestionId,delete r.structuralSuggestionKind,delete r.structuralSuggestionRole,delete r.structuralSuggestionLabel,r};switch(t.type){case"paragraph":return n({...t,children:t.children.map(o=>e(o))});case"list":return n({...t,children:t.children.map(o=>n({...o,children:o.children.map(r=>e(r))}))});case"table":return n({...t,children:t.children.map(o=>n({...o,children:o.children.map(r=>n({...r,children:r.children.map(i=>this.sanitizePreviewBlock(i))}))}))});case"table-cell":return n({...t,children:t.children.map(o=>this.sanitizePreviewBlock(o))});case"container":case"footnote":return n({...t,children:t.children.map(o=>this.sanitizePreviewBlock(o))});default:return n({...t})}}markBlockForGenericSuggestionChange(t,e,n){const o=this.sanitizePreviewBlock(t);return o.type==="paragraph"||o.type==="list"?{...o,structuralSuggestionId:e,structuralSuggestionKind:"change",structuralSuggestionLabel:n}:{...o,diffState:"insert",suggestionId:e}}getListItemSignatureForSuggestionBridge(t){const e=n=>{const o=this.sanitizePreviewMarks(n);if(!o)return{};if(o.fontFamily===jt||o.fontFamily==="Arial"){const r={...o};return delete r.fontFamily,r}return o};return JSON.stringify({...Object.fromEntries(An.map(n=>[n,t[n]])),direction:t.direction,checked:t.checked??!1,indentLevel:t.indentLevel??0,children:t.children.map(n=>({text:n.text,marks:e(n.marks)}))})}computeListItemLcsForSuggestionBridge(t,e){const{beforeKeys:n,afterKeys:o}=this.getListItemAlignmentKeysForSuggestionBridge(t,e);return Fr(n,o)}getListItemAlignmentKeysForSuggestionBridge(t,e){return ma(t,e,n=>this.getListItemSignatureForSuggestionBridge(n))}computeListSuggestionBridgeOperations(t,e){const n=[],o=this.computeListItemLcsForSuggestionBridge(t.children,e.children),{beforeKeys:r,afterKeys:i}=this.getListItemAlignmentKeysForSuggestionBridge(t.children,e.children),a=t.children.map(u=>this.getListItemSignatureForSuggestionBridge(u)),l=e.children.map(u=>this.getListItemSignatureForSuggestionBridge(u)),c=(u,f,h,p)=>{const m=Math.min(u.length,f.length);for(let y=0;y<m;y++)n.push({kind:"change",index:h+y,beforeItem:u[y],afterItem:f[y]});for(let y=m;y<u.length;y++)n.push({kind:"delete",index:h+y,beforeItem:u[y]});for(let y=m;y<f.length;y++)n.push({kind:"insert",index:h+y,afterIndex:p+y,afterItem:f[y]})};let d=0,g=0;for(const u of o){let f=d;for(;f<r.length&&r[f]!==u;)f+=1;let h=g;for(;h<i.length&&i[h]!==u;)h+=1;c(t.children.slice(d,f),e.children.slice(g,h),d,g),a[f]!==l[h]&&n.push({kind:"change",index:f,beforeItem:t.children[f],afterItem:e.children[h]}),d=f+1,g=h+1}return c(t.children.slice(d),e.children.slice(g),d,g),n}findListItemIndexForSuggestionBridge(t,e){if(!e)return-1;if(e.id){const o=t.findIndex(r=>r.id===e.id);if(o!==-1)return o}const n=this.getListItemSignatureForSuggestionBridge(e);return t.findIndex(o=>this.getListItemSignatureForSuggestionBridge(o)===n)}buildListSuggestionChange(t,e,n,o,r){const i=this.sanitizePreviewBlock(t),a=this.sanitizePreviewBlock(e),l=r?this.cloneSuggestionSnapshot(r):null;if(o.kind==="insert"){const g=this.cloneSuggestionSnapshot(l??i),u=this.cloneSuggestionSnapshot(o.afterItem),f=this.findListItemIndexForSuggestionBridge(g.children,a.children[o.afterIndex-1]),h=this.findListItemIndexForSuggestionBridge(g.children,a.children[o.afterIndex+1]);let p=Math.min(o.afterIndex,g.children.length);return o.afterIndex===0?p=0:f!==-1?p=f+1:h!==-1&&(p=h),g.children.splice(p,0,{...u,structuralSuggestionId:n,structuralSuggestionKind:"insert",structuralSuggestionLabel:"Insert"}),{liveBlock:g,label:"Insert",listItemSuggestion:{kind:"insert",afterItem:this.cloneSuggestionSnapshot(u)}}}if(o.kind==="delete"){const g=this.cloneSuggestionSnapshot(l??i),u=this.findListItemIndexForSuggestionBridge(g.children,o.beforeItem);if(u!==-1){const f=g.children[u];return g.children[u]={...f,structuralSuggestionId:n,structuralSuggestionKind:"delete",structuralSuggestionLabel:"Delete"},{liveBlock:g,acceptedBlock:this.cloneSuggestionSnapshot(a),label:"Delete",listItemSuggestion:{kind:"delete",beforeItem:this.cloneSuggestionSnapshot(o.beforeItem)}}}}if(o.kind!=="change")return null;const c=this.cloneSuggestionSnapshot(l??i),d=this.findListItemIndexForSuggestionBridge(c.children,o.beforeItem);return d!==-1?(c.children[d]={...this.cloneSuggestionSnapshot(o.afterItem),structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:"Change"},{liveBlock:c,label:"Change",listItemSuggestion:{kind:"change",beforeItem:this.cloneSuggestionSnapshot(o.beforeItem),afterItem:this.cloneSuggestionSnapshot(o.afterItem)}}):null}applyGranularListSuggestionChanges(t){const e=this.sanitizePreviewBlock(t.before),n=this.sanitizePreviewBlock(t.after);if(!Bo(e,n))return!1;const o=this.computeListSuggestionBridgeOperations(e,n);if(o.length===0)return!1;let r=this.cloneSuggestionSnapshot(t.currentLiveBlock??e),i=!1;const a=[],l=[];for(let c=0;c<o.length;c++){const d=c===0?t.suggestionId:gt(),g=o[c];if(g.kind==="change"&&this.host.canBridgeListItemChangeAsInline(g.beforeItem,g.afterItem)){const f=this.findListItemIndexForSuggestionBridge(r.children,g.beforeItem);if(f===-1)return!1;l.push({suggestionId:d,itemIndex:f,beforeItem:this.cloneSuggestionSnapshot(g.beforeItem),afterItem:this.cloneSuggestionSnapshot(g.afterItem),formatOnly:this.host.getListItemPlainText(g.beforeItem)===this.host.getListItemPlainText(g.afterItem)});continue}const u=this.buildListSuggestionChange(e,n,d,g,r);if(!u?.listItemSuggestion)return!1;r=u.liveBlock,i=!0,a.push({id:d,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:u.acceptedBlock?this.cloneSuggestionSnapshot(u.acceptedBlock):void 0,listItemSuggestion:{kind:u.listItemSuggestion.kind,beforeItem:u.listItemSuggestion.beforeItem?this.cloneSuggestionSnapshot(u.listItemSuggestion.beforeItem):void 0,afterItem:u.listItemSuggestion.afterItem?this.cloneSuggestionSnapshot(u.listItemSuggestion.afterItem):void 0},label:u.label,createdAt:t.createdAt})}if(i){for(const c of a){const d=r.children.find(g=>g.structuralSuggestionId===c.id);d&&(d.structuralSuggestionRecord=JSON.stringify(this.normalizeLiveSuggestionRecord(c)))}if(!this.host.replaceBlockByIdWithoutSelection(t.blockId,r))return!1}this.host.transact(()=>{for(const c of a)this.saveLiveSuggestion(c)});for(const c of l){const d=this.host.getListItemPlainText(c.afterItem);let g;if(c.formatOnly){const u=this.host.extractTextNodesForRange(c.afterItem,0,d.length);g=this.applyBridgeInlineFormatSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:0,end:d.length,targetAttributes:{},targetTextNodes:u,createdAt:t.createdAt})}else{const u=this.host.getListItemPlainText(c.beforeItem),f=En(u,d).diffs;let h=0,p=0;g=!0;for(let m=0;m<f.length&&g;m++){const[y,b]=f[m];if(y===0){g=this.applyBridgeInlineFormatSuggestion({suggestionId:gt(),blockId:t.blockId,itemIndex:c.itemIndex,start:p,end:p+b.length,targetAttributes:{},targetTextNodes:this.host.extractTextNodesForRange(c.afterItem,h,h+b.length),createdAt:t.createdAt}),h+=b.length,p+=b.length;continue}if(y===-1){const k=f[m+1];if(k&&k[0]===1){const S=this.host.extractTextNodesForRange(c.afterItem,h,h+k[1].length);g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:p,deleteLength:b.length,insertNodes:S,label:"Replace",createdAt:t.createdAt}),p+=b.length+k[1].length,h+=k[1].length,m++}else g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:p,deleteLength:b.length,insertNodes:[],label:"Replace",createdAt:t.createdAt}),p+=b.length}else{const k=this.host.extractTextNodesForRange(c.afterItem,h,h+b.length);g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:p,deleteLength:0,insertNodes:k,label:"Replace",createdAt:t.createdAt}),p+=b.length,h+=b.length}}}if(!g)return!1}return a.length>0||l.length>0}applyBridgeInlineTextSuggestion(t){const e=this.getYTextForSuggestionSpan({blockId:t.blockId,itemIndex:t.itemIndex});if(!e)return!1;let n=!1;return this.host.transact(()=>{let o=t.start;if(t.deleteLength>0){const i=this.applySuggestedDeletionToTextRange(e,t.start,t.deleteLength,t.suggestionId);o=t.start+i.retainedLength,n=n||i.changed}let r=o;for(const i of t.insertNodes){if(!i.text)continue;const a=this.buildSuggestionInsertionMarks(this.sanitizePreviewMarks(i.marks),t.suggestionId,t.label,t.createdAt);lt(e,r,i.text,a),r+=i.text.length,n=!0}}),n}applyBridgeInlineFormatSuggestion(t){const e=this.getYTextForSuggestionSpan({blockId:t.blockId,itemIndex:t.itemIndex});if(!e||t.end<=t.start)return!1;const n=t.end-t.start,o=this.host.collectOverlappingTextSpans(e,t.start,n);if(o.length===0||t.targetTextNodes&&t.targetTextNodes.reduce((d,g)=>d+g.text.length,0)!==n)return!1;const r=[];let i=t.start;const a=t.targetTextNodes?t.targetTextNodes.map(d=>({length:d.text.length,marks:d.marks})):[{length:n,marks:t.targetAttributes}];let l=0;for(const d of a){const g=i+d.length;for(;l<o.length&&o[l].start+o[l].length<=i;)l++;for(let u=l;u<o.length&&o[u].start<g;u++){const f=o[u],h=Math.max(f.start,i),p=Math.min(f.start+f.length,g);if(p<=h)continue;const m=t.targetTextNodes?mi(f.attributes,d.marks):{...d.marks??{}};r.push({...f,start:h,length:p-h,targetAttributes:m})}i=g}const c=[];return this.host.transact(()=>{for(const d of r){const g={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(t.suggestionId,"Format",t.createdAt)},u=new Set([...Object.keys(d.attributes||{}),...Object.keys(d.targetAttributes)]);if(u.delete("insertion"),u.delete("deletion"),u.delete("suggestionId"),u.delete("formatChange"),u.delete("suggestionSource"),u.delete("suggestionAuthorType"),u.delete("suggestionCreatedAt"),u.delete("suggestionLabel"),u.delete("suggestionCommentThreadId"),u.delete("suggestionAuthorName"),u.delete("suggestionAgentModel"),u.delete("suggestionAgentConversationId"),u.delete("suggestionAgentRequestId"),u.delete("suggestionAgentTurn"),u.delete("suggestionPriorAttributes"),u.delete("layeredInsertion"),u.delete("proposalId"),u.delete("toolCallId"),u.delete("toolType"),![...u].every(f=>(d.attributes?.[f]??null)===(d.targetAttributes[f]??null))){c.push(d);for(const f of u)Object.prototype.hasOwnProperty.call(d.targetAttributes,f)?g[f]=d.targetAttributes[f]:g[f]=null;at(e,d.start,d.length,{...g,suggestionPriorAttributes:Ue(d.attributes)})}}c.length!==0&&this.saveLiveSuggestion({id:t.suggestionId,type:"inline-format",spans:c.map(d=>({blockId:t.blockId,itemIndex:t.itemIndex,start:d.start,end:d.start+d.length,attributes:d.attributes})),label:"Format",createdAt:t.createdAt})}),!0}insertBlockRelativeWithSuggestion(t){const e=t.batchInsertedBlocks?.get(t.referenceId),n=e||ot(this.host.ydoc,t.referenceId),o=t.referenceId===Ve;if(!n&&!o)return!1;const r=n?.yParent??this.host.getYContentFragment(),i=n?.index??0,a=this.sanitizePreviewBlock(t.block),l=a.id||G();let c=null;this.host.transact(()=>{const g=this.host.blockToYjsElement({...a,id:l});c=g,g.setAttribute("id",l),this.markInsertedBlockElement(g,t.suggestionId,t.label);const u=o?r.length:t.position==="before"?i:i+1;r.insert(u,[g]),t.batchInsertedBlocks?.set(l,{yBlock:g,yParent:r,index:u})});const d=this.host.ensureTrailingParagraph();return this.host.transact(()=>{this.saveLiveSuggestion({id:t.suggestionId,type:"block-insert",blockId:l,label:t.label,createdAt:t.createdAt,cleanupTrailingParagraphId:d??void 0},c??void 0)}),!0}applyBridgeBlockDeleteSuggestion(t){const e=Z(this.host.ydoc,t.blockId);if(!(e instanceof I.XmlElement))return!1;const n=this.host.getTrailingCleanupParagraphIdForTopLevelBlock(this.host.getDocument(),t.blockId);return this.host.transact(()=>{this.markDeletedBlockElement(e,t.suggestionId,t.label),this.saveLiveSuggestion({id:t.suggestionId,type:"block-delete",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(t.beforeBlock),label:t.label,createdAt:t.createdAt,cleanupTrailingParagraphId:n??void 0})}),!0}applyBridgeBlockChangeSuggestion(t){const e=this.sanitizePreviewBlock(t.beforeBlock),n=this.sanitizePreviewBlock(t.afterBlock),o=e.type==="list"||e.type==="table"?W(this.host.getDocument(),t.blockId):null;let r=this.markBlockForGenericSuggestionChange(n,t.suggestionId,t.label),i,a,l=null,c=t.label;if(e.type==="paragraph"&&n.type==="paragraph"&&Ot(e)!==Ot(n))r=this.host.buildParagraphReplacementLiveBlock(e,n,t.suggestionId,t.label),i=n;else if(e.type==="paragraph"&&n.type==="paragraph")i=n;else if(e.type==="list"&&n.type==="list"){if(!t.optimizeFormatting&&this.applyGranularListSuggestionChanges({blockId:t.blockId,before:e,after:n,suggestionId:t.suggestionId,currentLiveBlock:o?.type==="list"?o:void 0,createdAt:t.createdAt}))return!0;r={...n,structuralSuggestionId:t.suggestionId,structuralSuggestionKind:"change",structuralSuggestionLabel:"List"},i=n,c="List"}else if(e.type==="table"&&n.type==="table"&&o?.type==="table"&&(l=this.buildTablePropertyOnlyChange(t.blockId,o,e,n,t.suggestionId)))r=l.liveBlock,a=l.record,c=l.label;else if(e.type==="table"&&n.type==="table"){const d=W(this.createLiveSuggestionProjection("accept").doc,t.blockId),g=d?.type==="table"?d:e,u=this.reconcileTableDescendantIds(g,n),f=He(e,u),h=f?null:this.buildSuggestedTableChange(g,u,t.suggestionId),p=h||f?null:this.decomposeTableRowAndCellChanges(g,u,t.suggestionId,t.label);if(p)r=p.liveBlock,a=p.record,c=p.record?.label??t.label;else if(h)r=(o?.type==="table"&&!this.tableHasPendingStructure(t.blockId)&&this.buildTableStructureChange(g,u,t.suggestionId)?this.graftTableStructureChange(o,h.record,u):null)??(o?.type==="table"?this.mergePendingTableRevisionState(o,h.liveBlock):h.liveBlock),a=h.record,c=h.label;else if(!this.hasSameTableGeometry(g,u)||f||He(g,u))r=this.markBlockForGenericSuggestionChange(u,t.suggestionId,"Table"),i=u,c="Change";else{if(o?.type==="table"&&this.collectNestedSuggestionIdsForBlock(t.blockId,t.suggestionId).length>0)return!0;r={...this.cloneSuggestionSnapshot(u),diffState:"insert",suggestionId:t.suggestionId}}}if(t.optimizeFormatting&&e.type==="paragraph"&&n.type==="paragraph"&&Ot(e)===Ot(n)){const d=this.batchYBlockLocationsById?.get(t.blockId)?.yBlock??Z(this.host.ydoc,t.blockId),g=d?d._item:null,u=d?ct(d):null;if(d&&u&&!g?.deleted){const f=new Set(["insertion","deletion","suggestionId","formatChange","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","proposalId","toolCallId","toolType"]),h=[];let p=0,m=!1;for(const y of n.children){if(y.type!=="text"||y.text.length===0)continue;const b=this.sanitizePreviewMarks(y.marks)??{},k=this.host.collectOverlappingTextSpans(u,p,y.text.length);m||(m=k.some(S=>["insertion","deletion","suggestionId","formatChange"].some(v=>Object.prototype.hasOwnProperty.call(S.attributes,v)))),h.push({targetAttributes:b,spans:k}),p+=y.text.length}if(!m)return this.host.transact(()=>{Zt(d,r);for(const{targetAttributes:y,spans:b}of h)for(const k of b){const S=new Set([...Object.keys(k.attributes??{}),...Object.keys(y)]),v={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(t.suggestionId,"Format",t.createdAt)};for(const x of S)f.has(x)||(v[x]=Object.prototype.hasOwnProperty.call(y,x)?y[x]:null);v.suggestionPriorAttributes=Ue(k.attributes),at(u,k.start,k.length,v)}this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:this.cloneSuggestionSnapshot(n),label:c,createdAt:t.createdAt},d)}),!0}}if(e.type==="paragraph"&&n.type==="paragraph"&&JSON.stringify(e.children)===JSON.stringify(n.children)){const d=this.batchYBlockLocationsById?.get(t.blockId),g=d?d.yBlock._item:null;if(d&&!g?.deleted)return Zt(d.yBlock,r),this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:this.cloneSuggestionSnapshot(n),label:c,createdAt:t.createdAt},d.yBlock),!0}return this.host.replaceBlockByIdWithoutSelection(t.blockId,r,e.type==="paragraph"?this.batchYBlockLocationsById?.get(t.blockId):void 0)?(this.host.transact(()=>{a?this.saveLiveSuggestion({...a,label:c,createdAt:t.createdAt}):this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:i?this.cloneSuggestionSnapshot(i):void 0,label:c,createdAt:t.createdAt})}),!0):!1}sortBlockSuggestionPlansByDependency(t){if(t.length<=1)return t;const e=[],n=new Set,o=[...t],r=new Set(o.flatMap(i=>[i.blockId,...i.producedBlockIds??[]]).filter(i=>!!i));for(;o.length>0;){let i=!1;for(let a=0;a<o.length;a++){const l=o[a],c=l.insertReferenceId;if(!(c&&r.has(c)&&!n.has(c))){e.push(l),l.blockId&&n.add(l.blockId),l.producedBlockIds?.forEach(d=>n.add(d)),o.splice(a,1),i=!0;break}}if(!i){e.push(...o);break}}return e}buildAgentSuggestionPlanFromProposal(t,e,n,o,r,i,a,l=!1,c=!1){const d=e.getSuggestion(t);if(!d)return null;const g=r??d.createdAt;if(d.blockSequencePreview){const{blockId:v,blocks:x}=d.blockSequencePreview,w=W(n,v);return!w||x.length===0?null:{proposalId:t,category:"block",blockId:v,producedBlockIds:x.map(A=>A.id),apply:()=>{const A=ot(this.host.ydoc,v);if(!A)return!1;const P=x.map(T=>this.sanitizePreviewBlock(T));return this.host.transact(()=>{A.yParent.delete(A.index,1);const T=P.map(B=>this.host.blockToYjsElement(B));A.yParent.insert(A.index,T);for(const B of T)this.setElementStructuralSuggestion(B,"change",void 0,t,"Paragraph");const E=this.normalizeLiveSuggestionRecord({id:t,type:"block-change",blockId:P[0].id,beforeBlock:this.cloneSuggestionSnapshot(w),sequenceBlockIds:P.map(B=>B.id),label:"Paragraph",createdAt:g});this.saveLiveSuggestion(E,T[0]);for(const B of T.slice(1))this.embedLiveSuggestionRecordInTree(E,B)}),!0}}}if(d.blockPreview?.id){const v=W(n,d.blockPreview.id);if(!v)return null;const x=d.blockPreview;return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:x,optimizeFormatting:l,label:v.type==="paragraph"&&x.type==="paragraph"?Ot(v)===Ot(x)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})}}if(d.toolCallAction?.name==="insert_block"){const v=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,x=typeof v?.referenceId=="string"?v.referenceId:null,w=v?.position==="before"||v?.position==="after"?v.position:null,A=typeof v?.content=="string"?v.content:Array.isArray(v?.content)&&typeof v?.content[0]=="string"?v?.content[0]:null;if(!x||!w||!A)return null;const P=Wn(d.toolCallAction),T=(P&&i?W(i,P):null)??it.fromAgentHtml(A,{existingDocument:n}).children[0];if(!T)return null;const E={...T,id:P||T.id||G()};return{proposalId:t,category:"block",blockId:E.id,insertReferenceId:x,apply:()=>this.insertBlockRelativeWithSuggestion({block:E,referenceId:x,position:w,suggestionId:t,label:"Insert",createdAt:g,batchInsertedBlocks:a})}}if(d.insertionContext){const v=this.host.resolvePositionAwareInsertionReference({baseDoc:n,mustBeAfter:d.insertionContext.mustBeAfter,mustBeBefore:d.insertionContext.mustBeBefore});return v?{proposalId:t,category:"block",blockId:d.insertionContext.paragraphId,insertReferenceId:v.referenceId,apply:()=>this.insertBlockRelativeWithSuggestion({block:{...this.cloneSuggestionSnapshot(d.insertionContext.content),id:d.insertionContext.content.id||d.insertionContext.paragraphId||G()},referenceId:v.referenceId,position:v.position,suggestionId:t,label:"Insert",createdAt:g,batchInsertedBlocks:a})}:null}const u=e.resolveAnchorsAgainstDoc(t,o),f=d.anchors?.[0]?.paragraphId??null,h=d.inlinePreview&&!d.toolCallAction?d.inlinePreview:null,p=h?{resolvedPreview:(d.anchors??[]).map(v=>({kind:v.kind,paragraphId:v.paragraphId,fromIndex:h.startOffset,toIndex:h.startOffset+h.newText.length,text:v.text})),previewAnchorBlock:null}:e.withMaterializedSuggestion(t,v=>({resolvedPreview:e.resolveAnchorsAgainstDoc(t,v),previewAnchorBlock:f?Bl(v,f):null}));if(!p)return null;const{resolvedPreview:m,previewAnchorBlock:y}=p;if(d.toolCallAction?.name==="remove_block"){const v=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,x=typeof v?.id=="string"?v.id:null,w=x?W(n,x):null;return!x||!w?null:{proposalId:t,category:"block",blockId:x,apply:()=>this.applyBridgeBlockDeleteSuggestion({suggestionId:t,blockId:x,beforeBlock:w,label:"Delete",createdAt:g})}}const b=d.anchors?.[0],k=u[0],S=m[0];if(b?.paragraphId){const v=W(n,b.paragraphId);let x=v?.type==="table"&&i?W(i,v.id):null;v?.type==="table"&&x?.type==="table"&&this.hasSameTableGeometry(v,x)&&!He(v,x)&&(x={...x,children:x.children.map((T,E)=>({...T,children:T.children.map((B,N)=>({...B,children:v.children[E].children[N].children}))}))});const w=x??y;if(d.toolCallAction?.name==="replace_block"&&v&&w&&(v.type!=="paragraph"||w.type!=="paragraph"||this.host.paragraphReplaceShouldStayAtomic(v,w)))return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:w,optimizeFormatting:l,label:v.type==="paragraph"&&w.type==="paragraph"?Ot(v)===Ot(w)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})};if(v?.type==="paragraph"){const T=k?.fromIndex??k?.toIndex,E=b.previewStartOffset??S?.fromIndex??S?.toIndex;if(b.kind==="delete"){const B=T??E??0,N=b.text?.length??Math.max(0,(k?.toIndex??B)-B),R=Math.max(0,B-N);return{proposalId:t,category:"inline",blockId:v.id,start:R,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:v.id,start:R,deleteLength:N,insertNodes:[],label:"Delete",createdAt:g})}}if(b.kind==="insert"&&(h||w?.type==="paragraph")){const B=E??T??0,N=E??B,R=b.previewStartOffset!==void 0?N+(b.text?.length??0):S?.toIndex??N+(b.text?.length??0),M=b.previewTextNodes?b.previewTextNodes.map(O=>({...O,marks:O.marks?{...O.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(w,N,R);return{proposalId:t,category:"inline",blockId:v.id,start:B,inlinePriority:0,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:v.id,start:B,deleteLength:0,insertNodes:M,label:"Insert",createdAt:g})}}if(b.kind==="replace"&&(h||w?.type==="paragraph")){const B=E??T??0,N=E??B,R=b.previewStartOffset!==void 0?N+(b.text?.length??0):S?.toIndex??N+(b.text?.length??0),M=b.previewTextNodes?b.previewTextNodes.map(O=>({...O,marks:O.marks?{...O.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(w,N,R);return b.oldText===b.text?{proposalId:t,category:"inline",blockId:v.id,start:B,inlinePriority:1,apply:()=>this.applyBridgeInlineFormatSuggestion({suggestionId:t,blockId:v.id,start:B,end:B+(b.text?.length??0),targetAttributes:{},targetTextNodes:M,createdAt:g})}:{proposalId:t,category:"inline",blockId:v.id,start:B,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:v.id,start:B,deleteLength:b.oldText?.length??0,insertNodes:M,label:"Replace",createdAt:g})}}}if(v?.type==="list"&&w?.type==="list")return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:w,optimizeFormatting:!c&&(l||b.oldText===b.text),label:"List",createdAt:g})};const A=v?.type,P=w?.type;if(A==="list-item"&&P==="list-item"){const T=v,E=w,B=Xt(n,T.id)?.children.find(N=>N?.type!=="list"?!1:N.children.some(R=>R.id===T.id));if(B?.id){const N=B.children.findIndex(R=>R.id===T.id);if(N!==-1){const R=this.cloneSuggestionSnapshot(B),M=this.cloneSuggestionSnapshot(B);return M.children[N]=this.cloneSuggestionSnapshot(E),{proposalId:t,category:"block",blockId:B.id,apply:()=>{const O=W(this.host.getDocument(),B.id);return this.applyGranularListSuggestionChanges({blockId:B.id,before:R,after:M,suggestionId:t,currentLiveBlock:O?.type==="list"?O:void 0,createdAt:g})}}}}}if(v&&w)return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:w,optimizeFormatting:l,label:v.type==="table"?"Table":v.type==="paragraph"?"Format":"Change",createdAt:g})}}return null}describeAgentSuggestionApplyFailure(t,e,n,o){const r=e.getSuggestion(t.proposalId),i=(S,v)=>{const x=W(S,v);if(!x||x.id===v)return x;if(x.type==="list"){const w=x.children.find(A=>A.id===v);if(w)return w}return x},a=r?.toolCallAction,l=a?.arguments&&typeof a.arguments=="object"?a.arguments:null,c=typeof l?.id=="string"&&l.id.length>0?l.id:t.blockId,d=o?.find(S=>{const v=S.arguments&&typeof S.arguments=="object"?S.arguments:null,x=typeof v?.id=="string"&&v.id.length>0?v.id:null,w=x?i(n,x):null;if(!w)return!1;if(x===c)return!0;const A=typeof v?.find=="string"?v.find:"";return A.length>0&&Ot(w).includes(A)})??a,g=d?.name??"agent change",u=d?.arguments&&typeof d.arguments=="object"?d.arguments:null,f=typeof u?.id=="string"&&u.id.length>0?u.id:t.blockId,h=this.host.getDocument(),p=f?i(h,f):null,m=f?i(n,f):null,y=p??m,b=y?y.type:null,k=f?`'${f}'${typeof b=="string"?` (${b})`:""}`:"the requested target";return!p&&m?`Could not apply ${t.category} suggestion for ${g} to block ${k}: the target was present when the action was planned but is no longer available at replay time. The attempted change was rolled back; re-read that block and retry.`:y?`Could not apply ${t.category} suggestion for ${g} to block ${k}: the requested edit is not compatible with the target's current structure. The attempted change was rolled back; re-read the target and retry with a narrower edit or the containing block.`:`Could not apply ${t.category} suggestion for ${g}: the target block is unavailable at replay time. The attempted change was rolled back; re-read the document and retry.`}liveTextRuns(t){const e=[];let n=0;for(const o of st(t)){if(typeof o.insert!="string")return null;const r=o.attributes??{};e.push({start:n,text:o.insert,attrs:r,hidden:!!r.deletion}),n+=o.insert.length}return e}visibleLiveChars(t){const e=this.liveTextRuns(t);if(!e)return null;const n=[],o=[];let r="";for(const i of e)if(!i.hidden){for(let a=0;a<i.text.length;a++)n.push(i.start+a),o.push(i.attrs);r+=i.text}return{offsets:n,attrs:o,text:r}}static formattingMarks(t){const e={};for(const[n,o]of Object.entries(t??{}))ho.has(n)||o==null||(e[n]=o);return e}static sliceTextNodes(t,e,n){const o=[];let r=0;for(const i of t){const a=Math.max(e,r),l=Math.min(n,r+i.text.length);l>a&&o.push({...i,text:i.text.slice(a-r,l-r)}),r+=i.text.length}return o}static textOf(t){return t.map(e=>e.text).join("")}static onlyTextNodes(t){return t?.type!=="paragraph"?null:t.children.every(e=>e.type==="text")?t.children:null}planLayeredParagraphText(t,e,n){const o=this.visibleLiveChars(t),r=ft.textOf(e),i=ft.textOf(n);if(!o||o.text!==r)return null;const a=y=>y.flatMap(b=>{const k=Pt(ft.formattingMarks(b.marks));return Array.from({length:b.text.length},()=>k)}),l=a(e),c=a(n),d=[],g=[],u=r===i?[[0,r]]:En(r,i).diffs;let f=0,h=0,p=null;const m=()=>{p&&(d.push({from:p.from,to:p.to,nodes:ft.sliceTextNodes(n,p.afterFrom,h)}),p=null)};for(const[y,b]of u){if(y===0){m();let k=-1;for(let S=0;S<=b.length;S++){const v=S<b.length&&l[f+S]!==c[h+S];v&&k<0&&(k=S),!v&&k>=0&&(g.push({from:f+k,to:f+S,nodes:ft.sliceTextNodes(n,h+k,h+S)}),k=-1)}f+=b.length,h+=b.length;continue}p??(p={from:f,to:f,afterFrom:h}),y<0?(f+=b.length,p.to=f):h+=b.length}return m(),{expected:r,text:d,format:g}}applyLayeredParagraphText(t,e,n){const o=Z(this.host.ydoc,t),r=o?ct(o):null;if(!r||this.visibleLiveChars(r)?.text!==e.expected)throw new Error("A paragraph with pending suggestions changed while this edit was applied.");let i=!1;const a=gt();for(const c of[...e.format].sort((d,g)=>g.from-d.from)){const d=this.visibleLiveChars(r);let g=c.from;for(const u of c.nodes){const f=ft.formattingMarks(this.sanitizePreviewMarks(u.marks)),h=g+u.text.length;for(;g<h;){const p=d.attrs[g];let m=g+1;for(;m<h&&d.attrs[m]===p&&d.offsets[m]===d.offsets[m-1]+1;)m++;const y=ft.formattingMarks(p),b={};for(const k of new Set([...Object.keys(y),...Object.keys(f)]))Pt(y[k]??null)!==Pt(f[k]??null)&&(b[k]=f[k]??null);if(Object.keys(b).length>0){const k=d.offsets[g],S=m-g;if(n||p.insertion||p.formatChange){let v={};if(n&&p.formatChange)try{const x=JSON.parse(p.suggestionPriorAttributes??"{}");for(const[w,A]of Object.entries(b))A===null?delete x[w]:x[w]=A;v={suggestionPriorAttributes:JSON.stringify(x)}}catch{v={}}at(r,k,S,{...b,...v})}else at(r,k,S,{...b,formatChange:!0,...this.buildInlineSuggestionMetadataMarks(a,"Format"),suggestionPriorAttributes:Ue(p)});i=!0}g=m}}if(n&&c.nodes.length>0){const u=this.visibleLiveChars(r),f=c.from>0?u.offsets[c.from-1]+1:0,h=c.to<u.offsets.length?u.offsets[c.to]:r.length,p=c.nodes.flatMap(m=>Array.from({length:m.text.length},()=>ft.formattingMarks(this.sanitizePreviewMarks(m.marks))));for(const m of this.liveTextRuns(r)??[]){if(!m.hidden||m.start<f||m.start+m.text.length>h)continue;let y=u.offsets.findIndex(v=>v>m.start);y<0&&(y=c.to-1);const b=p[Math.min(Math.max(y,c.from),c.to-1)-c.from],k=ft.formattingMarks(m.attrs),S={};for(const v of new Set([...Object.keys(k),...Object.keys(b)]))Pt(k[v]??null)!==Pt(b[v]??null)&&(S[v]=b[v]??null);Object.keys(S).length!==0&&(at(r,m.start,m.text.length,S),i=!0)}}}for(const c of[...e.text].sort((d,g)=>g.from-d.from)){const d=this.visibleLiveChars(r),g=gt(),u=c.to>0?d.offsets[c.to-1]+1:0;let f={};if(n){const m=c.from<c.to?d.attrs.slice(c.from,c.to):c.from>0&&c.from<d.attrs.length?[d.attrs[c.from-1],d.attrs[c.from]]:[],y=m[0];if(y?.insertion&&y.suggestionId&&m.every(b=>b.insertion&&!b.deletion&&b.suggestionId===y.suggestionId)){for(const[b,k]of Object.entries(y))(b==="insertion"||b==="layeredInsertion"||b.startsWith("suggestion"))&&(f[b]=k);delete f.suggestionPriorAttributes}}let h=u;for(const m of c.nodes){if(!m.text)continue;const y=this.sanitizePreviewMarks(m.marks)??{},b=n?{...y,...f}:this.buildSuggestionInsertionMarks(y,g,"Insert");lt(r,h,m.text,b),h+=m.text.length,i=!0}const p=[];for(let m=c.from;m<c.to;m++){const y=p[p.length-1];y&&y[0]+y[1]===d.offsets[m]?y[1]++:p.push([d.offsets[m],1])}for(const[m,y]of p.reverse())n?r.delete(m,y):this.applySuggestedDeletionToTextRange(r,m,y,g),i=!0}const l=[];for(const c of this.liveTextRuns(r)??[]){if(c.attrs.suggestionId!==a||!c.attrs.formatChange)continue;let d={};try{d=JSON.parse(c.attrs.suggestionPriorAttributes??"{}")}catch{d={}}l.push({blockId:t,start:c.start,end:c.start+c.text.length,attributes:d})}return l.length>0&&this.saveLiveSuggestion({id:a,type:"inline-format",label:"Format",spans:l}),i}static changedParagraphFields(t,e){const n=new Set(["children","id","type","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),o=t,r=e;return[...new Set([...Object.keys(o),...Object.keys(r)])].filter(i=>!n.has(i)&&Pt(o[i]??null)!==Pt(r[i]??null))}applyLayeredParagraphFields(t,e,n,o){const r=ft.changedParagraphFields(e,n);if(r.length===0)return!1;const i=Z(this.host.ydoc,t),a=W(this.host.getDocument(),t);if(!i||a?.type!=="paragraph")return!1;const l={...a,children:[]},c={...l};for(const u of r){const f=n[u],h=e[u];f===void 0?delete l[u]:l[u]=this.cloneSuggestionSnapshot(f),h===void 0?delete c[u]:c[u]=this.cloneSuggestionSnapshot(h)}if(o)return Zt(i,l),!0;const d=gt(),g=this.cloneSuggestionSnapshot(e.children);return Zt(i,this.markBlockForGenericSuggestionChange(l,d,"Format")),this.saveLiveSuggestion({id:d,type:"block-change",blockId:t,beforeBlock:{...c,children:g},acceptedBlock:{...l,children:g},label:"Format"},i),!0}static hasPendingInlineMarks(t){return t?.type==="paragraph"&&t.children.some(e=>{const n=e.marks;return!!n?.suggestionId&&!!(n.insertion||n.deletion||n.formatChange)})}static hasForeignPendingInlineMarks(t,e){return t.type==="paragraph"&&t.children.some(n=>{const o=n.marks,r=typeof o?.suggestionAuthorName=="string"?o.suggestionAuthorName.trim():"";return!!o?.suggestionId&&!!(o.insertion||o.deletion||o.formatChange)&&!!r&&r!==e})}planPendingListEdit(t,e,n,o,r,i,a,l){if(n?.type!=="list")return!1;if(!r&&this.host.docxRoundTripRequired&&o?.type==="list"&&(n.variant!==o.variant||(n.startNumber??1)!==(o.startNumber??1)||(n.numberingFormat??null)!==(o.numberingFormat??null)))return"numbering";const c=b=>({type:"paragraph",id:b.id,children:b.children}),d=e.children.filter(b=>ft.hasPendingInlineMarks(c(b)));if(o?.type==="list"){const b=new Set(o.children.map(x=>x.id)),k=new Set(n.children.map(x=>x.id)),S=n.children.filter(x=>b.has(x.id)),v=o.children.filter(x=>k.has(x.id));if(S.some((x,w)=>x.id!==v[w]?.id)){if(!(d.length===0&&!e.structuralSuggestionId&&e.children.every(w=>!w.structuralSuggestionId)))return"refuse";if(!r)return"reorder";a.add(t);for(const w of[...n.children,...o.children])a.add(w.id);const x=this.cloneSuggestionSnapshot(o);return l.push(()=>{if(!this.runWithoutSuggesting(()=>this.host.replaceBlockByIdWithoutSelection(t,x)))throw new Error("Could not reorder the list.");return!0}),!0}}if(d.length===0||!r&&!d.some(b=>ft.hasForeignPendingInlineMarks(c(b),i))||!o)return!1;if(o.type!=="list"||e.structuralSuggestionId||!Bo(n,o))return"refuse";const g=new Map(n.children.map(b=>[b.id,b])),u=new Map(o.children.map(b=>[b.id,b])),f=n.children.filter(b=>u.has(b.id)),h=o.children.filter(b=>g.has(b.id));if(f.some((b,k)=>b.id!==h[k]?.id))return"refuse";const p=[],m=[];for(const b of h){const k=g.get(b.id);if(Ut(k,b))continue;const S=e.children.find(A=>A.id===b.id);if(!S||S.structuralSuggestionId)return"refuse";if(ft.changedParagraphFields(k,b).length>0&&m.push({prior:k,item:b}),Ut(k.children,b.children))continue;const v=Z(this.host.ydoc,b.id),x=v?ct(v):null,w=x?this.planLayeredParagraphText(x,k.children,b.children):null;if(!w)return"refuse";p.push({itemId:b.id,plan:w})}const y=f.length!==n.children.length||h.length!==o.children.length;if(!y&&p.length===0&&m.length===0)return!1;a.add(t);for(const b of[...n.children,...o.children])a.add(b.id);return l.push(()=>{let b=!1;if(y){const k=W(this.host.getDocument(),t);if(k?.type!=="list")throw new Error("Could not apply the list edit.");const S={...n,children:n.children.map(x=>u.get(x.id)??x)},v=new Set(this.getLiveSuggestionIds());if(!this.applyGranularListSuggestionChanges({blockId:t,before:S,after:o,suggestionId:gt(),currentLiveBlock:k}))throw new Error("Could not apply the list edit.");for(const x of this.getLiveSuggestionIds()){if(v.has(x))continue;const w=this.getLiveSuggestion(x);if(w?.type!=="block-change"||w.listItemSuggestion?.kind!=="delete"||!w.listItemSuggestion.beforeItem)continue;const A=k.children.find(T=>T.id===w.listItemSuggestion.beforeItem.id);if(!A)continue;const P=this.cloneSuggestionSnapshot(A);delete P.structuralSuggestionId,delete P.structuralSuggestionKind,delete P.structuralSuggestionLabel,this.saveLiveSuggestion({...w,listItemSuggestion:{...w.listItemSuggestion,beforeItem:P}})}b=!0}for(const k of p)this.applyLayeredParagraphText(k.itemId,k.plan,r)&&(b=!0);for(const k of m)this.applyListItemFields(t,k.prior,k.item,r)&&(b=!0);return b}),!0}applyListItemFields(t,e,n,o){const r=ft.changedParagraphFields(e,n),i=Z(this.host.ydoc,n.id),a=W(this.host.getDocument(),t),l=a?.type==="list"?a.children.find(f=>f.id===n.id):void 0;if(!r.length||!i||!l)return!1;const c={...l,children:[]},d={...l,children:[]};for(const f of["structuralSuggestionId","structuralSuggestionKind","structuralSuggestionLabel","structuralSuggestionRecord"])delete c[f],delete d[f];for(const f of r){const h=n[f],p=e[f];h===void 0?delete c[f]:c[f]=this.cloneSuggestionSnapshot(h),p===void 0?delete d[f]:d[f]=this.cloneSuggestionSnapshot(p)}if(o)return Zt(i,c),!0;const g=gt(),u=this.normalizeLiveSuggestionRecord({id:g,type:"block-change",blockId:t,beforeBlock:{...a,children:[]},listItemSuggestion:{kind:"change",beforeItem:d,afterItem:c},label:"Format"});return Zt(i,{...c,structuralSuggestionId:g,structuralSuggestionKind:"change",structuralSuggestionLabel:"Format",structuralSuggestionRecord:JSON.stringify(u)}),this.saveLiveSuggestion(u),!0}planPendingParagraphEdits(t,e,n,o,r,i){const a=new Set,l=[],c=[],d=[],g=[],u=Ct(this.host.getDocument()),f=Ct(n),h=Ct(o),p=(k,S,v)=>{const x=k.get(v);if(!x)return null;const w=x.parentContainer,A=w?w.children:S.children;return A?{list:A,index:x.indexInParent}:null},m=k=>{const S=u.get(k)?.block;return S?.type==="paragraph"&&!S.structuralSuggestionId&&ft.hasPendingInlineMarks(S)&&(r||ft.hasForeignPendingInlineMarks(S,i))},y=k=>{const S=Z(this.host.ydoc,k);return S?ct(S):null},b=(k,S)=>{const v=S.get(k)?.block,x=u.get(k)?.block;return ft.onlyTextNodes(v)&&x?.type==="paragraph"&&!x.structuralSuggestionId?v:null};for(const k of new Set(t)){if(!a.has(k)&&u.get(k)?.block.type==="list"){const $=u.get(k).containerPath.some(L=>e.has(L))?!1:this.planPendingListEdit(k,u.get(k).block,f.get(k)?.block,h.get(k)?.block,r,i,a,l);if($==="refuse"&&c.push(k),$==="reorder"&&d.push(k),$==="numbering"&&g.push(k),$)continue}if(a.has(k)||!m(k)||u.get(k).containerPath.some($=>e.has($)))continue;const S=b(k,f);if(!S)continue;const v=h.get(k)?.block,x=y(k);if(!x)continue;if(v&&Ut(S,v)){a.add(k);continue}const w=p(f,n,k),A=v?p(h,o,k):null,P=($,L)=>{const D=b($,f),H=b(L,f),F=ft.onlyTextNodes(h.get($)?.block),X=y($),C=y(L);if(!D||!H||!F||h.has(L)||!X||!C||Z(this.host.ydoc,$)?.parent!==Z(this.host.ydoc,L)?.parent)return!1;const j=ft.textOf(F),U=ft.textOf(H.children);let z=0;for(;z<U.length&&z<j.length&&U[U.length-1-z]===j[j.length-1-z];)z++;if(z<U.trimStart().length)return!1;const tt=j.length-z,_=this.planLayeredParagraphText(X,D.children,ft.sliceTextNodes(F,0,tt)),V=this.planLayeredParagraphText(C,H.children,ft.sliceTextNodes(F,tt,j.length));if(!_||!V)return!1;const nt=h.get($).block;return a.add($),a.add(L),l.push(()=>{this.applyLayeredParagraphText($,_,r),this.applyLayeredParagraphText(L,V,r);const J=this.host.getDocument(),K=W(J,$),q=W(J,L),Q=Xt(J,$)??J;if(K?.type!=="paragraph"||q?.type!=="paragraph")throw new Error("Could not join the paragraphs.");const ut=this.getSuggestionMutationSelection(),yt=()=>this.host.mergeAdjacentParagraphs(K,q,{block:$,offset:ct(Z(this.host.ydoc,$)).length},{block:L,offset:0},Q,ut,ut),Lt=this.host.suggestingMode;this.host.suggestingMode=!r;try{if(!yt())throw new Error("Could not join the paragraphs.")}finally{this.host.suggestingMode=Lt}return this.applyLayeredParagraphFields($,D,nt,r),!0}),!0};if(!v){const $=w&&w.index>0?w.list[w.index-1]:null;if($&&!a.has($.id)&&P($.id,k))continue;!r&&!h.has(k)&&(a.add(k),l.push(()=>{const L=this.getSuggestionMutationSelection(),D=this.host.suggestingMode;this.host.suggestingMode=!0;try{if(!this.host.deleteBlockById(k,L,L))throw new Error("Could not remove the paragraph.")}finally{this.host.suggestingMode=D}return!0}));continue}if(v.type!=="paragraph")continue;const T=w&&w.index+1<w.list.length?w.list[w.index+1]:null;if(T&&!h.has(T.id)){a.has(T.id)||P(k,T.id);continue}const E=ft.onlyTextNodes(v);if(!E)continue;const B=A&&A.index+1<A.list.length?A.list[A.index+1]:null,N=B?ft.onlyTextNodes(B):null,R=ft.textOf(E),M=ft.textOf(S.children);if(B&&N&&!f.has(B.id)&&!u.has(B.id)&&R.length>0&&R.length<M.length&&R+ft.textOf(N)===M){const $=B.id,L=R.length;a.add(k),a.add($),l.push(()=>{const D=Z(this.host.ydoc,k),H=D?ct(D):null,F=H?this.visibleLiveChars(H):null;if(!F||F.text!==M)throw new Error("Could not split the paragraph.");const X=this.getSuggestionMutationSelection(),C=new Set(this.getLiveSuggestionIds()),j=this.host.suggestingMode;this.host.suggestingMode=!r;let U;try{U=this.host.splitParagraph({block:k,offset:F.offsets[L]},X)}finally{this.host.suggestingMode=j}const z=U&&U.block!==k?U.block:null,tt=z?Z(this.host.ydoc,z):null;if(!z||!tt)throw new Error("Could not split the paragraph.");tt.setAttribute("id",$);for(const _ of this.getLiveSuggestionIds()){if(C.has(_))continue;const V=this.getLiveSuggestion(_);V?.type==="paragraph-split"?this.saveLiveSuggestion({...V,insertedBlockId:$}):V?.type==="block-insert"&&this.saveLiveSuggestion({...V,blockId:$})}return!0});continue}const O=this.planLayeredParagraphText(x,S.children,E);O&&(a.add(k),l.push(()=>{const $=this.applyLayeredParagraphText(k,O,r);return this.applyLayeredParagraphFields(k,S,v,r)||$}))}return{owned:a,apply:l,refused:c,reordered:d,numbering:g}}tableKeepsLiveCells(t,e,n){const o=W(e,t),r=W(n,t);return o?.type==="table"&&r?.type==="table"&&!this.tableHasPendingStructure(t)&&(!rn(o,r)||!!this.buildTableStructureChange(o,r,"probe"))}applyValidatedAgentActionsAsSuggestions(t){const e=this.host.tryCancelInsertedBlockForRemoveAction(t.processedActions,t.docBeforeToolCall);if(e)return e;const n=!!t.processedActions?.length&&t.processedActions.every(C=>C.name==="style_blocks"),o=new qr(t.baseFork,n),r=new Map;for(const{block:C}of Ct(t.docBeforeToolCall).values())C.type==="list"&&C.id&&r.set(C.id,C.children.map(j=>j.id));for(const C of this.getLiveSuggestionIds()){const j=this.getLiveSuggestion(C);j?.type==="block-change"&&j.sequenceBlockIds&&j.beforeBlock.id&&r.set(j.beforeBlock.id,this.getSequenceReplacementMembers(j).map(({yBlock:U})=>U.getAttribute("id")))}const i=Ur(t.validationFork,o,{...t.flattenOptions,precomputedLiveDocSchema:t.baseDocForSuggestions,precomputedCurrentDocSchema:t.baseDocForSuggestions,listUnwrapMemberIds:r,precomputedFinalDocSchema:t.docAfterToolCall,precomputedVisibleBeforeDocSchema:t.docBeforeToolCall}),a=t.validationAnchorsByAction.flat().filter(C=>C.kind==="replace"&&C.previewStartOffset!==void 0&&!!C.paragraphId);for(const C of a){const j=i.filter(U=>(o.getSuggestion(U)?.anchors??[]).some(z=>z.kind==="replace"&&z.paragraphId===C.paragraphId&&(z.oldText??"").includes(C.oldText??"")&&(z.text??"").includes(C.text??"")));if(j.length===1){const U=o.getSuggestion(j[0]),z=C.sourceFrom?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(C.sourceFrom),t.baseFork):null,tt=C.paragraphId?Z(t.baseFork,C.paragraphId):null,_=tt?ct(tt):null,V=_?st(_).map(nt=>typeof nt.insert=="string"?nt.insert:"").join(""):"";U&&z&&z.type===_&&V.slice(z.index,z.index+(C.oldText?.length??0))===(C.oldText??"")&&(U.anchors=[{...C,previewStartOffset:z.index}])}}const l=i.length>=100,c=Date.now(),d=C=>{l&&(`${i.length}${C}`,Date.now()-c)};if(d("flattened"),i.length===0)return this.tryRejectRevertedPendingSuggestions({actions:t.processedActions,validationAnchorsByAction:t.validationAnchorsByAction,baseDoc:t.baseDocForSuggestions,docAfterToolCall:t.docAfterToolCall})||{success:!1,error:"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content."};const g=t.baseDocForSuggestions,u=(t.processedActions??[]).map((C,j)=>{const U=C.arguments&&typeof C.arguments=="object"?C.arguments:null,z=typeof U?.comment=="string"?U.comment.trim():"";return{action:C,comment:z,anchors:t.validationAnchorsByAction[j]??[]}}).filter(({action:C,comment:j})=>(C.name==="replace"||C.name==="replace_all")&&j.length>0),f=new Map;for(const C of u){const j=C.anchors.flatMap(U=>{if(!U.from||!U.to||!U.paragraphId)return[];const z=I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(U.from),t.validationFork),tt=I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(U.to),t.validationFork);if(!z||!tt||z.type!==tt.type)return[];const _=U.oldText??"",V=U.text??"";let nt=0;for(;nt<_.length&&nt<V.length&&_[nt]===V[nt];)nt++;let J=0;for(;J<_.length-nt&&J<V.length-nt&&_[_.length-1-J]===V[V.length-1-J];)J++;const K=_.length>V.length&&nt+J===V.length?z.index+nt:null;return[{paragraphId:U.paragraphId,start:z.index,end:tt.index,deletionPoint:K}]});f.set(C,j)}const h=new Map,p=i.map(C=>this.buildAgentSuggestionPlanFromProposal(C,o,g,t.baseFork,void 0,t.docAfterToolCall,h,t.optimizeStyleFormatting===!0,u.length>0)).filter(C=>!!C);if(d("built plans"),p.length!==i.length)return{success:!1,error:"Could not translate one or more agent changes into live suggestions."};const m=new Set;for(const C of p){if(C.category!=="block"||!C.blockId)continue;const j=W(this.host.getDocument(),C.blockId);j&&j.type!=="paragraph"&&!(j.type==="table"&&this.tableKeepsLiveCells(C.blockId,t.docBeforeToolCall,t.docAfterToolCall))&&m.add(C.blockId)}const y=t.directMode===!0&&u.length===0,b=t.agentName??Nt;for(const C of m){const j=W(this.host.getDocument(),C);if(!(j?.type!=="table"||!j.children.some(U=>U.children.some(z=>z.children.some(tt=>tt.type==="paragraph"&&ft.hasPendingInlineMarks(tt)&&(y||ft.hasForeignPendingInlineMarks(tt,b)))))))return sn("pending_table_changes",{subject:C,reason:this.tableHasPendingStructure(C)?"a pending row or column change":"merged cells or moved content"},{tableId:C})}const k=C=>[C.blockId,...C.producedBlockIds??[]].filter(j=>!!j),S=new Set(t.flattenOptions?.affectedBlockIds??[]);for(const C of p)for(const j of k(C))S.add(j);let v=this.planPendingParagraphEdits(S,m,t.docBeforeToolCall,t.docAfterToolCall,t.directMode===!0&&u.length===0,t.agentName??Nt);if(v.numbering.length>0)return sn("list_numbering_tracked_unsupported",{subject:v.numbering[0]},{listIds:v.numbering});if(v.reordered.length>0)return sn("list_reorder_unsupported",{subject:v.reordered[0]},{listIds:v.reordered});if(v.refused.length>0)return sn("pending_list_changes",{subject:v.refused[0]},{listIds:v.refused});p.some(C=>{const j=k(C);return j.some(U=>v.owned.has(U))&&!j.every(U=>v.owned.has(U))})&&(v={owned:new Set,apply:[],refused:[],reordered:[],numbering:[]});const x=C=>k(C).some(j=>v.owned.has(j));let w=!1;const A=this.sortBlockSuggestionPlansByDependency(p.filter(C=>C.category==="block"&&!x(C))),P=new Map(i.map((C,j)=>[C,j])),T=p.filter(C=>C.category==="inline"&&!x(C)).sort((C,j)=>{if(C.blockId&&j.blockId&&C.blockId===j.blockId){const U=(j.start??0)-(C.start??0);if(U!==0)return U;const z=(j.inlinePriority??0)-(C.inlinePriority??0);if(z!==0)return z}return(P.get(C.proposalId)??0)-(P.get(j.proposalId)??0)});let E=[];const B=this.host.beginRollbackScope();let N=null;try{d("applying plans"),E=this.withSuggestionMetadata({source:"agent",authorType:"ai",label:`${t.agentName??Nt} revision`,agentName:t.agentName??Nt,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,historyOrigin:`live-suggestions:${t.toolCallId}`},()=>this.host.transact(()=>{const C=new Set(Array.from(t.flattenOptions?.affectedBlockIds??[]));for(const z of p)z.blockId&&C.add(z.blockId);for(const z of v.owned)C.delete(z);N=A[0]??T[0]??null,this.resetTablePropertyRevisions(C,g,t.docAfterToolCall,t.docBeforeToolCall),this.resetLiveSuggestionsForBlocks(C,g),this.batchYBlockLocationsById=new Map;const j=new Map;for(const z of A){if(!z.blockId)continue;const tt=Z(this.host.ydoc,z.blockId);tt&&j.set(tt,z.blockId)}const U=new Map;for(const[z,tt]of j){const _=z.parent;if(!(_ instanceof I.XmlElement||_ instanceof I.XmlFragment))continue;const V=U.get(_)??new Map;V.set(z,tt),U.set(_,V)}for(const[z,tt]of U)z.toArray().forEach((_,V)=>{if(!(_ instanceof I.XmlElement))return;const nt=tt.get(_);nt&&this.batchYBlockLocationsById.set(nt,{yBlock:_,yParent:z,index:V})});try{for(const z of A)if(N=z,!z.apply())throw new Error("suggestion application returned false");for(const z of T)if(N=z,!z.apply())throw new Error("suggestion application returned false");N=null;for(const z of v.apply)z()&&(w=!0)}finally{this.batchYBlockLocationsById=null}d("finished plan loop"),N=null})).suggestionIds,d("applied plans"),B.dispose()}catch(C){B.revert();const j=C instanceof Error?C.message:"suggestion application failed",U=j==="suggestion application returned false"?null:j,z=N?this.describeAgentSuggestionApplyFailure(N,o,g,t.originalActions):null;return{success:!1,error:z?`${z}${U?` Detail: ${U}`:""}`:U??"Could not apply the requested edit."}}this.host.relinkCommentSuggestionIds();const R=u.length?this.host.getSuggestionCommentRanges(E):[],M=[],O=[];let $=0,L=0;const D=(C,j)=>C.flatMap(U=>j.flatMap(z=>{if(U.structural){if(z.paragraphId!==U.blockId)return[];const tt=Math.max(U.projectedStart,z.start),_=Math.min(U.projectedEnd,z.end);return _<tt||_===tt&&z.start!==z.end?[]:[{...U,start:U.start+tt-U.projectedStart,end:U.start+_-U.projectedStart}]}return(()=>{if(z.paragraphId!==U.blockId)return!1;const tt=U.projectedStart,_=U.projectedEnd;return tt===_&&z.start===z.end?tt===z.start:tt===_?z.deletionPoint===tt||z.start<tt&&tt<z.end:z.start===z.end?tt<z.start&&z.start<_:tt<z.end&&z.start<_})()?[U]:[]}));let H=null;for(const[C,j]of f){const U=D(R,j),z=Array.from(new Set(U.map(V=>V.suggestionId)));if(z.length===0&&j.length>0&&(H??(H=this.host.getSuggestionCommentRanges(this.getLiveSuggestionIds())),D(H,j).length===0)){L++;continue}if(z.length===0){$++;for(const V of E)M.includes(V)||M.push(V);continue}for(const V of z)M.includes(V)||M.push(V);const tt={author:t.agentName??Nt,authorType:"ai",agentName:t.agentName??Nt,agentModel:t.agentModel,suggestionId:z[0],...z.length>1?{relatedSuggestionIds:z}:{}},_=U.every(V=>V.structural&&V.start===V.end)?this.host.addBlockComment(U[0].blockId,C.comment,tt):this.host.addCommentToRanges(U.map(({blockId:V,start:nt,end:J})=>({blockId:V,start:nt,end:J})),C.comment,tt);_?O.push(_):$++}const F=cl(t.agentFeedback,t.originalActions,i,t.docBeforeToolCall,t.docAfterToolCall),X=E.length>0||w;return{success:X,planningSuggestionIds:i,suggestionIds:E,commentedSuggestionIds:M,attachedCommentIds:O,commentAttachmentFailureCount:$,commentOnRestoredTextCount:L,agentFeedback:X?F:void 0,error:X?void 0:"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content."}}captureLiveSuggestionApplicationSnapshot(){return{doc:this.cloneSuggestionSnapshot(this.host.getDocument()),liveSuggestions:Array.from(this.getLiveSuggestionStore().entries()).map(([t,e])=>[t,this.cloneSuggestionSnapshot(e)])}}restoreLiveSuggestionApplicationSnapshot(t){const e=this.host.getYContentFragment(),n=this.host.getYNotesFragment();this.host.transact(()=>{e.length>0&&e.delete(0,e.length),n.length>0&&n.delete(0,n.length)}),El(this.host.ydoc,t.doc),this.host.transact(()=>{const o=this.getLiveSuggestionStore();for(const r of Array.from(o.keys()))o.delete(r);for(const[r,i]of t.liveSuggestions)o.set(r,this.cloneSuggestionSnapshot(i))}),this.host.cachedDoc=this.cloneSuggestionSnapshot(t.doc),Rn(this.host.ydoc,this.host.cachedDoc),this.host.invalidateDerivedDocumentState()}tryRejectRevertedPendingSuggestions(t){const e=Array.from(new Set([...this.host.getActionTargetBlockIds(t.actions,t.baseDoc),...(t.validationAnchorsByAction??[]).flatMap(a=>a.map(l=>l?.paragraphId).filter(l=>typeof l=="string"&&l.length>0))]));if(e.length===0)return null;const n=this.host.getDocument(),o=new Set,r=[];for(const a of e){const l=W(n,a);l&&this.collectSuggestionIdsFromBlockValue(l,o);const c=W(t.baseDoc,a),d=W(t.docAfterToolCall,a);c&&d&&Ut(c,d)&&r.push(a)}if(o.size===0||r.length===0||this.rejectLiveSuggestions(Array.from(o))===0)return null;const i=r.length===1?`block ${r[0]}`:`${r.length} blocks`;return{success:!0,planningSuggestionIds:[],suggestionIds:[],agentFeedback:`Rejected pending suggestion changes for ${i}.`}}resetToolCallHistory(){this.host.toolCallHistory.clear()}getToolCallHistory(){return this.host.toolCallHistory.getAllToolCalls()}setToolCallHistory(t){this.host.toolCallHistory.clear();for(const e of t)this.host.toolCallHistory.getAllToolCalls().push(e)}getDetachedSuggestionStore(){return this.host.detachedSuggestionStore}hasSerializedDetachedSuggestions(t){return t?Object.keys(t.proposals||{}).length>0||Object.keys(t.metadata||{}).length>0:!1}rebuildDetachedSuggestionsFromSnapshot(t){const e=new qr(this.host.cloneYDoc(this.host.ydoc));return this.rebuildDetachedSuggestionsFromSnapshotWithStore(t,e)}rebuildDetachedSuggestionsFromSnapshotWithStore(t,e){const n=Eo(t);return Ur(n,e)}setDetachedSuggestionConversation(t,e){this.host.detachedSuggestionStore.setConversation(t,e)}clearLegacyDetachedSuggestionState(){const t=Array.from(this.host.detachedSuggestionStore.getAllSuggestions().keys());t.length>0&&this.host.detachedSuggestionStore.rejectSuggestions(t),Rr.clearAllStoredSuggestions(this.host.documentId)}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){const e=this.host.cloneYDoc(this.host.ydoc),n=new qr(e);if(this.hasSerializedDetachedSuggestions(t.serverDetachedSuggestions)){const d=this.host.cloneYDoc(this.host.ydoc),g=new Rr(d,`${this.host.documentId}-legacy-proposal-materialization`,!0,t.conversationId);g.loadFromServerData(t.serverDetachedSuggestions);const u=Array.from(g.getPendingSuggestions().keys());if(u.length>0){const f=mt(g.materializeWithSuggestions(u));this.rebuildDetachedSuggestionsFromSnapshotWithStore(f,n)}}else t.legacyDetachedSuggestionSnapshot?.proposedDocument&&this.rebuildDetachedSuggestionsFromSnapshotWithStore(t.legacyDetachedSuggestionSnapshot.proposedDocument,n);const o=Array.from(n.getPendingSuggestions().keys());if(o.length===0)return{success:!1,migratedSuggestionCount:0,error:"No legacy proposals to migrate."};const r=mt(e),i=o.map(d=>this.buildAgentSuggestionPlanFromProposal(d,n,r,e,t.legacyCreatedAt)).filter(d=>!!d);if(i.length!==o.length)return{success:!1,migratedSuggestionCount:0,error:"Could not translate one or more legacy proposals into live suggestions."};const a=this.sortBlockSuggestionPlansByDependency(i.filter(d=>d.category==="block")),l=i.filter(d=>d.category==="inline").sort((d,g)=>d.blockId&&g.blockId&&d.blockId===g.blockId?(g.start??0)-(d.start??0):o.indexOf(d.proposalId)-o.indexOf(g.proposalId));let c=[];try{c=this.withSuggestionMetadata({source:"agent",authorType:"ai",createdAt:t.legacyCreatedAt,label:"Agent revision",agentName:Nt,historyOrigin:`migrated-legacy-proposals:${t.conversationId}`},()=>{for(const d of a)if(!d.apply())throw new Error(`Failed migrating block proposal ${d.proposalId}`);for(const d of l)if(!d.apply())throw new Error(`Failed migrating inline proposal ${d.proposalId}`)}).suggestionIds}catch(d){return{success:!1,migratedSuggestionCount:0,error:d instanceof Error?d.message:"Failed applying migrated live suggestions."}}return{success:c.length>0,suggestionIds:c,migratedSuggestionCount:o.length,error:c.length===0?"No legacy proposals were migrated.":void 0}}hydrateLegacyDetachedSuggestionSnapshotForConversation(t,e,n){if(!t||!e?.proposedDocument||this.host.detachedSuggestionStore.getConversationId()!==t||this.host.rebuiltMigrationSnapshotConversations.has(t))return 0;if(this.hasSerializedDetachedSuggestions(n))return this.host.rebuiltMigrationSnapshotConversations.add(t),0;const o=typeof e.pendingSuggestionCount=="number"?e.pendingSuggestionCount:0;try{const r=this.rebuildDetachedSuggestionsFromSnapshot(e.proposedDocument);return(r.length>0||o<=0)&&this.host.rebuiltMigrationSnapshotConversations.add(t),r.length}catch(r){return console.error("[DocumentMutator] Failed rebuilding detached changes from migration snapshot:",r),o<=0&&this.host.rebuiltMigrationSnapshotConversations.add(t),0}}setOnDetachedSuggestionsChanged(t){this.host.detachedSuggestionStore.setOnSuggestionsChanged(t)}}class yu{constructor(t){this.host=t}resolveListContext(t,e){const n=this.host.resolveEditableContext(t,e);if(!n||n.editable.block.type!=="list"||!n.yContext)return null;const o=[];for(let r=0;r<n.yContext.yBlock.length;r++){const i=n.yContext.yBlock.get(r);i instanceof I.XmlElement&&i.nodeName==="list-item"&&o.push(i)}return{doc:n.doc,list:n.editable.block,blockPath:n.editable.blockPath,yContext:n.yContext,yListItems:o}}convertParagraphToList(t,e,n){const o=this.host.getDocument().children[t];return o?.id?this.convertParagraphToListById(o.id,e,n):!1}convertParagraphToListById(t,e,n){const o=this.host.getDocument(),r=W(o,t);if(!r||r.type!=="paragraph")return!1;const i=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(r):null,a=this.host.suggestingMode?gt():null,l=ot(this.host.ydoc,t);if(!l)return!1;const{yBlock:c,yParent:d,index:g}=l;this.host.transact(()=>{if(!(c instanceof I.XmlElement))return;const h=new I.XmlElement("list"),p=c.getAttribute("id")||G();h.setAttribute("id",p),h.setAttribute("variant",e),a&&this.host.suggestionEngine.setElementStructuralSuggestion(h,"change",void 0,a,"List"),n&&e==="ordered"?(h.setAttribute("startNumber",String(n)),this.host.listStartNumberCache.set(p,n)):e==="ordered"?(h.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(p,1)):this.host.listStartNumberCache.delete(p);let m,y;for(let x=0;x<c.length;x++){const w=c.get(x);if(w instanceof I.XmlText){y=w;break}}if(y&&y.length>0){const x=st(y);for(const w of x)if(w.attributes?.fontFamily){m=w.attributes.fontFamily;break}}if(!m&&r.type==="paragraph"){for(const x of r.children)if(x.type==="text"&&x.marks?.fontFamily){m=x.marks.fontFamily;break}}const b=[],k=[],S=(x,w)=>{k.push({ops:x,plain:w})};if(y&&y.length>0){const x=st(y);let w=[],A="";const P=()=>{S(w,A),w=[],A=""};x.forEach(T=>{if(typeof T.insert=="string"){let E=T.insert;for(;E.length>0;){const B=E.indexOf(`
8
8
  `);if(B===-1)E.length>0&&(w.push({insert:E,attributes:T.attributes&&Object.keys(T.attributes).length>0?{...T.attributes}:void 0}),A+=E),E="";else{const N=E.slice(0,B);N.length>0&&(w.push({insert:N,attributes:T.attributes&&Object.keys(T.attributes).length>0?{...T.attributes}:void 0}),A+=N),P(),E=E.slice(B+1)}}}else if(T.insert!==void 0&&T.insert!==null){let E=null;if(typeof T.insert=="string")E=T.insert;else try{E=JSON.stringify(T.insert)}catch{E=String(T.insert)}E&&E.length>0&&(w.push({insert:E,attributes:T.attributes&&Object.keys(T.attributes).length>0?{...T.attributes}:void 0}),A+=E)}}),P()}else k.push({ops:[],plain:""});k.length===0&&k.push({ops:[],plain:""});const v=rt(c,"direction");k.forEach(x=>{const w=new I.XmlElement("list-item");w.setAttribute("id",G()),e==="todo"&&w.setAttribute("checked","false"),(v==="rtl"||v==="ltr")&&w.setAttribute("direction",v);const A=new I.XmlText;if(k.length===1&&(e==="unordered"&&(x.plain==="-"||x.plain==="*")||e==="ordered"&&/^\d+\.$/.test(x.plain.trim())||e==="todo"&&(x.plain==="[]"||x.plain.trim()==="[]"))){const P=[...x.ops].reverse().find(E=>E.insert.length>0)?.attributes,T={...de(P)??{}};T.fontFamily||(T.fontFamily=m||jt),w.setAttribute("_emptyTextMarks",JSON.stringify(T))}else{let P=0;x.ops.forEach(({insert:T,attributes:E})=>{if(T.length===0)return;const B=E?{...E}:{};B.fontFamily||(m||console.warn("[DocumentMutator] convertParagraphToList: No font found, defaulting to Arial. This may indicate a bug."),B.fontFamily=m||jt),A.insert(P,T,B),P+=T.length})}w.insert(0,[A]),b.push(w)}),h.insert(0,b),d.delete(g,1),d.insert(g,[h]),this.host.suggestingMode&&a&&i&&this.host.suggestionEngine.saveLiveSuggestion({id:a,type:"block-change",blockId:t,beforeBlock:i,label:"List"})});const u={block:c.getAttribute("id")||t,offset:0};this.host.setSelectionAfterOperation({anchor:u,focus:u});const f=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(f),!0}setListDirectionById(t,e){const n=ot(this.host.ydoc,t);if(!n)return!1;const{yBlock:o}=n;return!(o instanceof I.XmlElement)||o.nodeName!=="list"?!1:(this.host.transact(()=>{for(let r=0;r<o.length;r++){const i=o.get(r);!(i instanceof I.XmlElement)||i.nodeName!=="list-item"||(e===null?et(i,"direction"):i.setAttribute("direction",e))}}),!0)}getListItemPlainText(t){return t.children.filter(e=>e.type==="text").map(e=>e.text).join("")}convertParagraphRangeToList(t,e,n){t>e&&([t,e]=[e,t]);const o=this.host.getDocument();if(t<0||e>=o.children.length||t>=o.children.length)return!1;const r=[];for(let i=t;i<=e;i++){const a=o.children[i];if(!a)return!1;if(a.type==="paragraph")r.push({type:"paragraph",node:a});else if(a.type==="list")r.push({type:"list",node:a});else return!1}return r.length===0?!1:(this.host.transact(()=>{const i=this.host.getYContentFragment(),a=i.get(t),l=a instanceof I.XmlElement?a.getAttribute("id"):void 0,c=new I.XmlElement("list"),d=l||G();c.setAttribute("id",d),c.setAttribute("variant",n),n==="ordered"?(c.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(d,1)):this.host.listStartNumberCache.delete(d);const g=[];let u;for(const p of r){if(p.type==="paragraph"){for(const m of p.node.children)if(m.type==="text"&&m.marks?.fontFamily){u=m.marks.fontFamily;break}}else if(p.type==="list")for(const m of p.node.children){for(const y of m.children)if(y.type==="text"&&y.marks?.fontFamily){u=y.marks.fontFamily;break}if(u)break}if(u)break}let f=!1;const h=(p,m)=>{const y=new I.XmlElement("list-item");y.setAttribute("id",G()),n==="todo"&&y.setAttribute("checked",String(m?.checked??!1)),(m?.direction==="rtl"||m?.direction==="ltr")&&y.setAttribute("direction",m.direction);const b=new I.XmlText;let k=p;if((n==="unordered"&&(p==="-"||p==="*")||n==="ordered"&&/^\d+\.$/.test(p)||n==="todo"&&p==="[]")&&(k=""),k){const v=m?.fontFamily||u;v||console.warn("[DocumentMutator] convertParagraphRangeToList: No font found for list item, defaulting to Arial. This may indicate a bug."),b.insert(0,k,{fontFamily:v||jt})}const S=m?.indentLevel;typeof S=="number"&&S>0&&y.setAttribute("indentLevel",String(S)),y.insert(0,[b]),g.push(y),f=!0};r.forEach(p=>{if(p.type==="paragraph"){const m=p.node.children.filter(b=>b.type==="text").map(b=>b.text).join("");let y;for(const b of p.node.children)if(b.type==="text"&&b.marks?.fontFamily){y=b.marks.fontFamily;break}(m.length>0?m.split(`