revise 2.0.0 → 2.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 (85) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/assets/{historyMaterializeWorker-CoAX9ZAi.js → historyMaterializeWorker-C4uxcZEh.js} +1 -1
  3. package/backend.d.ts +22 -0
  4. package/backend.js +1 -1
  5. package/chunks/AgentPageRenderer-BIf_Fza8.js +1 -0
  6. package/chunks/AgentPageRenderer-DT9sNxEn.js +1 -0
  7. package/chunks/{AttachmentDocumentImporter-dNMtkxrv.js → AttachmentDocumentImporter-BUavYRxO.js} +1 -1
  8. package/chunks/{AttachmentDocumentImporter-DSic_6At.js → AttachmentDocumentImporter-DGwfDJSH.js} +1 -1
  9. package/chunks/{BidiText-B4Hzrjg9.js → BidiText-D7LYTAUL.js} +1 -1
  10. package/chunks/DocumentMutator-CjN7Kk-X.js +31 -0
  11. package/chunks/DocumentScrubber-C9ZZEcYW.js +1 -0
  12. package/chunks/DocumentScrubber-DrgzBlx4.js +1 -0
  13. package/chunks/DocumentScrubber-W0EfGmL-.js +1 -0
  14. package/chunks/{DocxConverter-COV6CjUM.js → DocxConverter-Be3uPNcD.js} +3 -3
  15. package/chunks/{DocxConverter-B7P52lw7.js → DocxConverter-CGYMfz-j.js} +6 -6
  16. package/chunks/{DocxConverter-Cq_zCEJC.js → DocxConverter-DabDLfsu.js} +6 -6
  17. package/chunks/{DocxGraft-CJ12C9WP.js → DocxGraft-B6W7fbh4.js} +1 -1
  18. package/chunks/{DocxGraft-DcmFuUkd.js → DocxGraft-Cj7v78BO.js} +1 -1
  19. package/chunks/DocxGraft-Duvo2cpy.js +1 -0
  20. package/chunks/FileImporter-CjUX2S4s.js +1 -0
  21. package/chunks/FileImporter-DtkbI6rF.js +1 -0
  22. package/chunks/{HtmlConverter-JvRlkQM3.js → HtmlConverter-ikXImzTY.js} +1 -1
  23. package/chunks/{MarkdownConverter-B-tPY7X3.js → MarkdownConverter-CFrcLyO_.js} +2 -2
  24. package/chunks/{OdtConverter-DYHnR4E8.js → OdtConverter-BFT_P8SI.js} +1 -1
  25. package/chunks/OdtConverter-Cnda9T0q.js +1 -0
  26. package/chunks/OdtConverter-WdwwXKVM.js +1 -0
  27. package/chunks/PdfConverter-D7UM58vc.js +21 -0
  28. package/chunks/PdfConverter-TB-QPw29.js +21 -0
  29. package/chunks/PdfConverter-wVP63986.js +21 -0
  30. package/chunks/PdfImportService-Dj1-3L2B.js +2 -0
  31. package/chunks/PdfImportService-OE9G383I.js +2 -0
  32. package/chunks/{RtfConverter-oIwzoqCD.js → RtfConverter-D-oqPWNl.js} +5 -5
  33. package/chunks/{RtfConverter-BQGge3K-.js → RtfConverter-D9zhE07-.js} +5 -5
  34. package/chunks/{RtfConverter-CMfZ4olw.js → RtfConverter-DZgwU-_R.js} +1 -1
  35. package/chunks/{TableBorders-BLkZYt1k.js → TableBorders-BorZS8aZ.js} +1 -1
  36. package/chunks/{TxtConverter-C1lp6dBS.js → TxtConverter-BYazsp6P.js} +3 -3
  37. package/chunks/ar-C8zx2RwP.js +8 -0
  38. package/chunks/backend-MFpDFVrD.js +1 -0
  39. package/chunks/base64-BNMNG-lN.js +1 -0
  40. package/chunks/{browser-module-6b2Fq-5C.js → browser-module-BbaxnHNK.js} +1 -1
  41. package/chunks/{browser-module-CkO57IPL.js → browser-module-D2ixluMg.js} +1 -1
  42. package/chunks/capture-qC26xmfy.js +1 -0
  43. package/chunks/{carrier-WgcRSu7a.js → carrier-BWONvrA7.js} +1 -1
  44. package/chunks/de-ByQFqecF.js +8 -0
  45. package/chunks/es-PHpJXv5S.js +8 -0
  46. package/chunks/{footnoteFlatten-CW-DUcgK.js → footnoteFlatten-Bdnn_bz1.js} +1 -1
  47. package/chunks/{graftExport-CVg7PO2A.js → graftExport-CP3h2T88.js} +1 -1
  48. package/chunks/index-CjeGoI2g.js +351 -0
  49. package/chunks/index-D7V8zn4w.js +36 -0
  50. package/chunks/index-DyOcu9mD.js +351 -0
  51. package/chunks/{index.es-DOqegDGr.js → index.es-B97tjxvW.js} +1 -1
  52. package/chunks/{index.es-tXDO0RMv.js → index.es-mTU7Sl3w.js} +1 -1
  53. package/chunks/{jspdf.es.min-CzYti8jo.js → jspdf.es.min-DGiD4mlU.js} +1 -1
  54. package/chunks/{jspdf.es.min-ejWOGhkJ.js → jspdf.es.min-Mykp4BZO.js} +1 -1
  55. package/chunks/{pseudoLocale-CdBtPHRi.js → pseudoLocale-C90lXrPg.js} +1 -1
  56. package/chunks/{pseudoLocale-DEVWLkGC.js → pseudoLocale-UA_TkGrH.js} +1 -1
  57. package/chunks/serverDocumentSession-CRZSb5SO.js +11 -0
  58. package/chunks/signatures-CsL_TjvW.js +1 -0
  59. package/full.js +1 -1
  60. package/index.d.ts +27 -4
  61. package/index.js +1 -1
  62. package/package.json +2 -2
  63. package/root.js +2 -2
  64. package/style.css +1 -1
  65. package/chunks/AgentPageRenderer-C0n4EnuW.js +0 -1
  66. package/chunks/AgentPageRenderer-DURfmiu0.js +0 -1
  67. package/chunks/DocxGraft-CQpvFcYb.js +0 -1
  68. package/chunks/FileImporter-DVnYOJHp.js +0 -1
  69. package/chunks/FileImporter-q9mCch0J.js +0 -1
  70. package/chunks/OdtConverter-Br81BSoJ.js +0 -1
  71. package/chunks/OdtConverter-CQjh0vlo.js +0 -1
  72. package/chunks/PdfConverter-D26rXumc.js +0 -21
  73. package/chunks/PdfConverter-DGZpUSVf.js +0 -21
  74. package/chunks/PdfConverter-DZzVP0-B.js +0 -21
  75. package/chunks/PdfImportService-CBD8TL1k.js +0 -2
  76. package/chunks/PdfImportService-D6uUKGMf.js +0 -2
  77. package/chunks/ar-kgSWdrXF.js +0 -8
  78. package/chunks/backend-Cq-khfdG.js +0 -1
  79. package/chunks/base64-CfDUyGi8.js +0 -36
  80. package/chunks/capture-DU3MC7tb.js +0 -1
  81. package/chunks/de-C2QTHrqo.js +0 -8
  82. package/chunks/es-BKboUn4q.js +0 -8
  83. package/chunks/index-CLw_BlSL.js +0 -353
  84. package/chunks/index-F-kHIwWT.js +0 -353
  85. package/chunks/serverDocumentSession-DZrYbdpk.js +0 -42
@@ -1,42 +0,0 @@
1
- import{r as be,p as Gt,t as Ss,g as Ar,e as kd,n as Tr,a as Sd,h as Id,H as Cr,S as vd,b as ho,i as Is,c as Pr,d as le,f as vs,j as de,k as et,l as bt,m as xd,o as wd,q as Ad,s as Td,u as Cd,v as xs,P as Me,w as Mr,y as $r,x as ws,z as Pd,D as As,A as rt,B as Ut,C as Tt,E as ut,F as mt,G as kt,I as Ue,J as at,K as Pn,L as It,M as xt,N as Ts,O as Cs,Q as Md,R as Ps,T as xe,U as Mn,V as $d,W as Bd,X as _d,Y as po,Z as Ld,_ as Nd,$ as Fd,a0 as qe,a1 as Ed,a2 as Ms,a3 as Rd,a4 as Dd,a5 as Od,a6 as $s,a7 as jd,a8 as Ct,a9 as Br,aa as ze,ab as an,ac as fo,ad as cn,ae as Bs,af as mo,ag as bo,ah as Ud,ai as yo,aj as qd,ak as zd,al as $n,am as _s,an as Ls,ao as Ns,ap as Xd,aq as _r,ar as Hd,as as Wd,at as Jd,au as Yd,av as ye,aw as Kd,ax as Lr,ay as Vd,az as Gd,aA as Zd,aB as Qd,aC as tu,aD as Nr,aE as eu,aF as nu,aG as Fs,aH as ou,aI as Fr,aJ as ru,aK as iu,aL as Es,aM as su,aN as au,aO as cu}from"./backend-Cq-khfdG.js";import{f as z,a as ee,r as lu,g as du,c as uu,b as we,t as ko,d as qt,e as ke,h as Rs,i as Er,j as Rr,k as $e,l as Xe,m as Ds,n as ln,o as Dr,p as gu,q as hu,s as pu,u as Or,v as fu,w as mu,x as bu,y as yu,z as ku,A as Su}from"./base64-CfDUyGi8.js";import{e as Iu,r as vu,s as xu,p as wu,i as Au}from"./ListNumbering-Qlu6AuRZ.js";import{i as Os}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";import{a as Tu,R as Ae,A as js,s as Us,b as qs,c as jr,d as zs,i as Cu}from"./DocumentStylesheet-byN5dtC6.js";import{b as dn}from"./TableGrid-DVWaRZv0.js";import{p as So,a as Xs,c as Hs,b as Ur,d as Pu,e as Mu,s as Io,f as Ws,g as Js,h as $u,i as Bu,n as Ys}from"./TableBorders-BLkZYt1k.js";import{h as ue,H as Bn,D as _u,C as Ks,a as Vs,b as Gs,n as Lu,g as Nu,r as Fu}from"./BidiText-B4Hzrjg9.js";import*as x from"yjs";import{l as _n,k as Eu}from"./capture-DU3MC7tb.js";import{MarkdownConverter as vo}from"./MarkdownConverter-B-tPY7X3.js";import{s as Ru}from"./carrier-WgcRSu7a.js";function Du(r){const t=r.children.filter(e=>e.type==="text");return t.length===0?[{type:"text",text:""}]:t}function xo(r){return Du(r).reduce((t,e)=>t+e.text.length,0)}function Ou(r,t){const e=z(r,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 i=0;i<n.children.length;i++)o+=xo(n.children[i]),i<n.children.length-1&&(o+=1);return{block:e.id,offset:o}}return{block:e.id,offset:0}}class Nt extends Error{constructor(t,e,n="validation",o=!1,i="unchanged",s){super(e),this.code=t,this.phase=n,this.retryable=o,this.mutationOutcome=i,this.details=s,this.name="SemanticToolError"}}function Ln(r){return r instanceof Nt?{code:r.code,phase:r.phase,retryable:r.retryable,mutationOutcome:r.mutationOutcome,details:r.details}:void 0}const Zs=r=>r.replace(/\\+u([0-9a-fA-F]{4})/g,(t,e)=>String.fromCharCode(Number.parseInt(e,16)));function Qs(r,t){if(!r)return;const e=r.trim().toLowerCase();if(!e||e==="normal")return;const n=e.match(/^(-?\d+(?:\.\d+)?|-?\.\d+)(px|pt|em|rem|pc|in|cm|mm)?$/);if(!n)return;const o=parseFloat(n[1]);if(Number.isFinite(o))switch(n[2]??"px"){case"px":return o;case"pt":return o*(96/72);case"em":return o*(t??16);case"rem":return o*16;case"pc":return o*16;case"in":return o*96;case"cm":return o*(96/2.54);case"mm":return o*(96/25.4);default:return}}function ju(r){const t=r?.trim().match(/^([\d.]+)(px|pt)?$/i);if(!t)return;const e=parseFloat(t[1]);if(Number.isFinite(e))return t[2]?.toLowerCase()==="pt"?e*4/3:e}function Uu(r){if(!r)return;const t=o=>r.match(new RegExp(`(?:^|;)\\s*${o}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim(),e=So(t("border")),n={};for(const o of["top","bottom","left","right"]){const i=r.match(new RegExp(`border-${o}:\\s*([\\d.]+)px\\s+(solid|double|dashed|dotted|none)\\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)`,"i"));let s;if(i){const c=i[2].toLowerCase();s={width:c==="none"?0:parseFloat(i[1]),style:c==="solid"?"single":c,color:i[3]}}else{const c=So(t(`border-${o}`))??e;c&&(s={...c})}if(!s)continue;const a=ju(t(`padding-${o}`));a!==void 0&&a>0&&(s.space=Math.round(a*100)/100),n[o]=s}return Object.keys(n).length>0?JSON.stringify(n):void 0}const qu=new Set(["p","center","h1","h2","h3","h4","h5","h6","ul","ol","div","table","pre","img","latex","page-break","section-break","toc","hr","docx-raw"]),zu=/[&<>"']/,Xu=/[&<>"']/g,Hu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};function Wu(r){return Hu[r]??r}function Ju(r){const t=r.trim();if(t.length<2)return t;const e=[['"','"'],["'","'"],["“","”"],["‘","’"]];for(const[n,o]of e)if(t.startsWith(n)&&t.endsWith(o))return t.slice(n.length,t.length-o.length).trim();return t}let wo=null;function qr(r){return wo||(wo=new DOMParser().parseFromString("","text/html")),wo.body.innerHTML=r.replace(/<!--[\s\S]*?-->|<\/?[a-z][a-z0-9-]*(?:[^<>"']|"[^"]*"|'[^']*')*>/gi,t=>{const e=t.match(/^<(page-break|section-break|docx-raw|toc)(?=[\s/>])/i);return e&&/\/\s*>$/.test(t)?t.replace(/\/\s*>$/,`></${e[1]}>`):t}),wo}function Yu(r,t={}){return!r||t.code||t.latex?r:Zs(r.replace(/\\+(["'])/g,"$1"))}function ta(r){const t=new Set;function e(n){if("id"in n&&n.id&&t.add(n.id),n.type!=="paragraph"){if(n.type==="list")for(const o of n.children)o.id&&t.add(o.id);else if(n.type==="container")for(const o of n.children)e(o);else if(n.type==="table")for(const o of n.children){o.id&&t.add(o.id);for(const i of o.children){i.id&&t.add(i.id);for(const s of i.children)e(s)}}}}for(const n of r.children)e(n);return t}function Lt(r,t){if(!t?.validIds)return r||et();if(r&&t.validIds.has(r)&&!t.usedIds.has(r))return t.usedIds.add(r),r;let e=et();for(;t.usedIds.has(e);)e=et();return t.usedIds.add(e),e}const zr=class{static createParsingContext(t){const e=new Map,n=o=>{o.type==="image"&&e.set(o.id,o),"children"in o&&o.children.forEach(n)};n(t);for(const o of t.notes??[])n(o);return{imagesById:e,validIds:ta(t),indentStepPx:this.resolveIndentStepPx(t),documentFontFamily:this.findOmittableDocumentFontFamily(t)}}static toAgentHtml(t,e={}){const n=this.resolveOmittableDocumentFontFamily(t,e),o=this.pageLayoutToHtmlComment(t),i=[...t.children,...t.notes??[]].map(s=>this.blockToHtml(s,t,n,e)).filter(s=>s.length>0).join(`
2
- `);return o&&i.length>0?`${o}
3
- ${i}`:o||i}static toInternalImageHtml(t){return this.imageBlockToHtml(t,!0)}static toInternalHtml(t){return this.toAgentHtml(t,{scanDocumentFontFamily:!1,includeImageSources:!0,includeZeroListLevels:!0})}static pageLayoutToHtmlComment(t){const e=t.pageless===!0;if(!t.pageLayout&&!e)return null;const n=be(t.pageLayout),o=this.formatInchesForComment(Gt(n.marginTopPx)),i=this.formatInchesForComment(Gt(n.marginRightPx)),s=this.formatInchesForComment(Gt(n.marginBottomPx)),a=this.formatInchesForComment(Gt(n.marginLeftPx)),c=this.formatInchesForComment(Gt(n.indentStepPx)),l=this.formatInchesForComment(Gt(n.blockSpacingPx)),d=n.marginTopPx===n.marginRightPx&&n.marginTopPx===n.marginBottomPx&&n.marginTopPx===n.marginLeftPx?` margin-in="${o}"`:"",u=this.getEffectivePageNumberSettings(t,n),g=` show-page-numbers="${u.showPageNumbers?"true":"false"}" page-number-position="${u.pageNumberPosition}" page-number-start="${n.pageNumberStart}"${n.pageNumberFormat!=="decimal"?` page-number-format="${n.pageNumberFormat}"`:""}`,p=this.formatInchesForComment(Ss(n.columnGapTwips));return`<!--revise-page-layout${e?' pageless="true"':""} page-size="${n.pageSize}" orientation="${n.orientation}" margin-top-in="${o}" margin-right-in="${i}" margin-bottom-in="${s}" margin-left-in="${a}"${d} indent-in="${c}" block-spacing-in="${l}" column-count="${n.columnCount}" column-gap-in="${p}"${g}-->`}static formatInchesForComment(t){return Number.isFinite(t)?t.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):"0"}static toDocumentOverview(t,e){const n=t.children.length,o=e?.pendingChangeCounts,i=e?.measurements,s=b=>{if(!o)return 0;const k=o instanceof Map?o.get(b):o[b];return typeof k=="number"&&Number.isFinite(k)?Math.max(0,Math.floor(k)):0},a=[],c=[],l=[];for(let b=0;b<t.children.length;b++){const k=t.children[b];k.id&&s(k.id)>0&&l.push(b),k.type==="paragraph"&&k.heading!==void 0&&k.heading<=2?a.push(b):k.type!=="image"&&c.push(b)}const d=a.length>this.MAX_OVERVIEW_BLOCKS?Math.ceil(a.length/this.MAX_OVERVIEW_BLOCKS):1,u=d>1?a.filter((b,k)=>k%d===0):a,g=Math.max(0,this.MAX_OVERVIEW_BLOCKS-u.length),p=[];let h=1;if(g>0&&c.length>0){h=Math.max(1,Math.ceil(c.length/g));for(let b=0;b<c.length;b++)b%h===0&&p.push(c[b])}const f=Array.from(new Set([...u,...p,...l])).sort((b,k)=>b-k),m=n-1;m>=0&&!f.includes(m)&&f.push(m);const y=f.map(b=>{const k=this.getBlockId(t.children[b]),v=s(k),S=i?.blocks?.get(k);return{index:b,id:k,type:this.getBlockTypeLabel(t.children[b]),preview:this.getBlockPreview(t.children[b]),...S?.wordCount!==void 0?{wordCount:S.wordCount}:{},...S?.pageStart!==void 0?{pageStart:S.pageStart,pageEnd:S.pageEnd}:{},...v>0?{pendingChangeCount:v}:{},isLast:b===m}});return{title:t.title||"Untitled",totalBlocks:n,...i?{totalWords:i.wordCount,totalParagraphs:i.paragraphCount}:{},...i?.pageCount!==void 0?{pageCount:i.pageCount}:{},blockIds:y,samplingInterval:Math.max(d,h),...i?.sections&&i.sections.length>0?{sections:i.sections}:{}}}static toDocumentLayoutContext(t){const e=be(t.pageLayout),n=Ar(e),o=this.getEffectivePageNumberSettings(t,e);return{pageless:t.pageless===!0,pageSize:e.pageSize,orientation:e.orientation,pageWidth:this.formatInchesLength(Gt(n.pageWidth)),pageHeight:this.formatInchesLength(Gt(n.pageHeight)),marginTop:this.formatInchesLength(Gt(e.marginTopPx)),marginRight:this.formatInchesLength(Gt(e.marginRightPx)),marginBottom:this.formatInchesLength(Gt(e.marginBottomPx)),marginLeft:this.formatInchesLength(Gt(e.marginLeftPx)),indentStep:this.formatInchesLength(Gt(e.indentStepPx)),blockSpacing:this.formatInchesLength(Gt(e.blockSpacingPx)),columnCount:e.columnCount,columnGap:this.formatInchesLength(Ss(e.columnGapTwips)),showPageNumbers:o.showPageNumbers,pageNumberPosition:o.pageNumberPosition,pageNumberStart:e.pageNumberStart,...e.pageNumberFormat!=="decimal"?{pageNumberFormat:e.pageNumberFormat}:{},pageBorders:e.pageBorders,...e.pageNumberRestart?{pageNumberRestart:!0}:{}}}static getEffectivePageNumberSettings(t,e){for(const n of t.chrome??[])for(let o=0;o<n.children.length;o+=1){const i=n.children[o],s=c=>{if(!c||typeof c!="object")return!1;if(Array.isArray(c))return c.some(s);const l=c;return l.marks?.field==="page"||s(l.children)};if(!s(i))continue;const a=o===0?"left":o===2?"right":null;return{showPageNumbers:!0,pageNumberPosition:a?`${n.side==="header"?"top":"bottom"}-${a}`:e.pageNumberPosition}}return{showPageNumbers:e.showPageNumbers,pageNumberPosition:e.pageNumberPosition}}static formatInchesLength(t){return`${this.formatInchesForComment(t)}in`}static formatOverview(t){const e=[];if(e.push(`Document: "${t.title}"`),e.push(`Total blocks: ${t.totalBlocks}`),t.totalWords!==void 0&&e.push(`Total words: ${t.totalWords}`),t.totalParagraphs!==void 0&&e.push(`Total paragraphs: ${t.totalParagraphs}`),t.pageCount!==void 0&&e.push(`Pages: ${t.pageCount}`),t.sections&&t.sections.length>0){e.push(""),e.push("Sections (inclusive ranges):");for(const n of t.sections){const o=this.formatOverviewPageRange(n.pageStart,n.pageEnd);e.push(`[${n.startIndex}-${n.endIndex} inclusive] [#${n.startBlockId}-#${n.endBlockId} inclusive] h${n.headingLevel} "${n.title}" words=${n.wordCount} paragraphs=${n.paragraphCount}${o?` pages=${o}`:""}`)}}t.samplingInterval>1&&e.push(`(Showing every ${t.samplingInterval}${this.ordinalSuffix(t.samplingInterval)} block ID)`),e.push(""),e.push("Block IDs:");for(const n of t.blockIds){const o=n.preview?` — ${n.preview}`:"",i=n.wordCount!==void 0?` words=${n.wordCount}`:"",s=this.formatOverviewPageRange(n.pageStart,n.pageEnd),a=s?` pages=${s}`:"",c=n.isLast?" [LAST BLOCK]":"",l=n.pendingChangeCount&&n.pendingChangeCount>0?` [${n.pendingChangeCount} pending ${n.pendingChangeCount===1?"change":"changes"}]`:"";e.push(`[${n.index}] ${n.id} (${n.type})${i}${a}${l}${o}${c}`)}return e.join(`
4
- `)}static formatOverviewPageRange(t,e){return t===void 0||e===void 0?"":t===e?`${t}`:`${t}-${e}`}static extractBlocksById(t,e,n){const o=ee(t,e);return o===-1?null:this.extractBlocksByIndex(t,o,n)}static extractBlocksByIndex(t,e,n,o={}){const i=Math.max(0,Math.min(e,t.children.length)),s=Math.min(n,100),a=Math.min(i+s,t.children.length),c=this.resolveOmittableDocumentFontFamily(t,o);return{html:t.children.slice(i,a).map(l=>this.blockToHtml(l,t,c)).filter(l=>l.length>0).join(`
5
- `),startIndex:i,endIndex:a-1,totalBlocks:t.children.length}}static formatBlockRange(t){const e=[];return e.push(`Showing blocks ${t.startIndex}-${t.endIndex} of ${t.totalBlocks} total:`),e.push(""),e.push(t.html),e.join(`
6
- `)}static searchDocument(t,e){const n=[],o=e.map(s=>{if(s.startsWith("regex:")){const a=s.slice(6);try{const c=new RegExp(a,"i");return{query:s,match:l=>c.test(l)}}catch{return{query:s,match:c=>c.toLowerCase().includes(a.toLowerCase())}}}else{const a=Ju(s).toLowerCase();return{query:s,match:c=>c.toLowerCase().includes(a)}}}),i=[...t.children,...t.notes??[]];for(let s=0;s<i.length;s++){const a=i[s],c=this.getBlockPlainText(a),l=this.getBlockId(a),d=[];for(const u of o)u.match(c)&&d.push(u.query);d.length>0&&l&&n.push({blockId:l,blockIndex:s,matchedQueries:d})}return n}static findHighlights(t,e){const n=e?ue(e):void 0;if(e&&!n)return[];const o=[];for(let i=0;i<t.children.length;i++){const s=t.children[i],a=this.getBlockId(s);if(!a)continue;const c=Array.from(this.collectHighlightColors(s));c.length!==0&&(n&&!c.includes(n)||o.push({blockId:a,blockIndex:i,matchedColors:n?[n]:c}))}return o}static extractSpecificBlocks(t,e,n,o={}){const i=[],s=[],a=[],c=[],l=new Set,d=this.resolveOmittableDocumentFontFamily(t,o),u=[...t.children,...t.notes??[]],g=this.findTopLevelIndexesByBlockId(t,e),p=n&&n.length>0?this.buildSelectionInfoForBlocks(u,n):null;for(const h of e){const f=g.get(h);if(f===void 0){s.push(h);continue}const m=u[f],y=this.getBlockId(m);if(!y){s.push(h);continue}if(i.push(h),l.has(y))continue;l.add(y);const b=p?.get(y),k=this.blockToHtmlWithSelections(m,t,b,d,p??void 0);a.push(k),c.push({id:y,blockIndex:f,html:k})}return{html:a.filter(h=>h.length>0).join(`
7
- `),foundIds:i,missingIds:s,foundBlocks:c}}static renderTopLevelBlocks(t,e,n={}){const o=this.resolveOmittableDocumentFontFamily(t,n),i=[],s=new Set;for(const a of e){if(s.has(a)||a<0||a>=t.children.length)continue;s.add(a);const c=t.children[a],l=this.getBlockId(c);l&&i.push({id:l,blockIndex:a,html:this.blockToHtml(c,t,o)})}return i}static buildSelectionInfoForBlocks(t,e){const n=[],o=new Map,i=a=>{if(a.type==="paragraph"||a.type==="list"){if(n.push(a.id),a.type==="list"){let c=0;for(const l of a.children){const d=l.children.reduce((u,g)=>u+g.text.length,0);o.set(l.id,{listId:a.id,offset:c,length:d}),c+=d+1}}}else if("children"in a)for(const c of a.children)i(c)};t.forEach(i);const s=e.map(a=>{const c=o.get(a.startBlock),l=o.get(a.endBlock);return{...a,startBlock:c?.listId??a.startBlock,endBlock:l?.listId??a.endBlock,startOffset:c?c.offset+(a.startOffset??0):a.startOffset,endOffset:l?l.offset+(a.endOffset??l.length):a.endOffset}});return this.buildSelectionInfoForMultiple(n,s)}static buildSelectionInfoForMultiple(t,e){const n=new Map;for(const o of e){let i=o,s=t.indexOf(i.startBlock),a=t.indexOf(i.endBlock);if(!(s===-1||a===-1)){(s>a||s===a&&i.startOffset!==void 0&&i.endOffset!==void 0&&i.startOffset>i.endOffset)&&([s,a]=[a,s],i={...i,startOffset:i.endOffset,endOffset:i.startOffset});for(let c=s;c<=a;c++){const l=t[c],d={};c===s&&(d.startOffset=i.startOffset),c===a&&(d.endOffset=i.endOffset),n.has(l)||n.set(l,[]),n.get(l).push(d)}}}return n}static blockToHtmlWithSelections(t,e,n,o,i){if(t.type==="paragraph"&&n&&n.length>0)return this.paragraphToHtmlWithSelections(t,e,n,o);if(t.type==="list"&&n?.length)return this.listToHtml(t,o,e,{},n);const s=this.blockToHtml(t,e,o);if(!i?.size||!("children"in t))return s;const a=[],c=d=>{const u=i.get(d.id);(d.type==="paragraph"||d.type==="list")&&u?.length?a.push({block:d,ranges:u}):"children"in d&&d.type!=="list"&&d.children.forEach(g=>c(g))};if(t.children.forEach(d=>c(d)),!a.length)return s;const l=document.createElement("div");l.innerHTML=s;for(const d of a){const u=Array.from(l.querySelectorAll("[id]")).find(g=>g.id===d.block.id);u&&(u.outerHTML=this.blockToHtmlWithSelections(d.block,e,d.ranges,o))}return l.innerHTML}static paragraphToHtmlWithSelections(t,e,n,o){if(t.type!=="paragraph")return"";const i=t.heading?this.extractUniformTextFontSize(t.children):void 0,s=this.textNodesToHtmlWithSelections(t.children,e,n,o,t),a=[];t.align&&a.push(`text-align: ${t.align}`),this.appendParagraphIndentStyles(a,t,this.resolveIndentStepPx(e)),t.heading&&i!==void 0&&a.push(`font-size: ${i}px`);const c=a.length>0?` style="${a.join("; ")}"`:"",l=t.id?` id="${this.escapeHtml(t.id)}"`:"",d=t.styleId?` data-style-id="${this.escapeHtml(t.styleId)}"`:"",u=t.tabStops?` data-tab-stops="${this.escapeHtml(t.tabStops)}"`:"",g=t.direction?` dir="${t.direction}"`:"";return t.heading?`<h${t.heading}${l}${g}${d}${u}${c}>${s}</h${t.heading}>`:`<p${l}${g}${d}${u}${c}>${s}</p>`}static textNodesToHtmlWithSelections(t,e,n,o,i){const s=this.extractUniformTextFontFamily(t);let a=0;for(const h of t)h.type==="text"&&(a+=h.text.length);const c=[];n.forEach((h,f)=>{const m=h.startOffset??0,y=h.endOffset??a;c.push({pos:m,type:"open",idx:f}),c.push({pos:y,type:"close",idx:f})}),c.sort((h,f)=>h.pos!==f.pos?h.pos-f.pos:h.type==="open"&&f.type==="close"?-1:h.type==="close"&&f.type==="open"?1:0);let l=0,d=0;const u=[],g=i?.heading?this.extractUniformTextFontSize(t):void 0,p=this.coalesceAdjacentTextNodesForHtml(t,s,i?.heading?g:void 0,o);for(const h of p)if(h.type==="text"){const f=h.text,m=l,y=l+f.length;let b=0;for(;d<c.length&&c[d].pos<=y;){const k=c[d];if(k.pos>m+b){const v=f.slice(b,k.pos-m);u.push(this.textToHtmlWithMarks(v,h.marks,i,e,g,s,o)),b=k.pos-m}u.push(k.type==="open"?"<user-selection>":"</user-selection>"),d++}if(b<f.length){const k=f.slice(b);u.push(this.textToHtmlWithMarks(k,h.marks,i,e,g,s,o))}l=y}for(;d<c.length;){const h=c[d];u.push(h.type==="open"?"<user-selection>":"</user-selection>"),d++}return u.join("")}static textToHtmlWithMarks(t,e,n,o,i,s,a){let c=this.escapeHtml(t);if(c=c.replace(/\r\n|\r|\n/g,"<br>"),e){const l=[];if(e.fontFamily){const h=s??lu(void 0,n,o,this.DEFAULT_FONT_FAMILY);e.fontFamily!==h&&e.fontFamily!==a&&l.push(`font-family: ${this.escapeHtml(e.fontFamily)}`)}if(e.bold&&(c=`<b>${c}</b>`),e.italic&&(c=`<i>${c}</i>`),e.underline&&(c=`<u>${c}</u>`),e.strikethrough&&(c=`<s>${c}</s>`),e.code&&(c=`<code>${c}</code>`),e.latex&&(c=`<latex-inline>${c}</latex-inline>`),e.superscript||e.footnoteRef||e.footnotePendingBody){const h=[];e.footnoteRef&&h.push(`data-footnote-ref="${this.escapeHtml(e.footnoteRef)}"`),e.footnotePendingBody!==void 0&&(h.push(`data-footnote="${this.escapeHtml(e.footnotePendingBody)}"`),e.footnotePendingKind==="endnote"&&h.push('data-note-kind="endnote"')),c=`<sup${h.length>0?` ${h.join(" ")}`:""}>${c}</sup>`}e.subscript&&(c=`<sub>${c}</sub>`),e.fontSize&&!(n?.heading&&i===e.fontSize)&&l.push(`font-size: ${e.fontSize}px`),e.color&&l.push(`color: ${this.escapeHtml(e.color)}`),e.doubleStrikethrough&&l.push("text-decoration: line-through double"),e.smallCaps&&l.push("font-variant: small-caps"),e.allCaps&&l.push("text-transform: uppercase"),typeof e.letterSpacing=="number"&&Number.isFinite(e.letterSpacing)&&l.push(`letter-spacing: ${e.letterSpacing}px`);const d=[];l.length>0&&d.push(`style="${l.join("; ")}"`);const u=kd(e);u.length>0&&d.push(`data-docx-explicit-false-marks="${u.join(",")}"`);const g=Tr(e.docxRunPropertyResets);g&&d.push(`data-docx-run-property-resets="${g}"`),d.length>0&&(c=`<span ${d.join(" ")}>${c}</span>`),e.hidden&&(c=`<span data-word-hidden="true">${c}</span>`),e.bookmark&&(c=`<span data-bookmark="${this.escapeHtml(e.bookmark)}">${c}</span>`),e.fieldInstr&&(c=`<span data-field-instr="${this.escapeHtml(e.fieldInstr)}">${c}</span>`);const p=ue(e.backgroundColor);p&&(c=`<mark color="${this.escapeHtml(p)}">${c}</mark>`),e.link&&(c=`<a href="${this.escapeHtml(e.link)}">${c}</a>`),e.comment&&o&&(c=this.wrapWithCommentThreads(c,e.comment.split(","),o))}return c}static formatSpecificBlocks(t){const e=[],n=t.foundBlocks&&t.foundBlocks.length>0?t.foundBlocks.length:t.foundIds.length;if(t.missingIds.length>0&&(e.push(`Note: ${t.missingIds.length} block(s) not found: ${t.missingIds.join(", ")}`),e.push("")),e.push(`Showing ${n} block(s):`),e.push(""),t.foundBlocks&&t.foundBlocks.length>0)for(let o=0;o<t.foundBlocks.length;o++){const i=t.foundBlocks[o];if(o>0){const s=t.foundBlocks[o-1],a=i.blockIndex-s.blockIndex-1;if(a>0){const c=a===1?"block":"blocks";e.push(`(${a} ${c} omitted...)`)}}e.push(i.html)}else e.push(t.html);return e.join(`
8
- `)}static getBlockId(t){return"id"in t&&t.id?t.id:""}static getBlockTypeLabel(t){return t.type==="paragraph"&&t.heading!==void 0&&t.heading>=1&&t.heading<=6?`h${t.heading}`:t.type}static getBlockPreview(t){const e=this.getBlockPlainText(t).split(/\s+/).filter(o=>o.length>0),n=e.slice(0,10).join(" ");return e.length>10?n+"...":n}static getBlockPlainText(t){switch(t.type){case"paragraph":return t.children.map(e=>e.type==="text"?e.text:"").join("");case"list":return t.children.map(e=>e.children.map(n=>n.type==="text"?n.text:"").join("")).join(" ");case"code":return t.content||"";case"table":return"[table] "+t.children.flatMap(e=>e.children).map(e=>this.getBlockPlainText(e)).join(" ");case"table-cell":case"container":case"footnote":return t.children.map(e=>this.getBlockPlainText(e)).join(" ");case"image":return`[image${t.alt?`: ${t.alt}`:""}]`;case"math":return`[math: ${t.content||""}]`;case"docx-raw":return`[${t.tagName}${t.detail?`: ${t.detail}`:""}]`;case"page-break":return"[page break]";case"section-break":return"[section break]";case"toc":return"[table of contents]";default:return""}}static collectHighlightColors(t,e=new Set){switch(t.type){case"paragraph":for(const n of t.children){const o=ue(n.marks?.backgroundColor);o&&e.add(o)}break;case"list":for(const n of t.children)for(const o of n.children){const i=ue(o.marks?.backgroundColor);i&&e.add(i)}break;case"container":for(const n of t.children)this.collectHighlightColors(n,e);break;case"table":for(const n of t.children)for(const o of n.children)for(const i of o.children)this.collectHighlightColors(i,e);break}return e}static ordinalSuffix(t){const e=["th","st","nd","rd"],n=t%100;return e[(n-20)%10]||e[n]||e[0]}static blockToHtml(t,e,n,o={}){let i;switch(t.type){case"placeholder":i="";break;case"image":i=this.imageBlockToHtml(t,o.includeImageSources);break;case"list":i=this.listToHtml(t,n,e,o);break;case"container":i=this.containerToHtml(t,e,n,o);break;case"table":i=this.tableToHtml(t,e,n,o);break;case"table-cell":i=this.tableCellToHtml(t,e,n,o);break;case"paragraph":i=this.paragraphToHtml(t,e,n);break;case"code":i=this.codeBlockToHtml(t);break;case"math":i=this.mathBlockToHtml(t);break;case"page-break":i=this.pageBreakToHtml(t);break;case"docx-raw":i=this.docxRawToHtml(t);break;case"section-break":i=this.sectionBreakToHtml(t);break;case"toc":i=this.tocToHtml(t);break;case"header-footer":i="";break;case"footnote":i=this.footnoteToHtml(t,e,n,o);break;default:i="";break}if(!i||!e||!("id"in t)||!t.id)return i;const s=(e.comments??[]).filter(a=>!a.parentId&&a.anchorBlockId===t.id).map(a=>a.id);return this.wrapWithCommentThreads(i,s,e)}static footnoteToHtml(t,e,n,o={}){const i=t.children.map(s=>this.blockToHtml(s,e,n,o)).filter(Boolean).join("");return`<aside data-footnote data-note-kind="${t.noteKind==="endnote"?"endnote":"footnote"}" id="${t.id}">${i}</aside>`}static docxRawToHtml(t){const e=t.id?` id="${this.escapeAttribute(t.id)}"`:"",n=t.detail?` detail="${this.escapeAttribute(t.detail)}"`:"";return`<docx-raw${e} tag="${this.escapeAttribute(t.tagName)}"${n} />`}static pageBreakToHtml(t){return`<page-break${t.id?` id="${this.escapeAttribute(t.id)}"`:""} />`}static sectionBreakToHtml(t){const e=t.id?` id="${this.escapeAttribute(t.id)}"`:"",n=t.breakType?` break-type="${this.escapeAttribute(t.breakType)}"`:"",o=t.layout?` layout="${this.escapeAttribute(JSON.stringify(t.layout))}"`:"";return`<section-break${e}${n}${o} />`}static tocToHtml(t){const e=t.id?` id="${this.escapeAttribute(t.id)}"`:"",n=[];t.direction&&n.push(`direction: ${t.direction}`),t.align&&n.push(`text-align: ${t.align}`),t.fontFamily&&n.push(`font-family: ${t.fontFamily}`),t.fontSize&&n.push(`font-size: ${t.fontSize}px`),t.color&&n.push(`color: ${t.color}`);const o=n.length>0?` style="${this.escapeAttribute(n.join("; "))}"`:"";return`<toc${e} levels="${Sd(t)}"${t.direction?` dir="${t.direction}"`:""}${o}></toc>`}static codeBlockToHtml(t){const e=t.language?.trim().toLowerCase();if(e==="latex"||e==="latex-inline"){const s=t.id?` id="${this.escapeAttribute(t.id)}"`:"",a=e==="latex-inline"?' display="inline"':"",c=this.escapeHtml(t.content||"");return`<latex${s}${a}>${c}</latex>`}const n=t.id?` id="${this.escapeAttribute(t.id)}"`:"",o=t.language?` language="${this.escapeAttribute(t.language)}"`:"",i=this.escapeHtml(t.content||"");return`<pre${n}${o}>${i}</pre>`}static mathBlockToHtml(t){const e=t.id?` id="${this.escapeAttribute(t.id)}"`:"",n=t.displayMode&&t.displayMode!=="block"?` display="${t.displayMode}"`:"",o=t.align&&t.align!=="center"?` align="${t.align}"`:"",i=this.escapeHtml(t.content||"");return`<latex${e}${n}${o}>${i}</latex>`}static paragraphToHtml(t,e,n){if(t.type!=="paragraph")return"";const o=this.paragraphCarriesNonRuleLayout(t)?null:Id(t);if(o){const h=t.id?` id="${this.escapeHtml(t.id)}"`:"",f=Os(o.style),m=o.width===Cr.width&&o.color.toLowerCase()===Cr.color.toLowerCase(),y=f?` data-rule="${o.style}"`:"";let b="";if(!m||!f&&o.style!==Cr.style){const k=f||o.style==="single"?"solid":o.style;b=` style="border-bottom: ${o.width}px ${k} ${o.color}"`}return`<hr${h}${y}${b} />`}const i=this.extractUniformTextFontFamily(t.children),s=t.heading?this.extractUniformTextFontSize(t.children):void 0,a=this.coalesceAdjacentTextNodesForHtml(t.children,i,t.heading?s:void 0,n).map(h=>h.type==="text"?this.textNodeToHtml(h,t,e,s,i,n):"").join(""),c=[];t.align&&c.push(`text-align: ${t.align}`),this.appendParagraphIndentStyles(c,t,this.resolveIndentStepPx(e)),t.heading&&s!==void 0&&c.push(`font-size: ${s}px`),i&&i!==n&&c.push(`font-family: ${this.escapeAttribute(i)}`);const l=c.length>0?` style="${c.join("; ")}"`:"",d=t.id?` id="${this.escapeHtml(t.id)}"`:"",u=t.styleId?` data-style-id="${this.escapeHtml(t.styleId)}"`:"",g=t.tabStops?` data-tab-stops="${this.escapeHtml(t.tabStops)}"`:"",p=t.direction?` dir="${t.direction}"`:"";return t.heading?`<h${t.heading}${d}${p}${u}${g}${l}>${a}</h${t.heading}>`:`<p${d}${p}${u}${g}${l}>${a}</p>`}static paragraphCarriesNonRuleLayout(t){if(t.spaceBefore!==void 0||t.spaceAfter!==void 0||t.lineSpacing!==void 0||t.keepNext||t.keepLines||t.widowControl===!1)return!0;if(!t.borders)return!1;try{const e=JSON.parse(t.borders)?.bottom;return typeof e?.space=="number"&&e.space>0}catch{return!1}}static textNodeToHtml(t,e,n,o,i,s){return this.textToHtmlWithMarks(t.text,t.marks,e,n,o,i,s)}static coalesceAdjacentTextNodesForHtml(t,e,n,o){if(t.length<=1)return t;const i=[];let s=null;for(const a of t){const c=this.getTextSerializationKey(a.marks,e,n,o),l=i[i.length-1];if(l&&s===c){l.text+=a.text;continue}i.push({...a,marks:a.marks?{...a.marks}:void 0}),s=c}return i}static getTextSerializationKey(t,e,n,o){const i=t?.fontFamily&&t.fontFamily!==e&&t.fontFamily!==o?t.fontFamily:null,s=t?.fontSize!==void 0&&t.fontSize!==n?t.fontSize:null;return JSON.stringify([i,s,t?.bold,t?.italic,t?.underline,t?.strikethrough,t?.doubleStrikethrough,t?.code,t?.latex,t?.superscript,t?.subscript,t?.footnoteRef,t?.footnotePendingBody,t?.footnotePendingKind,t?.color,ue(t?.backgroundColor)??null,t?.smallCaps,t?.allCaps,t?.letterSpacing,t?.hidden,t?.bookmark,t?.fieldInstr,t?.link,t?.comment,Tr(t?.docxRunPropertyResets)])}static wrapWithCommentThreads(t,e,n){const o=Array.from(new Set(e.map(i=>i.trim()).filter(Boolean))).sort();for(const i of o.reverse()){const s=(n.comments??[]).find(u=>u.id===i&&!u.parentId),a=s?this.collectCommentThreadRecords(s.id,n):[],c=this.serializeCommentTranscript(a),l=s?.resolved===!0?"true":"false",d=s?.suggestionId?` suggestion-id="${this.escapeAttribute(s.suggestionId)}"`:"";t=`<comment-thread id="${this.escapeAttribute(i)}" resolved="${l}"${d} transcript="${this.escapeAttribute(c)}">${t}</comment-thread>`}return t}static collectCommentThreadRecords(t,e){const n=e.comments??[],o=new Set([t]);let i=!0;for(;i;){i=!1;for(const s of n)s.parentId&&o.has(s.parentId)&&!o.has(s.id)&&(o.add(s.id),i=!0)}return n.filter(s=>o.has(s.id)).sort((s,a)=>(s.createdAt??"").localeCompare(a.createdAt??""))}static serializeCommentTranscript(t){const e=t.length<=20?t:[t[0],...t.slice(-19)],n=(c,l)=>{const d=c.agentName??c.author,u=(c.authorType??"human")==="ai"?" (AI)":"",g=(c.createdAt??"").slice(0,10),p=c.bodyMd.replace(/\s+/g," ").trim(),h=p.length>l?`${p.slice(0,l)}…`:p;return`${d}${u}${g?` on ${g}`:""}: ${h}`},o=(c,l)=>(l?["(older replies omitted)",...c]:c).join(" — "),i=t.length>e.length;let s=o(e.map(c=>n(c,2e3)),i);if(s.length<=4e3)return s;const a=Math.max(80,Math.floor(4e3/Math.max(1,e.length)-60));return s=o(e.map(c=>n(c,a)),!0),s.length<=4e3?s:o(e.slice(-5).map(c=>n(c,300)),!0)}static normalizeAgentHighlightColor(t){return ue(t)}static escapeHtml(t){return zu.test(t)?t.replace(Xu,Wu):t}static escapeAttribute(t){return this.escapeHtml(t)}static resolveFontToCss(t){if(this.isDisallowedFontFamilyValue(t))throw new Error('font-family does not support CSS-wide values like "inherit"; use a concrete font family such as "Arial, sans-serif".');if(t.includes(",")||t.includes("'")||t.includes('"'))return t;const e=vd.find(n=>n.value===t.toLowerCase());return e?e.cssValue:t}static isDisallowedFontFamilyValue(t){const e=t.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(e)}static extractFontSizeFromStyle(t){const e=t.match(/font-size:\s*(\d+(?:\.\d+)?)(px|pt)?/i);if(!e)return;const n=parseFloat(e[1]);if(Number.isFinite(n))return e[2]?.toLowerCase()==="pt"?n*4/3:n}static extractTextStyleMarksFromStyle(t){const e={},n=this.extractFontSizeFromStyle(t);n!==void 0&&n>0&&(e.fontSize=n),this.parseCssFontWeightToBold(t)&&(e.bold=!0),/(?:^|;)\s*font-style:\s*(italic|oblique)/i.test(t)&&(e.italic=!0);const o=t.match(/(?:^|;)\s*color:\s*([^;]+)/i);if(o){const a=ho(o[1].trim());a&&!Is(a)&&(e.color=a)}const i=t.match(/(?:^|;)\s*letter-spacing:\s*([^;]+)/i);if(i){const a=Qs(i[1].trim(),e.fontSize);a!==void 0&&(e.letterSpacing=a)}const s=t.match(/(?:^|;)\s*font-family:\s*([^;]+)/i);if(s){const a=s[1].trim();this.isDisallowedFontFamilyValue(a)||(e.fontFamily=this.resolveFontToCss(a))}return e}static parseCssFontWeightToBold(t){const e=t.match(/(?:^|;)\s*font-weight:\s*([^;]+)/i);if(!e)return;const n=e[1].trim().toLowerCase();if(n==="bold"||n==="bolder")return!0;if(n==="normal"||n==="lighter")return!1;const o=parseInt(n,10);if(Number.isFinite(o))return o>=600}static resolveIndentStepPx(t){return be(t?.pageLayout).indentStepPx}static applyParagraphElementAttributes(t,e,n){const o=e.getAttribute("style");if(o){const c=this.extractParagraphStyleAttributes(o,n);c.align&&(t.align=c.align),c.leftIndent!==void 0&&(t.leftIndent=c.leftIndent),c.firstLineIndent!==void 0&&(t.firstLineIndent=c.firstLineIndent),c.keepNext&&(t.keepNext=!0),c.keepLines&&(t.keepLines=!0),c.widowControl===!1&&(t.widowControl=!1);const l=c;l.borders&&(t.borders=l.borders),l.shading&&(t.shading=l.shading),this.applyParagraphSpacingAttributes(t,c)}const i=e.getAttribute("data-style-id");i&&(t.styleId=i);const s=e.getAttribute("data-tab-stops");s&&(t.tabStops=s);const a=e.getAttribute("dir")?.trim().toLowerCase();(a==="rtl"||a==="ltr")&&(t.direction=a)}static applyParagraphSpacingAttributes(t,e){e.spaceBefore!==void 0&&(t.spaceBefore=e.spaceBefore),e.spaceAfter!==void 0&&(t.spaceAfter=e.spaceAfter),e.lineSpacing!==void 0&&(t.lineSpacing=e.lineSpacing)}static cssLengthToPx(t){if(!t)return;const e=t.trim().match(/^([\d.]+)(px|pt)?$/i);if(!e)return;const n=parseFloat(e[1]);if(Number.isFinite(n))return e[2]?.toLowerCase()==="pt"?n*4/3:n}static extractParagraphStyleAttributes(t,e=this.resolveIndentStepPx()){const n={};/break-after:\s*avoid/i.test(t)&&(n.keepNext=!0),/break-inside:\s*avoid/i.test(t)&&(n.keepLines=!0),/(?:^|;)\s*(?:widows|orphans):\s*1\b/i.test(t)&&(n.widowControl=!1);{const y=Uu(t);y&&(n.borders=y);const b=t.match(/(?:^|;)\s*background-color:\s*(#[0-9a-fA-F]{3,8}|transparent)/i);b&&(n.shading=b[1])}const o=t.match(/text-align:\s*([^;]+)/i);if(o){const y=o[1].trim().toLowerCase();(y==="left"||y==="center"||y==="right"||y==="justify")&&(n.align=y)}let i,s,a;const c=t.match(/(?:^|;)\s*margin:\s*([^;]+)/i)?.[1];if(c){const y=c.trim().split(/\s+/);if(y.length>=1&&y.length<=4){const[b,k=b,v=b,S=k]=y;i=b,s=v,a=S}}i=t.match(/(?:^|;)\s*margin-top:\s*([^;]+)/i)?.[1]??i,s=t.match(/(?:^|;)\s*margin-bottom:\s*([^;]+)/i)?.[1]??s;const l=this.cssLengthToPx(i);l!==void 0&&(n.spaceBefore=Math.round(l*100)/100);const d=this.cssLengthToPx(s);d!==void 0&&(n.spaceAfter=Math.round(d*100)/100);const u=t.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(u){const y=parseFloat(u[1]);Number.isFinite(y)&&y>=.5&&y<=4&&(n.lineSpacing=y)}const g=t.match(/margin-left:\s*([^;]+)/i),p=this.cssLengthToPx(a)?a:void 0,h=Pr(g?.[1]??p,{indentStepPx:e});h!==void 0&&(n.leftIndent=h);const f=t.match(/text-indent:\s*([^;]+)/i),m=Pr(f?.[1],{indentStepPx:e,firstLine:!0});return m!==void 0&&(n.firstLineIndent=m),n}static appendParagraphIndentStyles(t,e,n){const o=e.leftIndent===0?0:le(e.leftIndent);o!==void 0&&t.push(`margin-left: ${vs(o,n)}px`);const i=e.firstLineIndent===0?0:de(e.firstLineIndent);if(i!==void 0&&t.push(`text-indent: ${Math.sign(i)*vs(Math.abs(i),n)}px`),typeof e.spaceBefore=="number"&&t.push(`margin-top: ${e.spaceBefore}px`),typeof e.spaceAfter=="number"&&t.push(`margin-bottom: ${e.spaceAfter}px`),typeof e.lineSpacing=="number"&&t.push(`line-height: ${e.lineSpacing}`),e.keepNext&&t.push("break-after: avoid"),e.keepLines&&t.push("break-inside: avoid"),e.widowControl===!1&&t.push("orphans: 1"),e.shading&&t.push(`background-color: ${e.shading}`),e.borders)try{const s=JSON.parse(e.borders);for(const a of["top","bottom","left","right"]){const c=s[a];if(!c)continue;const l=c.style==="none"?"none":c.style==="double"||c.style==="dashed"||c.style==="dotted"?c.style:"solid";t.push(`border-${a}: ${c.style==="none"?0:c.width??1}px ${l} ${c.color??"#000000"}`),typeof c.space=="number"&&c.space>0&&t.push(`padding-${a}: ${c.space}px`)}}catch{}}static extractUniformTextFontFamily(t){let e,n=!1;for(const o of t){if(o.type!=="text"||o.text.length===0)continue;const i=o.marks?.fontFamily;if(i===void 0)return;if(e===void 0)e=i;else if(e!==i)return;n=!0}return n?e:void 0}static extractUniformTextFontSize(t){let e,n=!1;for(const o of t){if(o.type!=="text"||o.text.length===0)continue;const i=o.marks?.fontSize;if(i===void 0)return;if(e===void 0)e=i;else if(e!==i)return;n=!0}return n?e:void 0}static findOmittableDocumentFontFamily(t){if(!t)return;const e=new Set,n=i=>{for(const s of i)if(!(s.type!=="text"||s.text.length===0)&&(e.add(s.marks?.fontFamily??this.DEFAULT_FONT_FAMILY),e.size>1))return},o=i=>{if(!(e.size>1))switch(i.type){case"paragraph":n(i.children);break;case"list":for(const s of i.children)if(n(s.children),e.size>1)return;break;case"container":for(const s of i.children)if(o(s),e.size>1)return;break;case"table":for(const s of i.children)for(const a of s.children)for(const c of a.children)if(o(c),e.size>1)return;break;case"table-cell":for(const s of i.children)if(o(s),e.size>1)return;break}};for(const i of t.children)if(o(i),e.size>1)return;return e.size===1?Array.from(e)[0]:void 0}static resolveOmittableDocumentFontFamily(t,e={}){if(e.scanDocumentFontFamily!==!1)return this.findOmittableDocumentFontFamily(t)}static findTopLevelIndexesByBlockId(t,e){const n=new Map,o=new Set(e);if(o.size===0)return n;const i=[...t.children,...t.notes??[]];for(let s=0;s<i.length;s++){const a=this.getBlockId(i[s]);if(a&&o.has(a)&&(n.set(a,s),o.delete(a),o.size===0))return n}for(let s=0;s<i.length&&(this.collectRequestedBlockIndexesForTopLevel(i[s],o,n,{topLevelIndex:s,includeRootBlock:!1}),o.size!==0);s++);return n}static collectRequestedBlockIndexesForTopLevel(t,e,n,o){if(e.size!==0&&!(o.includeRootBlock&&t.id&&e.has(t.id)&&(n.set(t.id,o.topLevelIndex),e.delete(t.id),e.size===0)))switch(t.type){case"list":for(const i of t.children)if(i.id&&e.has(i.id)&&(n.set(i.id,o.topLevelIndex),e.delete(i.id),e.size===0))return;break;case"container":case"table-cell":case"footnote":for(const i of t.children)if(this.collectRequestedBlockIndexesForTopLevel(i,e,n,{topLevelIndex:o.topLevelIndex,includeRootBlock:!0}),e.size===0)return;break;case"table":for(const i of t.children){if(i.id&&e.has(i.id)&&(n.set(i.id,o.topLevelIndex),e.delete(i.id),e.size===0))return;for(const s of i.children){if(s.id&&e.has(s.id)&&(n.set(s.id,o.topLevelIndex),e.delete(s.id),e.size===0))return;for(const a of s.children)if(this.collectRequestedBlockIndexesForTopLevel(a,e,n,{topLevelIndex:o.topLevelIndex,includeRootBlock:!0}),e.size===0)return}}break}}static imageBlockToHtml(t,e=!1){const n=t.alt?` alt="${this.escapeAttribute(t.alt)}"`:"",o=t.align?` align="${t.align}" data-align="${t.align}"`:"",i=this.getImageStyle(t),s=i?` style="${i}"`:"",a=Math.max(1,Math.round(t.width)),c=Math.max(1,Math.round(t.height)),l=t.sourceUrl?` data-source-url="${this.escapeAttribute(t.sourceUrl)}"`:"",d=e?` src="${this.escapeAttribute(t.src)}"`:' data-image-source="hidden"';return`<img id="${this.escapeAttribute(t.id)}"${d}${l} width="${a}" height="${c}"${n}${o}${s}>`}static listToHtml(t,e,n,o={},i){const s=t.variant==="ordered"?"ol":"ul",a=new Map;let c=0;for(const k of t.children){const v=k.children.reduce((I,w)=>I+w.text.length,0),S=(i??[]).flatMap(I=>{const w=Math.max(0,(I.startOffset??0)-c),A=Math.min(v,(I.endOffset??1/0)-c);return w<A?[{startOffset:w,endOffset:A}]:[]});S.length&&a.set(k,S),c+=v+1}const l=(k,v)=>{const S=[];let I=0;for(;I<k.length;){const w=k[I],A=w.indentLevel||0;if(A<v)break;if(A>=v){const _=this.extractUniformTextFontFamily(w.children),B=[...w.lineSpacing!==void 0?[`line-height: ${w.lineSpacing}`]:[],...w.spaceBefore!==void 0?[`margin-top: ${w.spaceBefore}px`]:[],...w.spaceAfter!==void 0?[`margin-bottom: ${w.spaceAfter}px`]:[]];_&&_!==e&&B.push(`font-family: ${this.escapeHtml(_)}`);const P=B.length>0?` style="${B.join("; ")}"`:"",$=w.id?` id="${this.escapeAttribute(w.id)}"`:"",T=w.direction?` dir="${w.direction}"`:"",C=A!==0||o.includeZeroListLevels?` data-indent-level="${A}"`:"",N=`${$}${P}${T}${C}`,L=a.get(w),R=L?this.textNodesToHtmlWithSelections(w.children,n,L,e):this.coalesceAdjacentTextNodesForHtml(w.children,_,void 0,e).map(D=>D.type==="text"?this.textNodeToHtml(D,void 0,n,void 0,_,e):"").join(""),M=[];let F=I+1;for(;F<k.length&&(k[F].indentLevel||0)>A;)M.push(k[F]),F++;let j=R;if(M.length>0){const D=t.variant==="ordered"?"ol":"ul",O=`<${D}>${l(M,A+1)}</${D}>`;j=R+O}if(t.variant==="todo"&&(j=`<input type="checkbox"${w.checked?" checked":""}>${j}`),n&&w.id){const D=(n.comments??[]).filter(O=>!O.parentId&&O.anchorBlockId===w.id).map(O=>O.id);j=this.wrapWithCommentThreads(j,D,n)}S.push(`<li${N}>${j}</li>`),I=F}else I++}return S.join("")},d=l(t.children,0),u=t.id?` id="${this.escapeAttribute(t.id)}"`:"",g=t.variant==="ordered"?Iu((n?vu(n).get(t.id):void 0)??xu(t)):1,p=t.variant==="ordered"&&g!==1?` start="${g}"`:"",h=[...t.lineSpacing!==void 0?[`line-height: ${t.lineSpacing}`]:[],...t.spaceBefore!==void 0?[`margin-top: ${t.spaceBefore}px`]:[],...t.spaceAfter!==void 0?[`margin-bottom: ${t.spaceAfter}px`]:[]],f=h.length?` style="${h.join("; ")}"`:"",m=t.contextualSpacing!==void 0?` data-contextual-spacing="${t.contextualSpacing}"`:"",y=t.numberingChainId?` data-numbering-chain-id="${this.escapeAttribute(t.numberingChainId)}" data-start-number="${t.startNumber??""}" data-effective-start="${g}"`:"",b=t.numberingFormat?` data-numbering-format="${this.escapeAttribute(t.numberingFormat)}"`:"";return`<${s}${u}${p}${f}${m}${y}${b}>${d}</${s}>`}static containerToHtml(t,e,n,o={}){const i=t.id?` id="${this.escapeAttribute(t.id)}"`:"",s=[];t.borderColor&&s.push(`border-color: ${this.escapeHtml(t.borderColor)}`),t.padding!==void 0&&s.push(`padding: ${t.padding}px`);const a=s.length>0?` style="${s.join("; ")}"`:"",c=t.children.map(l=>this.blockToHtml(l,e,n,o)).filter(l=>l.length>0).join(`
9
- `);return`<div class="container"${i}${a}>
10
- ${c}
11
- </div>`}static tableToHtml(t,e,n,o={}){const i=t.id?` id="${this.escapeAttribute(t.id)}"`:"",s=["border-collapse: collapse"];t.tableWidth!==void 0?s.push(`width: ${t.tableWidth}px`):s.push("width: 100%"),t.align&&t.align!=="left"&&(t.align==="center"?s.push("margin-left: auto","margin-right: auto"):t.align==="right"&&s.push("margin-left: auto","margin-right: 0")),t.borderColor&&s.push(`border-color: ${this.escapeHtml(t.borderColor)}`);const a=Xs(t.borders);let c="";if(a){for(const g of["top","right","bottom","left"]){const p=a[g];p&&s.push(`border-${g}: ${Hs(p)}`)}c=` data-borders="${this.escapeAttribute(t.borders)}"`}const l=` style="${s.join("; ")}"`,d=dn(t),u=t.children.map((g,p)=>{const h=t.hasHeader&&p===0?"th":"td",f=g.children.map((m,y)=>{const b=m.id?` id="${this.escapeAttribute(m.id)}"`:"",k=d.byId.get(m.id);let v="";k&&k.colSpan>1&&(v+=` colspan="${k.colSpan}"`),k&&k.rowSpan>1&&(v+=` rowspan="${k.rowSpan}"`);let S;if(k){let $=0;for(let T=k.col;T<k.col+k.colSpan;T++)$+=t.columnWidths[T]||0;S=$>0?$:void 0}else S=t.columnWidths[y];const I=[];let w="";const A=Ur(m.borders);if(A){for(const $ of["top","right","bottom","left"]){const T=A[$];T&&I.push(`border-${$}: ${Hs(T)}`)}w+=` data-borders="${this.escapeAttribute(m.borders)}"`}else I.push("border: 1px solid #ccc");const _=Pu(m.padding);_?I.push(`padding: ${Mu(_)}`):I.push("padding: 8px"),S!==void 0&&I.push(`width: ${S}%`),m.verticalAlign&&I.push(`vertical-align: ${m.verticalAlign}`),m.backgroundColor&&I.push(`background-color: ${this.escapeHtml(m.backgroundColor)}`);const B=` style="${I.join("; ")}"`,P=m.children.map($=>this.blockToHtml($,e,n,o)).filter($=>$.length>0).join("");return`<${h}${b}${v}${w}${B}>${P}</${h}>`}).join("");return`<tr${g.id?` id="${this.escapeAttribute(g.id)}"`:""}>${f}</tr>`}).join(`
12
- `);return`<table${i}${c}${l}>
13
- ${u}
14
- </table>`}static tableCellToHtml(t,e,n,o={}){const i=t.id?` id="${this.escapeAttribute(t.id)}"`:"",s=["border: 1px solid #ccc","padding: 8px"];t.verticalAlign&&s.push(`vertical-align: ${t.verticalAlign}`),t.backgroundColor&&s.push(`background-color: ${this.escapeHtml(t.backgroundColor)}`);const a=` style="${s.join("; ")}"`,c=t.children.map(l=>this.blockToHtml(l,e,n,o)).filter(l=>l.length>0).join(`
15
- `);return`<div class="table-cell"${i}${a}>
16
- ${c}
17
- </div>`}static parsePositiveImageDimension(t,e){const n=t.getAttribute(e);if(!n)return;const o=Number.parseInt(n,10);return Number.isFinite(o)&&o>0?o:void 0}static parseImageSourceUrl(t){const e=t.getAttribute("data-source-url")?.trim();if(e)try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"?n.href:void 0}catch{return}}static parseSingleImageParagraph(t,e){if(t.textContent?.trim())return null;let n=t,o=null;for(;;){const d=Array.from(n.children);if(d.length!==1)return null;const u=d[0],g=u.tagName.toLowerCase();if(g==="img"){o=u;break}if(g!=="span")return null;n=u}const i=this.parsePositiveImageDimension(o,"data-revise-natural-width"),s=this.parsePositiveImageDimension(o,"data-revise-natural-height"),a=this.parseImageElement(o,e);if(!a)return null;if(!a.align){const d=t.getAttribute("style");if(d){const u=d.match(/text-align:\s*([^;]+)/);if(u){const g=u[1].trim();(g==="left"||g==="center"||g==="right")&&(a.align=g)}}}const c=d=>{const u=d.trim().match(/^(\d+(?:\.\d+)?)px$/i);if(!u)return;const g=Number(u[1]);return Number.isFinite(g)&&g>0?Math.round(g):void 0};let l=o.parentElement;for(;l&&l!==t;){const d=l.getAttribute("style")??"",u=d.match(/(?:^|;)\s*width\s*:\s*([^;]+)/i),g=d.match(/(?:^|;)\s*height\s*:\s*([^;]+)/i),p=u?c(u[1]):void 0,h=g?c(g[1]):void 0,f=o.getAttribute("style")??"";if(p!==void 0&&h!==void 0&&/(?:^|;)\s*transform\s*:/i.test(f))a.width=p,a.height=h;else if(p!==void 0){const m=i??a.width,y=s??a.height;a.width=p,a.height=Math.max(1,Math.round(p*y/m))}else if(h!==void 0){const m=i??a.width,y=s??a.height;a.height=h,a.width=Math.max(1,Math.round(h*m/y))}if(p!==void 0||h!==void 0)break;l=l.parentElement}return a}static parseImageElement(t,e){const n=e?.imageReferences?.get(t);if(n){e?.remainingImageReferences?.delete(t);const f={...n,id:e?.imageIdsToPreserve?.has(n.id)?Lt(n.id,e):Lt(null,e)};f.width=this.parsePositiveImageDimension(t,"width")??f.width,f.height=this.parsePositiveImageDimension(t,"height")??f.height,t.hasAttribute("alt")&&(f.alt=t.getAttribute("alt")||void 0);const m=this.parseImageAlign(t);return m&&(f.align=m),f}const o=t.getAttribute("src");if(!o)return null;e?.remainingImageReferences?.delete(t);const i=this.parsePositiveImageDimension(t,"width"),s=this.parsePositiveImageDimension(t,"height"),a=this.parsePositiveImageDimension(t,"data-revise-natural-width"),c=this.parsePositiveImageDimension(t,"data-revise-natural-height"),l=t.getAttribute("alt")||void 0,d=this.parseImageAlign(t),u=this.parseImageSourceUrl(t);let g=i??a??200,p=s??c??200;a&&c&&(i?p=Math.max(1,Math.round(i*c/a)):s&&(g=Math.max(1,Math.round(s*a/c))));const h={type:"image",id:et(),src:o,width:g,height:p};return l&&(h.alt=l),d&&(h.align=d),u&&(h.sourceUrl=u),h}static parseListElement(t,e,n=0){const o=t.tagName.toLowerCase();if(o!=="ul"&&o!=="ol")return null;let i=o==="ol"?"ordered":"unordered";const s=(h,f,m={},y=Math.min(n+2,8))=>{const b=[],k=h.getAttribute("style"),v=k?{...m,...this.extractTextStyleMarksFromStyle(k)}:m;for(const S of Array.from(h.children))if(S.tagName.toLowerCase()==="li"){const I=document.createElement("div");let w=!1;const A=[];for(const F of Array.from(S.childNodes))if(F.nodeType===Node.ELEMENT_NODE){const j=F,D=j.tagName.toLowerCase();D==="ul"||D==="ol"?(w=!0,A.push(j)):I.appendChild(F.cloneNode(!0))}else I.appendChild(F.cloneNode(!0));const _=S.getAttribute("style"),B=_?{...v,...this.extractTextStyleMarksFromStyle(_)}:v,P=I.querySelector('input[type="checkbox"]');P&&(i="todo",P.remove());const $=this.parseHtmlElement(I,B),T={type:"list-item",id:Lt(S.getAttribute("id"),e),children:$.length>0?$:[{type:"text",text:"",marks:{}}]};P&&(T.checked=P.hasAttribute("checked"));const C=S.getAttribute("dir")??_?.match(/(?:^|;)\s*direction:\s*(rtl|ltr)\s*(?:;|$)/i)?.[1];if((C==="rtl"||C==="ltr")&&(T.direction=C),_){const F=this.extractParagraphStyleAttributes(_);for(const j of["lineSpacing","spaceBefore","spaceAfter"])F[j]!==void 0&&(T[j]=F[j])}const N=S.getAttribute("data-indent-level"),L=N!==null?Number(N):NaN,R=Number.isInteger(L)&&L>=0&&L<=8,M=R?L:f;if(M>0&&(T.indentLevel=M),b.push(T),w)for(const F of A){const j=R?Math.max(y,Math.min(M+2,8)):y,D=s(F,Math.min(M+1,j),B,j);b.push(...D)}}return b},a=s(t,n);if(a.length===0)return null;const c={type:"list",id:Lt(t.getAttribute("id"),e),variant:i,children:a};if(i==="ordered"){const h=t.getAttribute("start");if(h){const f=parseInt(h,10);!isNaN(f)&&f!==1&&(c.startNumber=f)}}const l=t.getAttribute("style");if(l){const h=this.extractParagraphStyleAttributes(l);for(const m of["spaceBefore","spaceAfter"])h[m]!==void 0&&(c[m]=h[m]);const f=l.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(f){const m=parseFloat(f[1]);Number.isFinite(m)&&m>=.5&&m<=4&&(c.lineSpacing=m)}}const d=t.getAttribute("data-contextual-spacing");(d==="true"||d==="false")&&(c.contextualSpacing=d==="true");const u=t.getAttribute("data-numbering-chain-id");if(u&&i==="ordered"){c.numberingChainId=u;const h=t.getAttribute("data-start-number"),f=Number(t.getAttribute("data-effective-start")),m=Number(t.getAttribute("start")??1);t.hasAttribute("start")&&Number.isInteger(f)&&f>0&&Number.isInteger(m)&&m>0&&m!==f?c.startNumber=m:h===""?delete c.startNumber:h!==null&&Number.isInteger(Number(h))&&Number(h)>0&&(c.startNumber=Number(h))}const g=t.getAttribute("data-numbering-format");g&&wu(g)&&(c.numberingFormat=g);const p=t.getAttribute("style");if(p){const h=p.match(/font-family:\s*([^;]+)/);if(h){const f=this.resolveFontToCss(h[1].trim());for(const m of c.children)for(const y of m.children)y.type==="text"&&(y.marks||(y.marks={}),y.marks.fontFamily||(y.marks.fontFamily=f))}}return c}static parseContainerElement(t,e,n){const o=Lt(t.getAttribute("id"),n),i=t.getAttribute("style");let s,a;if(i){const u=i.match(/border-color:\s*([^;]+)/);u&&(s=u[1].trim());const g=i.match(/padding:\s*(\d+)px/);g&&(a=parseInt(g[1],10))}const c=this.resolveIndentStepPx(e?.existingDocument),l=[];for(const u of Array.from(t.children)){const g=u.tagName.toLowerCase();if(g==="p"||g.match(/^h[1-6]$/)){const p=g.match(/^h([1-6])$/),h=u.getAttribute("style"),f=this.parseHtmlElement(u,h?this.extractTextStyleMarksFromStyle(h):{}),m={type:"paragraph",id:Lt(u.getAttribute("id"),n),children:f.length>0?f:[{type:"text",text:"",marks:{}}]};p&&(m.heading=parseInt(p[1])),this.applyParagraphElementAttributes(m,u,c),l.push(m)}else if(g==="ul"||g==="ol"){const p=this.parseListElement(u,n);p&&l.push(p)}else if(g==="hr")l.push(this.parseHrElement(u,n));else if(g==="img"){const p=this.parseImageElement(u,n);p&&l.push(p)}else if(g==="div"&&u.classList.contains("container")){const p=this.parseContainerElement(u,e,n);p&&l.push(p)}}if(l.length===0)return null;const d={type:"container",id:o,children:l};return s&&(d.borderColor=s),a!==void 0&&(d.padding=a),d}static parseTableElement(t,e,n){const o=Lt(t.getAttribute("id"),n),i=this.resolveIndentStepPx(e?.existingDocument),s=t.getAttribute("style");let a,c,l;if(s){const I=s.match(/width:\s*(\d+)px/);I&&(a=parseInt(I[1],10));const w=s.match(/border-color:\s*([^;]+)/);w&&(c=w[1].trim()),/margin-left:\s*auto/.test(s)&&/margin-right:\s*auto/.test(s)?l="center":/margin-left:\s*auto/.test(s)&&/margin-right:\s*0/.test(s)&&(l="right")}const d=[],u=new Map;let g=!1;const p=Array.from(t.rows);for(let I=0;I<p.length;I++){const w=p[I],A=[],_=w.querySelectorAll(":scope > td, :scope > th");I===0&&_.length>0&&_[0].tagName.toLowerCase()==="th"&&(g=!0);for(let P=0;P<_.length;P++){const $=_[P],T=$.getAttribute("style");let C,N;if(T){const q=T.match(/vertical-align:\s*([^;]+)/);if(q){const ct=q[1].trim();(ct==="top"||ct==="middle"||ct==="bottom")&&(C=ct)}const W=T.match(/background-color:\s*([^;]+)/);W&&(N=W[1].trim())}const L=[],R=$.children;if(R.length===0){const q=$.textContent||"";L.push({type:"paragraph",id:Lt(null,n),children:[{type:"text",text:q,marks:{}}]})}else for(const q of Array.from(R)){const W=q.tagName.toLowerCase(),ct=W==="img"?this.parseImageElement(q,n):W==="p"?this.parseSingleImageParagraph(q,n):null;if(ct){L.push(ct);continue}if(W==="p"||W.match(/^h[1-6]$/)){const vt=W.match(/^h([1-6])$/),Dt=q.getAttribute("style"),Qt=this.parseHtmlElement(q,Dt?this.extractTextStyleMarksFromStyle(Dt):{}),Vt={type:"paragraph",id:Lt(q.getAttribute("id"),n),children:Qt.length>0?Qt:[{type:"text",text:"",marks:{}}]};vt&&(Vt.heading=parseInt(vt[1])),this.applyParagraphElementAttributes(Vt,q,i),L.push(Vt)}else if(W==="ul"||W==="ol"){const vt=this.parseListElement(q,n);vt&&L.push(vt)}else if(W==="hr")L.push(this.parseHrElement(q,n));else if(W==="table"){const vt=this.parseTableElement(q,e,n);vt&&L.push(vt)}else{const vt=q.textContent||"";vt.trim()&&L.push({type:"paragraph",id:Lt(null,n),children:[{type:"text",text:vt,marks:{}}]})}}L.length===0&&L.push({type:"paragraph",id:Lt(null,n),children:[{type:"text",text:"",marks:{}}]});const M={type:"table-cell",id:Lt($.getAttribute("id"),n),children:L},F=T?.match(/width:\s*([\d.]+)%/);if(F){const q=parseFloat(F[1]);Number.isFinite(q)&&q>0&&u.set(M,q)}C&&(M.verticalAlign=C),N&&(M.backgroundColor=N);const j=Ur($.getAttribute("data-borders")),D=j?Io(j):Ws(Js(T));if(D&&(M.borders=D),T){const q=T.match(/(?:^|;)\s*padding\s*:\s*([^;]+)/i),W=$u(q?.[1]);W&&!(W.top===8&&W.right===8&&W.bottom===8&&W.left===8)&&(M.padding=Bu(W))}const O=this.parseSpanAttribute($.getAttribute("colspan")),H=this.parseSpanAttribute($.getAttribute("rowspan"));O>1&&(M.colSpan=O),H>1&&(M.rowSpan=H),A.push(M)}const B=Lt(w.getAttribute("id"),n);d.push({type:"table-row",id:B,children:A})}if(!d.some(I=>I.children.length>0))return null;const h=dn({children:d,columnWidths:[]}),f=h.cols||1,m=new Array(f).fill(0),y=new Array(f).fill(!1);for(const I of h.cells){if(I.colSpan!==1||y[I.col])continue;const w=u.get(I.cell);w!==void 0&&(m[I.col]=w,y[I.col]=!0)}const b=y.filter(I=>!I).length;if(b>0){const I=m.reduce((A,_)=>A+_,0),w=Math.max(1,(100-I)/b);for(let A=0;A<f;A++)y[A]||(m[A]=w)}const k={type:"table",id:o,columnWidths:m,children:d};a!==void 0&&(k.tableWidth=a),l&&(k.align=l),c&&(k.borderColor=c),g&&(k.hasHeader=g);const v=Xs(t.getAttribute("data-borders")),S=v?Io(v):Ws(Js(s));return S&&(k.borders=S),k}static parseSpanAttribute(t){const e=parseInt(t||"1",10);return Number.isFinite(e)?Math.min(Math.max(1,e),1e3):1}static parseCodeBlockElement(t,e){const n=Lt(t.getAttribute("id"),e);let o;const i=t.getAttribute("language"),s=t.getAttribute("data-language");if(i)o=i;else if(s)o=s;else{const l=t.className.split(" ");for(const d of l)if(d.startsWith("language-")){o=d.substring(9);break}}let a="";const c=t.querySelector("code");return c?a=c.textContent||"":a=t.textContent||"",{type:"code",id:n,content:a,language:o}}static parseMathElement(t,e){const n=Lt(t.getAttribute("id"),e);let o="block";t.getAttribute("display")==="inline"&&(o="inline");const i=t.textContent||"",s=bt(t,"align"),a={type:"math",id:n,content:i,displayMode:o};return(s==="left"||s==="center"||s==="right")&&(a.align=s),a}static parseHrElement(t,e){let n;const o=t.getAttribute("style");if(o){const s=o.match(/border(?:-bottom)?:\s*([\d.]+)px\s+(solid|double|dashed|dotted)\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)/i);if(s){const a=s[2].toLowerCase();n={width:parseFloat(s[1]),style:a==="solid"?"single":a,color:s[3]}}}const i=t.getAttribute("data-rule");return Os(i??void 0)&&(n={...n,style:i}),{type:"paragraph",id:Lt(t.getAttribute("id"),e),children:[{type:"text",text:"",marks:{}}],borders:xd(n)}}static parsePageBreakElement(t,e){return{type:"page-break",id:Lt(t.getAttribute("id"),e)}}static parseDocxRawElement(t,e){const n=t.getAttribute("origin");return{type:"docx-raw",id:Lt(t.getAttribute("id"),e),xml:"",tagName:t.getAttribute("tag")||"unknown",...t.getAttribute("detail")?{detail:t.getAttribute("detail")}:{},origin:n==="body"?"body":"run"}}static parseTocElement(t,e){const n={type:"toc",...wd(t),id:Lt(t.getAttribute("id"),e)},o=t.getAttribute("levels");if(o){const i=parseInt(o,10);Number.isFinite(i)&&i>=1&&i<=6&&(n.levels=i)}return Object.assign(n,Ad(t.getAttribute("style"))),n}static parseSectionBreakElement(t,e){const n={type:"section-break",id:Lt(t.getAttribute("id"),e)},o=t.getAttribute("break-type");(o==="nextPage"||o==="continuous"||o==="evenPage"||o==="oddPage")&&(n.breakType=o);const i=t.getAttribute("layout");if(i)try{const s=JSON.parse(i);s&&typeof s=="object"&&!Array.isArray(s)&&(n.layout=s)}catch{}return n}static parseCenterElement(t,e,n){const o=[],i=Array.from(t.children);for(const a of i){const c=a.tagName.toLowerCase();if(c==="p"||c.match(/^h[1-6]$/)){const l=c.match(/^h([1-6])$/),d=this.parseHtmlElement(a),u={type:"paragraph",id:Lt(a.getAttribute("id"),n),children:d.length>0?d:[{type:"text",text:"",marks:{}}],align:"center"};l&&(u.heading=parseInt(l[1])),o.push(u);continue}if(c==="img"){const l=this.parseImageElement(a,n);l&&(l.align=l.align??"center",o.push(l));continue}if(c==="table"){const l=this.parseTableElement(a,e,n);l&&(l.align=l.align??"center",o.push(l));continue}if(c==="pre"){const l=this.parseCodeBlockElement(a,n);l&&o.push(l);continue}if(c==="latex"){o.push(this.parseMathElement(a,n));continue}if(c==="page-break"){o.push(this.parsePageBreakElement(a,n));continue}if(c==="docx-raw"){o.push(this.parseDocxRawElement(a,n));continue}if(c==="section-break"){o.push(this.parseSectionBreakElement(a,n));continue}if(c==="toc"){o.push(this.parseTocElement(a,n));continue}if(c==="hr"){o.push(this.parseHrElement(a,n));continue}if(c==="ul"||c==="ol"){const l=this.parseListElement(a,n);l&&o.push(l);continue}}if(o.length>0)return o;const s=this.parseHtmlElement(t);return[{type:"paragraph",id:Lt(t.getAttribute("id"),n),align:"center",children:s.length>0?s:[{type:"text",text:"",marks:{}}]}]}static parseImageAlign(t){const e=bt(t,"align");if(e==="left"||e==="center"||e==="right")return e;const n=t.getAttribute("data-align");if(n==="left"||n==="center"||n==="right")return n;const o=t.getAttribute("style")||"";if(o.includes("margin-left: auto")&&o.includes("margin-right: auto"))return"center";if(o.includes("margin-left: auto"))return"right";if(o.includes("margin-right: auto"))return"left"}static getImageStyle(t){const e=["display: block","max-width: 100%","height: auto"];switch(t.align){case"center":e.push("margin-left: auto","margin-right: auto");break;case"right":e.push("margin-left: auto");break;case"left":e.push("margin-right: auto");break}return e.join("; ")}static escapePreContent(t){return t.replace(/<pre(\s[^>]*)?>(([\s\S](?!<\/pre>))*[\s\S]?)<\/pre>/gi,(e,n,o)=>{if(!o)return e;const i=o.match(/^(\s*)<code(\s[^>]*)?>(([\s\S](?!<\/code>))*[\s\S]?)<\/code>(\s*)$/i);if(i){const[,a,c,l,,d]=i,u=this.escapeCodeContent(l||"");return`<pre${n||""}>${a||""}<code${c||""}>${u}</code>${d||""}</pre>`}const s=this.escapeCodeContent(o);return`<pre${n||""}>${s}</pre>`})}static escapeCodeContent(t){return t.replace(/&(?!(lt|gt|amp|quot|apos|nbsp|#\d+|#x[0-9a-fA-F]+);)/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}static coalesceAdjacentBareListFragments(t){if(t.length<2)return t;const e=[];let n=!1;for(const o of t){const i=qr(o),s=Array.from(i.body.childNodes),a=s.filter(d=>d.nodeType===Node.ELEMENT_NODE||d.nodeType===Node.TEXT_NODE&&d.textContent?.trim()),c=d=>d?.nodeType===Node.ELEMENT_NODE&&d.tagName.toLowerCase()==="li",l=a.length===0&&s.some(d=>d.nodeType===Node.COMMENT_NODE);n&&(c(a[0])||l)?e[e.length-1]+=o:e.push(o),l||(n=c(a.at(-1)))}return e}static fromAgentHtml(t,e){t=this.escapePreContent(t);const n=e?.parsingContext??(e?.existingDocument?this.createParsingContext(e.existingDocument):void 0),o=n?.validIds,i=e?.preserveImageReferenceIds?o??new Set:e?.replacementBlock?ta({children:[e.replacementBlock]}):new Set,s={validIds:o,usedIds:new Set,imageIdsToPreserve:i,imageReferences:new Map,remainingImageReferences:new Set};e={...e,parsingContext:n};let a=qr(t),c;const l=Array.from(a.body.children).some(f=>f.tagName.toLowerCase()==="li");for(const f of Array.from(a.body.childNodes))if(f.nodeType!==Node.COMMENT_NODE){if(f.nodeType===Node.TEXT_NODE){if(l&&f.textContent?.trim()){c=void 0;const m=a.createElement("p");a.body.insertBefore(m,f),m.appendChild(f)}continue}if(f.nodeType!==Node.ELEMENT_NODE||f.tagName.toLowerCase()!=="li"){c=void 0;continue}c||(c=a.createElement("ul"),a.body.insertBefore(c,f)),c.appendChild(f)}Array.from(a.body.children).some(f=>qu.has(f.tagName.toLowerCase()))||(a=qr(`<p>${t}</p>`));const d=new Set,u=Array.from(a.body.querySelectorAll("img"));for(const f of u){s.remainingImageReferences.add(f);const m=f.getAttribute("id")??"",y=m?n?.imagesById?.get(m):void 0,b=f.getAttribute("data-image-id"),k=f.getAttribute("src")??"",v=k.startsWith("#")?k.slice(1):void 0;if(b!==null||v!==void 0){const I=b??v,w=n?.imagesById?.get(I);if(!w?.src||v!==void 0&&v!==I||y&&y.id!==I||k&&v===void 0&&k!==I&&k!==w.src)throw new Nt("invalid_image_reference",`Image reference "${I}" is missing or contradicts the supplied source. Copy an existing image with <img src="IMAGE_ID"> using the exact id from the document.`);s.imageReferences.set(f,w);continue}const S=n?.imagesById?.get(f.getAttribute("src")??"");if(S){s.imageReferences.set(f,S);continue}if(k&&k!==y?.src&&!/^(?:https?:\/\/|data:image\/|blob:)/i.test(k))throw new Nt("invalid_image_reference",`Image source "${k}" is not a known image id or an absolute image URL. Copy an existing image with <img src="IMAGE_ID"> using its exact document id, or provide an absolute image URL.`);if(!f.getAttribute("src")){const I=!m&&e?.replacementBlock?.type==="image"&&u.length===1?n?.imagesById?.get(e.replacementBlock.id):void 0,w=y??I;if(!w?.src)throw new Nt("invalid_image_reference",`${f.getAttribute("data-image-source")==="hidden"?"Cannot resolve hidden image":"Image"} ${m?'"'+m+'"':"without an id"} has no valid source. Supply src, copy a verified existing image with <img src="IMAGE_ID"> using its exact document id, or resize an explicitly targeted image block.`);if(d.has(w.id))throw new Nt("invalid_image_reference",`Image "${w.id}" is referenced more than once. Each existing image may appear only once in replacement HTML.`);d.add(w.id),s.imageReferences.set(f,w);continue}y?.src===f.getAttribute("src")&&s.imageReferences.set(f,y)}const g=Array.from(a.body.children),p=e?.parsingContext?.indentStepPx??this.resolveIndentStepPx(e?.existingDocument),h=[];g.length===0&&a.body.textContent&&h.push({type:"paragraph",id:Lt(null,s),children:[{type:"text",text:a.body.textContent||"",marks:{}}]});for(const f of g){const m=f.tagName.toLowerCase();if(m==="img"){const w=this.parseImageElement(f,s);w&&h.push(w);continue}if(m==="ul"||m==="ol"){const w=this.parseListElement(f,s,e?.listItemBaseIndent);w&&h.push(w);continue}if(m==="div"&&f.classList.contains("container")){const w=this.parseContainerElement(f,e,s);w&&h.push(w);continue}if(m==="table"){const w=this.parseTableElement(f,e,s);w&&h.push(w);continue}if(m==="pre"){const w=this.parseCodeBlockElement(f,s);w&&h.push(w);continue}if(m==="p"){const w=this.parseSingleImageParagraph(f,s);if(w){h.push(w);continue}}if(m==="latex"){const w=this.parseMathElement(f,s);h.push(w);continue}if(m==="page-break"){h.push(this.parsePageBreakElement(f,s));continue}if(m==="docx-raw"){h.push(this.parseDocxRawElement(f,s));continue}if(m==="section-break"){h.push(this.parseSectionBreakElement(f,s));continue}if(m==="toc"){h.push(this.parseTocElement(f,s));continue}if(m==="center"){h.push(...this.parseCenterElement(f,e,s));continue}if(m==="hr"){h.push(this.parseHrElement(f,s));continue}const y=m.match(/^h([1-6])$/),b=f.getAttribute("style");let k,v;if(b){const w=b.match(/font-family:\s*([^;]+)/);w&&(k=this.resolveFontToCss(w[1].trim())),v=this.extractFontSizeFromStyle(b)}const S=Lt(f.getAttribute("id"),s),I=b?this.extractTextStyleMarksFromStyle(b):{};if(y){const w=parseInt(y[1]),A=this.parseHtmlElement(f,I,e?.preserveExplicitMarkResets),_={type:"paragraph",id:S,heading:w,children:A.length>0?A:[{type:"text",text:"",marks:{}}]};if(k)for(const B of _.children)B.type==="text"&&(B.marks||(B.marks={}),B.marks.fontFamily||(B.marks.fontFamily=k));v!==void 0&&this.ensureTextNodesHaveFontSize(_.children,v),this.applyParagraphElementAttributes(_,f,p),h.push(_)}else{const w=this.parseHtmlElement(f,I,e?.preserveExplicitMarkResets),A={type:"paragraph",id:S,children:w.length>0?w:[{type:"text",text:"",marks:{}}]};if(k)for(const _ of A.children)_.type==="text"&&(_.marks||(_.marks={}),_.marks.fontFamily||(_.marks.fontFamily=k));this.applyParagraphElementAttributes(A,f,p),h.push(A)}}if(s.remainingImageReferences.size>0){const f=Array.from(s.remainingImageReferences,m=>m.getAttribute("id")||"(new image)").join(", ");throw new Nt("invalid_image_reference",`Image(s) ${f||"without ids"} are in unsupported HTML positions. Put each image directly in a table cell or as its own image block; mixed text/image paragraphs and list items are not supported.`)}return h.length===0&&h.push(Td()),Tu(h,e?.existingDocument?.stylesheet),this.applyInheritedFontStyling(h,e),Au(()=>Lt(null,s),h),this.hydrateDocxRawPlaceholders(h,e?.existingDocument),{type:"doc",children:h}}static hydrateDocxRawPlaceholders(t,e){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.type==="docx-raw"){if(o.xml)continue;const s=o.id&&e?z(e,o.id):void 0;s&&s.type==="docx-raw"&&s.xml?(o.xml=s.xml,o.tagName=s.tagName,s.detail&&(o.detail=s.detail),o.origin=s.origin):t.splice(n,1);continue}const i=o.children;Array.isArray(i)&&i.length>0&&i.filter(s=>typeof s=="object"&&s!==null&&typeof s.type=="string"&&s.type!=="text").length>0&&this.hydrateDocxRawPlaceholders(i,e)}}static parseHtmlElement(t,e={},n=!1){const o=[];let i;const s=(a,c={})=>{if(a.nodeType===Node.TEXT_NODE){const l=Yu(a.textContent||"",c);l&&o.push({type:"text",text:l,marks:{...c}})}else if(a.nodeType===Node.ELEMENT_NODE){const l=a,d={...c};switch(l.tagName.toLowerCase()){case"b":case"strong":d.bold=!0;break;case"i":case"em":d.italic=!0;break;case"u":d.underline=!0;break;case"s":case"strike":d.strikethrough=!0;break;case"code":d.code=!0;break;case"l":case"latex-inline":d.latex=!0;break;case"sup":{d.superscript=!0;const p=l.getAttribute("data-footnote-ref");p&&(d.footnoteRef=p);const h=l.getAttribute("data-footnote");h!==null&&(d.footnoteRef=p??et(),d.footnotePendingBody=h,l.getAttribute("data-note-kind")==="endnote"&&(d.footnotePendingKind="endnote"));break}case"sub":d.subscript=!0;break;case"mark":{const p=l.getAttribute("color"),h=this.normalizeAgentHighlightColor(p);if(p!==null&&!h)throw new Error(`Unsupported highlight color ${JSON.stringify(p)}. Use one of: ${Bn.join(", ")}.`);d.backgroundColor=h??_u}break;case"a":const u=l.getAttribute("href");u&&(d.link=u);break;case"comment-thread":{const p=l.getAttribute("id")?.trim();if(p){const h=d.comment?.split(",").map(f=>f.trim()).filter(Boolean);d.comment=[...h??[],p].join(",")}break}case"br":o.push({type:"text",text:`
18
- `,marks:{...c}});return;case"span":Cd(d,l.getAttribute("data-docx-explicit-false-marks"),l.getAttribute("data-docx-run-property-resets")),l.getAttribute("data-word-hidden")==="true"&&(d.hidden=!0);{const p=l.getAttribute("data-bookmark");p&&(d.bookmark=p);const h=l.getAttribute("data-field-instr");h&&(d.fieldInstr=h);const f=l.getAttribute("data-word-lang");f&&(d.lang=f);const m=l.getAttribute("data-dynamic-field");(m==="page"||m==="numPages")&&(d.field=m);const y=l.getAttribute("data-sdt-inline");y&&(d.sdtInline=y),l.getAttribute("data-ai-generated")==="true"&&(d.aiGenerated=!0);const b=l.getAttribute("data-html-class");b&&(d.__htmlClassName=b)}const g=l.getAttribute("style");if(g){const p=g.match(/font-family:\s*([^;]+)/);p&&(d.fontFamily=this.resolveFontToCss(p[1].trim()));const h=this.extractFontSizeFromStyle(g);h!==void 0&&(d.fontSize=h);const f=this.parseCssFontWeightToBold(g);f===!0?d.bold=!0:f===!1&&(n?d.bold=!1:delete d.bold);const m=g.match(/(?:^|;)\s*font-style:\s*([^;]+)/i);if(m){const S=m[1].trim().toLowerCase();S==="italic"||S==="oblique"?d.italic=!0:S==="normal"&&(n?d.italic=!1:delete d.italic)}const y=g.match(/background-color:\s*([^;]+)/i);if(y){const S=this.normalizeAgentHighlightColor(y[1].trim());S&&(d.backgroundColor=S)}const b=g.match(/(?:^|;)\s*color:\s*([^;]+)/i);if(b){const S=ho(b[1].trim());S&&!Is(S)&&(d.color=S)}const k=g.match(/text-decoration:\s*([^;]+)/i);if(k){const S=k[1].toLowerCase();if(S.trim()==="none")for(const I of["underline","strikethrough","doubleStrikethrough"])n?d[I]=!1:delete d[I];S.includes("line-through")&&(S.includes("double")?d.doubleStrikethrough=!0:d.strikethrough=!0)}/font-variant:\s*small-caps/i.test(g)&&(d.smallCaps=!0),/text-transform:\s*uppercase/i.test(g)&&(d.allCaps=!0);const v=g.match(/letter-spacing:\s*([^;]+)/i);if(v){const S=Qs(v[1],d.fontSize);S!==void 0&&(d.letterSpacing=S)}}break}l.tagName.toLowerCase()!=="img"&&(i=d);for(const u of Array.from(a.childNodes))s(u,d)}};for(const a of Array.from(t.childNodes))s(a,{...e});if(o.length===0){const a=i??e;if(Object.keys(a).length>0)return[{type:"text",text:"",marks:{...a}}]}return o}static applyInheritedFontStyling(t,e){const n=this.extractBlockFontStyling(e?.replacementBlock),o=this.extractBlockFontStyling(e?.previousBlock);let i=n.fontFamily??o.fontFamily??(e?.parsingContext?e.parsingContext.documentFontFamily:this.findOmittableDocumentFontFamily(e?.existingDocument)),s=e?.replacementBlock?n.fontSize:o.fontSize;for(const a of t){if(a.type!=="paragraph"&&a.type!=="list")continue;if(a.type==="paragraph")this.ensureTextNodesHaveFontStyling(a.children,i,s);else if(a.type==="list")for(const l of a.children)this.ensureTextNodesHaveFontStyling(l.children,i,s);const c=this.extractBlockFontStyling(a);i=c.fontFamily??i,s=c.fontSize??s}}static extractBlockFontStyling(t){if(!t)return{};const e=[];if(t.type==="paragraph")for(const i of t.children)i.type==="text"&&!i.marks?.footnoteRef&&e.push(i);else if(t.type==="list")for(const i of t.children)for(const s of i.children)s.type==="text"&&!s.marks?.footnoteRef&&e.push(s);if(e.length===0)return{};const n=e[0].marks?.fontFamily,o=e[0].marks?.fontSize;return{fontFamily:e.every(i=>i.marks?.fontFamily===n)?n:void 0,fontSize:e.every(i=>i.marks?.fontSize===o)?o:void 0}}static ensureTextNodesHaveFontStyling(t,e,n){t.forEach(o=>{o.type==="text"?(o.marks=o.marks?{...o.marks}:{},!o.marks.fontFamily&&e&&(o.marks.fontFamily=e),o.marks.fontSize===void 0&&n!==void 0&&(o.marks.fontSize=n)):o.children&&this.ensureTextNodesHaveFontStyling(o.children,e,n)})}static ensureTextNodesHaveFontSize(t,e){for(const n of t)n.type==="text"&&(n.marks=n.marks?{...n.marks}:{},n.marks.fontSize||(n.marks.fontSize=e))}static formatLockedSelectionContext(t){if(!t||t.length===0)return null;const e=[];for(const n of t){const o=n.contextBlocks;if(!o||o.length===0)continue;const i=this.buildSelectionInfoForBlocks(o,[n]);for(const s of o){const a=this.getBlockId(s),c=i?.get(a);e.push(this.blockToHtmlWithSelections(s,void 0,c,void 0,i))}}return e.length===0?null:e.filter(n=>n.length>0).join(`
19
- `)}};zr.DEFAULT_FONT_FAMILY="Arial, sans-serif",zr.MAX_OVERVIEW_BLOCKS=50;let it=zr;function Ft(r){if(!r||typeof r!="object")return"";const t=r;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=>Ft(n)).join(e)}return""}const ea=/<!--[^]*?-->|<\/?[a-zA-Z][\w:-]*(?:\s+(?:[^"'<>]|"[^"]*"|'[^']*')*)?\s*\/?>/g,na={amp:"&",lt:"<",gt:">",quot:'"',AMP:"&",LT:"<",GT:">",QUOT:'"',apos:"'",nbsp:" ",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",laquo:"«",raquo:"»",lsaquo:"‹",rsaquo:"›",ensp:" ",emsp:" ",thinsp:" ",ndash:"–",mdash:"—",hellip:"…",copy:"©",reg:"®",trade:"™"};function Ku(r){return r.replace(/\\+(["'])/g,"$1")}function Nn(r){return Ku(r.replace(/&(#(?:\d+|x[0-9a-f]+)|[a-z]+);/gi,(t,e)=>{if(!e.startsWith("#"))return Object.prototype.hasOwnProperty.call(na,e)?na[e]:t;const n=e[1].toLowerCase()==="x",o=Number.parseInt(e.slice(n?2:1),n?16:10);return o>=0&&o<=1114111&&!(o>=55296&&o<=57343)?String.fromCodePoint(o):t}))}function Te(r){return r.search(ea)>=0}function Fn(r){return Nn(r.replace(ea,t=>/^<br\b/i.test(t)?`
20
- `:""))}function Ao(r){const t=Nn(r);return[...new Set(Te(r)?[r,t,Fn(r)]:[r,t])]}function To(r,t,e="prefer-exact",n){if(n&&e!=="normalized"){const o=ra(r,n,t);if(o.length)return o}for(const o of Ao(t)){const i=En(r,o,e);if(i.length)return i}return[]}function un(r){return r.replace(/<\/?comment-thread\b[^>]*>/gi,"")}function oa(r,t){return Hr(un(r),un(t))}function ra(r,t,e){if(!Te(e))return[];t=un(t);const n=Fn(t);return n.length!==r.length||Be(n)!==Be(r)?[]:oa(t,e).map(({start:o,end:i})=>({start:Fn(t.slice(0,o)).length,end:Fn(t.slice(0,i)).length})).filter(o=>o.end>o.start)}function Xr(r){let t="";const e=[],n=[];for(let o=0;o<r.length;o++){const i=o;let s=ia(r[o]);if(/[\s\u0085]/u.test(s)){for(;o+1<r.length&&/[\s\u0085]/u.test(r[o+1]);)o++;s=" "}t+=s,e.push(i),n.push(o+1)}return{text:t,starts:e,ends:n}}function ia(r){return/[\s\u0085]/u.test(r)?" ":/[\u2018-\u201b\u2039\u203a\uff07]/u.test(r)?"'":/[\u201c-\u201f\u00ab\u00bb\uff02]/u.test(r)?'"':r}function Be(r){let t="";for(let e=0;e<r.length;e++){const n=ia(r[e]);t+=/[\u2012-\u2014]/u.test(n)?"-":n}return t}function Hr(r,t){if(!t)return[];const e=[];let n=0;for(;n<=r.length-t.length;){const o=r.indexOf(t,n);if(o<0)break;e.push({start:o,end:o+t.length}),n=o+1}return e}function En(r,t,e="prefer-exact"){if(e!=="normalized"){const i=Hr(r,t);if(i.length>0||e==="exact")return i}const n=Xr(r),o=Xr(t).text;return o.trim()?Hr(n.text,o).map(({start:i,end:s})=>({start:n.starts[i],end:n.ends[s-1]})):[]}function Vu(r,t,e,n,o){for(const i of["exact","normalized"]){const s=o?o(t,i):To(r,t,i,n),a=o?o(e,i):To(r,e,i,n),c=[];let l=0;for(const d of s){for(;l<a.length&&a[l].start<d.end;)l++;for(let u=l;u<a.length;u++)if(c.push({start:d.start,end:a[u].end}),c.length===2)return c}if(c.length)return c}return[]}const sa={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 aa(r,t){if(!/<[^>]+\bid\s*=/i.test(t))return null;const e=Ft(r);if(e.includes(t)||e.includes(Nn(t)))return null;const n=document.createElement("template");n.innerHTML=t;const o=[...n.content.querySelectorAll("[id]")].filter(l=>sa[l.tagName]);if(!o.length)return null;const i=new Map,s=(l,d=null)=>{if(!l||typeof l!="object")return;const u=l;u.id&&(d?d.add(u.id):i.set(u.id,[...i.get(u.id)??[],u])),u.children?.forEach(g=>s(g,d))};s(r);const a=new Set,c=new Set;for(const l of o){const d=i.get(l.id)??[];if(a.has(l.id)||d.length!==1||d[0].type!==sa[l.tagName])throw new Nt("target_stale",`HTML matcher id '${l.id}' is missing, contradictory, or outside the authorized target. Read the target again.`,"target_resolution");a.add(l.id);const u=d[0],g=Ft(u),p=l.textContent??"",h=En(g,p,"prefer-exact");if(g!==p&&!h.some(y=>y.start===0&&y.end===g.length))throw new Nt("target_stale",`HTML matcher text for '${l.id}' no longer matches that block. Read it again before editing.`,"matching");const f=new Set;s(u,f);const m=o.filter(y=>y!==l&&l.contains(y));if(m.some(y=>!f.has(y.id)))throw new Nt("target_stale",`HTML matcher ids contradict the document hierarchy inside '${l.id}'.`,"target_resolution");m.length||f.forEach(y=>c.add(y))}return c}function Se(r,t){const e=z(r,t);return e?.type==="list"&&e.id!==t?e.children.find(n=>n.id===t)??null:e}function Co(r){if(!(!r||r.type!=="paragraph"&&r.type!=="list-item"))return it.toAgentHtml({type:"doc",children:[{...r,type:"paragraph"}]})}function Po(r,t,e="prefer-exact"){const n=aa(r,t),o=To(Ft(r),t,e,Te(t)?Co(r):void 0);if(!n)return o;const i=ca(r);return o.filter(s=>{const a=i.filter(c=>c.start<s.end&&s.start<c.end);return a.length>0&&a.every(c=>n.has(c.blockId))})}function ca(r){const t=[];let e=0;const n=o=>{if(!o||typeof o!="object")return;const i=o,s=Array.isArray(i.children)?i.children:[],a=i.type==="list"||i.type==="table"||i.type==="table-row"||i.type==="table-cell"||i.type==="container";if(i.id&&!a){const c=Ft(o);if(c.length>0){t.push({blockId:i.id,start:e,end:e+c.length,text:c}),e+=c.length;return}}s.forEach((c,l)=>{i.type==="list"&&l>0&&(e+=1),n(c)})};return n(r),t}function Gu(r,t,e){const n=[];for(const o of r){const i=Math.max(t,o.start),s=Math.min(e,o.end);s<=i||n.push({blockId:o.blockId,start:i-o.start,end:s-o.start})}return n}function la(r){const t=new Map;let e=0;const n=o=>{if(!o||typeof o!="object")return;const i=o;if(i.type==="text"&&typeof i.text=="string"){const s=e;e+=i.text.length;for(const a of i.marks?.comment?.split(",")??[]){const c=a.trim();if(!c)continue;const l=t.get(c);t.set(c,{start:l?Math.min(l.start,s):s,end:l?Math.max(l.end,e):e})}return}if((i.type==="code"||i.type==="math")&&typeof i.content=="string"){e+=i.content.length;return}if(Array.isArray(i.children)){const s=i.type==="list"?1:0;i.children.forEach((a,c)=>{s&&c>0&&(e+=s),n(a)})}};return n(r),t}const da=300;function Wr(r,t,e,n,o){const i=la(t);return(r.comments??[]).filter(s=>!s.parentId&&s.resolved!==!0).filter(s=>!o.has(s.id)).filter(s=>{if(s.anchorBlockId===e)return!0;const a=i.get(s.id);return a?n?n.start<a.end&&a.start<n.end:!0:!1}).map(s=>({id:s.id,author:s.agentName??s.author,bodyMd:s.bodyMd.length>da?`${s.bodyMd.slice(0,da)}…`:s.bodyMd}))}function ua(r,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 ${r} 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 Zu(r,t,e,n,o,i,s,a){const c=i&&typeof i=="object"?["text"in i,"start_text"in i||"end_text"in i,"whole_block"in i]:[],l=c.length>0&&("text"in i?typeof i.text=="string"&&i.text.length>0:"whole_block"in i?i.whole_block===!0:typeof i.start_text=="string"&&i.start_text.length>0&&typeof i.end_text=="string"&&i.end_text.length>0);if(c.filter(Boolean).length!==1||!l)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)),u=Se(r,n);if(!u)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in i){const w=Wr(r,u,n,null,d);if(w.length>0)return ua(n,w);const A=e.addBlockComment(n,o,s);return A?{success:!0,commentId:A}:{success:!1,error:`Could not attach a comment to block ${n}`}}const g=Se(t,n),p=Ft(g??u);let h=-1,f=-1;const m="text"in i?Po(g??u,i.text):Vu(p,i.start_text,i.end_text,Co(g??u),(w,A)=>Po(g??u,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:f}=m[0]);const y=ca(g??u),b=Gu(y,h,f);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=Se(t,w.blockId),_=Se(r,w.blockId);if(!A||!_)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 B={start:w.start,end:w.end};if(Ft(_)!==Ft(A)){const P=e.mapAcceptedSuggestionRangeToLiveRange(w.blockId,w.start,w.end);if(!P)return{success:!1,error:`The anchor range in block ${n} could not be mapped across pending suggestions; read the block again and retry`};B=P}k.push({blockId:w.blockId,...B})}const v=new Map;for(const w of Wr(r,u,n,{start:h,end:f},d))r.comments?.some(A=>A.id===w.id&&A.anchorBlockId===n)&&v.set(w.id,w);for(const w of k){const A=Se(r,w.blockId);if(A)for(const _ of Wr(r,A,w.blockId,{start:w.start,end:w.end},d))v.set(_.id,_)}const S=Array.from(v.values());if(S.length>0)return ua(n,S);const I=e.addCommentToRanges(k,o,s);return I?{success:!0,commentId:I,range:{start:h,end:f}}:{success:!1,error:`Could not attach a comment to block ${n}`}}function ga(r,t){const e=r.comments??[];let n=e.find(i=>i.id===t);if(!n)return null;const o=new Set([n.id]);for(;n.parentId&&!o.has(n.parentId);){o.add(n.parentId);const i=e.find(s=>s.id===n.parentId);if(!i)break;n=i}return n}function Qu(r,t,e,n,o){const i=ga(r,e);if(!i)return{success:!1,error:`Comment ${e} not found`,errorCode:"target_not_found"};if(i.resolved)return{success:!1,error:`Comment thread ${i.id} is resolved; leave a new comment instead`,errorCode:"already_resolved"};const s=t.replyToComment(i.id,n,o);return s?{success:!0,commentId:s,threadId:i.id}:{success:!1,error:`Could not reply to comment ${e}`,errorCode:"comment_mutation_failed"}}function tg(r,t,e){const n=z(r.getDocument(),t),o=z(r.getDocumentWithAcceptedSuggestions(),t);if(!n||!o)throw new Nt("target_missing",`Footnote target '${t}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||o.type!=="paragraph")throw new Nt("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const i=e?Po(o,e):[];if(e&&i.length!==1)throw new Nt(i.length?"anchor_ambiguous":"anchor_not_found",i.length?`Anchor text matched ${i.length} locations in block ${t}; include unique surrounding text.`:`Anchor text ${JSON.stringify(e)} not found in block ${t}. Read it again.`,"matching");let s=e?i[0].end:Ft(o).length;if(Ft(n)!==Ft(o)){const a=r.mapAcceptedSuggestionRangeToLiveRange(t,s,s);if(!a)throw new Nt("target_stale","Anchor could not be mapped across pending suggestions. Read the block again.","target_resolution");s=a.end}return{block:t,offset:s}}function Jr(r,t){return{indentStepPx:be(t).indentStepPx,storedAsUnits:r.get(Me.paragraphIndentStorageVersion)===Mr}}const ha=new WeakMap;function Yr(r){return r.getXmlFragment("content")}function pa(r,t){let e=t,n=null;for(;e;){if(n=e.parent,n===r)return e instanceof x.XmlElement&&e.getAttribute("id")||null;e=n}return null}function eg(r){const t=Yr(r),e={nestedBlocks:new WeakMap,doc:null,blockCache:new Map,elementByBlockId:new Map,dirtyBlockIds:new Set,structuralChange:!1,observer:()=>{}},n=o=>{for(const i of o){let s=i.target;for(;s&&s!==t;)s instanceof x.XmlElement&&e.nestedBlocks.delete(s),s=s.parent;if(i.target===t&&i instanceof x.YXmlEvent&&i.childListChanged){e.structuralChange=!0;continue}if(i instanceof x.YXmlEvent&&i.childListChanged){const c=pa(t,i.target);c!==null&&e.dirtyBlockIds.add(c);continue}const a=pa(t,i.target);a!==null&&e.dirtyBlockIds.add(a)}};return e.observer=n,t.observeDeep(n),e}function fa(r){let t=ha.get(r);return t||(t=eg(r),ha.set(r,t)),t}function Mo(r,t){const e=fa(r);e.nestedBlocks=new WeakMap,e.doc=t,e.blockCache.clear(),e.elementByBlockId.clear();const n=Yr(r).toArray();for(const o of t.children)o.id&&e.blockCache.set(o.id,o);for(const o of n)if(o instanceof x.XmlElement){const i=o.getAttribute("id");i&&e.elementByBlockId.set(i,o)}e.dirtyBlockIds.clear(),e.structuralChange=!1}function $o(r,t,e){const n=e.nestedBlocks.get(r);if(n)return n;const o=$r(r,t,void 0,i=>$o(i,t,e));return o&&e.nestedBlocks.set(r,o),o}const Bo=new WeakMap;function ng(r){let t=Bo.get(r);t||(t={blocks:[],dirty:!0,observing:!1},Bo.set(r,t));const e=r.getXmlFragment("chrome");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=Bo.get(r);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof x.XmlElement||o?.constructor?.name==="YXmlElement"){const i=$r(o,Jr(r.getMap("metadata"),void 0));i&&i.type==="header-footer"&&n.push(i)}t.blocks=n,t.dirty=!1}return t.blocks}const _o=new WeakMap;function og(r){let t=_o.get(r);t||(t={blocks:[],dirty:!0,observing:!1},_o.set(r,t));const e=r.getXmlFragment("notes");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=_o.get(r);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof x.XmlElement||o?.constructor?.name==="YXmlElement"){const i=$r(o,Jr(r.getMap("metadata"),void 0));i&&i.type==="footnote"&&n.push(i)}t.blocks=n,t.dirty=!1}return t.blocks}function rg(r){return!!(Bo.get(r)?.dirty||_o.get(r)?.dirty)}function Lo(r,t){const e=og(t);e.length>0?(r.notes=e,Pd(r)):delete r.notes}function No(r,t){const e=t.getMap("comments"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,i)=>(o.createdAt??"").localeCompare(i.createdAt??"")),r.comments=n):delete r.comments}function Kr(r,t){const e=t.getMap("oxml-ranges"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,i)=>o.id.localeCompare(i.id)),r.oxmlRanges=n):delete r.oxmlRanges}function Fo(r,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;r.children.forEach((s,a)=>{s.id&&o.set(s.id,a)});const i=s=>s.blockIds?.[0]??s.startBlockId??"";n.sort((s,a)=>(o.get(i(s))??Number.MAX_SAFE_INTEGER)-(o.get(i(a))??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)),r.sdtWrappers=n}else delete r.sdtWrappers}function Eo(r,t){const e=ng(t);e.length>0?r.chrome=e:delete r.chrome;const n=ws(e);n.headers?r.headers=n.headers:delete r.headers,n.footers?r.footers=n.footers:delete r.footers}function Ie(r){const t=fa(r),e=Yr(r),n=r.getMap("metadata"),o=n?.get("title"),i=n?.get("pageless"),s=n?.get("watermark"),a=typeof s=="string"&&s.trim()!==""?s:void 0,c=n?.get("chromeImages"),l=Array.isArray(c)&&c.length>0?c:void 0,d=n?.get("stylesheet"),u=d&&typeof d=="object"&&Array.isArray(d.paragraphStyles)&&d.paragraphStyles.length>0?d:void 0,g=n?.get("stylesXml"),p=typeof g=="string"&&g.length>0?g:void 0,h=n?.get("docxSource"),f=h&&typeof h=="object"&&Array.isArray(h.spans)?h:void 0,m=n?.get("coreProperties"),y=m&&typeof m=="object"&&Object.keys(m).length>0?m:void 0,b=n?.get("fontSubstitutes"),k=b&&typeof b=="object"&&Object.keys(b).length>0?b:void 0,v=xs(n),S=Jr(n,v);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 I=[],w=e.toArray();for(let A=0;A<w.length;A++){const _=w[A];if(_ instanceof x.XmlElement){const B=$o(_,S,t);B&&(I.push(B),t.blockCache.set(B.id,B),t.elementByBlockId.set(B.id,_))}}return t.doc={type:"doc",children:I},o&&(t.doc.title=o),i!==void 0&&(t.doc.pageless=i),v&&(t.doc.pageLayout=v),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),u&&(t.doc.stylesheet=u),p&&(t.doc.stylesXml=p),f&&(t.doc.docxSource=f),y&&(t.doc.coreProperties=y),k&&(t.doc.fontSubstitutes=k),Eo(t.doc,r),Lo(t.doc,r),No(t.doc,r),Fo(t.doc,r),Kr(t.doc,r),t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(e.length!==t.doc.children.length&&(t.structuralChange=!0),t.structuralChange){const I=[],w=new Map,A=new Map,_=e.toArray();for(let B=0;B<_.length;B++){const P=_[B];if(P instanceof x.XmlElement){const $=P.getAttribute("id"),T=$?t.dirtyBlockIds.has($):!0,C=$?t.blockCache.get($):void 0,N=$!==null&&t.elementByBlockId.get($)===P;if($&&!T&&C&&N)I.push(C),w.set($,C),A.set($,P);else{const L=$o(P,S,t);L&&(I.push(L),w.set(L.id,L),A.set(L.id,P))}}}return t.doc={type:"doc",children:I},o&&(t.doc.title=o),i!==void 0&&(t.doc.pageless=i),v&&(t.doc.pageLayout=v),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),u&&(t.doc.stylesheet=u),p&&(t.doc.stylesXml=p),f&&(t.doc.docxSource=f),y&&(t.doc.coreProperties=y),k&&(t.doc.fontSubstitutes=k),Eo(t.doc,r),Lo(t.doc,r),No(t.doc,r),Fo(t.doc,r),Kr(t.doc,r),t.blockCache=w,t.elementByBlockId=A,t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(t.dirtyBlockIds.size>0){const I=[...t.doc.children],w=e.toArray();for(let A=0;A<I.length;A++){const _=I[A];if(_?.id&&t.dirtyBlockIds.has(_.id)&&A<w.length){const B=w[A];if(B instanceof x.XmlElement){const P=$o(B,S,t);P&&(t.blockCache.delete(_.id),I[A]=P,t.blockCache.set(P.id,P),t.elementByBlockId.set(P.id,B))}}}t.doc={type:"doc",children:I},o&&(t.doc.title=o),i!==void 0&&(t.doc.pageless=i),v&&(t.doc.pageLayout=v),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),u&&(t.doc.stylesheet=u),p&&(t.doc.stylesXml=p),f&&(t.doc.docxSource=f),y&&(t.doc.coreProperties=y),k&&(t.doc.fontSubstitutes=k),Eo(t.doc,r),Lo(t.doc,r),No(t.doc,r),Fo(t.doc,r),Kr(t.doc,r),t.dirtyBlockIds.clear()}return o!==void 0?t.doc.title=o:delete t.doc.title,i!==void 0?t.doc.pageless=i:delete t.doc.pageless,v?t.doc.pageLayout=v:delete t.doc.pageLayout,p?t.doc.stylesXml=p:delete t.doc.stylesXml,f?t.doc.docxSource=f:delete t.doc.docxSource,y?t.doc.coreProperties=y:delete t.doc.coreProperties,k?t.doc.fontSubstitutes=k: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!==u&&(t.doc={...t.doc},u!==void 0?t.doc.stylesheet=u:delete t.doc.stylesheet),rg(r)&&(t.doc={...t.doc}),Eo(t.doc,r),Lo(t.doc,r),No(t.doc,r),Fo(t.doc,r),t.doc}const Vr=new WeakMap,Rn="__revise_end_of_document__";function zt(r,t){Vr.set(r,{...Vr.get(r),...t})}function ne(r){return Vr.get(r)}function Ro(r){if(r.name==="insert_block")return ne(r)?.stableId}function ig(r){return!!ne(r)?.allowNoopContinuation}function sg(r){if(r.name==="replace_block")return ne(r)?.multiBlockReplace}function Gr(r,t){if(Te(t)){let e=null;for(const n of r){const o=n.html?ra(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 r){const i=To(o.text,t,e);if(i.length){if(i.length>1||n!==null)return null;n=o.blockId}}if(n!==null)return n}return null}function Zr(r){const t=Ao(r).at(-1);return Xr(Be(t)).text}function ma(r){return r?.type==="paragraph"||r?.type==="list-item"||r?.type==="code"||r?.type==="math"}function ba(r){const t=[],e=(n,o)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&ma(n)&&t.push({blockId:n.id,topLevelBlockId:o,text:Ft(n)}),Array.isArray(n.children)))for(const i of n.children)e(i,o)};for(const n of r.children)e(n,n.id??null);for(const n of r.notes??[])e(n,n.id);return t}function gn(r,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 r.notes??[])if(e(n))return n.id;return null}function Qr(r,t){const e=gn(r,t);if(!e)return null;if(t!==e)return t;const n=r.notes?.find(s=>s.id===e);if(!n)return t;const o=[],i=s=>{!s||typeof s!="object"||(typeof s.id=="string"&&(s.type==="paragraph"||s.type==="list-item"||s.type==="code"||s.type==="math")&&o.push(s.id),Array.isArray(s.children)&&s.children.forEach(i))};return n.children.forEach(i),o.length===1?o[0]:t}function ya(r,t){return t.has(r.blockId)||r.topLevelBlockId!==null&&t.has(r.topLevelBlockId)}function ka(r){if(!r.loadedBlockIds||r.loadedBlockIds.size===0)return null;const t=Zr(r.find);if(!t||/^\s*$/.test(t))return null;const e=z(r.doc,r.requestedBlockId);if(e&&Zr(Ft(e)).includes(t))return null;const n=Ao(r.find).at(-1),o=ba(r.doc).filter(s=>s.blockId!==r.requestedBlockId&&ya(s,r.loadedBlockIds));if(o.some(s=>En(s.text,n).length>0))return Gr(o,n);let i=null;for(const s of o)if(Zr(s.text).includes(t)){if(i!==null)return null;i=s.blockId}return i}function ag(r){if(r.action.name!=="replace"&&r.action.name!=="replace_all")return{action:r.action};if(!r.action.arguments||typeof r.action.arguments!="object")return{action:r.action};const t=r.action.arguments,e=typeof t.id=="string"?t.id.trim():"",n=typeof t.find=="string"?t.find:"";if(!e||!n)return{action:r.action};const o=ka({doc:r.doc,requestedBlockId:e,find:n,loadedBlockIds:r.loadedBlockIds});if(!o)return{action:r.action};const i={...r.action,arguments:{...t,id:o}},s=ne(r.action);return s&&zt(i,s),{action:i,retarget:{fromBlockId:e,toBlockId:o}}}function cg(r){const t=[],e=[];for(const n of r.actions){const o=ag({action:n,doc:r.doc,loadedBlockIds:r.loadedBlockIds});t.push(o.action),o.retarget&&e.push(o.retarget)}return{actions:t,retargets:e}}function ti(r){return r.children.map(t=>{const e={type:"doc",children:[t]};return it.toInternalHtml(e).trim()})}function lg(r,t=0){const e=vo.fromMarkdown(r);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 ti(e)}function dg(r){return r.replace(/<span\b([^>]*?)\sdir\s*=\s*["']?(ltr|rtl|auto)["']?([^>]*)>([\s\S]*?)<\/span>/gi,(t,e,n,o,i)=>{const s=n.toLowerCase(),a=s==="ltr"?"⁦":s==="rtl"?"⁧":"⁨",c=`${e}${o}`.trim(),l=c?`<span ${c}>${i}</span>`:i;return`${a}${l}⁩`})}function ug(r,t,e,n){return ti(it.fromAgentHtml(dg(r),{existingDocument:t,replacementBlock:e,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const He=/<\/?[a-z][^>]*>/i;function hn(r){return r.replace(/\s+/g," ").trim()}function Sa(r){return hn(r).replace(/^>\s+/,"")}function gg(r,t){if(r.replace==="")return null;const e=r.format==="html"||He.test(r.replace),n=e?it.fromAgentHtml(r.replace,{replacementBlock:z(t,r.id)??void 0,existingDocument:t,preserveImageReferenceIds:!0}):vo.fromMarkdown(r.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 i=z(t,r.id);if(!i||i.type!=="list")return null;const s=i,a=He.test(r.find)?it.fromAgentHtml(r.find,{existingDocument:t,preserveImageReferenceIds:!0}):vo.fromMarkdown(r.find),c=a.children.length===1&&a.children[0].type==="list"?a.children[0].children.map(y=>hn(Ft(y))):[hn(Ft(a))];if(c.length===0||c.some(y=>y===""))return null;const l=s.children.map(y=>hn(Ft(y))),d=[];for(let y=0;y+c.length<=l.length;y++)c.every((b,k)=>l[y+k]===b)&&(d.push(y),y+=c.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 '${r.id}' — it did not. Include each full item's text in "find" (or use insert_markdown to add items).`);if(d.length>1&&!r.all)throw new Error(`replace: "find" matches ${d.length} runs of list items in block '${r.id}'. Include more items in "find" so it matches exactly one location, or set all: true.`);const u=r.all?d:[d[0]],g=[];let p=0;for(const y of u)g.push(...s.children.slice(p,y)),g.push(...o),p=y+c.length;g.push(...s.children.slice(p));const h=u.length===1&&u[0]===0&&c.length===s.children.length,f=h?{...n.children[0],id:s.id}:{...s,children:g},m=h&&e?r.replace:ti({children:[f]})[0];return{name:"replace_block",arguments:{id:s.id,content:[m]}}}function hg(r,t){if(r.replace===""||r.all)return null;const e=z(t,r.id);if(!e)return null;const n=r.format==="html"||!r.format&&He.test(r.find)?Ft(it.fromAgentHtml(r.find,{existingDocument:t,preserveImageReferenceIds:!0})):Ft(vo.fromMarkdown(r.find)),o=Ft(e);if(Sa(n)!==Sa(o))return null;const i=r.format==="html"||!r.format&&He.test(r.replace)?ug(r.replace,t,e):lg(r.replace),s=i.length===1&&/^<p\b[^>]*>[\s\S]*<\/p>$/i.test(i[0]),a=(r.format==="html"||!r.format&&He.test(r.replace))&&/^<p\s+[^>]+>/i.test(r.replace.trim()),c=e.type==="footnote"?Qr(t,r.id):null,l=c!==null&&c!==r.id&&z(t,c)?.type==="paragraph",d=r.format!=="markdown"&&He.test(r.find)&&!He.test(r.find.replace(/<\/?(?:b|strong|i|em|u|s|strike|sup|sub|code|mark|span|a|br)\b[^>]*>/gi,""));return s&&!a&&(e.type==="table-cell"||l||e.type==="paragraph"&&(d||hn(r.find)===hn(o)))?null:{name:"replace_block",arguments:{id:r.id,content:i}}}function pg(r,t){return gg(r,t)??hg(r,t)}function Dn(r,t){const e=z(r,t);if(!e)return null;const n=JSON.stringify(e);let o=2166136261;for(let i=0;i<n.length;i++)o^=n.charCodeAt(i),o=Math.imul(o,16777619);return(o>>>0).toString(36)}function ei(r,t){const e=new Map;for(const n of t){if(e.has(n))continue;const o=Dn(r,n);o!==null&&e.set(n,o)}return e}const Ia=50,va="document_state_changed",fg=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function ni(r,t){const e=r.name==="replace"&&!!r.arguments&&typeof r.arguments=="object"&&Object.prototype.hasOwnProperty.call(r.arguments,"replacements"),n=r.name==="replace_many";if(!e&&!n)return{actions:[r]};const o=n?"replace_many":"replace";if(!r.arguments||typeof r.arguments!="object")return{actions:[],error:`${o} requires object arguments`};const i=r.arguments.id,s=r.arguments.replacements;if(!Array.isArray(s)||s.length===0)return{actions:[],error:`${o} requires a non-empty replacements array`};if(s.length>Ia)return{actions:[],error:`${o} supports at most ${Ia} replacements per call`};const a=[];for(let l=0;l<s.length;l++){const d=s[l];if(!d||typeof d!="object")return{actions:[],error:`${o} replacement #${l+1} must be an object`};if(typeof d.find!="string")return{actions:[],error:`${o} replacement #${l+1} is missing "find"`};if(d.find.length===0&&(n||typeof i!="string"||i.trim().length===0))return{actions:[],error:n?`${o} replacement #${l+1} has an empty "find"`:`${o} replacement #${l+1} has an empty "find" and therefore requires a direct block id`};if(typeof d.replace!="string")return{actions:[],error:`${o} replacement #${l+1} is missing "replace"`};if(d.occurrence!==void 0&&d.occurrence!==null&&d.occurrence!=="unique"&&d.occurrence!=="all")return{actions:[],error:`${o} replacement #${l+1} has invalid "occurrence"; use "unique" or "all"`};if(d.comment!==void 0&&d.comment!==null&&(typeof d.comment!="string"||d.comment.trim().length===0))return{actions:[],error:`${o} replacement #${l+1} comment must be a non-empty string when provided`};let u=typeof i=="string"?i.trim():"";if(!u&&d.find.length>0&&t&&(u=ka({doc:t.doc,requestedBlockId:"",find:d.find,loadedBlockIds:t.loadedBlockIds})??""),!u)return{actions:[],error:`${o} replacement #${l+1} requires a block id unless its find text uniquely identifies one loaded block`};if(t&&!d.comment)try{const g=pg({type:"replace",id:u,find:d.find,replace:d.replace,format:"html",all:d.occurrence==="all"},t.doc);if(g){a.push({...g,id:`${r.id||o}-${l+1}`});continue}}catch(g){return{actions:[],error:g instanceof Error?g.message:String(g),failure:Ln(g)}}a.push({id:`${r.id||o}-${l+1}`,name:d.occurrence==="all"?"replace_all":"replace",arguments:{id:u,find:d.find,replace:d.replace,...typeof d.comment=="string"?{comment:d.comment.trim()}:{}}})}const c=Array.from(new Set(a.map(l=>l.arguments?.id).filter(l=>typeof l=="string"&&l.length>0)));return{actions:a,blockId:c.length===1?c[0]:void 0}}function mg(r){const{toolCall:t,docBefore:e,resultSets:n}=r,o=t.arguments;if(!o||typeof o!="object")return null;const i=o.search_result_id;if(i==null)return null;if(typeof i!="string"||i.trim().length===0)return{actions:[],targetBlockIds:[],error:"search_result_id must be a non-empty string"};const s=i.trim();if(!fg.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(s);if(!a)return{actions:[],targetBlockIds:[],error:`Search result '${s}' is unavailable. Search result references are request-scoped; rerun search_document in this request, then retry.`,errorCode:va};for(const u of a.blockIds){if(gn(e,u))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const g=Dn(e,u);if(g===null||g!==a.blockHashes.get(u))return{actions:[],targetBlockIds:[],error:`Search result '${s}' is stale because block '${u}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:va}}const{search_result_id:c,...l}=o,d=[];if(t.name==="replace")for(let u=0;u<a.blockIds.length;u++){const g=ni({...t,id:`${t.id||"replace"}-search-${u+1}`,arguments:{...l,id:a.blockIds[u]}});if(g.error)return{actions:[],targetBlockIds:[],error:g.error};d.push(...g.actions)}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 g=0;g<a.blockIds.length;g++)d.push({...t,id:`${t.id||"replace_block"}-search-${g+1}`,arguments:{...l,id:a.blockIds[g],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,g=(Array.isArray(u)?u:typeof u=="string"?[u]:[]).flatMap(h=>typeof h=="string"?h.split(",").map(f=>f.trim()):[h]);if(g.length===0||g.some(h=>typeof h!="string"||h.trim().length===0))return{actions:[],targetBlockIds:[],error:"style_blocks requires one or more non-empty selectors"};const p=a.blockIds.flatMap(h=>g.map(f=>{const m=String(f).trim();return/^(?:\*|all|document|:root)$/i.test(m)?`#${h}`:`#${h} ${m}`}));d.push({...t,arguments:{...l,selectors:p}})}return{actions:d,targetBlockIds:[...a.blockIds],resultSet:a}}function xa(r,t){const e={...t};for(const n of["lang","oxmlRPr","oxmlRange","sdtInline","field","aiGenerated","__htmlClassName"])e[n]===void 0&&r?.[n]!==void 0&&Object.assign(e,{[n]:r[n]});for(const n of As)e[n]===void 0&&r?.[n]===!1&&(e[n]=!1);if(e.docxRunPropertyResets===void 0){const n=Tr(r?.docxRunPropertyResets)?.split(",").filter(o=>o==="color"?e.color===void 0:e.backgroundColor===void 0);n?.length&&(e.docxRunPropertyResets=n.join(","))}return e}function Do(r,t){const e=r.map(s=>s.text).join("");if(!e||e!==t.map(s=>s.text).join("")){const s=new Set(r.filter(c=>c.text.length>0).map(c=>c.marks?.lang)),a=s.size===1?[...s][0]:void 0;return a===void 0?t:t.map(c=>({...c,marks:{lang:a,...c.marks}}))}const n=[];let o=0,i=0;for(const s of t){if(s.text.length===0){n.push({...s,marks:s.marks?{...s.marks}:void 0});continue}let a=0;for(;a<s.text.length;){for(;i===r[o].text.length;)o++,i=0;const c=r[o],l=Math.min(s.text.length-a,c.text.length-i);n.push({...s,text:s.text.slice(a,a+l),marks:xa(c.marks,s.marks)}),a+=l,i+=l}}return n}function bg(r,t){const e=dn(r),n=Array.from({length:e.cols},(c,l)=>Math.max(.001,r.columnWidths[l]||100/e.cols)),o=new Map;for(const c of t){const l=e.byId.get(c.cellId);if(!l)throw new Nt("target_stale","The requested table cell no longer exists. Read the table again.","target_resolution");if(!Number.isFinite(c.percent)||c.percent<=0||c.percent>100)throw new Nt("attribute_value_unsupported","Cell width must be greater than 0 and at most 100 percent.");const d=n.slice(l.col,l.col+l.colSpan).reduce((u,g)=>u+g,0);for(let u=l.col;u<l.col+l.colSpan;u++){const g=c.percent*n[u]/d;if(o.has(u)&&Math.abs(o.get(u)-g)>.001)throw new Nt("attribute_conflict","Conflicting cell widths constrain the same table column. Set each column once, using one unmerged row.");o.set(u,g)}}const i=[...o.values()].reduce((c,l)=>c+l,0),s=n.map((c,l)=>l).filter(c=>!o.has(c));if(i>100.001||!s.length&&Math.abs(i-100)>.001||s.length&&i>=100)throw new Nt("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=s.reduce((c,l)=>c+n[l],0);return n.map((c,l)=>o.get(l)??(100-i)*c/a)}let yg=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});yg.decode();const oi=new TextEncoder;"encodeInto"in oi||(oi.encodeInto=function(r,t){const e=oi.encode(r);return t.set(e),{read:r.length,written:e.length}});function kg(r,t){return null}function Sg(r,t){return null}let Oo;function wa(r){if(Oo===void 0){const t=Intl.Segmenter;Oo=t?new t("en",{granularity:"sentence"}):null}return Oo?Array.from(Oo.segment(r),({segment:t})=>t):[r]}const Aa=/[\p{L}\p{N}\p{M}_'’]/u;function Ig(r,t){return t===0||t===r.length||!Aa.test(r[t-1])||!Aa.test(r[t])}function ge(r,t,e){if(!e)return;const n=r[r.length-1];n?.[0]===t?n[1]+=e:r.push([t,e])}function jo(r){const t=new Set(du(r));return e=>t.has(e)&&Ig(r,e)}function vg(r){const t=r.filter(([u])=>u!==1).map(([,u])=>u).join(""),e=r.filter(([u])=>u!==-1).map(([,u])=>u).join(""),n=jo(t),o=jo(e),i=[];let s=0,a=0,c="",l="";const d=()=>{ge(i,-1,c),ge(i,1,l),c=l=""};for(const[u,g]of r){if(u===0){let p=0,h=g.length;for(;p<h&&(!n(s+p)||!o(a+p));)p++;for(;h>p&&(!n(s+h)||!o(a+h));)h--;c+=g.slice(0,p),l+=g.slice(0,p),h>p&&(d(),ge(i,0,g.slice(p,h))),c+=g.slice(h),l+=g.slice(h)}else u===-1?c+=g:l+=g;u!==1&&(s+=g.length),u!==-1&&(a+=g.length)}return d(),i}function ri(r){r=vg(r);const t=[];for(let e=0;e<r.length;e++){const[n,o]=r[e];if(n!==-1||r[e+1]?.[0]!==1){ge(t,n,o);continue}const i=r[++e][1],s=jo(o),a=jo(i);let c=0;for(;c<Math.min(o.length,i.length)&&o[c]===i[c];)c++;for(;c>0&&(!s(c)||!a(c));)c--;let l=0;for(;l<Math.min(o.length,i.length)-c&&o[o.length-1-l]===i[i.length-1-l];)l++;for(;l>0&&(!s(o.length-l)||!a(i.length-l));)l--;ge(t,0,o.slice(0,c)),ge(t,-1,o.slice(c,o.length-l)),ge(t,1,i.slice(c,i.length-l)),ge(t,0,l?o.slice(-l):"")}for(let e=2;e+2<t.length;e++){const[n,o]=t[e];n===0&&/^[\p{L}\p{M}\t ]+$/u.test(o)&&o.trim().length<=12&&o.trim().split(/\s+/).length<=2&&t[e-2][0]===-1&&t[e-1][0]===1&&t[e+1][0]===-1&&t[e+2][0]===1&&Math.max(Math.abs(t[e-1][1].length-t[e-2][1].length),Math.abs(t[e+2][1].length-t[e+1][1].length))>2*o.length&&(t.splice(e-2,5,[-1,t[e-2][1]+o+t[e+1][1]],[1,t[e-1][1]+o+t[e+2][1]]),e=Math.max(1,e-3))}return t}function xg(r,t){if(r===t)return 3;const e=r.match(/[\p{L}\p{N}]+/gu)??[],n=t.match(/[\p{L}\p{N}]+/gu)??[],o=new Map;for(const l of e)o.set(l,(o.get(l)??0)+1);let i=0;for(const l of n){const d=o.get(l)??0;d>0&&(i++,o.set(l,d-1))}const s=Math.min(e.length,n.length);let a=0;for(;a<s&&e[a]===n[a];)a++;const c=2*i/Math.max(1,e.length+n.length);return!(a===e.length&&a>=2)&&a<3&&c<.5?0:c+a/Math.max(1,s)}function wg(r,t,e){if(!r||!t||r===t)return e(r,t);const n=wa(r),o=wa(t);if(n.length*o.length>4096||n.length<=1&&o.length<=1)return ri(e(r,t));const i=o.length+1,s=new Float64Array((n.length+1)*i),a=new Float64Array(n.length*o.length);for(let h=n.length-1;h>=0;h--)for(let f=o.length-1;f>=0;f--){const m=xg(n[h],o[f]);a[h*o.length+f]=m,s[h*i+f]=Math.max(s[(h+1)*i+f],s[h*i+f+1],m>0?m+s[(h+1)*i+f+1]:0)}const c=[];let l=0,d=0,u="",g="";const p=()=>{for(const[h,f]of ri(e(u,g)))ge(c,h,f);u=g=""};for(;l<n.length&&d<o.length;){const h=a[l*o.length+d];if(h>0&&s[l*i+d]===h+s[(l+1)*i+d+1]){p();const f=n[l++],m=o[d++],y=f.trimEnd(),b=m.trimEnd();for(const[k,v]of ri(e(y,b)))ge(c,k,v);for(const[k,v]of e(f.slice(y.length),m.slice(b.length)))ge(c,k,v)}else s[(l+1)*i+d]>=s[l*i+d+1]?u+=n[l++]:g+=o[d++]}return u+=n.slice(l).join(""),g+=o.slice(d).join(""),p(),c}const ie=-1,_e=0,se=1;function Uo(r){return/[\p{L}\p{N}]/u.test(r)}function Ag(r,t){const e=Math.min(r.length,t.length);let n=0;for(;n<e&&r[n]===t[n];)n++;return n}function Tg(r,t){const e=Math.min(r.length,t.length);let n=0;for(;n<e&&r[r.length-1-n]===t[t.length-1-n];)n++;return n}function Ta(r){const t=[];for(const[e,n]of r)n.length!==0&&(t.length>0&&t[t.length-1][0]===e?t[t.length-1][1]+=n:t.push([e,n]));return t}function Cg(r){const t=[];for(let e=0;e<r.length;e++){const n=r[e],o=r[e+1];if(!n||!o||n[0]!==ie||o[0]!==se){t.push(n);continue}const i=n[1],s=o[1];let a=Ag(i,s);if(a>0){const l=i.slice(0,a),d=i.slice(a),u=s.slice(a);if(!Uo(d)&&!Uo(u)){t.push([_e,l]),d.length>0&&t.push([ie,d]),u.length>0&&t.push([se,u]),e+=1;continue}}const c=Tg(i,s);if(c>0&&c<i.length&&c<s.length){const l=i.slice(i.length-c),d=i.slice(0,-c),u=s.slice(0,-c);if(!Uo(d)&&!Uo(u)){d.length>0&&t.push([ie,d]),u.length>0&&t.push([se,u]),t.push([_e,l]),e+=1;continue}}t.push(n)}return Ta(t)}function Ca(r){const t=[],e=r.match(/^\s*/),n=e?e[0]:"";let o=r.slice(n.length);const i=/(\S+)(\s*)/g;let s;for(;(s=i.exec(o))!==null;)t.push({word:s[1],trailingWs:s[2]});return{leadingWs:n,tokens:t}}function Pg(r,t){const e=Math.min(r.length,t.length);let n=0;for(;n<e&&r[n]===t[n];)n++;let o=0;for(;o<e-n&&r[r.length-1-o]===t[t.length-1-o];)o++;const i=r.slice(n,r.length-o),s=t.slice(n,t.length-o),a=i.length,c=s.length,l=Array(a+1).fill(null).map(()=>Array(c+1).fill(0));for(let h=1;h<=a;h++)for(let f=1;f<=c;f++)i[h-1]===s[f-1]?l[h][f]=l[h-1][f-1]+1:l[h][f]=Math.max(l[h-1][f],l[h][f-1]);const d=[];let u=a,g=c;for(;u>0&&g>0;)i[u-1]===s[g-1]?(d.push({originalIndex:n+u-1,newIndex:n+g-1}),u--,g--):l[u-1][g]>l[u][g-1]?u--:g--;d.reverse();const p=Array.from({length:n},(h,f)=>({originalIndex:f,newIndex:f}));p.push(...d);for(let h=0;h<o;h++)p.push({originalIndex:r.length-o+h,newIndex:t.length-o+h});return p}function ii(r,t,e){if(t===e)return t.length>0?[[_e,t]]:[];if(t.length===0)return e.length>0?[[se,e]]:[];if(e.length===0)return[[ie,t]];const n=kg();return n!==null?n:Pa(r,t,e)}function Pa(r,t,e){if(t===e)return t.length>0?[[_e,t]]:[];if(t.length===0)return e.length>0?[[se,e]]:[];if(e.length===0)return[[ie,t]];const n=Ca(t),o=Ca(e),i=n.tokens,s=o.tokens;if(i.length===0&&s.length===0)return t===e?[[_e,t]]:[[ie,t],[se,e]];if(i.length===0)return[[ie,t],[se,e]];if(s.length===0)return[[ie,t],[se,e]];const a=n.leadingWs,c=o.leadingWs,l=[];a===c?a.length>0&&l.push([_e,a]):(a.length>0&&l.push([ie,a]),c.length>0&&l.push([se,c]));const d=i.map(f=>f.word),u=s.map(f=>f.word),g=Pg(d,u);let p=0,h=0;for(const f of g){for(;p<f.originalIndex;){const k=i[p];l.push([ie,k.word+k.trailingWs]),p++}for(;h<f.newIndex;){const k=s[h];l.push([se,k.word+k.trailingWs]),h++}const m=i[f.originalIndex],y=s[f.newIndex];let b=0;for(;b<m.trailingWs.length&&b<y.trailingWs.length&&m.trailingWs[b]===y.trailingWs[b];)b++;l.push([_e,m.word+m.trailingWs.slice(0,b)]),m.trailingWs.length>b&&l.push([ie,m.trailingWs.slice(b)]),y.trailingWs.length>b&&l.push([se,y.trailingWs.slice(b)]),p=f.originalIndex+1,h=f.newIndex+1}for(;p<i.length;){const f=i[p];l.push([ie,f.word+f.trailingWs]),p++}for(;h<s.length;){const f=s[h];l.push([se,f.word+f.trailingWs]),h++}return Cg(Ta(l))}function qo(r,t){const e=r.split(`
21
- `),n=t.split(`
22
- `),o=e.length>1||n.length>1,i=wg(r,t,(c,l)=>ii([],c,l)),s=Math.max(r.length,t.length);let a=0;for(const[c,l]of i)c!==_e&&(a+=l.length);return{changePercentage:s>0?a/s*100:0,hasMultipleLines:o,diffs:i}}const Mg=Object.freeze(Object.defineProperty({__proto__:null,analyzeParagraphDiff:qo,roundDiffsToWordBoundaries:ii,roundDiffsToWordBoundariesJs:Pa},Symbol.toStringTag,{value:"Module"}));function Ma(r,t,e,n){if(!n?.length)return;const o=t==="row"?r.cols:r.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 i of r.cells){const s=t==="row"?i.row:i.col,a=t==="row"?i.rowSpan:i.colSpan;if(s>=e||s+a<=e)continue;const c=t==="row"?i.col:i.row,l=t==="row"?i.colSpan:i.rowSpan;for(let d=c;d<c+l;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 $g(r){return{type:"paragraph",id:et(),children:[{type:"text",text:""}]}}function Bg(r){return{type:"table-cell",id:et(),children:[$g()]}}function $a(r,t){return!r||r.length===0?Bg():{type:"table-cell",id:et(),children:r}}function zo(r,t){const e=r.get("content",x.XmlFragment);function n(o){for(let i=0;i<o.length;i++){const s=o.get(i);if(s instanceof x.XmlElement){if(s.nodeName==="table"&&s.getAttribute("id")===t)return s;if(s.nodeName==="container"||s.nodeName==="footnote"||s.nodeName==="table"||s.nodeName==="table-row"||s.nodeName==="table-cell"){const a=n(s);if(a)return a}}}return null}return n(e)??n(r.getXmlFragment("notes"))}function si(r,t){const e=Number(bt(r,t));return Number.isFinite(e)&&e>1?Math.floor(e):1}function Xo(r){const t=[];for(let a=0;a<r.length;a++){const c=r.get(a);c instanceof x.XmlElement&&c.nodeName==="table-row"&&t.push(c)}const e=r.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 c=0;for(let l=0;l<a.length;l++){const d=a.get(l);d instanceof x.XmlElement&&d.nodeName==="table-cell"&&(c+=si(d,"colSpan"))}n=Math.max(n,c)}n=Math.max(n,1);const o=t.length,i=Array.from({length:o},()=>new Array(n).fill(void 0)),s=[];for(let a=0;a<o;a++){const c=t[a];let l=0,d=0;for(let u=0;u<c.length;u++){const g=c.get(u);if(!(g instanceof x.XmlElement)||g.nodeName!=="table-cell")continue;for(;l<n&&i[a][l]!==void 0;)l++;if(l>=n)break;const p=Math.min(si(g,"colSpan"),n-l),h=Math.min(si(g,"rowSpan"),o-a),f={el:g,row:a,col:l,rowSpan:h,colSpan:p,physicalIndex:d};s.push(f);for(let m=a;m<a+h;m++)for(let y=l;y<l+p;y++)i[m][y]===void 0&&(i[m][y]=f);l+=p,d++}}return{rows:o,cols:n,cells:s,occupancy:i,rowEls:t}}function On(r,t,e){e>1?r.setAttribute(t,String(e)):rt(r,t)}function Ba(r){return Ut(r)}function _g(r){const t=new x.XmlElement("table-row");t.setAttribute("id",r.id);let e=0;for(const n of r.children){const o=Ba(n);t.insert(e++,[o])}return t}function Lg(r,t,e){const n=zo(r,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=Xo(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."}:(r.transact(()=>{for(const s of o.cells)s.col<=e&&e<s.col+s.colSpan&&(s.colSpan>1?On(s.el,"colSpan",s.colSpan-1):o.rowEls[s.row].delete(s.physicalIndex,1));const i=n.getAttribute("columnWidths");if(i){const s=JSON.parse(i);if(e<s.length){const a=s[e];s.splice(e,1);const c=s.reduce((d,u)=>d+u,0),l=c>0?s.map(d=>d+a*d/c):s;n.setAttribute("columnWidths",JSON.stringify(l))}}}),{success:!0})}function Ng(r,t){const e=Xo(r);if(t<0||t>=e.rows)return;for(const i of e.cells)i.row<t&&i.row+i.rowSpan>t&&On(i.el,"rowSpan",i.rowSpan-1);const n=e.cells.filter(i=>i.row===t&&i.rowSpan>1).sort((i,s)=>i.col-s.col);if(n.length>0&&t+1<e.rows){const i=e.rowEls[t+1],s=e.cells.filter(c=>c.row===t+1);let a=0;for(const c of n){const l=c.el.clone();On(l,"rowSpan",c.rowSpan-1);const d=s.filter(u=>u.col<c.col).length+a;i.insert(d,[l]),a++}}const o=e.rowEls[t];for(let i=0;i<r.length;i++)if(r.get(i)===o){r.delete(i,1);break}}function Fg(r,t,e){const n=zo(r,t);return n?e<0||e>=n.length?{success:!1,error:`Invalid row index ${e}. Table has ${n.length} rows.`}:n.length<=1?{success:!1,error:"Cannot remove the last row from a table."}:(r.transact(()=>{Ng(n,e)}),{success:!0}):{success:!1,error:`Table with ID "${t}" not found.`}}function Eg(r,t,e,n,o){const i=zo(r,t);if(!i)return{success:!1,error:`Table with ID "${t}" not found.`};const s=Xo(i);if(s.rows===0)return{success:!1,error:"Table has no rows."};const a=s.cols;if(n<0||n>=a)return{success:!1,error:`Invalid reference column index ${n}. Table has ${a} columns.`};const c=e==="before"?n:n+1;return Ma(s,"column",c,o)||(r.transact(()=>{for(let u=0;u<s.rows;u++){const g=c>0&&c<a&&s.occupancy[u][c-1]===s.occupancy[u][c]?s.occupancy[u][c]:void 0;if(g){g.row===u&&On(g.el,"colSpan",g.colSpan+1);continue}const p=o?.[u],h=$a(p),f=Ba(h),m=s.cells.filter(y=>y.row===u&&y.col<c).length;s.rowEls[u].insert(m,[f])}const d=i.getAttribute("columnWidths");if(d){const u=JSON.parse(d),g=100/(a+1),p=(100-g)/100,h=u.map(f=>f*p);h.splice(c,0,g),i.setAttribute("columnWidths",JSON.stringify(h))}}),{success:!0})}function Rg(r,t,e,n){const o=Xo(t);return Ma(o,"row",e,n)||(r.transact(()=>{const s=o.cells.filter(g=>g.row<e&&g.row+g.rowSpan>e),a=new Set;for(const g of s){On(g.el,"rowSpan",g.rowSpan+1);for(let p=g.col;p<g.col+g.colSpan;p++)a.add(p)}const c=[];for(let g=0;g<o.cols;g++)a.has(g)||c.push($a(n?.[g]));const l={id:et(),children:c},d=_g(l);let u=t.length;if(e<o.rows){const g=o.rowEls[e];for(let p=0;p<t.length;p++)if(t.get(p)===g){u=p;break}}t.insert(u,[d])}),{success:!0})}function Dg(r,t,e,n,o){const i=zo(r,t);if(!i)return{success:!1,error:`Table with ID "${t}" not found.`};if(n<0||n>=i.length)return{success:!1,error:`Invalid reference row index ${n}. Table has ${i.length} rows.`};const s=i.get(0);if(!(s instanceof x.XmlElement)||s.nodeName!=="table-row")return{success:!1,error:"Table has no rows."};const a=e==="before"?n:n+1;return Rg(r,i,a,o)}const _a=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"]);function Og(r){if(!r||r.length<4)return!1;if(/^https?:\/\//i.test(r))try{return new URL(r),!0}catch{return!1}if(/^www\./i.test(r))try{return new URL(`https://${r}`),!0}catch{return!1}if(!r.includes(".")||!/^[a-zA-Z0-9]/.test(r))return!1;try{const t=new URL(`https://${r}`).hostname.split(".").filter(n=>n.length>0);if(t.length<2)return!1;const e=t[t.length-1].toLowerCase();if(_a.has(e))return!0;if(t.length>=3){const n=t[t.length-2].toLowerCase();if(_a.has(n))return!0}return!1}catch{return!1}}function jg(r){return/^https?:\/\//i.test(r)?r:`https://${r}`}function La(r){return r===" "||r===" "||r===`
23
- `||r==="\r"}function Na(r){if(!r||r.length<4)return[];const t=[];let e=0;for(;e<r.length;){if(La(r[e])){e++;continue}let n=e,o=e;for(;o<r.length&&!La(r[o]);)o++;const i=r.slice(n,o);Og(i)&&t.push({url:jg(i),originalText:i,start:n,end:o}),e=o}return t}function _t(r){for(const t of r.toArray())if(t instanceof x.XmlText)return t;return null}function pn(r){return r instanceof x.XmlElement&&r.nodeName==="header-footer"}function fn(){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 Ug(r,t){const e=_t(r),n=r.parent instanceof x.XmlElement&&r.parent.nodeName==="list"?r.parent.getAttribute("variant")??void 0:void 0;if(e)return[{blockId:t,yBlock:r,yText:e,blockText:We(e),listVariant:r.nodeName==="list-item"?n:void 0}];if(r.nodeName==="list"){const s=[];for(const a of r.toArray()){if(!(a instanceof x.XmlElement)||a.nodeName!=="list-item")continue;const c=_t(a);if(!c)continue;const l=a.getAttribute("id")||t;s.push({blockId:l,yBlock:a,yText:c,blockText:We(c),listVariant:r.getAttribute("variant")??void 0})}return s}const o=[],i=s=>{for(const a of s.toArray()){if(!(a instanceof x.XmlElement))continue;const c=_t(a);c?o.push({blockId:a.getAttribute("id")??t,yBlock:a,yText:c,blockText:We(c)}):i(a)}};return i(r),o}function qg(r,t){const e=new Set,n=i=>{const s=i.getAttribute("id"),a=typeof s=="string"?s:"",c=_t(i);if(a&&c&&!e.has(a)){const l=t({blockId:a,yBlock:i,yText:c,blockText:We(c)});if(e.add(a),l===!0)return!0}for(const l of i.toArray())if(l instanceof x.XmlElement&&n(l))return!0;return!1},o=Pn(r);for(const i of o.toArray())if(i instanceof x.XmlElement&&n(i))return}function zg(r,t,e,n=3){const o=Te(e)?Fn(e):Nn(e);if(!o||/^\s*$/.test(o))return null;const i=Be(o);if(!i||/^\s*$/.test(i))return null;const s=[];let a=0,c=!1;return qg(r,l=>{if(!(l.blockId===t||!Be(l.blockText).includes(i))&&(a++,s.length<n&&s.push(l.blockId),a>n))return c=!0,!0}),a===0?null:{blockIds:s,totalMatches:a,truncated:c}}function Xg(r,t,e){const n=zg(r,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(", "),i=n.totalMatches-n.blockIds.length,s=i>0?n.truncated?` and at least ${i} more`:` and ${i} more`:"";return` This text appears in other blocks: ${o}${s}. Did you mean one of those block IDs?`}const ai=new WeakMap;function ci(r){return ai.get(r)}const Bt=r=>({kind:"block",...r}),Wt=r=>({kind:"textMark",...r}),Hg=new Set(["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","code","superscript","subscript"]),Fa={fontSize:{integer:!0,min:1,max:512},letterSpacing:{min:-20,max:100}},Wg=[Bt({attr:"align",nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"],aliases:["textAlign","text-align"]}),Bt({attr:"heading",nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6}),Bt({attr:"lineSpacing",nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4,aliases:["lineHeight","line-height"]}),Bt({attr:"leftIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20,aliases:["marginLeft","margin-left","left-indent","indent","indents"]}),Bt({attr:"direction",nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"],aliases:["dir"]}),Bt({attr:"firstLineIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1,aliases:["textIndent","text-indent","first-line-indent"]}),Bt({attr:"spaceBefore",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginTop","margin-top"]}),Bt({attr:"spaceAfter",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginBottom","margin-bottom"]}),Bt({attr:"width",nodeNames:["image"],valueType:"number",integer:!0,min:1}),Bt({attr:"height",nodeNames:["image"],valueType:"number",integer:!0,min:1}),Bt({attr:"alt",nodeNames:["image"],valueType:"string"}),Bt({attr:"language",nodeNames:["code"],valueType:"string"}),Bt({attr:"renderDiagram",nodeNames:["code"],valueType:"boolean"}),Bt({attr:"showDiagramSource",nodeNames:["code"],valueType:"boolean"}),Bt({attr:"displayMode",nodeNames:["math"],valueType:"string",enumValues:["inline","block"]}),Bt({attr:"variant",nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"],aliases:["listStyleType","list-style-type"]}),Bt({attr:"startNumber",nodeNames:["list"],valueType:"number",integer:!0,min:1}),Bt({attr:"numberingChainId",nodeNames:["list"],valueType:"string"}),Bt({attr:"checked",nodeNames:["list-item"],valueType:"boolean"}),Bt({attr:"indentLevel",nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10}),Bt({attr:"tableWidth",nodeNames:["table"],valueType:"number",integer:!0,min:1,aliases:["width"]}),Bt({attr:"borderColor",nodeNames:["table","table-cell","container"],valueType:"string",aliases:["border-color"]}),Bt({attr:"borderWidth",nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0,aliases:["border-width"]}),Bt({attr:"borders",nodeNames:["table","table-cell"],valueType:"string",aliases:["border"]}),Bt({attr:"cellPadding",nodeNames:["table"],valueType:"number",integer:!0,min:0,aliases:["cell-padding","padding"]}),Bt({attr:"hasHeader",nodeNames:["table"],valueType:"boolean"}),Bt({attr:"verticalAlign",nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"],aliases:["vertical-align"]}),Bt({attr:"backgroundColor",nodeNames:["table-cell"],valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),Bt({attr:"padding",nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}),Wt({attr:"bold",valueType:"boolean",aliases:["fontWeight","font-weight"]}),Wt({attr:"italic",valueType:"boolean",aliases:["fontStyle","font-style"]}),Wt({attr:"underline",valueType:"boolean",aliases:["textDecoration","text-decoration"]}),Wt({attr:"strikethrough",valueType:"boolean",aliases:["strike","line-through"]}),Wt({attr:"doubleStrikethrough",valueType:"boolean",aliases:["double-strikethrough","double-strike","dstrike"]}),Wt({attr:"smallCaps",valueType:"boolean",aliases:["small-caps","fontVariant","font-variant"]}),Wt({attr:"allCaps",valueType:"boolean",aliases:["all-caps","caps"]}),Wt({attr:"letterSpacing",valueType:"number",min:-20,max:100,aliases:["letter-spacing","characterSpacing","character-spacing"]}),Wt({attr:"code",valueType:"boolean"}),Wt({attr:"superscript",valueType:"boolean"}),Wt({attr:"subscript",valueType:"boolean"}),Wt({attr:"fontSize",valueType:"number",integer:!0,min:1,max:512,aliases:["font-size"]}),Wt({attr:"fontFamily",valueType:"string",aliases:["font-family"]}),Wt({attr:"backgroundColor",valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),Wt({attr:"color",valueType:"string"}),Wt({attr:"link",valueType:"string",aliases:["href"]})],li=new Map,Ea=(r,t)=>{const e=r.toLowerCase(),n=li.get(e)??[];n.push(t),li.set(e,n)};for(const r of Wg){Ea(r.attr,r);for(const t of r.aliases??[])Ea(t,r)}const Ra={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 We(r){const t=mt(r);let e="";for(const n of t)n.insert&&typeof n.insert=="string"&&(e+=n.insert);return e}function Da(r,t,e){if(We(t).length===0)return!!Ve(r.getAttribute("_emptyTextMarks"))[e];const n=mt(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 Jg(r,t,e){const n=Ve(r.getAttribute("_emptyTextMarks"));e?n[t]=!0:delete n[t],Object.keys(n).length===0?r.removeAttribute("_emptyTextMarks"):r.setAttribute("_emptyTextMarks",JSON.stringify(n))}function Ho(r,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&&r.setAttribute("_emptyTextMarks",JSON.stringify(n.marks))}function Oa(r,t,e){const n=Ve(r.getAttribute("_emptyTextMarks"));e==null?delete n[t]:n[t]=e,Object.keys(n).length===0?r.removeAttribute("_emptyTextMarks"):r.setAttribute("_emptyTextMarks",JSON.stringify(n))}function Yg(r,t,e){const n=mn(r,t);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${r}" expects a number.`);if(e.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${r}" expects an integer value.`);if(e.min!==void 0&&n<e.min)throw new Error(`set_block_attribute "${r}" must be >= ${e.min}.`);if(e.max!==void 0&&n>e.max)throw new Error(`set_block_attribute "${r}" must be <= ${e.max}.`);return n}function Kg(r){if(r==null)return"set";if(r==="set"||r==="toggle"||r==="remove")return r;throw new Error('set_block_attribute operation must be one of "set", "toggle", or "remove".')}function ja(r,t){let e=Array.isArray(t)?t:[t];if(typeof t=="string"){const i=t.trim();if(i.startsWith("[")&&i.endsWith("]"))try{const s=JSON.parse(i);Array.isArray(s)&&(e=s)}catch{}}const n=[],o=new Set;for(const i of e){if(typeof i!="string"||i.trim().length===0)throw new Error(`${r} requires a valid block ID or a non-empty list of block IDs.`);const s=i.trim();o.has(s)||(o.add(s),n.push(s))}if(n.length===0)throw new Error(`${r} requires a valid block ID or a non-empty list of block IDs.`);return n}function Ua(r){if(r===!0||r===!1)return r;if(typeof r=="string"){const t=r.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}return!1}function qa(r,t,e){if(e.valueType==="string"){if(typeof t!="string")throw new Error(`set_block_attribute "${r}" expects a string value.`);if(e.enumValues&&!e.enumValues.includes(t))throw new Error(`set_block_attribute "${r}" must be one of: ${e.enumValues.join(", ")}.`);return t}if(e.valueType==="boolean"){if(typeof t!="boolean")throw new Error(`set_block_attribute "${r}" expects a boolean value.`);return String(t)}const n=mn(r,t);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${r}" expects a number.`);if(e.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${r}" expects an integer value.`);if(e.min!==void 0&&n<e.min)throw new Error(`set_block_attribute "${r}" must be >= ${e.min}.`);if(e.max!==void 0&&n>e.max)throw new Error(`set_block_attribute "${r}" must be <= ${e.max}.`);return String(n)}function di(r,t,e){if(e===void 0){rt(r,t);return}r.setAttribute(t,String(e))}function za(r,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(qa("indentLevel",e,{valueType:"number",integer:!0,min:0,max:20})),o=n>0?de(1):void 0,i=n>1?le(n-1):void 0;di(r,"firstLineIndent",o),di(r,"leftIndent",i)}function Xa(r,t,e){if(e===null){rt(r,t);return}const n=t==="leftIndent"?le(e):de(e);di(r,t,n)}function mn(r,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(r==="leftIndent"||r==="firstLineIndent"){const s=Pr(e,{firstLine:r==="firstLineIndent"});if(s!==void 0)return s}const o=n.match(/^(-?\d+(?:\.\d+)?)(px|pt|in|cm|mm)$/);if(o){const s=Number(o[1]),a=o[2],c={px:1,pt:4/3,in:96,cm:96/2.54,mm:96/25.4};return s*c[a]}if(r==="heading"){const s=n.match(/^h([1-6])$/);if(s)return Number(s[1])}if(r==="lineSpacing"){const s={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(s[n]!==void 0)return s[n]}const i=Number(e);return Number.isFinite(i)?i:Number.NaN}function Le(r,t,e){const n=We(e);r.push({kind:"replace",paragraphId:t,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(e,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(e,n.length,0)),text:n,oldText:n})}function Jt(r){const t=r.getAttribute("id");return typeof t=="string"&&t.length>0?t:r.nodeName}function Wo(r){return li.get(r.trim().toLowerCase())??[]}function Je(r,t,e,n){if(typeof e!="string")throw new Error(`${r} "${t}" expects a string value.`);const o=e.trim();if(o.length===0)throw new Error(`${r} "${t}" expects a non-empty string.`);if(/[<>;]/.test(o))throw new Error(`${r} "${t}" contains unsupported characters.`);if(t==="fontFamily"&&Vg(o))throw new Error(`${r} "fontFamily" does not support CSS-wide values like "inherit"; use a concrete font family such as "Arial, sans-serif".`);const i=o.toLowerCase();if(n&&!n.includes(i))throw new Error(`${r} "${t}" must be one of: ${n.join(", ")}.`);return n?i:o}function Vg(r){const t=r.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(t)}function ui(r,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(`${r} "${t}" expects a boolean value.`)}function Ha(r,t,e){if(typeof e!="string"&&typeof e!="number")return e;const n=r.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 i=Number(o);if(Number.isFinite(i))return i>=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 bn(r,t,e,n){const o=mn(t,e);if(!Number.isFinite(o))throw new Error(`${r} "${t}" expects a number.`);const i=n.integer?Math.round(o):o;if(n.min!==void 0&&i<n.min)throw new Error(`${r} "${t}" must be >= ${n.min}.`);if(n.max!==void 0&&i>n.max)throw new Error(`${r} "${t}" must be <= ${n.max}.`);return i}function Zt(r,t,e,n){const o=Jt(t);if(e){Le(r,o,e);return}const i=`Updated ${n} on ${t.nodeName} block.`;r.push({kind:"replace",paragraphId:o,text:i,oldText:i})}function Jo(r,t){const e=r.parent;if(r.nodeName!=="paragraph"||!(e instanceof x.XmlElement)||e.nodeName!=="footnote"||!r.doc)return null;const n=Ie(r.doc).notes?.find(o=>o.id===e.getAttribute("id"))?.children.find(o=>o.id===r.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 Wa(r){const{toolName:t,yBlock:e,yText:n,attribute:o,operation:i,value:s,config:a,anchors:c}=r;if(!n||e.nodeName!=="paragraph"&&e.nodeName!=="list-item")throw new Error(`${t} "${o}" only supports paragraph or list-item text blocks.`);if(i==="toggle"&&a.valueType!=="boolean")throw new Error(`${t} "${o}" does not support toggle. Use operation "set" with a value or "remove".`);let l;if(i==="remove"||s===null)l=null;else if(i==="toggle")l=!Da(e,n,o);else if(a.valueType==="boolean")l=s===void 0?!0:ui(t,o,s);else{if(s===void 0)throw new Error(`${t} "${o}" requires a value.`);a.valueType==="number"?l=bn(t,o,s,a):l=Je(t,o,s)}if(o==="fontFamily"){const d=Jo(e,l);if(d)throw new Error(d)}if(n.length>0)It(n,0,n.length,{[o]:l===null?null:l}),Le(c,Jt(e),n);else{Oa(e,o,l);const d=`Text mark "${o}" ${l===null?"removed":"set"}.`;c.push({kind:"replace",paragraphId:Jt(e),text:d,oldText:d})}}const Ja=new Set(["fontSize","fontFamily","color"]);function Ya(r){const{toolName:t,yBlock:e,attribute:n,operation:o,value:i,config:s,anchors:a}=r;if(!Ja.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"||i===null)e.removeAttribute(n);else{if(i===void 0)throw new Error(`${t} "${n}" requires a value.`);if(n==="fontSize"){const c=bn(t,n,i,s);if(!$d(c))throw new Error(`${t} "fontSize" on a table of contents must be between ${Bd} and ${_d} px.`);e.setAttribute(n,String(c))}else if(n==="color"){const c=typeof i=="string"?ho(i):void 0;if(!c)throw new Error(`${t} "color" expects a CSS color string or null.`);e.setAttribute(n,c)}else e.setAttribute(n,Je(t,n,i))}Zt(a,e,null,n)}function Gg(r){const{yBlock:t}=r;if(t.nodeName==="paragraph"||t.nodeName==="list-item"){Wa({...r,yText:_t(t)});return}if(t.nodeName==="toc"){Ya(r);return}const e=[],n=[],o=c=>{for(let l=0;l<c.length;l++){const d=c.get(l);if(d instanceof x.XmlElement&&!r.independentlySelectedTargets?.has(d)){if(d.nodeName==="paragraph"||d.nodeName==="list-item"){e.push(d);continue}if(d.nodeName==="toc"){Ja.has(r.attribute)&&n.push(d);continue}o(d)}}};if(o(t),r.attribute==="fontFamily"&&r.operation!=="toggle"){const c=r.operation==="remove"||r.value===null?null:Je(r.toolName,r.attribute,r.value);for(const l of e){const d=Jo(l,c);if(d)throw new Error(d)}}let i=0;const s=[],a=c=>{try{Wa({...r,yBlock:c,yText:_t(c)}),i++}catch(l){s.push(l instanceof Error?l.message:String(l))}};for(const c of e)a(c);for(const c of n)try{Ya({...r,yBlock:c}),i++}catch(l){s.push(l instanceof Error?l.message:String(l))}if(i===0)throw new Error(s[0]??`${r.toolName} "${r.attribute}" found no descendant text blocks to style.`)}function Zg(r){const{toolName:t,yBlock:e,ranges:n,attribute:o,operation:i,value:s,config:a,anchors:c}=r,l=_t(e);if(!l)throw new Error(`${t} inline selector matched a block without text content.`);let d;if(i==="remove"||s===null?d=null:a.valueType==="boolean"?d=ui(t,o,s):a.valueType==="number"?d=bn(t,o,s,a):d=Je(t,o,s),o==="fontFamily"){const u=Jo(e,d);if(u)throw new Error(u)}for(const u of n)It(l,u.start,u.length,{[o]:d===null?null:d});Le(c,Jt(e),l)}function gi(r){const{toolName:t,yBlock:e,attribute:n,operation:o,value:i,config:s,anchors:a}=r;if(!s.nodeNames.includes(e.nodeName))throw new Error(`${t} "${n}" is not valid for ${e.nodeName} blocks.`);if(n==="indentLevel"&&e.nodeName==="paragraph"){za(e,o,i),Zt(a,e,_t(e),n);return}if(n==="padding"&&e.nodeName==="table-cell"){if(o==="remove"||i===null)rt(e,n);else{const c=bn(t,n,i,s);e.setAttribute(n,JSON.stringify({top:c,right:c,bottom:c,left:c}))}Zt(a,e,null,n);return}if(n==="borders"&&(e.nodeName==="table"||e.nodeName==="table-cell")){if(o==="remove"||i===null)rt(e,"borders");else{const c=Je(t,n,i),l=So(c);if(!l)throw new Error(`${t} "border" expects a CSS border shorthand like "1px solid #cccccc" or "none".`);const d={top:l,right:l,bottom:l,left:l};e.nodeName==="table"&&(d.insideH=l,d.insideV=l);const u=Io(d);u&&e.setAttribute("borders",u)}Zt(a,e,null,"borders");return}if(e.nodeName==="table-cell"&&(n==="borderColor"||n==="borderWidth")){if(o==="remove"||i===null)rt(e,"borders");else{const c=Ur(bt(e,"borders")),l=n==="borderColor"?Je(t,n,i):bn(t,n,i,s),d=["top","right","bottom","left"],u={};for(const p of d){const h=c?.[p]??{style:"single",width:1,color:"#cccccc"};u[p]={...h,...n==="borderColor"?{color:l}:{width:l}}}const g=Io(u);g&&e.setAttribute("borders",g)}Zt(a,e,null,"borders");return}if(o==="remove"||i===null)rt(e,n);else if(o==="toggle"){if(s.valueType!=="boolean")throw new Error(`${t} "${n}" only supports toggle for boolean attributes.`);const c=Ua(bt(e,n));e.setAttribute(n,String(!c))}else{if(i===void 0)throw new Error(`${t} "${n}" requires "value" when operation is "set".`);let c;s.valueType==="string"?c=Je(t,n,i,s.enumValues):s.valueType==="boolean"?c=String(ui(t,n,i)):c=String(bn(t,n,i,s)),e.nodeName==="paragraph"&&(n==="leftIndent"||n==="firstLineIndent")?Xa(e,n,Number(c)):e.setAttribute(n,c)}Zt(a,e,_t(e),n)}function Qg(r){if(r.config.nodeNames.includes(r.yBlock.nodeName)){gi(r);return}if(!(r.config.nodeNames.includes("paragraph")||r.config.nodeNames.includes("list-item"))){gi(r);return}let t=0;const e=[],n=o=>{for(let i=0;i<o.length;i++){const s=o.get(i);if(s instanceof x.XmlElement&&!r.independentlySelectedTargets.has(s)){if(s.nodeName==="paragraph"||s.nodeName==="list-item"){try{gi({...r,yBlock:s}),t++}catch(a){e.push(a instanceof Error?a.message:String(a))}continue}n(s)}}};if(n(r.yBlock),t===0)throw new Error(e[0]??`${r.toolName} "${r.attribute}" found no descendant text blocks to style.`)}function th(r){const t=[],e=n=>{n.nodeName!=="footnote"&&n.nodeName!=="header-footer"&&t.push(n);for(let o=0;o<n.length;o++){const i=n.get(o);i instanceof x.XmlElement&&e(i)}};for(const n of[Pn(r),r.getXmlFragment("notes")])for(const o of n.toArray())o instanceof x.XmlElement&&e(o);return t}function hi(r){switch(r.nodeName){case"paragraph":{const t=r.getAttribute("heading");return typeof t=="string"&&/^[1-6]$/.test(t)?[`h${t}`]:["p"]}case"list":return r.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[r.nodeName]}}function eh(r,t){const e=[],n=o=>{for(let i=0;i<o.length;i++){const s=o.get(i);s instanceof x.XmlElement&&(hi(s).includes(t)&&e.push(s),n(s))}};return n(r),e}function nh(r){const t=r.match(/^#([A-Za-z0-9_-]+)\s+([a-zA-Z][a-zA-Z0-9-]*)$/);return t?{id:t[1],tag:t[2].toLowerCase()}:null}function jn(r){return r.toLowerCase()==="th"?"td":r.toLowerCase()}function pi(r){const t=r.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:jn(t[1]),nthChild:e}}function Un(r,t){if(t.tag!=="*"&&!hi(r).includes(t.tag))return!1;if(t.nthChild===void 0)return!0;const e=r.parent;if(!(e instanceof x.XmlElement)&&!(e instanceof x.XmlFragment))return!1;const n=e.toArray().filter(i=>i instanceof x.XmlElement),o=n.indexOf(r)+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 Ka(r,t){if(!Un(r,t[t.length-1]))return!1;let e=r.parent;for(let n=t.length-2;n>=0;n--){for(;e instanceof x.XmlElement&&!Un(e,t[n]);)e=e.parent;if(!(e instanceof x.XmlElement))return!1;e=e.parent}return!0}const fi={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 oh(r){const t=r.split(/\s+/).filter(Boolean),e=t.findIndex(o=>fi[o.toLowerCase()]!==void 0);if(e<0)return null;const n=t.slice(e).map(o=>o.toLowerCase());return n.some(o=>!fi[o])?null:{scopeSelector:e===0?"*":t.slice(0,e).join(" "),markAttributes:Array.from(new Set(n.map(o=>fi[o])))}}function rh(r){if(r.nodeName==="paragraph"||r.nodeName==="list-item")return[r];const t=[],e=n=>{for(let o=0;o<n.length;o++){const i=n.get(o);i instanceof x.XmlElement&&(i.nodeName==="paragraph"||i.nodeName==="list-item"?t.push(i):e(i))}};return e(r),t}function ih(r,t){if(t==="*")return!0;const e=r?.[t];return t==="link"||t==="backgroundColor"?typeof e=="string"&&e.length>0:e===!0}function sh(r,t){const e=[];let n=0;for(const o of mt(r)){if(typeof o.insert!="string")continue;const i=o.insert.length,s=o.attributes;if(i>0&&t.every(a=>ih(s,a))){const a=e[e.length-1];a&&a.start+a.length===n?a.length+=i:e.push({start:n,length:i})}n+=i}return e}function ah(r,t){const e=[...r,...t].sort((o,i)=>o.start-i.start),n=[];for(const o of e){const i=n[n.length-1];i&&o.start<=i.start+i.length?i.length=Math.max(i.length,o.start+o.length-i.start):n.push({...o})}return n}function ch(r){const t=Array.isArray(r)?r:[r],e=[],n=new Set;for(const o of t){if(typeof o!="string")throw new Error("style_blocks selectors must be strings.");for(const i of o.split(",")){const s=i.trim(),a=["all","document",":root"].includes(s.toLowerCase())?"*":s.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 Va(r,t){const e=th(r),n=[],o=new Set,i=[],s=[],a=c=>{const l=Jt(c),d=`${c.nodeName}:${l}`;o.has(d)||(o.add(d),n.push(c))};for(const c of t){if(c==="*"){for(const m of e)a(m);continue}const l=c.match(/^(p|h[1-6]|li)\[data-style-id=(?:"([^"]+)"|'([^']+)'|([^\]]+))\]$/i);if(l){const m=jn(l[1]),y=(l[2]??l[3]??l[4]).trim(),b=e.filter(k=>Un(k,{tag:m})&&k.getAttribute("styleId")===y);b.length===0&&i.push(c);for(const k of b)a(k);continue}const d=c.match(/^#([A-Za-z0-9_-]+)\s*~\s*(\*|[a-zA-Z][a-zA-Z0-9-]*)$/);if(d){const m=at(r,d[1]),y=m?.parent;if(!m||!(y instanceof x.XmlElement)&&!(y instanceof x.XmlFragment)){i.push(c);continue}const b=y.toArray(),k=b.indexOf(m),v=jn(d[2]),S=e.filter(I=>I.parent===y&&b.indexOf(I)>k&&Un(I,{tag:v}));S.length===0&&i.push(c);for(const I of S)a(I);continue}const u=c.match(/^#([A-Za-z0-9_-]+)\s+(.+)$/);if(u){const m=at(r,u[1]);if(!m){i.push(c);continue}const y=u[2].split(/\s+/).filter(Boolean).map(pi);if(y.some(S=>S===null)){s.push(`selector "${c}" is not supported; descendants may use block tags, :first-child, and :nth-child(n).`);continue}const b=y,k=S=>{let I=S;for(;I;){if(I===m)return!0;I=I.parent}return!1},v=e.filter(S=>k(S)&&(b.length!==1||b[0].tag!=="*"||S!==m)&&Ka(S,b));v.length===0&&i.push(c);for(const S of v)a(S);continue}const g=nh(c);if(g){if(g.tag==="span"){s.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}const m=at(r,g.id);if(!m){i.push(c);continue}const y=eh(m,jn(g.tag));if(y.length===0){i.push(c);continue}for(const b of y)a(b);continue}if(c.includes(" ")&&!c.startsWith("#")){const m=c.split(/\s+/).filter(Boolean).map(pi);if(m.some(k=>k===null)){s.push(`selector "${c}" 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")){s.push(`selector "${c}" contains an inline selector; target its containing block instead.`);continue}const b=e.filter(k=>Ka(k,y));b.length===0&&i.push(c);for(const k of b)a(k);continue}if(c.startsWith("#")){const m=c.slice(1).trim();if(!m||/[\s.#:[\]>+~]/.test(m)){s.push(`selector "${c}" is not supported; use #blockId with a plain block ID.`);continue}const y=at(r,m);y?a(y):i.push(c);continue}const p=pi(c);if(p){let m=0;for(const y of e)Un(y,p)&&(a(y),m+=1);m===0&&i.push(c);continue}if(!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(c)){s.push(`selector "${c}" is not supported; use *, #id, or tag selectors like p, h2, li, table.`);continue}const h=jn(c);if(h==="span"){s.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}let f=0;for(const m of e)hi(m).includes(h)&&(a(m),f++);f===0&&i.push(c)}return{targets:n,unmatchedSelectors:i,invalidSelectorErrors:s}}function lh(r,t){const e=ch(t),n=[],o=[];for(const l of e){const d=oh(l);d?o.push({selector:l,parsed:d}):n.push(l)}const i=n.length>0?Va(r,n):{targets:[],unmatchedSelectors:[],invalidSelectorErrors:[]},s=new Map,a=[...i.unmatchedSelectors],c=[...i.invalidSelectorErrors];for(const{selector:l,parsed:d}of o){const u=Va(r,[d.scopeSelector]);if(u.invalidSelectorErrors.length>0){c.push(...u.invalidSelectorErrors.map(h=>`selector "${l}": ${h}`));continue}let g=0;const p=new Set;for(const h of u.targets)for(const f of rh(h)){const m=Jt(f);if(p.has(m))continue;p.add(m);const y=_t(f);if(!y)continue;const b=sh(y,d.markAttributes);if(b.length===0)continue;g+=b.length;const k=s.get(m);k?k.ranges=ah(k.ranges,b):s.set(m,{yBlock:f,ranges:b})}g===0&&a.push(l)}return{targets:i.targets,inlineTargets:Array.from(s.values()),unmatchedSelectors:a,invalidSelectorErrors:c}}function Ye(r){return r.trim().toLowerCase().replace(/[-_\s]/g,"")}function dh(r){let t;if(Array.isArray(r))t=r.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(r&&typeof r=="object")t=Object.entries(r);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:Ye(e),value:n}))}function uh(r){const t=[],e=[],n=new Set,o=(i,s,a)=>{const c=`${s.kind}:${s.attr}`;let l=a;if(s.kind==="textMark"&&s.attr==="color"||s.kind==="block"&&(s.attr==="borderColor"||s.attr==="backgroundColor")){if(a!==null&&typeof a!="string")throw new Error(`style_blocks "${s.attr}" expects a CSS color string or null.`);if(typeof a=="string"&&(l=ho(a),!l))throw new Error(`style_blocks "${s.attr}" does not support ${JSON.stringify(a)}. Use a CSS named color, hex color, or CSS color function.`)}if(s.attr==="variant"&&typeof a=="string"){const u=a.trim().toLowerCase();["decimal","number","numbered","numeric","ol"].includes(u)?l="ordered":["disc","circle","square","bullet","bulleted","ul"].includes(u)?l="unordered":["check","checklist","checkbox","task"].includes(u)&&(l="todo")}const d={rawName:i,entry:s,value:l};if(n.has(c)){const u=t.findIndex(g=>`${g.entry.kind}:${g.entry.attr}`===c);u>=0&&(t[u]=d);return}n.add(c),t.push(d)};for(const{rawName:i,value:s}of r){if(i.trim().toLowerCase()==="border"){if(typeof s=="string"&&So(s)){for(const d of Wo("borders"))o(i,d,s);continue}const c=Wo("borderWidth"),l=Wo("borderColor");if(s===null||typeof s=="number"){for(const d of c)o(i,d,s);if(s===null)for(const d of l)o(i,d,null);continue}if(typeof s=="string"){const d=s.match(/(?:^|\s)(\d+(?:\.\d+)?)(?:px|pt)?(?:\s|$)/i),u=Array.from(s.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(g=>!["solid","dashed","dotted","double","none"].includes(g[1].toLowerCase()));if(d)for(const g of c)o(i,g,d[1]);if(u)for(const g of l)o(i,g,u[1]);if(d||u)continue}e.push(i);continue}const a=Wo(i);if(a.length===0){e.push(i);continue}for(const c of a)o(i,c,s)}return Object.assign(t,{unsupportedAttrs:e})}function Ga(r,t,e){const n=new Map;for(const i of r){const s=Ye(i.rawName),a=n.get(s)??[];a.push(i),n.set(s,a)}const o=[];for(const i of n.values()){const s=i.filter(l=>l.entry.kind==="textMark"),a=i.filter(l=>l.entry.kind==="block");if(s.length===0&&a.length>1){const l=a.filter(d=>d.entry.kind==="block"&&d.entry.nodeNames.some(u=>u===t.nodeName));o.push(...l.length?l:i);continue}if(s.length===0||a.length===0){o.push(...i);continue}if(e){o.push(...s);continue}const c=a.filter(l=>l.entry.kind==="block"&&l.entry.nodeNames.some(d=>d===t.nodeName));o.push(...c.length>0?c:s)}return o}function Za(r){const t=[];for(const e of r){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: ${Bn.join(", ")}.`);const n=e.value.trim(),o=ue(n);if(!o)throw new Error(`style_blocks "backgroundColor" does not support ${JSON.stringify(n)} as a text highlight. Use one of: ${Bn.join(", ")}.`);e.value=o,n.toLowerCase()!==o&&t.push(`${e.rawName}: ${n} -> ${o}`)}return t}function yn(r,t,e,n){r[e].push(n);const o=r.issuesByRawName.get(t.canonicalName)??[];o.push(n),r.issuesByRawName.set(t.canonicalName,o)}function Yo(r,t){for(let e=r.length-1;e>=0;e--)if(r[e].canonicalName===t)return r[e]}function he(r){return typeof r=="string"?r.trim().toLowerCase():void 0}function qn(r){if(typeof r!="string")return;const t=r.trim().match(/^(-?\d+(?:\.\d+)?)%$/);if(!t)return;const e=Number(t[1]);return Number.isFinite(e)&&e>0?e:void 0}function Ko(r){return r===0?!0:typeof r=="string"&&/^[-+]?0+(?:\.0+)?(?:px|pt|in|cm|mm|%)?$/i.test(r.trim())}function gh(r){let t=r;for(;t.parent instanceof x.XmlElement;)t=t.parent;return t}function mi(r,t){const e=Jt(gh(t)),n=r.children.findIndex(l=>l.id===e),o=n>=0?r.children.slice(n).find(l=>l.type==="section-break"):void 0,i=Cs(r.pageLayout,o?.type==="section-break"?o.layout:void 0),{pageWidth:s}=Ar(i),a=Math.max(1,s-i.marginLeftPx-i.marginRightPx),c=i.columnGapTwips/15;return Math.max(1,Math.round(uu(a,i.columnCount,c)))}function hh(r){if(r===null)return{remove:!0};if(typeof r=="number")return!Number.isFinite(r)||r<0?null:r===0?{remove:!0}:{remove:!1,style:"single",width:r};if(typeof r!="string")return null;const t=r.trim(),e=t.toLowerCase();if(e==="none"||Ko(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|$)/),i=Array.from(t.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(l=>!["solid","double","dashed","dotted","none"].includes(l[1].toLowerCase()));if(!n&&!o&&!i)return null;if(o?.[1]==="none")return{remove:!0};const s=n?Number(n[1]):void 0,a=s===void 0?void 0:n?.[2]?.toLowerCase()==="pt"?s*(4/3):s,c=o?.[1];return{remove:!1,style:c==="double"||c==="dashed"||c==="dotted"?c:"single",...a!==void 0?{width:a}:{},...i?{color:i[1]}:{}}}function ph(r){if(r.yBlock.nodeName!=="paragraph")return;const t={bordertop:"top",borderright:"right",borderbottom:"bottom",borderleft:"left"};for(const e of r.rawAttrs){const n=t[e.canonicalName];if(e.canonicalName!=="border"&&!n)continue;r.result.handledRawNames.add(e.canonicalName);const o=hh(e.value);if(!o){yn(r.result,e,"errors",`${Jt(r.yBlock)}.borders: style_blocks "${e.rawName}" expects CSS border syntax such as "1px solid #cccccc".`);continue}let i={};try{const a=JSON.parse(String(bt(r.yBlock,"borders")??"{}"));a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{i={}}const s=n?[n]:["top","right","bottom","left"];if(o.remove)for(const a of s)delete i[a];else for(const a of s){const c=i[a]??{style:"single",width:1,color:"#000000"};i[a]={style:o.style??c.style,width:o.width??c.width,color:o.color??c.color}}Object.keys(i).length>0?r.yBlock.setAttribute("borders",JSON.stringify(i)):rt(r.yBlock,"borders"),Zt(r.anchors,r.yBlock,_t(r.yBlock),"borders"),r.result.appliedAttrs.push(`${e.rawName} -> paragraph borders`),r.result.exactMappings.push(`${e.rawName} -> paragraph borders`)}}function fh(r){if(r.yBlock.nodeName!=="image")return;const t=I=>Yo(r.rawAttrs,I),e=t("display");e&&he(e.value)==="block"&&(r.result.handledRawNames.add(e.canonicalName),yn(r.result,e,"ignoredAttrs",`${e.rawName}: block`));const n=t("float"),o=he(n?.value);n&&(o==="left"||o==="right")&&(r.result.handledRawNames.add(n.canonicalName),r.yBlock.setAttribute("align",o),Zt(r.anchors,r.yBlock,null,"align"),r.result.appliedAttrs.push(`${n.rawName} -> align`),r.result.approximateMappings.push(`${n.rawName}: ${o} -> align: ${o} without text wrapping`));const i=t("marginleft"),s=t("marginright"),a=he(i?.value),c=he(s?.value);let l;a==="auto"&&c==="auto"?l="center":a==="auto"&&(!s||Ko(s.value))?l="right":c==="auto"&&(!i||Ko(i.value))&&(l="left"),l&&(i&&r.result.handledRawNames.add(i.canonicalName),s&&r.result.handledRawNames.add(s.canonicalName),r.yBlock.setAttribute("align",l),Zt(r.anchors,r.yBlock,null,"align"),r.result.appliedAttrs.push("auto margins -> align"),r.result.exactMappings.push(`margin-left/margin-right auto -> align: ${l}`));for(const I of["margintop","marginright","marginbottom","marginleft"]){const w=t(I);!w||r.result.handledRawNames.has(w.canonicalName)||(r.result.handledRawNames.add(w.canonicalName),Ko(w.value)?yn(r.result,w,"ignoredAttrs",`${w.rawName}: ${String(w.value)}`):yn(r.result,w,"unsupportedImageSpacing",`${w.rawName}: ${String(w.value)}`))}const d=t("width"),u=t("maxwidth"),g=t("height"),p=he(g?.value)==="auto",h=qn(d?.value),f=qn(u?.value),m=mi(r.doc,r.yBlock),y=Math.max(1,Number(r.yBlock.getAttribute("width"))||1),b=Math.max(1,Number(r.yBlock.getAttribute("height"))||1);let k=y,v=!1,S=!1;if(h!==void 0&&d)k=Math.max(1,Math.round(m*h/100)),r.result.handledRawNames.add(d.canonicalName),v=!0,S=!0;else if(p&&d){const I=mn("width",d.value);Number.isFinite(I)&&I>0&&(k=Math.max(1,Math.round(I)),r.result.handledRawNames.add(d.canonicalName),v=!0,S=!0)}if(f!==void 0&&u){const I=Math.max(1,Math.round(m*f/100));k=Math.min(k,I),r.result.handledRawNames.add(u.canonicalName),v=!0,r.result.approximateMappings.push(`${u.rawName}: ${String(u.value)} -> fixed ${k}px snapshot`)}if(v){r.yBlock.setAttribute("width",String(k));const I=g&&!p?mn("height",g.value):Number.NaN,w=p||!Number.isFinite(I);if(w){const A=Math.max(1,Math.round(b*k/y));r.yBlock.setAttribute("height",String(A))}p&&g&&r.result.handledRawNames.add(g.canonicalName),Zt(r.anchors,r.yBlock,null,"width/height"),r.result.appliedAttrs.push("responsive image size -> fixed snapshot"),S&&d&&r.result.approximateMappings.push(`${d.rawName}: ${String(d.value)} -> fixed ${k}px snapshot${w?" with auto height":""}`)}else p&&g&&(r.result.handledRawNames.add(g.canonicalName),yn(r.result,g,"ignoredAttrs",`${g.rawName}: auto`))}function mh(r){if(r.yBlock.nodeName!=="table")return;const t=s=>Yo(r.rawAttrs,s),e=t("width"),n=qn(e?.value);if(e&&n!==void 0){const s=mi(r.doc,r.yBlock),a=Math.max(1,Math.round(s*n/100));r.result.handledRawNames.add(e.canonicalName),r.yBlock.setAttribute("tableWidth",String(a)),Zt(r.anchors,r.yBlock,null,"tableWidth"),r.result.appliedAttrs.push("responsive table width -> fixed snapshot"),r.result.approximateMappings.push(`${e.rawName}: ${String(e.value)} -> fixed ${a}px snapshot`)}const o=t("marginleft"),i=t("marginright");he(o?.value)==="auto"&&he(i?.value)==="auto"&&(r.result.handledRawNames.add(o.canonicalName),r.result.handledRawNames.add(i.canonicalName),r.yBlock.setAttribute("align","center"),Zt(r.anchors,r.yBlock,null,"align"),r.result.appliedAttrs.push("auto margins -> align"),r.result.exactMappings.push("margin-left/margin-right auto -> align: center"))}function bh(r){if(r.yBlock.nodeName!=="paragraph")return;const t=a=>Yo(r.rawAttrs,a),e=t("breakafter"),n=t("breakbefore"),o=t("breakinside");if(!e&&!n&&!o)return;const i=new Set(String(bt(r.yBlock,"pagination")??"").split(",").filter(Boolean));e&&(r.result.handledRawNames.add(e.canonicalName),e.value===null||he(e.value)==="auto"?i.delete("keepNext"):["avoid","avoid-page"].includes(he(e.value)??"")&&i.add("keepNext"),r.result.appliedAttrs.push(`${e.rawName} -> keepNext`)),o&&(r.result.handledRawNames.add(o.canonicalName),o.value===null||he(o.value)==="auto"?i.delete("keepLines"):["avoid","avoid-page"].includes(he(o.value)??"")&&i.add("keepLines"),r.result.appliedAttrs.push(`${o.rawName} -> keepLines`)),n&&(r.result.handledRawNames.add(n.canonicalName),yn(r.result,n,"ignoredAttrs",`${n.rawName}: ${String(n.value)}`));const s=Array.from(i).join(",");s?r.yBlock.setAttribute("pagination",s):rt(r.yBlock,"pagination"),Zt(r.anchors,r.yBlock,_t(r.yBlock),"pagination")}function yh(r){const t={issuesByRawName:new Map,handledRawNames:new Set,appliedAttrs:[],exactMappings:[],approximateMappings:[],ignoredAttrs:[],unsupportedImageSpacing:[],errors:[]};return ph({yBlock:r.yBlock,rawAttrs:r.rawAttrs,anchors:r.anchors,result:t}),bh({...r,result:t}),fh({...r,result:t}),mh({...r,result:t}),t}function kh(r){const{inlineRangeCount:t,unsupportedAttrs:e,unmatchedSelectors:n,invalidSelectorErrors:o,skippedTargetErrors:i,exactCompatibilityMappings:s,approximateCompatibilityMappings:a,ignoredCompatibilityAttrs:c,unsupportedImageSpacing:l}=r,d=r.styleEffects,u=[`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(g=>`${g.name}: applied to ${g.appliedBlockIds.length} targets (including already-equal values), skipped on ${new Set(g.skipped.map(p=>p.blockId)).size}.`)];if(s.length>0&&u.push(`Compatibility mappings: ${Array.from(new Set(s)).join("; ")}.`),a.length>0&&u.push(`Approximate compatibility mappings: ${Array.from(new Set(a)).join("; ")}.`),c.length>0&&u.push(`Ignored compatibility attrs: ${Array.from(new Set(c)).join(", ")}.`),l.length>0&&u.push(`Unsupported image spacing ignored: ${Array.from(new Set(l)).join(", ")}.`),n.length>0&&u.push(`Unmatched selectors: ${n.join(", ")}.`),o.length>0&&u.push(`Invalid selectors ignored: ${o.join("; ")}.`),e.length>0&&u.push(`Unsupported attrs ignored: ${e.join(", ")}.`),i.length>0){const g=Array.from(new Set(i)),p=g.slice(0,12),h=g.length-p.length;u.push(`Skipped invalid target/style pairs: ${p.join("; ")}${h>0?`; and ${h} more`:""}.`)}return u.join(" ")}function Sh(r){const t=Ve(r.getAttribute("_emptyTextMarks"));for(const e of Gs)delete t[e];Object.keys(t).length===0?r.removeAttribute("_emptyTextMarks"):r.setAttribute("_emptyTextMarks",JSON.stringify(t))}function Ih(r,t=1){if(typeof r!="number"||!Number.isFinite(r))return t;const e=Math.floor(r);return e>=1?e:t}function vh(r){const t=_t(r);if(t){const n=mt(t);let o="";for(const i of n)i.insert&&typeof i.insert=="string"&&(o+=i.insert);return o}const e=r.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 Qa(r,t,e){const n=vh(r),o=_t(r),i=t&&t.length>0?t:void 0;if(o&&n.length>0){e.push({kind:"delete",paragraphId:i,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(o,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(o,n.length,0)),text:n});return}e.push({kind:"delete",paragraphId:i,text:n})}function xh(r,t){const e=r.parent;if(!(e instanceof x.XmlElement)&&!(e instanceof x.XmlFragment)||r.nodeName!=="list")return!1;const n=e.toArray().indexOf(r);if(n<0)return!1;const o=[];for(const i of r.toArray()){if(!(i instanceof x.XmlElement)||i.nodeName!=="list-item")continue;const s=new x.XmlElement("paragraph");s.setAttribute("id",i.getAttribute("id")||et());const a=bt(i,"direction");(a==="ltr"||a==="rtl")&&s.setAttribute("direction",a);const c=i.getAttribute("_emptyTextMarks");c&&s.setAttribute("_emptyTextMarks",c);const l=_t(i),d=new x.XmlText;l&&Md(d,mt(l)),s.insert(0,[d]),o.push(s)}if(o.length===0)return!1;Qa(r,r.getAttribute("id"),t),e.delete(n,1),e.insert(n,o);for(const i of o){const s=_t(i);if(!s)continue;const a=We(s);t.push({kind:"insert",paragraphId:i.getAttribute("id"),from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(s,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(s,a.length,0)),text:a})}return!0}function tc(r,t){if(t.link)return[{text:r,marks:t}];const e=Na(r);if(e.length===0)return[{text:r,marks:t}];const n=[];let o=0;for(const i of e)i.start>o&&n.push({text:r.slice(o,i.start),marks:t}),n.push({text:i.originalText,marks:{...t,link:i.url}}),o=i.end;return o<r.length&&n.push({text:r.slice(o),marks:t}),n}function Vo(r){return Ut(Ps(r,t=>!t.text||t.marks?.link?t:tc(t.text,t.marks||{}).map(e=>({type:"text",text:e.text,marks:e.marks}))))}function ec(r,t){return _n(Eu(t==="todo"?{...r,checked:r.checked??!1}:r))}function nc(r,t,e,n=!1){return r.flatMap(o=>{if(o.type==="list")return o.children.map(i=>({...i,indentLevel:(n?0:t)+(i.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,i)=>({...o,id:i===0?e:o.id||et()}))}function Ne(r,t,e,n){const o=tc(e,n);let i=t;for(const s of o)kt(r,i,s.text,s.marks),i+=s.text.length;return i}function oc(r,t,e){const n=r.toString(),o=e??n.length,i=n.slice(t,o),s=Na(i);for(const a of s){const c=t+a.start;It(r,c,a.end-a.start,{link:a.url})}}function bi(r,t){if(!Mn(r,t)||r.children.length!==t.children.length)return!1;for(let e=0;e<r.children.length;e++){const n=r.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 Go(r,t){const e=["heading","align","leftIndent","firstLineIndent","spaceBefore","spaceAfter","lineSpacing","styleId","direction","borders","shading","tabStops"];for(const o of e){const i=t[o];i===void 0?rt(r,o):r.setAttribute(o,String(i))}const n=xe(t);n===void 0?rt(r,"pagination"):r.setAttribute("pagination",n)}function wh(r,t){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++){const n=r[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 Ah(r,t){return r.type!==t.type?!1:r.type==="paragraph"&&t.type==="paragraph"?bi(r,t):wh(r.children,t.children)}function rc(r){return r.map(t=>({...t,marks:t.marks?{...t.marks}:void 0}))}function ic(r,t){const e=n=>{for(const o of n){if(o.type==="paragraph"&&o.id===t)return o;if(o.type==="list"){for(const i of o.children)if(i.id===t)return i;continue}if(o.type==="container"||o.type==="table-cell"){const i=e(o.children);if(i)return i;continue}if(o.type==="table")for(const i of o.children)for(const s of i.children){const a=e(s.children);if(a)return a}}return null};return e(r.children)}function sc(r){return r.replace(/&#0?39;|&apos;/g,"'").trim()}function Th(r,t,e){const n=r.indexOf(t);return n===-1?r:r.slice(0,n)+e+r.slice(n+t.length)}function Ch(r,t){if(t.type==="paragraph")return sc(it.toAgentHtml({type:"doc",children:[{...t,children:rc(t.children)}]}));if(r.listVariant==="todo")return null;const e={type:"list",id:"__agent_html_replace__",variant:r.listVariant==="ordered"?"ordered":"unordered",children:[{...t,children:rc(t.children),indentLevel:void 0}]},n=sc(it.toAgentHtml({type:"doc",children:[e]})).match(/^<(?:ul|ol)(?:\s[^>]*)?>([\s\S]*)<\/(?:ul|ol)>$/);return n?n[1].trim():null}function Ph(r,t,e,n){try{if(e.type==="paragraph"){const s=it.fromAgentHtml(t,{existingDocument:n,replacementBlock:e});return s.children.length!==1||s.children[0].type!=="paragraph"?null:s.children[0]}if(r.listVariant==="todo")return null;const o=r.listVariant==="ordered"?"ol":"ul",i=it.fromAgentHtml(`<${o}>${t}</${o}>`,{existingDocument:n});return i.children.length!==1||i.children[0].type!=="list"||i.children[0].children.length!==1?null:i.children[0].children[0]}catch{return null}}function Mh(r,t){const e=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/i,n=r.match(e),o=t.match(e),i=n?.[1]??n?.[2],s=o?.[1]??o?.[2];if(!i||!s||i===s)return null;const a=ue(i),c=ue(s);return!a||a!==c?null:`Highlight colors ${JSON.stringify(i)} and ${JSON.stringify(s)} both resolve to ${JSON.stringify(a)}, so this replacement is a no-op. Use a different canonical highlight color: ${Bn.join(", ")}.`}function $h(r){const t=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/gi;for(const e of r.matchAll(t)){const n=e[1]??e[2];if(n&&!ue(n))throw new Error(`Unsupported highlight color ${JSON.stringify(n)}. Use one of: ${Bn.join(", ")}.`)}}function ac(r){const t=r?.comment;return typeof t!="string"||t.length===0?[]:Array.from(new Set(t.split(",").map(e=>e.trim()).filter(Boolean))).sort()}function Fe(r,t={}){const e=Object.entries(r??{}).filter(([n,o])=>o!==void 0&&(n!=="comment"||!t.ignoreComment)).map(([n,o])=>n==="comment"?[n,ac(r).join(",")]:[n,o]).filter(([,n])=>n!=="").sort(([n],[o])=>n<o?-1:n>o?1:0);return JSON.stringify(e)}function Bh(r){return Object.fromEntries(Object.entries(r).sort(([t],[e])=>t<e?-1:t>e?1:0))}function Zo(r){return r.flatMap(t=>{const{comment:e,...n}=t.marks??{},o=ac(t.marks);return Array.from({length:t.text.length},(i,s)=>({value:t.text[s],marks:n,comment:o}))})}function _h(r){return r.length===0?[]:r.reduce((t,e)=>t.filter(n=>e.includes(n)))}const Ke=-1,yi=0,zn=1;function Lh(r){const t=[];for(let e=0;e<r.length;e++){const[n,o]=r[e],i=r[e+1];if(!(i!==void 0&&(n===Ke&&i[0]===zn||n===zn&&i[0]===Ke))){t.push([n,o]);continue}const s=n===Ke?o:i[1],a=n===zn?o:i[1];let c=0;const l=Math.min(s.length,a.length);for(;c<l&&s[c]===a[c];)c++;let d=0;const u=l-c;for(;d<u&&s[s.length-1-d]===a[a.length-1-d];)d++;c>0&&t.push([yi,s.slice(0,c)]);const g=s.slice(c,s.length-d),p=a.slice(c,a.length-d);g.length>0&&t.push([Ke,g]),p.length>0&&t.push([zn,p]),d>0&&t.push([yi,s.slice(s.length-d)]),e++}return t}function Nh(r,t){const e=Zo(r),n=Zo(t),o=Lh(ii([],e.map(d=>d.value).join(""),n.map(d=>d.value).join(""))),i=new Array(n.length),s=new Array(n.length);let a=0,c=0;for(let d=0;d<o.length;d++){const[u,g]=o[d];if(u===yi){for(let v=0;v<g.length;v++)i[c+v]=e[a+v].comment,s[c+v]=e[a+v].marks.lang;a+=g.length,c+=g.length;continue}if(u===Ke){a+=g.length;continue}if(u!==zn)continue;const p=o[d-1],h=o[d+1],f=[];p?.[0]===Ke&&f.push(...e.slice(a-p[1].length,a)),h?.[0]===Ke&&f.push(...e.slice(a,a+h[1].length));const m=f.length>0?f:[e[a-1],e[a]].filter(v=>!!v),y=_h(m.map(v=>v.comment)),b=m[0]?.marks.lang,k=typeof b=="string"&&m.every(v=>v.marks.lang===b)?b:void 0;for(let v=0;v<g.length;v++)i[c+v]=y,s[c+v]=k;c+=g.length}const l=[];return n.forEach((d,u)=>{const g=i[u]??[],p=Bh({...d.marks,...d.marks.lang===void 0&&s[u]!==void 0?{lang:s[u]}:{},...g.length>0?{comment:g.join(",")}:{}}),h=l[l.length-1];h&&Fe(h.marks)===Fe(p)?h.text+=d.value:l.push({type:"text",text:d.value,...Object.keys(p).length>0?{marks:p}:{}})}),l}function Fh(r,t){const e=Zo(r),n=Zo(t);return e.length===n.length&&e.every((o,i)=>o.value===n[i].value&&Fe(o.marks)===Fe(n[i].marks)&&o.comment.join(",")===n[i].comment.join(","))}function cc(r,t,e,n,o){if(e=un(e),n=un(n),e.length===0)return null;const i=ic(t,r.blockId);if(!i)return null;const s=Ch(r,i),a=s?un(s):null;if(!a||!a.includes(e))return null;const c=oa(a,e).length;if(!o&&c>1)throw new Error(`Found ${c} matches for ${JSON.stringify(e)} in block '${r.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.`);$h(n);const l=o?a.split(e).join(n):Th(a,e,n);if(l===a)return null;const d=Ph(r,l,i,t);if(!d)throw new Error(`Matched AgentHtml in block '${r.blockId}', but the replacement is not a supported single-block text update.`);if(d.type!==i.type)throw new Error(`Matched AgentHtml in block '${r.blockId}', but the replacement changes the block structure. Keep replace() within a single compatible text block.`);const u={...d,children:Nh(i.children,Do(i.children,d.children))};if(Ah(i,u)||Fh(i.children,u.children)&&(i.type!=="paragraph"||u.type!=="paragraph"||Mn(i,u)))throw new Error(Mh(e,n)??`Matched AgentHtml in block '${r.blockId}', but the replacement would not change any supported text or formatting.`);return{blockId:r.blockId,yBlock:r.yBlock,currentBlock:i,replacementBlock:u}}function Qo(r,t){const e=_t(r.yBlock);if(!e)throw new Error(`Target block '${r.blockId}' has no text content to replace.`);const n=h=>h.flatMap(f=>Array.from({length:f.text.length},(m,y)=>({value:f.text[y],marks:f.marks||{}}))),o=(h,f)=>h.value===f.value&&Fe(h.marks)===Fe(f.marks),i=n(r.currentBlock.children),s=n(r.replacementBlock.children);let a=0;for(;a<i.length&&a<s.length&&o(i[a],s[a]);)a++;let c=0;for(;c<i.length-a&&c<s.length-a&&o(i[i.length-c-1],s[s.length-c-1]);)c++;const l=i.length-a-c,d=s.slice(a,s.length-c),u=x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(e,a,-1));l>0&&e.delete(a,l);let g=a;const p=[];for(let h=0;h<d.length;){const f=d[h].marks;let m=d[h].value;for(h++;h<d.length&&Fe(d[h].marks)===Fe(f);)m+=d[h].value,h++;p.push({type:"text",text:m,marks:f}),g=Ne(e,g,m,f)}r.currentBlock.type==="paragraph"&&r.replacementBlock.type==="paragraph"&&(r.replacementBlock.heading?r.yBlock.setAttribute("heading",String(r.replacementBlock.heading)):r.yBlock.removeAttribute("heading"),r.replacementBlock.align?r.yBlock.setAttribute("align",r.replacementBlock.align):rt(r.yBlock,"align")),t.push({kind:"replace",paragraphId:r.blockId,previewStartOffset:a,sourceFrom:u,previewTextNodes:p,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(e,a,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(e,g,0)),text:d.map(h=>h.value).join(""),oldText:i.slice(a,i.length-c).map(h=>h.value).join("")})}function ve(r,t,e,n){const o=[];zt(t,{verifiedUnchanged:!1,styleEffects:void 0}),ai.delete(t);const i=t.name;n&&i!=="insert_block"&&(n.lastInsertedBlock=void 0);const s=t.arguments;if(i==="replace_many"||i==="replace"&&Array.isArray(s?.replacements)){const a=ni({...t,id:e??"replacement-batch"},{doc:Ie(r),loadedBlockIds:null});if(a.error){const d=a.failure;throw new Nt(d?.code??"invalid_arguments",a.error,d?.phase??"validation",d?.retryable,d?.mutationOutcome,d?.details)}let c=n,l=!0;for(const d of a.actions){const u=d,g=ve(r,u,e,c);if(l=l&&!!ne(u)?.verifiedUnchanged,o.push(...g),!c){const p=Ie(r);c={document:p,htmlParsingContext:it.createParsingContext(p),refreshDocumentIncrementally:!0}}}return zt(t,{verifiedUnchanged:l}),o}switch(t.name){case"insert_block":{const{referenceId:a,position:c,content:l}=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=Ro(t),u=n?.document??Tt(r);if(!Array.isArray(l))throw new Error("insert_block content must be an array");if(l.length!==1)throw new Error("insert_block should only receive a single block after preprocessing. Got array with "+l.length+" items");const g=l[0];let p,h;if(a===Rn)p=Pn(r),h=p.length;else if(n?.lastInsertedBlock&&n.lastInsertedBlock.id===a)p=n.lastInsertedBlock.yParent,h=c==="before"?n.lastInsertedBlock.index:n.lastInsertedBlock.index+1;else{const k=ut(r,a);if(!k)throw new Error(`Reference block '${a}' not found in the current document. Read the document again and use a current block ID.`);p=k.yParent,h=c==="before"?k.index:k.index+1}if((pn(p)||p===r.getXmlFragment("chrome"))&&fn(),p instanceof x.XmlElement&&(p.nodeName==="table"||p.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 f;const m=n?.lastInsertedBlock;if(m?.yParent===p&&m.index===h-1)f=m.block;else if(h>0){const k=p.get(h-1);if(k instanceof x.XmlElement){const v=k.getAttribute("id");v&&(f=n?.lastInsertedBlock?.id===v?n.lastInsertedBlock.block:z(u,v)??void 0)}}let y;if(g.includes("<")&&g.includes(">")?y=it.fromAgentHtml(g,{previousBlock:f,existingDocument:u,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof x.XmlElement&&p.nodeName==="list"?Number(at(r,a)?.getAttribute("indentLevel")??0):void 0}):y=it.fromAgentHtml(`<p>${g}</p>`,{previousBlock:f,existingDocument:u,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof x.XmlElement&&p.nodeName==="list"?Number(at(r,a)?.getAttribute("indentLevel")??0):void 0}),y.children.length!==1)throw new Error(`insert_block should produce exactly one block. Got ${y.children.length} blocks from content: ${g}`);const b=y.children[0];if(!d)throw new Error("insert_block must have stableId set by preprocessor");if(b.id=d,p instanceof x.XmlElement&&p.nodeName==="list"){const k=at(r,a),v=nc([b],Number(k?.getAttribute("indentLevel")??0),d,!0);p.insert(h,v.map(S=>Ut(S))),o.push({kind:"insert",paragraphId:p.getAttribute("id"),text:v.map(S=>S.children.map(I=>I.text).join("")).join(`
24
- `)});break}if(b.type==="paragraph"){const k=b,v=new x.XmlElement("paragraph");v.setAttribute("id",d),Go(v,k);const S=new x.XmlText;let I=0;k.children.forEach(A=>{if(A.type==="text"){const _=A;I=Ne(S,I,_.text,_.marks||{})}}),Ho(v,k,I),v.insert(0,[S]),p.insert(h,[v]);const w=k.children.filter(A=>A.type==="text").map(A=>A.text).join("");o.push({kind:"insert",paragraphId:d,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(S,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(S,w.length,0)),text:w})}else if(b.type==="list"){const k=Vo(b);p.insert(h,[k]);const v=[];for(const S of k.toArray()){if(!(S instanceof x.XmlElement))continue;const I=xt(S);if(!I)continue;const w=mt(I).map(A=>typeof A.insert=="string"?A.insert:"").join("");w.length&&v.push({yText:I,plainText:w})}v.forEach(({yText:S,plainText:I})=>{o.push({kind:"insert",paragraphId:d,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(S,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(S,I.length,0)),text:I})})}else if(b.type==="table"){const k=Vo({...b,id:d});p.insert(h,[k]),o.push({kind:"insert",paragraphId:d,text:"Table inserted"})}else if(b.type==="code"){const k=b,v=new x.XmlElement("code");v.setAttribute("id",d),k.language&&v.setAttribute("language",k.language),k.renderDiagram!==void 0&&v.setAttribute("renderDiagram",String(k.renderDiagram)),k.showDiagramSource!==void 0&&v.setAttribute("showDiagramSource",String(k.showDiagramSource));const S=new x.XmlText;v.insert(0,[S]),kt(S,0,k.content||""),p.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Code block inserted"})}else if(b.type==="math"){const k=b,v=new x.XmlElement("math");v.setAttribute("id",d),k.displayMode&&v.setAttribute("displayMode",k.displayMode),k.align&&v.setAttribute("align",k.align);const S=new x.XmlText;v.insert(0,[S]),kt(S,0,k.content||""),p.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Math block inserted"})}else if(b.type==="page-break"){const k=new x.XmlElement("page-break");k.setAttribute("id",d),p.insert(h,[k]),o.push({kind:"insert",paragraphId:d,text:"Page break inserted"})}else if(b.type==="toc"){const k=Ut({...b,id:d});p.insert(h,[k]),o.push({kind:"insert",paragraphId:d,text:"Table of contents inserted"})}else if(b.type==="image"){const k=b,v=new x.XmlElement("image");v.setAttribute("id",d),v.setAttribute("src",k.src),k.sourceUrl&&v.setAttribute("sourceUrl",k.sourceUrl),v.setAttribute("width",String(k.width)),v.setAttribute("height",String(k.height)),k.alt&&v.setAttribute("alt",k.alt),k.align&&v.setAttribute("align",k.align),p.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 ${b.type}`);n&&(n.lastInsertedBlock={id:d,yParent:p,index:h,block:b},p===r.getXmlFragment("content")?n.document.children.splice(h,0,b):(n.document=Tt(r),n.htmlParsingContext=it.createParsingContext(n.document)));break}case"replace":case"replace_all":{const{id:a}=t.arguments;let{find:c,replace:l}=t.arguments;const d=n?.document??Tt(r),u=at(r,a);if(!u)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);let g=Ug(u,a);const p=aa(ic(d,a)??z(d,a),c);if(p&&(g=g.filter(y=>p.has(y.blockId))),p&&g.length===0)throw new Nt("target_stale","HTML matcher identities no longer resolve to editable text within this target. Read the target again.","target_resolution");if(g.length===0)break;if(c.length===0){if(g.length!==1||g[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=g[0];Si(y.yText,0,0,c,l,y.blockId,o,Ve(y.yBlock.getAttribute("_emptyTextMarks")));break}const h=y=>g.map(b=>({...b,matches:pc(b.blockText,y)})).filter(b=>b.matches.length>0);if(Te(c)){const y=g.map(b=>cc(b,d,c,l,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 "${c}" in block '${a}'. Include more surrounding AgentHtml so it matches exactly one location, or use replace_all.`);if(t.name==="replace")Qo(y[0],o);else for(const b of y)Qo(b,o);break}}let f=h(c);if(f.length===0){const y=gc(c);if(y!==c&&y.trim()!==""){const b=h(y);b.length>0&&(c=y,l=gc(l),f=b)}}if(f.length===0){const y=g.map(I=>cc(I,d,c,l,t.name==="replace_all")).filter(I=>I!==null);if(y.length>0){if(t.name==="replace")Qo(y[0],o);else for(const I of y)Qo(I,o);break}const b=g.map(I=>I.blockText).join(`
25
- `),k=b.length>100?b.slice(0,100)+"...":b,v=Xg(r,a,c),S=/(?:\*\*|__|^>|^#{1,6}\s|^[-*+]\s|^\d+[.)]\s|\|)/m.test(c)?" The requested find contains Markdown syntax, while this preview is stored plain text; formatting markers are not literal characters.":"";throw c.includes("<")&&c.includes(">")?new Nt("text_not_found",`No match found for "${c}" 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.${v}`,"matching"):new Nt("text_not_found",`No match found for "${c}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}.${S} Make sure the text you're searching for exists exactly as written (case-sensitive, including punctuation and spaces).${v}`,"matching")}const m=f.reduce((y,b)=>y+b.matches.length,0);if((t.name==="replace_all"||m===1)&&f.every(y=>y.matches.every(b=>dc(y.yText,b.offset,b.length,c,l)))){zt(t,{verifiedUnchanged:!0});break}if(t.name==="replace"){const y=f.reduce((v,S)=>v+S.matches.length,0);if(y>1)throw new Error(`Found ${y} matches for "${c}" 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=f[0],k=b.matches[0];Si(b.yText,k.offset,k.length,c,l,b.blockId,o)}else for(const y of f){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 v=y.matches[k];Si(y.yText,v.offset,v.length,c,l,y.blockId,o)}}break}case"replace_block":{const{id:a,content:c,count:l}=t.arguments;if(l!==void 0&&(!Number.isFinite(l)||Math.floor(l)<1))throw new Error("replace_block count must be a positive integer.");const d=Ih(l,1),u=n?.document??Tt(r),g=z(u,a);if(!g){const v=u.children.map(S=>S.id).filter(S=>S).slice(0,10);throw console.error(`[ForkActionApplicator] Block with id '${a}' not found. Available IDs:`,v),new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`)}const p=ut(r,a);if(!p)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:h,yParent:f,index:m}=p,y=pn(f);if((h.nodeName==="header-footer"||y&&d!==1)&&fn(),d>1){const v=Math.max(0,f.length-(m+1)),S=Math.min(d-1,v);for(let I=0;I<S;I++){const w=f.get(m+1);if(!(w instanceof x.XmlElement))break;const A=w.getAttribute("id");Qa(w,A??void 0,o),f.delete(m+1,1)}}const b=ee(u,a),k=b>0?u.children[b-1]:void 0;{const v=(Array.isArray(c)?c:[c]).join(""),S=it.fromAgentHtml(v,{previousBlock:k,replacementBlock:g,existingDocument:u,listItemBaseIndent:h.nodeName==="list-item"?Number(h.getAttribute("indentLevel")??0):void 0});if(y&&(S.children.length!==1||S.children[0].type!=="paragraph")&&fn(),h.nodeName==="list-item"&&f instanceof x.XmlElement&&f.nodeName==="list"){const I=nc(S.children,Number(h.getAttribute("indentLevel")??0),a,!0);if(d===1&&I.length===1&&g.type==="list"){const w=g.children.find(A=>A.id===a);if(g.variant==="todo"&&I[0].checked===void 0&&w?.checked!==void 0&&(I[0].checked=w.checked),I[0].children=Do(w?.children??[],I[0].children),w&&ec(w,g.variant)===ec(I[0],g.variant)){zt(t,{verifiedUnchanged:!0});break}}f.delete(m,1),f.insert(m,I.map(w=>Ut(w))),o.push({kind:"replace",paragraphId:f.getAttribute("id"),oldText:"List item",text:I.map(w=>w.children.map(A=>A.text).join("")).join(`
26
- `)});break}if(g.type==="paragraph"){const I=A=>A.children.filter(_=>!_.marks?.footnoteRef),w=it.extractUniformTextFontFamily(I(g));if(w){for(const A of S.children)if(A.type==="paragraph"&&it.extractUniformTextFontFamily(I(A)))for(const _ of I(A))_.marks={..._.marks,fontFamily:w}}}if(S.children.length>0)if(S.children.length===1){const I=S.children[0];if(d===1&&(g.type==="paragraph"||g.type==="list")&&I.type===g.type){if(g.type==="paragraph"&&I.type==="paragraph")I.children=Do(g.children,I.children);else if(g.type==="list"&&I.type==="list"){const L=new Map(g.children.map(M=>[M.id,M])),R=g.children.length===I.children.length&&I.children.every((M,F)=>M.children.map(j=>j.text).join("")===g.children[F].children.map(j=>j.text).join(""));I.children=I.children.map((M,F)=>({...M,children:Do((L.get(M.id)??(R?g.children[F]:void 0))?.children??[],M.children)}))}const T=L=>Array.isArray(L)?L.map(T):L&&typeof L=="object"?Object.fromEntries(Object.entries(L).filter(([R,M])=>R!=="id"&&M!==void 0&&!(R==="marks"&&Object.keys(M).length===0)).sort(([R],[M])=>R.localeCompare(M)).map(([R,M])=>[R,T(M)])):L,C=L=>JSON.stringify(T(L)),N=L=>it.toInternalHtml({type:"doc",children:[T(L)]});if(C(g)===C(I)||N(g)===N(I)){zt(t,{verifiedUnchanged:!0});break}}if(!(h instanceof x.XmlElement))break;if(I.type==="list"){f.delete(m,1);const T=Vo({...I,id:a});f.insert(m,[T]);const C=g.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:C});break}if(I.type==="table"){const T=I;f.delete(m,1);const C=Vo({...T,id:a});f.insert(m,[C]);const N=g.type==="table"?"Table":g.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:N});break}if(I.type==="code"){const T=I;f.delete(m,1);const C=new x.XmlElement("code");C.setAttribute("id",a),T.language&&C.setAttribute("language",T.language),T.renderDiagram!==void 0&&C.setAttribute("renderDiagram",String(T.renderDiagram)),T.showDiagramSource!==void 0&&C.setAttribute("showDiagramSource",String(T.showDiagramSource));const N=new x.XmlText;C.insert(0,[N]),kt(N,0,T.content||""),f.insert(m,[C]);const L=g.type==="code"?"Code block":g.type==="table"?"Table":g.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Code block replaced",oldText:L});break}if(I.type==="math"){const T=I;f.delete(m,1);const C=new x.XmlElement("math");C.setAttribute("id",a),T.displayMode&&C.setAttribute("displayMode",T.displayMode),T.align&&C.setAttribute("align",T.align);const N=new x.XmlText;C.insert(0,[N]),kt(N,0,T.content||""),f.insert(m,[C]);const L=g.type==="math"?"Math block":g.type==="code"?"Code block":g.type==="table"?"Table":g.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Math block replaced",oldText:L});break}if(I.type==="page-break"){f.delete(m,1);const T=new x.XmlElement("page-break");T.setAttribute("id",a),f.insert(m,[T]);const C=g.type==="image"?"Image":g.type==="math"?"Math block":g.type==="code"?"Code block":g.type==="table"?"Table":g.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Page break replaced",oldText:C});break}if(I.type==="toc"){f.delete(m,1);const T=Ut({...I,id:a});f.insert(m,[T]),o.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(I.type==="image"){const T=I;f.delete(m,1);const C=new x.XmlElement("image");C.setAttribute("id",a),C.setAttribute("src",T.src),T.sourceUrl&&C.setAttribute("sourceUrl",T.sourceUrl),C.setAttribute("width",String(T.width)),C.setAttribute("height",String(T.height)),T.alt&&C.setAttribute("alt",T.alt),T.align&&C.setAttribute("align",T.align),f.insert(m,[C]);const N=g.type==="image"?"Image":g.type==="math"?"Math block":g.type==="code"?"Code block":g.type==="table"?"Table":g.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Image replaced",oldText:N});break}if((g.type==="math"||g.type==="code")&&I.type==="paragraph"){f.delete(m,1);const T=new x.XmlElement("paragraph");T.setAttribute("id",a),Go(T,I);const C=new x.XmlText;let N=0;for(const L of I.children)L.type==="text"&&(N=Ne(C,N,L.text,L.marks||{}));Ho(T,I,N),T.insert(0,[C]),f.insert(m,[T]),o.push({kind:"replace",paragraphId:a,text:I.children.filter(L=>L.type==="text").map(L=>L.text).join(""),oldText:g.type==="code"?"Code block":"Math block"});break}if((g.type==="list"||g.type==="table")&&I.type==="paragraph"){f.delete(m,1);const T=new x.XmlElement("paragraph");T.setAttribute("id",a),Go(T,I);const C=new x.XmlText;let N=0;for(const L of I.children)L.type==="text"&&(N=Ne(C,N,L.text,L.marks||{}));Ho(T,I,N),T.insert(0,[C]),f.insert(m,[T]),o.push({kind:"replace",paragraphId:a,text:I.children.filter(L=>L.type==="text").map(L=>L.text).join(""),oldText:g.type==="table"?"Table":"List"});break}const w=_t(h);if(!w)break;const A=g.type==="paragraph"?g:null,_=w.length,B=S.children[0],P=A!==null&&bi(A,B);let $=0;if(!P){if(_>0&&w.delete(0,_),B.children.length>0){for(const T of B.children)if(T.type==="text"){const C=T;$=Ne(w,$,C.text,C.marks||{})}}Go(h,B)}if(!P){const T=g.type==="paragraph"?g.children.filter(C=>C.type==="text").map(C=>C.text).join(""):"";o.push({kind:"replace",paragraphId:a,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(w,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(w,$,0)),text:B.children.filter(C=>C.type==="text").map(C=>C.text).join(""),oldText:T})}}else{if(!(h instanceof x.XmlElement))break;const I=_t(h);if(!I)break;const w=g.type==="paragraph"?g:null,A=I.length,_=g.type==="paragraph"?g.children.filter(C=>C.type==="text").map(C=>C.text).join(""):"",B=S.children[0],P=w!==null&&bi(w,B);let $=0;if(!P){if(A>0&&I.delete(0,A),B.children.length>0){for(const C of B.children)if(C.type==="text"){const N=C;$=Ne(I,$,N.text,N.marks||{})}}B.heading&&h.setAttribute("heading",String(B.heading)),B.align&&h.setAttribute("align",B.align)}P||o.push({kind:"replace",paragraphId:a,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(I,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(I,$,0)),text:B.children.filter(C=>C.type==="text").map(C=>C.text).join(""),oldText:_});let T=m+1;for(let C=1;C<S.children.length;C++){const N=S.children[C],L=new x.XmlElement("paragraph"),R=N.id||et();L.setAttribute("id",R),N.heading&&L.setAttribute("heading",String(N.heading)),N.align&&L.setAttribute("align",N.align);const M=new x.XmlText;let F=0;N.children.forEach(D=>{if(D.type==="text"){const O=D;F=Ne(M,F,O.text,O.marks||{})}}),Ho(L,N,F),L.insert(0,[M]),f.insert(T,[L]),T++;const j=N.children.filter(D=>D.type==="text").map(D=>D.text).join("");o.push({kind:"insert",paragraphId:R,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(M,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(M,j.length,0)),text:j})}}}break}case"style_blocks":{const{selectors:a,attrs:c}=t.arguments,{targets:l,inlineTargets:d,unmatchedSelectors:u,invalidSelectorErrors:g}=lh(r,a),p=dh(c),h=uh(p);if(l.length===0&&d.length===0)throw new Error(`style_blocks matched no blocks. Unmatched selectors: ${u.length>0?u.join(", "):"all"}. ${g.length>0?`Invalid selectors: ${g.join("; ")}.`:""}`);const f=[],m=new Map,y=(G,gt,yt)=>{const Q=Ye(G);let wt=m.get(Q);wt||(wt={name:G,applied:new Set,skipped:new Map},m.set(Q,wt)),yt?wt.skipped.set(`${gt}\0${yt}`,{blockId:gt,reason:yt}):wt.applied.add(gt)},b=o.length,k=new Set,v=new Set,S=new Set(l),I=new Set,w=[],A=[],_=[],B=[],P=Ie(r),$=new Set([...l,...d.map(G=>G.yBlock)].map(Jt)),T=G=>"id"in G&&$.has(String(G.id))||"children"in G&&G.children.some(gt=>T(gt)),C=G=>[...G.children,...G.notes??[],...G.chrome??[]],N=new Set(C(P).filter(T).map(G=>G.id)),L=G=>_n({order:G.children.map(gt=>gt.id),noteOrder:(G.notes??[]).map(gt=>gt.id),chromeOrder:(G.chrome??[]).map(gt=>gt.id),targets:C(G).filter(gt=>N.has(gt.id))}),R=L(P),M=new Set,F=new Set,j=Yo(p,"width");if(j&&!(l.some(G=>G.nodeName==="image")&&qn(j.value)===void 0)){const G=new Map;for(const yt of l){if(yt.nodeName!=="table-cell")continue;let Q=yt.parent;for(;Q instanceof x.XmlElement&&Q.nodeName!=="table";)Q=Q.parent;if(!(Q instanceof x.XmlElement))continue;const wt=z(P,Jt(Q));if(!wt||wt.type!=="table")continue;const ft=qn(j.value),dt=mn("width",j.value),Pt=wt.tableWidth??mi(P,Q),Et=ft??(typeof dt=="number"&&Number.isFinite(dt)?dt/Pt*100:NaN);G.has(Q)||G.set(Q,[]),G.get(Q).push({cellId:Jt(yt),percent:Et}),M.add(yt)}const gt=[...G].map(([yt,Q])=>({table:yt,requests:Q,widths:bg(z(P,Jt(yt)),Q)}));for(const yt of gt){const Q=String(yt.table.getAttribute("columnWidths")??""),wt=JSON.stringify(yt.widths),ft=z(P,Jt(yt.table)),dt=dn(ft);for(const Pt of yt.requests){const Et=dt.byId.get(Pt.cellId),E=U=>U.slice(Et.col,Et.col+Et.colSpan).reduce((X,ot)=>X+ot,0);Math.abs(E(ft.columnWidths)-E(yt.widths))>.001&&F.add(Pt.cellId)}Q!==wt&&(yt.table.setAttribute("columnWidths",wt),Zt(o,yt.table,null,"columnWidths"),k.add(Jt(yt.table))),I.add(j.canonicalName),v.add("columnWidths")}}for(const G of l){const gt=Jt(G);let yt=!1;const Q=yh({doc:P,yBlock:G,rawAttrs:p,anchors:o});M.has(G)&&j&&(Q.handledRawNames.add(j.canonicalName),Q.appliedAttrs.push("cell width -> table columns"));for(const ft of Q.handledRawNames){const dt=p.find(Et=>Et.canonicalName===ft),Pt=Q.issuesByRawName.get(ft)??[];y(dt?.rawName??ft,gt,Pt.length?Pt.join("; "):void 0),I.add(ft)}for(const ft of Q.appliedAttrs)v.add(ft),k.add(gt);w.push(...Q.exactMappings),A.push(...Q.approximateMappings),_.push(...Q.ignoredAttrs),B.push(...Q.unsupportedImageSpacing),f.push(...Q.errors);const wt=Ga(h,G,!1);A.push(...Za(wt));for(const{rawName:ft,entry:dt,value:Pt}of wt)if(!Q.handledRawNames.has(Ye(ft)))try{if(dt.attr==="variant"&&typeof Pt=="string"&&Pt.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(ft.trim().toLowerCase())){if(G.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');yt=!0;continue}if(dt.kind==="textMark"){const Et=Ha(ft,dt.attr,Pt);Gg({toolName:"style_blocks",yBlock:G,attribute:dt.attr,operation:Et===null?"remove":"set",value:Et,config:dt,anchors:o,independentlySelectedTargets:S}),k.add(gt),v.add(`${ft} -> ${dt.attr}`),y(ft,gt);continue}Qg({toolName:"style_blocks",yBlock:G,attribute:dt.attr,operation:Pt===null?"remove":"set",value:Pt,config:{nodeNames:dt.nodeNames,valueType:dt.valueType,integer:dt.integer,min:dt.min,max:dt.max,enumValues:dt.enumValues},anchors:o,independentlySelectedTargets:S}),k.add(gt),v.add(`${ft} -> ${dt.attr}`),y(ft,gt)}catch(Et){y(ft,gt,Et instanceof Error?Et.message:String(Et)),f.push(`${gt}.${dt.attr}: ${Et instanceof Error?Et.message:String(Et)}`)}yt&&(xh(G,o)?(k.add(gt),v.add("listStyleType -> plain paragraphs"),y("listStyleType",gt)):f.push(`${gt}.variant: could not convert the list to plain paragraphs.`))}for(const{yBlock:G,ranges:gt}of d){const yt=Jt(G),Q=Ga(h,G,!0);A.push(...Za(Q));for(const{rawName:wt,entry:ft,value:dt}of Q){if(ft.kind!=="textMark"){const Pt="Block attributes cannot apply to an inline range; select its block instead.";y(wt,yt,Pt),f.push(`${yt}.${ft.attr}: ${Pt}`);continue}try{const Pt=Ha(wt,ft.attr,dt);Zg({toolName:"style_blocks",yBlock:G,ranges:gt,attribute:ft.attr,operation:Pt===null?"remove":"set",value:Pt,config:ft,anchors:o}),k.add(yt),v.add(`${wt} -> ${ft.attr}`),y(wt,yt)}catch(Pt){y(wt,yt,Pt instanceof Error?Pt.message:String(Pt)),f.push(`${yt}.${ft.attr}: ${Pt instanceof Error?Pt.message:String(Pt)}`)}}}for(const G of h.unsupportedAttrs??[]){const gt=m.get(Ye(G)),yt=new Set([...gt?.skipped.values()??[]].map(Q=>Q.blockId));for(const Q of $)!gt?.applied.has(Q)&&!yt.has(Q)&&y(G,Q,"Unsupported attribute for this target.")}const D=Ie(r),O=G=>{const gt=new Map,yt=Q=>{"id"in Q&&Q.id&&gt.set(Q.id,Q),"children"in Q&&Q.children.forEach(wt=>yt(wt))};return C(G).forEach(yt),gt},H=O(P),q=O(D),W=G=>_n(H.get(G)??null)!==_n(q.get(G)??null),ct=[...new Set([...$,...o.slice(b).map(G=>G.paragraphId).filter(G=>!!G)])].filter(W),vt=[...$].filter(G=>W(G)||F.has(G)),Dt=[...m.values()].map(G=>({name:G.name,appliedBlockIds:[...G.applied],skipped:[...G.skipped.values()]})),Qt=Dt.every(G=>G.skipped.length===0)&&v.size>0&&f.length===0&&u.length===0&&g.length===0&&_.length===0&&B.length===0&&(h.unsupportedAttrs??[]).every(G=>I.has(Ye(G))),Vt={outcome:Qt?vt.length?"complete":"unchanged":"partial",targetBlockIds:[...$],changedBlockIds:vt,affectedBlockIds:ct,attributes:Dt};if(zt(t,{styleEffects:Vt}),Qt&&R===L(D)&&zt(t,{verifiedUnchanged:!0}),o.length===b&&!ne(t)?.verifiedUnchanged){if(B.length||_.length)throw new Nt("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 G=h.unsupportedAttrs??[];throw new Error(G.length>0?`style_blocks has no supported attrs. Unsupported attrs: ${G.join(", ")}.`:"style_blocks requires at least one attr.")}throw new Error(`style_blocks could not apply to any target. ${f.length>0?`Skipped target attrs: ${f.join("; ")}`:"No matching supported attributes."}`)}ai.set(t,kh({styleEffects:Vt,matchedTargetCount:l.length+d.reduce((G,gt)=>G+gt.ranges.length,0),inlineRangeCount:d.reduce((G,gt)=>G+gt.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(G=>!I.has(Ye(G))),unmatchedSelectors:u,invalidSelectorErrors:g,skippedTargetErrors:f,exactCompatibilityMappings:w,approximateCompatibilityMappings:A,ignoredCompatibilityAttrs:_,unsupportedImageSpacing:B}));break}case"set_block_attribute":{const{id:a,attribute:c,operation:l,value:d}=t.arguments,u=ja("set_block_attribute",a),g=()=>{const b=Ie(r);return u.map(k=>z(b,k))},p=JSON.stringify(g());if(typeof c!="string"||c.trim().length===0)throw new Error("set_block_attribute requires a non-empty attribute name.");const h=c.trim();if(h==="id")throw new Error("set_block_attribute cannot modify the reserved 'id' attribute.");const f=Kg(l),m=[],y=(b,k)=>{if(u.length<=1)throw new Error(k);return m.push(`${b}: ${k}`),!0};for(const b of u){const k=ut(r,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:v}=k,S=_t(v);if(h==="fontFamily"){const w=Jo(v);if(w){y(b,w);continue}}if(Hg.has(h)){if(!S||v.nodeName!=="paragraph"&&v.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}let w;if(f==="remove")w=!1;else if(f==="toggle")w=!Da(v,S,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(S.length>0)It(S,0,S.length,{[h]:w?!0:null}),Le(o,b,S);else{Jg(v,h,w);const A=`Text mark "${h}" ${w?"enabled":"removed"}.`;o.push({kind:"replace",paragraphId:b,text:A,oldText:A})}continue}if(h in Fa){if(!S||v.nodeName!=="paragraph"&&v.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}if(f==="toggle")throw new Error(`set_block_attribute "${h}" does not support toggle. Use operation "set" with a numeric value or "remove".`);const w=Fa[h],A=f==="remove"?null:Yg(h,d,w);if(S.length>0)It(S,0,S.length,{[h]:A===null?null:A}),Le(o,b,S);else{Oa(v,h,A);const _=`Text mark "${h}" ${A===null?"removed":"set"}.`;o.push({kind:"replace",paragraphId:b,text:_,oldText:_})}continue}if(h==="indentLevel"&&v.nodeName==="paragraph"){za(v,f,d),S&&Le(o,b,S);continue}const I=Ra[h];if(!I){const w=Object.keys(Ra).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${w}.`)}if(!I.nodeNames.includes(v.nodeName)){y(b,`set_block_attribute "${h}" is not valid for ${v.nodeName} blocks.`);continue}if(f==="remove")rt(v,h);else if(f==="toggle"){if(I.valueType!=="boolean")throw new Error(`set_block_attribute "${h}" only supports toggle for boolean attributes.`);const w=Ua(bt(v,h));v.setAttribute(h,String(!w))}else{if(d===void 0)throw new Error(`set_block_attribute "${h}" requires "value" when operation is "set".`);const w=qa(h,d,I);v.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?Xa(v,h,Number(w)):v.setAttribute(h,w)}if(S)Le(o,b,S);else{const w=`Updated ${h} on ${v.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&&p===JSON.stringify(g())&&zt(t,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=t.arguments,c=ja("clear_formatting",a),l=()=>{const u=Ie(r);return c.map(g=>z(u,g))},d=JSON.stringify(l());for(const u of c){const g=ut(r,u);if(!g)throw new Error(`Target block '${u}' not found in the document. Please only reference IDs you see inside <document_content>.`);const p=[];if(g.yBlock.nodeName==="list"){for(let h=0;h<g.yBlock.length;h++){const f=g.yBlock.get(h);if(f instanceof x.XmlElement&&f.nodeName==="list-item"){const m=f.getAttribute("id")||u;p.push({id:m,yBlock:f})}}if(p.length===0){const h=`Cleared formatting on list block ${u}.`;o.push({kind:"replace",paragraphId:u,text:h,oldText:h});continue}}else p.push({id:u,yBlock:g.yBlock});for(const h of p){if(h.yBlock.nodeName!=="paragraph"&&h.yBlock.nodeName!=="list-item")throw new Error("clear_formatting only supports paragraph, list, or list-item blocks.");const f=_t(h.yBlock);if(!f)throw new Error("clear_formatting only supports paragraph, list, or list-item text blocks.");if(h.yBlock.nodeName==="paragraph")for(const m of Ks)rt(h.yBlock,m);if(Sh(h.yBlock),f.length>0){let m=0;for(const y of mt(f)){const b=typeof y.insert=="string"?y.insert.length:1,k={...Vs};typeof y.attributes?.footnoteRef=="string"&&y.attributes.footnoteRef.length>0&&delete k.superscript,It(f,m,b,k),m+=b}Le(o,h.id,f)}else{const m="Formatting cleared.";o.push({kind:"replace",paragraphId:h.id,text:m,oldText:m})}}}d===JSON.stringify(l())&&zt(t,{verifiedUnchanged:!0});break}case"remove_block":{const{id:a,count:c=1}=t.arguments,l=ut(r,a);if(!l)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const{yParent:d,index:u}=l;pn(d)&&fn();const g=Pn(r),p=d===g;for(let h=0;h<c;h++){const f=u;if(f>=d.length)break;const m=d.get(f);if(!(m instanceof x.XmlElement))break;const y=m.getAttribute("id"),b=m.nodeName;if(p&&d.length===1){if(b==="paragraph"){const k=_t(m);if(k&&k.length>0){const v=mt(k);let S="";for(const I of v)I.insert&&typeof I.insert=="string"&&(S+=I.insert);o.push({kind:"delete",paragraphId:y,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(k,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(k,S.length,0)),text:S}),k.delete(0,k.length)}}else{o.push({kind:"delete",paragraphId:y,text:b==="list"?"List removed":"Block removed"});const k=new x.XmlElement("paragraph");k.setAttribute("id",y);const v=new x.XmlText;k.insert(0,[v]),d.delete(f,1),d.insert(f,[k])}break}if(b==="list")o.push({kind:"delete",paragraphId:y,text:"List removed"});else{const k=_t(m);if(k){const v=mt(k);let S="";for(const I of v)I.insert&&typeof I.insert=="string"&&(S+=I.insert);o.push({kind:"delete",paragraphId:y,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(k,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(k,S.length,0)),text:S})}else o.push({kind:"delete",paragraphId:y,text:"Block removed"})}d.delete(f,1)}break}case"append_to_paragraph":{const{id:a,content:c}=t.arguments,l=at(r,a);if(!l)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const d=_t(l);if(!d)break;const u=d.length,g=Ue(u>0?tr(d,u-1,1):Ve(l.getAttribute("_emptyTextMarks"))),p=it.fromAgentHtml(c);if(p.children.length>0){const h=[];for(const y of p.children)y.type==="paragraph"&&y.children.forEach(b=>{b.type==="text"&&h.push(b)});let f=u,m="";for(const y of h)if(y.text){const b=Ne(d,f,y.text,{...g||{},...y.marks||{}});m+=y.text,f=b}m&&o.push({kind:"insert",paragraphId:a,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,u,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,f,0)),text:m})}break}case"break_paragraph":{const{id:a,substring:c}=t.arguments,l=typeof c=="string"?c:String(c??"");if(l.trim().length===0)throw new Error("break_paragraph requires a non-empty substring to split on.");const d=n?.document??Tt(r),u=z(d,a);if(!u)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);if(u.type!=="paragraph")throw new Error(`break_paragraph only works on paragraphs. Block '${a}' is type '${u.type}'.`);const g=jh(u,l);if(g.length===0){const q=u.children.filter(ct=>ct.type==="text").map(ct=>ct.text).join(""),W=q.length>100?q.slice(0,100)+"...":q;throw new Error(`No match found for "${l}" in block '${a}'. The block contains: "${W}".`)}const p=g[0].offset,h=ut(r,a);if(!h)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:f,yParent:m,index:y}=h;if(pn(m)&&fn(),!(f instanceof x.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const b=_t(f);if(!b)throw new Error(`break_paragraph only works on text paragraphs. Block '${a}' has no text content.`);const{beforeOps:k,afterOps:v,formatAtSplit:S,originalText:I,beforeText:w,afterText:A}=Eh(b,p);b.delete(0,b.length);let _=0;for(const q of k)kt(b,_,q.insert,q.attributes??{}),_+=q.insert.length;const B=et(),P=new x.XmlElement("paragraph");P.setAttribute("id",B);const $=f.getAttribute("heading");$&&P.setAttribute("heading",$);const T=bt(f,"align");T&&P.setAttribute("align",T);const C=bt(f,"lineSpacing");C!=null&&P.setAttribute("lineSpacing",C);const N=bt(f,"pagination");N!=null&&P.setAttribute("pagination",N);const L=f.getAttribute("styleId");L!=null&&P.setAttribute("styleId",L);const R=bt(f,"direction");R!=null&&P.setAttribute("direction",R);const M=bt(f,"borders");M!=null&&P.setAttribute("borders",M);const F=bt(f,"shading");F!=null&&P.setAttribute("shading",F);const j=bt(f,"tabStops");j!=null&&P.setAttribute("tabStops",j);const D=f.getAttribute("oxmlPPr");D!=null&&P.setAttribute("oxmlPPr",D);const O=new x.XmlText;let H=0;for(const q of v)O.insert(H,q.insert,q.attributes??{}),H+=q.insert.length;if(v.length===0){const q=Ve(f.getAttribute("_emptyTextMarks")),W=Ue({...q,...S??{}});W&&Object.keys(W).length>0&&P.setAttribute("_emptyTextMarks",JSON.stringify(W))}P.insert(0,[O]),m.insert(y+1,[P]),w!==I&&o.push({kind:"replace",paragraphId:a,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(b,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(b,_,0)),text:w,oldText:I}),o.push({kind:"insert",paragraphId:B,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(O,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(O,H,0)),text:A||"Paragraph split"});break}case"join_paragraphs":{const{firstId:a,secondId:c,separator:l}=t.arguments;if(!a||!c||a===c)throw new Error("join_paragraphs requires two different paragraph IDs: firstId and secondId.");const d=ut(r,a),u=ut(r,c);if(!d)throw new Error(`Target block '${a}' not found in the document.`);if(!u)throw new Error(`Target block '${c}' not found in the document.`);if((pn(d.yParent)||pn(u.yParent))&&fn(),d.yBlock.nodeName!=="paragraph"||u.yBlock.nodeName!=="paragraph")throw new Error("join_paragraphs only works on two paragraph blocks.");if(d.yParent!==u.yParent||u.index!==d.index+1)throw new Error(`join_paragraphs requires adjacent sibling paragraphs with secondId immediately after firstId. '${c}' does not immediately follow '${a}'.`);const g=_t(d.yBlock),p=_t(u.yBlock);if(!g||!p)throw new Error("join_paragraphs only works on text paragraph blocks.");const h=g.toString(),f=p.toString(),m=l!==void 0?String(l):/\S/.test(h)&&/\S/.test(f)?" ":"",y=h.match(/\s+$/)?.[0].length??0,b=f.match(/^\s+/)?.[0].length??0,k=m.length>0,v=k?h.slice(0,h.length-y):h,S=k?f.slice(b):f;k&&y>0&&g.delete(g.length-y,y);const I=mt(g),w=mt(p),A=I.length>0?I[I.length-1].attributes??{}:{},_=w.length>0?w[0].attributes??{}:{};let B=g.length;m.length>0&&(kt(g,B,m,Object.keys(A).length>0?A:_),B+=m.length);let P=k?b:0;for(const T of w){if(typeof T.insert!="string"||T.insert.length===0)continue;const C=T.insert.slice(P);P=Math.max(0,P-T.insert.length),C.length!==0&&(kt(g,B,C,T.attributes??{}),B+=C.length)}const $=`${v}${m}${S}`;o.push({kind:"replace",paragraphId:a,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(g,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(g,g.length,0)),text:$||"Paragraphs joined",oldText:h}),o.push({kind:"delete",paragraphId:c,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(p,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(p,p.length,0)),text:f||"Empty paragraph removed"}),u.yParent.delete(u.index,1);break}case"insert_table_row":{const a=Tt(r),c=it.createParsingContext(a),{tableId:l,referenceIndex:d,referenceRowId:u,position:g,content:p}=t.arguments,h=z(a,l);if(h?.type!=="table")throw new Error(`Table ${l} not found`);let f=d;if(u!==void 0){if(f=h.children.findIndex(k=>k.id===u),f<0)throw new Error(`Row ${u} not found in table ${l}. Read the table and use a current row ID.`);if(d!==void 0&&d!==f)throw new Error(`Row ${u} is at index ${f}, not ${d}. Use referenceRowId alone or reread the table.`)}if(f===void 0||!Number.isInteger(f)||f<0||f>=h.children.length)throw new Error("Invalid reference row index. Supply a current referenceRowId or a valid 0-based referenceIndex.");const m=h.children[f],y=p?.map(k=>{if(k==="")return;const v=it.fromAgentHtml(k,{existingDocument:a,parsingContext:c});return v.children.length>0?v.children:void 0}),b=Dg(r,l,g,f,y);if(!b.success)throw new Error(b.error||"Failed to insert table row");o.push({kind:"insert",paragraphId:l,text:`Row inserted ${g} row ${m.id} (reference index ${f}; new row index ${f+(g==="after"?1:0)})`});break}case"remove_table_row":{const{tableId:a,rowIndex:c}=t.arguments,l=Fg(r,a,c);if(!l.success)throw new Error(l.error||"Failed to remove table row");o.push({kind:"delete",paragraphId:a,text:`Row ${c} removed`});break}case"insert_table_column":{const a=Tt(r),c=it.createParsingContext(a),{tableId:l,referenceIndex:d,position:u,content:g}=t.arguments,p=g?.map(f=>{if(f==="")return;const m=it.fromAgentHtml(f,{existingDocument:a,parsingContext:c});return m.children.length>0?m.children:void 0}),h=Eg(r,l,u,d,p);if(!h.success)throw new Error(h.error||"Failed to insert table column");o.push({kind:"insert",paragraphId:l,text:`Column inserted ${u} column ${d}`});break}case"remove_table_column":{const{tableId:a,columnIndex:c}=t.arguments,l=Lg(r,a,c);if(!l.success)throw new Error(l.error||"Failed to remove table column");o.push({kind:"delete",paragraphId:a,text:`Column ${c} removed`});break}}return n?.refreshDocumentIncrementally&&(n.document=Ie(r)),o}function Ve(r){if(!r)return{};try{const t=JSON.parse(r);if(t&&typeof t=="object")return t}catch{}return{}}function Eh(r,t){const e=[],n=[];let o={},i="",s="",a="",c=0;const l=mt(r);for(const d of l){if(!d.insert||typeof d.insert!="string")continue;const u=d.insert,g=d.attributes||{},p=c+u.length;if(i+=u,p<=t)e.push({insert:u,attributes:g}),s+=u,p===t&&(o=g);else if(c>=t)n.push({insert:u,attributes:g}),a+=u;else{const h=t-c,f=u.slice(0,h),m=u.slice(h);f.length>0&&(e.push({insert:f,attributes:g}),s+=f),m.length>0&&(n.push({insert:m,attributes:g}),a+=m),o=g}c=p}return{beforeOps:e,afterOps:n,formatAtSplit:o,originalText:i,beforeText:s,afterText:a}}function tr(r,t,e){const n=t+e;let o=0,i=null;for(const s of mt(r)){if(typeof s.insert!="string")continue;const a=o+s.insert.length;if(a>t&&o<n){const c=s.attributes||{},l={};for(const d of Ts){const u=c[d];u!=null&&u!==!1&&(l[d]=u)}if(i===null)i=l;else for(const d of Object.keys(i))i[d]!==l[d]&&delete i[d]}if(o=a,o>=n)break}return i??{}}function ki(r){const t=new Set;if(!r.includes("<")||!r.includes(">"))return t;try{const e=it.fromAgentHtml(r),n=o=>{if(o.type==="text"){for(const i of po)o.marks?.[i]!==void 0&&t.add(i);return}if("children"in o&&Array.isArray(o.children))for(const i of o.children)n(i)};for(const o of e.children)n(o)}catch{}return t}function lc(r,t){const e=Nn(r);return t.code||t.latex?e:Zs(e)}function dc(r,t,e,n,o){if(o.includes("<")&&o.includes(">")||ki(n).size>0)return!1;const i=tr(r,t,e),s=lc(o,i);return r.toString().slice(t,t+e)===s}function Si(r,t,e,n,o,i,s,a={}){if(!dc(r,t,e,n,o))if(o.includes("<")&&o.includes(">")){const c={...a,...tr(r,t,e)};for(const p of ki(n))delete c[p];const l=o.trim(),d=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(l)?l:`<p>${o}</p>`,u=it.fromAgentHtml(d,{preserveExplicitMarkResets:!0}),g=u.children.length>0?u.children[0]:null;if(g&&g.type==="paragraph"&&g.children.length>0){r.delete(t,e);const p=[];for(const b of g.children)if(b.type==="text"){const k=b,v={...c,...k.marks||{}};p.push({text:k.text,marks:v})}const h=r.doc;let f=t;const m=[];for(const b of p){const k=m[m.length-1],v=JSON.stringify(b.marks||{}),S=k?JSON.stringify(k.marks||{}):null;k&&v===S?k.text+=b.text:m.push({text:b.text,marks:b.marks||{}})}const y=m.map(b=>b.text).join("");h.transact(()=>{kt(r,t,y);let b=t;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&It(r,b,k.text.length,k.marks),b+=k.text.length;f=t+y.length},"performReplacement"),oc(r,t,f),s.push({kind:"replace",paragraphId:i,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(r,t,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(r,f,0)),text:o.replace(/<[^>]*>/g,""),oldText:n.replace(/<[^>]*>/g,"")})}}else{const c={...a,...tr(r,t,e)},l=lc(o,c);for(const d of ki(n))delete c[d];r.delete(t,e),l.length>0&&kt(r,t,l,c),oc(r,t,t+l.length),s.push({kind:"replace",paragraphId:i,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(r,t,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(r,t+l.length,0)),text:l,oldText:n.replace(/<[^>]*>/g,"")})}}const er=/\\+u[0-9a-fA-F]{4}/;function uc(r){let t="";const e=[],n=[];for(let o=0;o<r.length;){const i=r.slice(o).match(/^(\\+u)([0-9a-fA-F]{4})/),s=i?o+i[0].length:o+1,a=i?String.fromCharCode(Number.parseInt(i[2],16)):r[o],c=Be(a);t+=c;for(let l=0;l<c.length;l++)e.push(o),n.push(s);o=s}return{text:t,sourceStarts:e,sourceEnds:n}}function Ii(r,t){return r.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 gc(r){return r.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function Rh(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hc(r,t){const e=t.split(/(\s+)/),n=[];for(const c of e)/^\s+$/.test(c)?n.push("\\s+"):c.length>0&&n.push(Rh(c));if(n.length===0)return[];const o=n.join(""),i=new RegExp(o,"g"),s=[];let a;for(;(a=i.exec(r))!==null;)s.push({offset:a.index,length:a[0].length});return s}function Dh(r,t,e,n,o){const i=[];let s=r.indexOf(t);for(;s!==-1;){const a=s+n-e.length,c=Math.min(s+o-e.length+1,r.length);for(let l=a;l<c;l++)if(r.substring(l,l+e.length)===e){const d=l+e.length-s;d>=n&&d<=o&&i.push({offset:s,length:d})}s=r.indexOf(t,s+1)}return i}function pc(r,t){const e=Ao(t);if(e.length>1)for(const n of e){const o=En(r,n);if(o.length)return o.map(({start:i,end:s})=>({offset:i,length:s-i}))}for(const n of e){if(Te(n))continue;const o=Oh(r,n);if(o.length)return o}return[]}function Oh(r,t){if(!t)return[];if(/^\s*$/.test(t))return vi(r,t);if(er.test(r)||er.test(t))return fc(r,t);const e=Sg();return e!==null?e:fc(r,t)}function fc(r,t){const e=En(r,t);if(e.length)return e.map(({start:d,end:u})=>({offset:d,length:u-d}));const n=Be(r),o=Be(t),i=vi(n,o);if(i.length>0)return i;const s=hc(n,o);if(s.length>0)return s;let a,c;if(er.test(r)||er.test(t)){a=uc(r),c=uc(t).text;const d=vi(a.text,c);if(d.length>0)return Ii(d,a);const u=hc(a.text,c);if(u.length>0)return Ii(u,a)}const l=8;if(o.length>=l*2){const d=mc(n,o,l);if(d!==null)return[d]}if(a&&c&&c.length>=l*2){const d=mc(a.text,c,l);if(d!==null)return Ii([d],a)}return[]}function jh(r,t){let e="";for(const n of r.children)n.type==="text"&&(e+=n.text);return pc(e,t)}function vi(r,t){const e=[];let n=r.indexOf(t);for(;n!==-1;)e.push({offset:n,length:t.length}),n=r.indexOf(t,n+t.length);return e}function mc(r,t,e){const n=Math.floor(t.length/2);for(let o=n;o>=e;o--){const i=t.substring(0,o),s=t.substring(t.length-o),a=Math.max(5,Math.floor(t.length*.2)),c=Math.max(o*2,t.length-a),l=t.length+a,d=Dh(r,i,s,c,l);if(d.length===1)return d[0]}return null}function Uh(r,t,e,n,o={}){if(!t.length)return{anchorsByAction:[],failures:[],alreadySatisfied:!1};const i=t.every(h=>h.name==="insert_block"),s=i?n:o.canonicalDocument?.()??n;i||Mo(r,s);let a;const c={document:i?{...n,children:[...n.children]}:s,get htmlParsingContext(){return a??(a=it.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!i},l=[],d=[],u=new Set,g=[],p=(h,f,m,y)=>{const b=ne(h);d.push({actionIndex:f,actionName:h.name,error:m,failure:y,sourceEditIndex:b?.sourceEditIndex,sourceEditType:b?.sourceEditType})};for(let h=0;h<t.length;h++){const f=t[h];try{const m=()=>ve(r,f,`${e}_${h}`,!o.skipContextForFirstAction||i||h>0?c:void 0),y=o.measure?o.measure(m):m();o.skipContextForFirstAction&&!i&&h===0&&t.length>1&&(c.document=Ie(r)),l.push(y);const b=ne(f);if(y.length&&b?.splitReplacementGroup&&u.add(b.splitReplacementGroup),!y.length&&o.rejectUnchangedAction&&!b?.verifiedUnchanged)if(ig(f)&&b?.splitReplacementGroup)g.push({action:f,index:h,group:b.splitReplacementGroup});else{p(f,h,ci(f)??`${JSON.stringify(f.arguments)} - no change made`);break}}catch(m){if(o.throwOnError)throw m;if(p(f,h,String(m),Ln(m)),!o.continueAfterError)break}}for(const{action:h,index:f,group:m}of g)u.has(m)||p(h,f,"Split replacement made no verified change");return{anchorsByAction:l,failures:d,alreadySatisfied:d.length===0&&t.every(h=>ne(h)?.verifiedUnchanged)}}const qh={count:()=>{},gauge:()=>{},distribution:()=>{}},xi=()=>{},zh={count:xi,gauge:xi,distribution:xi},bc=new WeakSet;function wi(r,t){try{zh.count("frontend.editor.yjs_observer_failure",1,{event:t})}catch{}console.error(`Yjs ${t} observer failed`,r)}function yc(r,t=wi){if(bc.has(r))return;bc.add(r);const e=r.emit;let n=Number.NEGATIVE_INFINITY;r.emit=function(o,i){if(!["update","updateV2","afterTransactionCleanup"].includes(o))return e.call(this,o,i);const s=Array.from(this._observers.get(o)??[]);for(const a of s)try{a(...i)}catch(c){const l=Date.now();if(l-n>=3e4){n=l;try{t(c,o)}catch{}}}}}const kc="suggestion-id-repair";function Xh(r){if(r.deleteSet.clients.size>0)return!0;for(const[t,e]of r.afterState){const n=r.beforeState.get(t)??0;if(n===e)continue;const o=r.doc.store.clients.get(t);for(let i=x.findIndexSS(o,n);i<o.length&&o[i].id.clock<e;i++){const s=o[i];if(s instanceof x.Item&&s.content instanceof x.ContentFormat&&["insertion","deletion","suggestionId","proposalId"].includes(s.content.key))return!0}}return!1}function Hh(r,t,e="recover"){const n=new Set(["content","chrome","notes"].filter(c=>r.share.has(c)).map(c=>r.getXmlFragment(c))),o=new Set,i=c=>{c._item?.deleted||(c instanceof x.XmlText?o.add(c):c instanceof x.XmlFragment&&c.toArray().forEach(i))};if(t){const c=Xh(t);for(const[l,d]of t.changed)l instanceof x.XmlText?c&&o.add(l):l instanceof x.XmlFragment&&(d.has("structuralSuggestionId")||d.has("suggestionId"))&&i(l);Ld(t,l=>{l.deleted||l.content instanceof x.ContentType&&i(l.content.type)})}else n.forEach(i);const s=c=>typeof c=="string"&&c.trim().length>0,a=[];for(const c of o){if(c._item?.deleted)continue;let l=c,d=!1;for(;l.parent;){l=l.parent;const h=l;if(h instanceof x.XmlElement&&["structuralSuggestionId","suggestionId","proposalId"].some(f=>s(h.getAttribute(f)))){d=!0;break}}if(d||!n.has(l))continue;let u=0,g,p;for(const h of mt(c)){const f=typeof h.insert=="string"?h.insert.length:1,m=h.attributes??{};if(typeof h.insert!="string"||f===0||!(m.insertion||m.deletion)||s(m.suggestionId)||s(m.proposalId)){g=void 0,p=void 0,u+=f;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(p&&g===y)p.length+=f;else{const b=x.createRelativePositionFromTypeIndex(c,u).item;if(!b){u+=f;continue}p={text:c,start:u,length:f,id:`recovered-inline-${b.client.toString(36)}-${b.clock.toString(36)}`},g=y,a.push(p)}u+=f}}return a.length&&r.transact(()=>{for(const c of a)It(c.text,c.start,c.length,e==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:c.id})},kc),a.length}const Wh=["borders","align","styleId","direction","_emptyTextMarks"],Jh=["id","heading","oxmlAttrs",...Fd],Yh=["pagination"],Kh=[...Nd("paragraph"),...Yh].filter(r=>!Wh.includes(r)&&!Jh.includes(r));function Sc(r,t){for(const e of Kh){const n=bt(r,e);n!=null&&t.setAttribute(e,n)}}const Ai=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"]);function Ic(r,t){if(!r)return[];const e=!!r.footnoteRef,n=[];for(const[o,i]of Object.entries(r))i===void 0||i===!1||i===null||Ai.has(o)||o==="link"&&t.excludeLink||o==="comment"&&t.excludeComment||o!=="footnoteRef"&&(o==="superscript"&&e||n.push([o,i]));return n}function Ti(r){const{explicitMarks:t,inheritedMarks:e,emptyParagraphMarks:n,exitingLink:o=!1,exitingComment:i=!1,noteBodyFontSize:s,suggestionMarks:a}=r,c={},l=[],d=p=>{l.includes(p)||l.push(p)},u=p=>c[p]!==void 0,g=p=>l.includes(p);if(t){for(const[p,h]of Object.entries(t))h===!1?d(p):h!=null&&(c[p]=h);c.footnoteRef&&(delete c.footnoteRef,e?.footnoteRef&&delete c.superscript)}for(const[p,h]of Ic(e,{excludeLink:o,excludeComment:i}))!u(p)&&!g(p)&&(c[p]=h);e?.footnoteRef&&!c.footnoteRef&&(d("footnoteRef"),c.superscript||d("superscript"));for(const[p,h]of Ic(n,{excludeLink:o,excludeComment:i}))!u(p)&&!g(p)&&(c[p]=h);return s!=null&&c.fontSize===void 0&&!g("fontSize")&&(c.fontSize=s),o&&!c.link&&d("link"),i&&!c.comment&&d("comment"),a&&Object.assign(c,a),{marksToApply:c,marksToRemove:l}}function vc(r,t,e,n){if(kt(r,t,e),Object.keys(n.marksToApply).length>0&&It(r,t,e.length,n.marksToApply),n.marksToRemove.length>0){const o={};for(const i of n.marksToRemove)o[i]=null;It(r,t,e.length,o)}}function nr(r,t,e){const n=Ms(t,e,qe(r.getDocument().children));r.transact(()=>{const o=r.getYChromeFragment();xc(o,s=>s.getAttribute("sectionIndex")===void 0);for(const s of n)o.push([r.blockToYjsElement(s)]);const i=r.ydoc.getMap("metadata");i.delete("headers"),i.delete("footers")})}function Ci(r){return ws(r.getDocument().chrome??[])}function xc(r,t){for(let e=r.length-1;e>=0;e--){const n=r.get(e);n instanceof x.XmlElement&&t(n)&&r.delete(e,1)}}function Vh(r,t,e,n){const o=qe(r.getDocument().children),i=Ms(e,n,o).map(s=>({...s,sectionIndex:t}));r.transact(()=>{const s=r.getYChromeFragment();xc(s,a=>a.getAttribute("sectionIndex")===String(t));for(const a of i)s.push([r.blockToYjsElement(a)])})}function Gh(r,t){return Od(r.getDocument().chrome??[],t)}function wc(r,t,e){const n=Rd(r.getDocument().chrome??[],t,e);if(n)return n;const o=Dd(t,e,void 0,qe(r.getDocument().children));return r.transact(()=>{r.getYChromeFragment().push([r.blockToYjsElement(o)])}),o}function Zh(r){const t=r.getYContentFragment(),e=[];for(const i of t.toArray())i instanceof x.XmlElement&&i.nodeName==="header-footer"&&e.push(i);const n=r.getYChromeFragment();if(e.length===0&&n.length<=3){Ac(r);return}const o=r.getYChromeFragment();r.transact(()=>{for(const s of e){const a=r.getDocument().children.find(c=>c.type==="header-footer"&&c.id===s.getAttribute("id"));a&&o.push([r.blockToYjsElement(a)])}const i=t.toArray();for(let s=i.length-1;s>=0;s--){const a=i[s];a instanceof x.XmlElement&&a.nodeName==="header-footer"&&t.delete(s,1)}}),Ac(r)}function Ac(r){const t=r.getYChromeFragment(),e=new Map,n=[],o=t.toArray(),i=r.getDocument().chrome??[],s=a=>{const c=i.find(l=>l.id===a);return!!(c&&jd(c))};o.forEach((a,c)=>{if(!(a instanceof x.XmlElement)||a.nodeName!=="header-footer")return;const l=`${a.getAttribute("side")}:${a.getAttribute("slot")}:${a.getAttribute("sectionIndex")??""}`,d=e.get(l);if(d===void 0){e.set(l,c);return}const u=o[d];!s(u.getAttribute("id"))&&s(a.getAttribute("id"))?(n.push(d),e.set(l,c)):n.push(c)}),n.length!==0&&r.transact(()=>{for(const a of n.sort((c,l)=>l-c))t.delete(a,1)})}function Qh(r){const t=r.ydoc.getMap("metadata"),e=t.get("headers"),n=t.get("footers");!e&&!n||((r.getDocument().chrome?.length??0)>0?r.transact(()=>{t.delete("headers"),t.delete("footers")}):nr(r,e,n))}function tp(r,t,e="bottom-right"){const{headers:n={},footers:o={}}=Ci(r),i=c=>!!(c&&c.length===1&&c[0].children.every(l=>l.type==="text"&&(l.marks?.field==="page"||l.text.trim()===""))),s={...n},a={...o};if(i(s.default)&&delete s.default,i(a.default)&&delete a.default,t){const c=$s(e),l=c.side==="headers"?s:a;l.default||(l.default=[c.paragraph])}nr(r,Object.keys(s).length>0?s:void 0,Object.keys(a).length>0?a:void 0)}function ep(r){const t=r.ydoc.getMap("metadata");if(t.get(Me.showPageNumbers)!==!0)return;const e=t.get(Me.pageNumberPosition)??"bottom-right",{headers:n={},footers:o={}}=Ci(r),i=$s(e),s=i.side==="headers"?n:o;if(r.transact(()=>{t.set(Me.showPageNumbers,!1)}),!s.default){const a={...s,default:[i.paragraph]};nr(r,i.side==="headers"?a:n,i.side==="footers"?a:o)}}function np(r,t){const e=t?{fontFamily:t}:{},n=[];for(const o of r.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 op(r,t,e,n,o){const i=r.getYChromeFragment(),s=()=>{for(const d of i.toArray())if(d instanceof x.XmlElement&&d.nodeName==="header-footer"&&d.getAttribute("side")===t&&d.getAttribute("slot")===e)return d;return null};if(o){const d=s();return d?(r.transact(()=>{const u=i.toArray().indexOf(d);u>=0&&i.delete(u,1)}),!0):!1}const a=[];if(typeof n.left=="string"&&a.push([0,n.left]),typeof n.center=="string"&&a.push([1,n.center]),typeof n.right=="string"&&a.push([2,n.right]),a.length===0)return!1;wc(r,t,e);const c=s();if(!c)return!1;const l=qe(r.getDocument().children);return r.transact(()=>{for(const[d,u]of a){const g=(r.getDocument().chrome??[]).find(f=>f.side===t&&f.slot===e)?.children[d],p=Ed[d],h={type:"paragraph",id:g?.id??et(),children:np(u,l),...g?.align??p?{align:g?.align??p}:{}};c.get(d)&&c.delete(d,1),c.insert(d,[r.blockToYjsElement(h)])}}),!0}function Ee(r){return r.ydoc?r.ydoc.getMap("comments"):null}function rp(r){const t=Ee(r);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 Tc(r){const t=r.getAttribute("structuralSuggestionKind")==="insert"?r.getAttribute("structuralSuggestionId"):r.getAttribute("diffState")==="insert"?r.getAttribute("suggestionId"):void 0;return typeof t=="string"?t:void 0}function ip(r,t){if(!r.ydoc||t.length===0)return[];const e=new Set(t),n=[],o=(i,s)=>{for(const a of i.toArray()){if(a instanceof x.XmlElement){const u=Tc(a);o(a,typeof u=="string"&&e.has(u)?u:s);continue}if(!(a instanceof x.XmlText)||!(i instanceof x.XmlElement))continue;const c=i.getAttribute("id");if(typeof c!="string")continue;let l=0,d=0;for(const u of mt(a)){if(typeof u.insert!="string")continue;const g=u.insert.length,p=d+(u.attributes?.deletion?0:g),h=u.attributes?.suggestionId??s,f=!u.attributes?.suggestionId&&!!s;if(g>0&&typeof h=="string"&&e.has(h)){const m=n[n.length-1];m?.blockId===c&&m.suggestionId===h&&!!m.structural===f&&m.end===l?(m.end+=g,m.projectedEnd=p):n.push({blockId:c,suggestionId:h,start:l,end:l+g,projectedStart:d,projectedEnd:p,...f?{structural:!0}:{}})}l+=g,d=p}l===0&&s&&n.push({blockId:c,suggestionId:s,start:0,end:0,projectedStart:0,projectedEnd:0,structural:!0})}};return o(r.getYContentFragment()),o(r.ydoc.getXmlFragment("notes")),o(r.ydoc.getXmlFragment("chrome")),n}function Pi(r,t,e,n){return{id:Ct(),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 Cc(r,t,e,n){const o=Ee(r);if(!o||!at(r.ydoc,t))return null;const i=Pi(r,e,{...n,anchorBlockId:t});return r.transact(()=>{o.set(i.id,i)}),i.id}function sp(r,t,e,n,o){const i=at(r.ydoc,t),s=i?xt(i):null;if(!s||n<=e||e>=s.length)return!1;const a=Math.min(n,s.length),c=mt(s);let l=0,d=!1;for(const u of c){if(typeof u.insert!="string")continue;const g=l,p=l+u.insert.length;l=p;const h=Math.max(g,e),f=Math.min(p,a);if(f<=h)continue;const m=u.attributes?.comment,y=m?m.split(","):[];y.includes(o)||y.push(o),It(s,h,f-h,{comment:y.join(",")}),d=!0}return d}function ap(r,t,e,n,o,i){return Mi(r,[{blockId:t,start:e,end:n}],o,i)}function Mi(r,t,e,n){const o=Ee(r);if(!o||t.length===0)return null;const i=Pi(r,e,n),s=i.id;let a=!1;return r.transact(()=>{for(const c of t)a=sp(r,c.blockId,c.start,c.end,s)||a;a&&o.set(s,i)}),a?s:null}function cp(r,t,e,n){const o=Ee(r);if(!o||!o.has(t))return null;const i=Pi(r,e,n,t);return r.transact(()=>{o.set(i.id,i)}),i.id}function lp(r,t,e){const n=Ee(r),o=n?.get(t);return!n||!o?!1:(r.transact(()=>{n.set(t,{...o,resolved:e})}),!0)}function dp(r,t,e){const n=Ee(r);if(!n)return 0;const o=new Set(t);if(o.size===0)return 0;const i=[];return n.forEach(s=>{const a=s;if(!a||typeof a!="object"||a.parentId||a.resolved)return;const c=[];typeof a.suggestionId=="string"&&a.suggestionId.length>0&&c.push(a.suggestionId);for(const l of a.relatedSuggestionIds??[])c.includes(l)||c.push(l);c.length!==0&&c.some(l=>o.has(l))&&(c.some(l=>e(l))||i.push(a))}),i.length===0?0:(r.transact(()=>{for(const s of i)n.set(s.id,{...s,resolved:!0})}),i.length)}function up(r,t){const e=Ee(r);if(!e)return 0;const n=[];if(e.forEach(c=>{const l=c;l&&typeof l=="object"&&!l.parentId&&!l.resolved&&typeof l.suggestionId=="string"&&l.suggestionId.length>0&&(!t(l.suggestionId)||l.relatedSuggestionIds?.some(d=>!t(d)))&&n.push(l)}),n.length===0)return 0;const o=new Map,i=(c,l)=>{for(const d of c.toArray()){if(d instanceof x.XmlElement){const u=Tc(d);i(d,u&&t(u)?u:l);continue}if(d instanceof x.XmlText)for(const u of mt(d)){const g=u.attributes?.comment,p=u.attributes?.suggestionId??l;if(!(!g||!p))for(const h of g.split(",")){const f=o.get(h)??[];f.includes(p)||f.push(p),o.set(h,f)}}}};try{i(r.getYContentFragment()),i(r.ydoc.getXmlFragment("notes")),i(r.ydoc.getXmlFragment("chrome"))}catch{}const s=c=>{const l=Array.from(new Set([...c.suggestionId?[c.suggestionId]:[],...o.get(c.id)??[],...c.relatedSuggestionIds??[]])).filter(t);if(l.length>0)return l;if(c.anchorBlockId){let d=at(r.ydoc,c.anchorBlockId)??null;for(;d;){if(d instanceof x.XmlElement){const u=d.getAttribute("structuralSuggestionId");if(typeof u=="string"&&t(u))return[u];for(const g of["structuralSuggestionRecord","structuralSuggestionRecords"]){const p=d.getAttribute(g);if(typeof p=="string")try{const h=JSON.parse(p),f=(Array.isArray(h)?h:[h]).find(m=>typeof m?.id=="string"&&t(m.id));if(f)return[f.id]}catch{}}}d=d.parent}}return[]};let a=0;return r.transact(()=>{for(const c of n){const l=s(c);if(l.length===0)continue;const d={...c,suggestionId:l[0]};l.length>1?d.relatedSuggestionIds=l:delete d.relatedSuggestionIds,e.set(c.id,d),a+=1}}),a}function gp(r,t){const e=Ee(r);if(!e||!e.has(t))return!1;const n=new Set([t]);let o=!0;for(;o;)o=!1,e.forEach((i,s)=>{const a=i;a?.parentId&&n.has(a.parentId)&&!n.has(s)&&(n.add(s),o=!0)});return r.transact(()=>{for(const s of n)e.delete(s);const i=s=>{for(const a of s.toArray()){if(a instanceof x.XmlElement){i(a);continue}if(!(a instanceof x.XmlText))continue;let c=0;for(const l of mt(a)){if(typeof l.insert!="string")continue;const d=l.insert.length,u=l.attributes?.comment;if(u){const g=u.split(",").filter(p=>!n.has(p));g.length!==u.split(",").length&&It(a,c,d,{comment:g.length>0?g.join(","):null})}c+=d}}};try{i(r.getYContentFragment()),i(r.ydoc.getXmlFragment("notes")),i(r.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function Pc(r,t){const e=d=>d.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&");if(!r.includes("<")||!r.includes(">"))return[{type:"text",text:e(r),marks:{...t}}];const n=[],o={},i=d=>{d&&n.push({type:"text",text:e(d),marks:{...o,...t}})},s=/<(\/?)(i|em|b|strong|u|a)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;let a=0,c;for(;(c=s.exec(r))!==null;){i(r.slice(a,c.index)),a=s.lastIndex;const d=c[1]==="/",u=c[2].toLowerCase();if(u==="i"||u==="em")d?delete o.italic:o.italic=!0;else if(u==="b"||u==="strong")d?delete o.bold:o.bold=!0;else if(u==="u")d?delete o.underline:o.underline=!0;else if(u==="a")if(d)delete o.link;else{const g=/href="([^"]*)"/.exec(c[3]??"");g?.[1]&&(o.link=e(g[1]))}}i(r.slice(a));const l=n.map(d=>({...d,text:d.text.replace(/<[^>]{1,80}>/g,"")})).filter(d=>d.text.length>0);return l.length>0?l:[{type:"text",text:e(r),marks:{...t}}]}function kn(r){const t=[],e=n=>{for(const o of n.toArray()){if(o instanceof x.XmlElement){if(o.nodeName==="footnote")continue;e(o);continue}if(!(o instanceof x.XmlText))continue;let i=0;for(const s of mt(o)){if(typeof s.insert!="string")continue;const a=s.attributes??{};typeof a.footnoteRef=="string"&&a.footnoteRef&&t.push({yText:o,start:i,length:s.insert.length,text:s.insert,attributes:a,footnoteId:a.footnoteRef}),i+=s.insert.length}}};try{e(r.getYContentFragment())}catch{}return t}function Ge(r){const t=new Map,e=n=>{for(const o of n.toArray())if(o instanceof x.XmlElement&&o.nodeName==="footnote"){const i=o.getAttribute("id");typeof i=="string"&&i&&t.set(i,o)}};try{e(r.getYNotesFragment()),e(r.getYContentFragment())}catch{}return t}function hp(r,t){const e=[...r.notes??[],...r.children.filter(n=>n.type==="footnote")];for(const n of e)if(n.id===t||z(n,t))return!0;return!1}function $i(r){const t=new Map;for(const[e,n]of Ge(r))t.set(e,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return t}function pp(r){const t=[];for(const a of kn(r))t.includes(a.footnoteId)||t.push(a.footnoteId);const e=$i(r),n=new Map,o=r.getDocument();for(const a of[...o.notes??[],...o.children.filter(c=>c.type==="footnote")])n.set(a.id,a);const i={footnote:0,endnote:0},s=[];for(const a of t){const c=n.get(a);if(!c)continue;const l=e.get(a)??"footnote";i[l]+=1,s.push({footnote:c,number:i[l],display:Br(i[l],l),kind:l})}return s}function Ze(r){const t=kn(r);if(t.length===0)return!1;const e=$i(r),n=new Map,o={footnote:0,endnote:0};for(const s of t)if(!n.has(s.footnoteId)){const a=e.get(s.footnoteId)??"footnote";o[a]+=1,n.set(s.footnoteId,Br(o[a],a))}const i=t.filter(s=>s.text!==n.get(s.footnoteId));return i.length===0?!1:(r.transact(()=>{for(const s of[...i].sort((a,c)=>c.start-a.start)){const a=n.get(s.footnoteId)??"";s.yText.delete(s.start,s.length),kt(s.yText,s.start,a,s.attributes)}}),!0)}function fp(r){Mc(r);const t=kn(r),e=Ge(r);if(t.length===0&&e.size===0)return;const n=new Set(t.map(o=>o.footnoteId));r.transact(()=>{for(const[o,i]of e)if(!n.has(o)&&!i.getAttribute("structuralSuggestionId")){const s=i.parent;if(s){const a=s.toArray().indexOf(i);a>=0&&s.delete(a,1)}}for(const o of[...t].sort((i,s)=>s.start-i.start))e.has(o.footnoteId)||o.yText.delete(o.start,o.length)}),Ze(r)}function Mc(r){let t;try{t=r.getYContentFragment()}catch{return!1}const e=[],n=d=>{for(const u of d.toArray()){if(u instanceof x.XmlElement){n(u);continue}if(!(u instanceof x.XmlText))continue;let g=0;for(const p of mt(u)){if(typeof p.insert!="string")continue;const h=p.attributes??{};typeof h.footnotePendingBody=="string"&&e.push({yText:u,start:g,length:p.insert.length,footnoteId:typeof h.footnoteRef=="string"&&h.footnoteRef?h.footnoteRef:et(),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}),g+=p.insert.length}}};if(n(t),e.length===0)return!1;const o=Ge(r),i=new Set(kn(r).map(d=>d.footnoteId)),s=r.getDocument(),a=new Map;for(const d of[...s.notes??[],...s.children.filter(u=>u.type==="footnote")])a.set(d.id,d.children.flatMap(u=>u.type==="paragraph"?u.children:[]).map(u=>u.type==="text"?u.text:"").join(""));const c=new Set;for(const d of e)if(!o.has(d.footnoteId)){for(const[u,g]of a)if(g===d.body&&!i.has(u)&&!c.has(u)&&o.has(u)){d.footnoteId=u,c.add(u);break}}const l=qe(r.getDocument().children);return r.transact(()=>{for(const d of e){if(It(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 f=o.get(d.footnoteId);let m=null;for(const b of f.toArray())if(b instanceof x.XmlElement&&b.nodeName==="paragraph"){m=b;break}const y=m?xt(m):null;if(y){const b=d.fontFamily??l;y.length>0&&y.delete(0,y.length);let k=0;for(const v of Pc(d.body,{fontSize:ze,...b?{fontFamily:b}:{}}))kt(y,k,v.text,v.marks),k+=v.text.length}}continue}const u=d.fontFamily??l,g={fontSize:ze,...u?{fontFamily:u}:{}},p={type:"footnote",id:d.footnoteId,...d.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:et(),children:Pc(d.body,g)}]},h=r.blockToYjsElement(p);h.setAttribute("id",d.footnoteId),d.kind==="endnote"&&h.setAttribute("noteKind","endnote"),d.suggested&&d.suggestionId&&r.suggestions.setElementStructuralSuggestion(h,"insert",void 0,d.suggestionId,"Insert footnote"),r.getYNotesFragment().push([h]),o.set(d.footnoteId,h)}}),Ze(r),!0}function mp(r){let t;try{t=r.getYContentFragment()}catch{return}const e=[];for(const s of t.toArray())s instanceof x.XmlElement&&s.nodeName==="footnote"&&e.push(s);if(e.length===0)return;const n=r.getYNotesFragment(),o=r.getDocument(),i=new Map([...o.notes??[],...o.children.filter(s=>s.type==="footnote")].map(s=>[s.id,s]));r.transact(()=>{for(const a of e){const c=a.getAttribute("id"),l=typeof c=="string"?i.get(c):void 0;l&&n.push([r.blockToYjsElement(l)])}const s=t.toArray();for(let a=s.length-1;a>=0;a--){const c=s[a];c instanceof x.XmlElement&&c.nodeName==="footnote"&&t.delete(a,1)}}),Ze(r)}function bp(r,t,e,n,o="footnote"){if(!r.ydoc)return null;const i=et(),s=r.suggestions.isSuggesting(),a=s?Ct():void 0,c=$i(r),l=new Set(kn(r).map(m=>m.footnoteId).filter(m=>(c.get(m)??"footnote")===o)).size,d=Br(l+1,o);let u,g;{const m=z(r.getDocument(),t.block);if(m&&m.type==="paragraph"){g=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){u=b.marks.fontFamily;break}y=k}}}const p={footnoteRef:i,superscript:!0,...u?{fontFamily:u}:{},...s&&a?{insertion:!0,...r.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!r.insertTextNodes(t,[{type:"text",text:d,marks:p}],n))return null;const h=u??qe(r.getDocument().children),f={fontSize:ze,...h?{fontFamily:h}:{}};return r.transact(()=>{const m={type:"footnote",id:i,...o==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:et(),...g?{direction:g}:{},children:[{type:"text",text:e||"",marks:f}]}]},y=r.blockToYjsElement(m);if(y.setAttribute("id",i),o==="endnote"&&y.setAttribute("noteKind","endnote"),s&&a&&r.suggestions.setElementStructuralSuggestion(y,"insert",void 0,a,"Insert footnote"),r.getYNotesFragment().push([y]),!e){const b=y.toArray()[0];b instanceof x.XmlElement&&b.setAttribute("_emptyTextMarks",JSON.stringify(f))}}),Ze(r),{footnoteId:i,...a?{suggestionId:a}:{}}}function yp(r,t,e){const n=Ge(r).get(t);if(!n)return!1;let o=null;for(const l of n.toArray())if(l instanceof x.XmlElement&&l.nodeName==="paragraph"){o=l;break}if(!o)return!1;const i=xt(o);if(!i)return!1;const s=r.getDocument(),a=[...s.notes??[],...s.children.filter(l=>l.type==="footnote")].find(l=>l.id===t)?.children.flatMap(l=>l.type==="paragraph"?l.children:[]).find(l=>l.type==="text"&&l.marks?.fontFamily)?.marks?.fontFamily??qe(r.getDocument().children),c={fontSize:ze,...a?{fontFamily:a}:{}};return r.transact(()=>{i.length>0&&i.delete(0,i.length),e.length>0?kt(i,0,e,c):o.setAttribute("_emptyTextMarks",JSON.stringify(c))}),!0}function kp(r,t,e,n,o=!1){if(!e)return{success:!1,replacements:0,error:"The text to find must not be empty."};let i=null;const s=m=>{if(!i){for(const y of m.toArray())if(y instanceof x.XmlElement){if(y.getAttribute("id")===t){i=y;return}s(y)}}};for(const m of Ge(r).values()){if(m.getAttribute("id")===t){i=m;break}if(s(m),i)break}if(!i)return{success:!1,replacements:0,error:`Note block '${t}' was not found.`};const a=xt(i);if(!a)return{success:!1,replacements:0,error:`Note block '${t}' does not contain editable text.`};const c=mt(a).map(m=>typeof m.insert=="string"?m.insert:"").join(""),l=[];let d=0;for(;d<=c.length-e.length;){const m=c.indexOf(e,d);if(m<0)break;l.push(m),d=m+e.length}if(l.length===0)return{success:!1,replacements:0,error:`No match found for ${JSON.stringify(e)} in note block '${t}'.`};if(!o&&l.length>1)return{success:!1,replacements:0,error:`Found ${l.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 u=o?l:l.slice(0,1),g=r.suggestions.isSuggesting()?Ct():null,p=g?r.suggestions.buildInlineMetadataMarks(g,"Replace footnote text"):null,h=m=>{let y=0;for(const b of mt(a)){if(typeof b.insert!="string")continue;const k=y+b.insert.length;if(m<k){const v={...b.attributes??{}};return delete v.insertion,delete v.deletion,delete v.suggestionId,delete v.suggestionLabel,delete v.suggestionCreatedAt,v}y=k}return{fontSize:ze}},f=new Map(u.map(m=>[m,h(m)]));return r.transact(()=>{for(const m of[...u].reverse()){const y=f.get(m)??{fontSize:ze};g&&p?(It(a,m,e.length,{deletion:!0,...p}),n&&kt(a,m,n,{...y,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(m,e.length),n&&kt(a,m,n,y))}}),{success:!0,replacements:u.length,...g?{suggestionId:g}:{}}}function Sp(r,t){const e=Ge(r);return e.size===0?!1:(r.transact(()=>{for(const n of e.values())t==="endnote"?n.setAttribute("noteKind","endnote"):n.removeAttribute("noteKind")}),Ze(r),!0)}function Ip(r,t){const e=kn(r).filter(o=>o.footnoteId===t),n=Ge(r).get(t);if(e.length===0&&!n)return!1;if(r.suggestions.isSuggesting()){const o=Ct();return r.transact(()=>{for(const i of e)It(i.yText,i.start,i.length,{deletion:!0,...r.suggestions.buildInlineMetadataMarks(o,"Delete footnote")});n&&r.suggestions.setElementStructuralSuggestion(n,"delete",void 0,o,"Delete footnote")}),!0}return r.transact(()=>{for(const o of[...e].sort((i,s)=>s.start-i.start))o.yText.delete(o.start,o.length);if(n){const o=n.parent;if(o){const i=o.toArray().indexOf(n);i>=0&&o.delete(i,1)}}}),Ze(r),!0}function $c(r,t,e){const n=a=>{const c=new Map;for(const l of a)l.id&&c.set(l.id,(c.get(l.id)??0)+1);return c},o=n(r),i=n(t),s=a=>a.id&&o.get(a.id)===1&&i.get(a.id)===1?`id:${a.id}`:`content:${e(a)}`;return{beforeKeys:r.map(s),afterKeys:t.map(s)}}function Bi(r,t){const e=r.length,n=t.length,o=Array.from({length:e+1},()=>Array(n+1).fill(0));for(let c=1;c<=e;c++)for(let l=1;l<=n;l++)r[c-1]===t[l-1]?o[c][l]=o[c-1][l-1]+1:o[c][l]=Math.max(o[c-1][l],o[c][l-1]);const i=[];let s=e,a=n;for(;s>0&&a>0;)r[s-1]===t[a-1]?(i.unshift(r[s-1]),s-=1,a-=1):o[s-1][a]>o[s][a-1]?s-=1:a-=1;return i}function vp(r){let t=r,e=null;for(;t;){if(t instanceof x.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 i=0;for(let s=0;s<t.length;s++){const a=t.get(s);if(a===e)return{blockId:o,offset:i};if(a instanceof x.XmlElement&&a.nodeName==="list-item"){for(let c=0;c<a.length;c++){const l=a.get(c);if(l instanceof x.XmlText){i+=l.length;break}}i+=1}}return{blockId:o,offset:0}}}t=t.parent}return null}function xp(r,t,e,n){const o=r.getArray("paragraphs"),i=o.toArray().findIndex(a=>a?.get("id")===t);if(i<0)return null;const s=o.get(i);if(!s)return null;if(e==="paragraph")return s.get("content");if(e==="list"&&n!==void 0){const a=s.get("items");return!a||n>=a.length?null:a.get(n)?.get("content")}return null}function wp(r,t,e,n){const o=at(r,t);if(!o)return null;if(e==="paragraph"||e==="list-item")return xt(o);if(e==="list"&&n!==void 0){let i=0;for(let s=0;s<o.length;s++){const a=o.get(s);if(a instanceof x.XmlElement&&a.nodeName==="list-item"){if(i===n)return xt(a);i++}}}return null}function Bc(r,t,e,n){return wp(r,t,e,n)||(an(r)?xp(r,t,e,n):null)}function Re(r,t,e){const n=z(e,r.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const o=n,i=Bc(t,n.id,"paragraph");if(!i)return null;const s=o.children.filter(l=>l.type==="text").reduce((l,d)=>l+d.text.length,0),a=Math.max(0,Math.min(r.offset,s)),c=x.createRelativePositionFromTypeIndex(i,a);return{blockId:n.id,textOffset:c}}if(n.type==="list"){const o=n;let i=-1,s=r.offset;if(r.offset,r.block!==n.id){let d=0;for(let u=0;u<o.children.length;u++){if(o.children[u].id===r.block){i=u,d+r.offset;break}d+=xo(o.children[u]),u<o.children.length-1&&(d+=1)}}if(i===-1){let d=r.offset;for(let u=0;u<o.children.length;u++){const g=xo(o.children[u]),p=u<o.children.length-1?1:0;if(d<=g){i=u,s=d;break}d-=g+p,u===o.children.length-1&&(i=u,s=g)}}i===-1&&(i=0,s=0);const a=Bc(t,n.id,"list",i);if(!a)return null;const c=Math.max(0,Math.min(s,a.length)),l=x.createRelativePositionFromTypeIndex(a,c);return{blockId:n.id,textOffset:l}}return null}function Ap(r,t,e){const n=r.getArray("paragraphs");for(let o=0;o<n.length;o++){const i=n.get(o);if(!i)continue;const s=i.get("id");if(!s)continue;const a=i.get("type");if(a==="paragraph"&&i.get("content")===t)return{blockId:s,offset:0,yTextOffset:0};if(a==="list"){const c=i.get("items");if(!c)continue;const l=z(e,s);if(!l||l.type!=="list")continue;const d=l;let u=0;for(let g=0;g<c.length;g++){if(c.get(g)?.get("content")===t)return{blockId:s,offset:u,yTextOffset:0};g<d.children.length&&(u+=xo(d.children[g]),g<d.children.length-1&&(u+=1))}}}return null}function or(r,t){const e=x.createAbsolutePositionFromRelativePosition(r.textOffset,t);if(!e||!(e.type instanceof x.XmlText))return at(t,r.blockId)?{block:r.blockId,offset:0}:null;const n=e.index,o=e.type,i=vp(o);if(i)return{block:i.blockId,offset:i.offset+n};if(an(t)){const s=Tt(t),a=Ap(t,o,s);if(a)return{block:a.blockId,offset:a.offset+n}}return at(t,r.blockId)?{block:r.blockId,offset:n}:null}function J(r,t,e){return{anchor:r.anchor?Re(r.anchor,t,e):null,focus:r.focus?Re(r.focus,t,e):null}}function _i(r,t){return{anchor:r.anchor?or(r.anchor,t):null,focus:r.focus?or(r.focus,t):null}}function Qe(r){if(typeof window>"u")return null;try{return window.localStorage??null}catch(t){return console.warn(`[${r}] localStorage unavailable:`,t),null}}function Tp(r,t){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0}class Li{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 i=t.getXmlFragment("content");this.undoManager=new x.UndoManager(i,{trackedOrigins:new Set}),this.documentId,this.conversationId,this.storageKey,n?this.clearDocumentProposalCacheIfRemote():this.loadFromLocalStorage(),Cp(this.documentId,this)}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=x.encodeStateAsUpdate(this.ydoc)),this.cachedBaseUpdate}seedForkFromBase(t){return this.cachedBaseUpdateV2||(this.cachedBaseUpdateV2=x.encodeStateAsUpdateV2(this.ydoc)),x.applyUpdateV2(t,this.cachedBaseUpdateV2),t}computeStorageKey(){return this.conversationId?`proposals_${this.documentId}_${this.conversationId}`:`proposals_${this.documentId}`}clearDocumentProposalCacheIfRemote(){if(!this.isLikelyRemoteDocumentId())return;const t=Qe("DetachedSuggestionStore");if(!t)return;const e=`proposals_${this.documentId}`,n=[];for(let o=0;o<t.length;o++){const i=t.key(o);i&&(i===e||i.startsWith(`${e}_`))&&n.push(i)}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 i={...o};i.anchors&&(i.anchors=i.anchors.map(s=>({...s,from:s.from?btoa(String.fromCharCode(...s.from)):s.from,to:s.to?btoa(String.fromCharCode(...s.to)):s.to}))),t.metadata[n]=i}for(const[n,o]of this.paragraphSuggestions){const i=o.filter(s=>e.has(s));i.length>0&&(t.paragraphSuggestions[n]=i)}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 i=Uint8Array.from(atob(o),s=>s.charCodeAt(0));this.proposals.set(n,i)}if(t.metadata)for(const[n,o]of Object.entries(t.metadata)){const i={...o};i.anchors&&(i.anchors=i.anchors.map(s=>({...s,from:s.from?Uint8Array.from(atob(s.from),a=>a.charCodeAt(0)):s.from,to:s.to?Uint8Array.from(atob(s.to),a=>a.charCodeAt(0)):s.to}))),this.suggestionMeta.set(n,i)}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=Qe("DetachedSuggestionStore");if(!e)return null;const n=`proposals_${t}`;try{const o=e.getItem(n);if(!o)return null;const i=JSON.parse(o);return!i.proposals||Object.keys(i.proposals).length===0?null:{proposals:i.proposals||{},metadata:i.metadata||{},paragraphSuggestions:i.paragraphSuggestions||{}}}catch(o){return console.error("[DetachedSuggestionStore] Failed to read old format proposals:",o),null}}static clearOldFormatProposals(t){const e=Qe("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=Qe("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`,o=[];for(let i=0;i<e.length;i++){const s=e.key(i);s&&(s===n||s.startsWith(`${n}_`))&&o.push(s)}try{for(const i of o)e.removeItem(i)}catch(i){console.error("[DetachedSuggestionStore] Failed to clear stored proposals for document:",t,i)}}loadFromLocalStorage(){const t=Qe("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,i]of Object.entries(n.proposals)){const s=Uint8Array.from(atob(i),a=>a.charCodeAt(0));this.proposals.set(o,s)}if(n.metadata)for(const[o,i]of Object.entries(n.metadata)){const s=i;s.anchors&&(s.anchors=s.anchors.map(a=>({...a,from:a.from?Uint8Array.from(atob(a.from),c=>c.charCodeAt(0)):a.from,to:a.to?Uint8Array.from(atob(a.to),c=>c.charCodeAt(0)):a.to}))),this.suggestionMeta.set(o,s)}if(n.paragraphSuggestions)for(const[o,i]of Object.entries(n.paragraphSuggestions))this.paragraphSuggestions.set(o,i);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=Qe("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 i={...o};i.anchors&&(i.anchors=i.anchors.map(s=>({...s,from:s.from?btoa(String.fromCharCode(...s.from)):s.from,to:s.to?btoa(String.fromCharCode(...s.to)):s.to}))),e.metadata[n]=i}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 x.Doc),i=x.encodeStateVector(o);let s=[];o.transact(()=>{s=e(o)},"proposal-edit");const a=x.encodeStateAsUpdate(o,i);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:s,...n}),this.saveToLocalStorage(),this.notifyListeners(),s.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,i,s={}){return this.createSuggestion(t,a=>{const c=at(a,e);if(!c)return console.warn(`Paragraph ${e} not found for text deletion`),[];const l=xt(c);return l?(l.delete(n,o),[{kind:"delete",paragraphId:e,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(l,n,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(l,n+o,0)),text:i}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...s,id:t})}createTextInsertion(t,e,n,o,i={},s={}){const a={...i,proposalId:t};return this.createSuggestion(t,c=>{const l=at(c,e);if(!l)return console.warn(`Paragraph ${e} not found for text insertion`),[];const d=xt(l);return d?(kt(d,n,o,a),[{kind:"insert",paragraphId:e,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,n,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...s,id:t})}createTextReplacement(t,e,n,o,i,s={},a,c={}){const l={...s,proposalId:t};return this.createSuggestion(t,d=>{const u=at(d,e);if(!u)return console.warn(`Paragraph ${e} not found for text replacement`),[];const g=xt(u);return g?(g.delete(n,o),kt(g,n,i,l),[{kind:"replace",paragraphId:e,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(g,n,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(g,n+i.length,0)),text:i,oldText:a}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...c,id:t})}createPositionAwareInsertion(t,e,n,o,i={}){const s=this.generateId();return this.suggestionMeta.set(s,{id:s,authorId:i.authorId||"system",authorType:i.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...i}),this.saveToLocalStorage(),this.notifyListeners(),n.length,o.length,s}materializeWithSuggestion(t){const e=this.proposals.get(t);if(!e)return null;const n=new x.Doc;return this.seedForkFromBase(n),x.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 i of this.suggestionMeta.values()){const s=i.insertionContext;s&&e.set(s.paragraphId,s)}const n=new Set,o=[...t.mustBeAfter];for(;o.length>0;){const i=o.pop();if(n.has(i))continue;n.add(i);const s=e.get(i);s&&o.push(...s.mustBeAfter)}return n}applyPositionAwareInsertionToDoc(t,e,n){const o=n.insertionContext;if(!o)return;const i=this.expandPositionAwarePredecessors(o),s=t.getXmlFragment("content");let a=0;for(let l=s.length-1;l>=0;l--){const d=s.get(l);if(!(d instanceof x.XmlElement))continue;const u=d.getAttribute("id");if(u&&i.has(u)){a=l+1;break}}const c=_c(o.content,o.paragraphId,e);s.insert(a,[c])}materializeWithSuggestions(t){const e=new x.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 i=this.proposals.get(n);if(i){const s=x.encodeStateAsUpdate(e);Tt(e),x.applyUpdate(e,i);const a=x.encodeStateAsUpdate(e);if(Tt(e),!!Tp(s,a)&&o&&o.status==="pending")if(o.toolCallAction?.name==="remove_block"){const c=o.toolCallAction.arguments.id,l=ut(e,c);if(l){const{yParent:d,index:u}=l;d.delete(u,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 i=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{x.applyUpdate(this.ydoc,n),this.ensureTrailingParagraphInTransaction(i)},o),this.undoManager.stopCapturing(),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage();const s={type:"accept",suggestionId:t,timestamp:Date.now()};return s.suggestionId,this.undoStack.length,this.recordAction(s),this.notifyListeners(),!0}}acceptPositionAwareInsertion(t,e){const n=e.insertionContext,o=this.ydoc.getXmlFragment("content"),i=this.expandPositionAwarePredecessors(n);let s=0;const a=new Set;for(let l=0;l<o.length;l++){const d=o.get(l);if(d instanceof x.XmlElement){const u=d.getAttribute("id");u&&a.add(u)}}for(let l=o.length-1;l>=0;l--){const d=o.get(l);if(d instanceof x.XmlElement){const u=d.getAttribute("id");if(u&&i.has(u)){s=l+1;break}}}for(let l=0;l<o.length;l++){const d=o.get(l);if(d instanceof x.XmlElement){const u=d.getAttribute("id");if(u&&n.mustBeBefore.includes(u)){l<s&&(s=l);break}}}const c=`proposal-${t}`;return this.undoManager.trackedOrigins.add(c),this.ydoc.transact(()=>{const l=_c(n.content,n.paragraphId,t);o.insert(s,[l]),this.ensureTrailingParagraphInTransaction(o)},c),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 x.XmlElement)||e.nodeName==="paragraph")return;const n=new x.XmlElement("paragraph");n.setAttribute("id",et());const o=new x.XmlText;n.insert(0,[o]),t.insert(t.length,[n])}acceptSuggestions(t){let e=!0;const n=[],o=()=>{if(n.length===0)return;const i=[...n];n.length=0;const s=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{for(const a of i){const c=this.proposals.get(a);c?x.applyUpdate(this.ydoc,c):e=!1}this.ensureTrailingParagraphInTransaction(s)},"accept-proposals");for(const a of i){const c=this.suggestionMeta.get(a);c&&(c.status="accepted",this.suggestionMeta.set(a,c))}};for(const i of t)this.suggestionMeta.get(i)?.insertionContext?(o(),this.acceptProposal(i)||(e=!1)):n.push(i);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 i of n.anchors){const s=i.from?x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(i.from),e):null,a=i.to?x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(i.to),e):null;o.push({kind:i.kind,paragraphId:i.paragraphId,fromIndex:s?.index??null,toIndex:a?.index??null,text:i.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 i=e.anchors[o],s=n[o];if(i.paragraphId&&s.fromIndex===null)return"conflicted"}}try{const n=this.materializeWithSuggestion(t);if(!n)return"stale";const o=fo(this.ydoc),i=fo(n),s=e.anchors?.filter(a=>a.kind==="insert"&&!a.paragraphId).length||0;return Math.abs(i-o)>s+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(i=>t.has(i))&&e.push(n);return e}clearAllProposals(){this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.disableLocalStorage||Qe("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,Fi.get(this.documentId)===this&&Fi.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(()=>Wp),{findBlockById:o}=await import("./base64-CfDUyGi8.js").then(d=>d.U),i=Tt(this.ydoc),s=o(i,t);if(!s){console.warn(`[DetachedSuggestionStore] Paragraph ${t} not found in document`);return}if(s.type!=="paragraph")return;const a=new x.Doc;this.seedForkFromBase(a);for(const d of e){const u=this.proposals.get(d);u&&x.applyUpdate(a,u)}const c=Tt(a),l=o(c,t);if(l&&l.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(i=>i!==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;at(this.ydoc,d);const u=new x.Doc;this.seedForkFromBase(u);const g=x.encodeStateVector(u);fo(u),u.transact(()=>{if(an(u)){const h=u.getArray("paragraphs");for(let f=0;f<h.length;f++)if(h.get(f).get("id")===d){h.delete(f,1);break}}else{const h=ut(u,d);if(h){const{yParent:f,index:m}=h;f.delete(m,1)}}}),fo(u);const p=x.encodeStateAsUpdate(u,g);this.proposals.set(t,p),p.length;return}const i=new x.Doc;x.applyUpdate(i,e);const s=new x.Doc;x.applyUpdate(s,n);const a=Tt(i),c=Tt(s);if(a.children.length===c.children.length)for(let d=0;d<a.children.length;d++){const u=a.children[d],g=c.children[d];if(u.type!=="paragraph"||g.type!=="paragraph")continue;const p=u,h=g,f=l(p),m=l(h);if(f!==m&&p.id===h.id){p.id;const y=new x.Doc;this.seedForkFromBase(y);const b=x.encodeStateVector(y),{analyzeParagraphDiff:k}=await Promise.resolve().then(()=>Mg),v=k(f,m).diffs;y.transact(()=>{let I=null;if(an(y)){const w=y.getArray("paragraphs");for(let A=0;A<w.length;A++){const _=w.get(A);if(_.get("id")===p.id){I=_.get("content");break}}}else{const w=at(y,p.id);w&&(I=xt(w))}if(I){const w=[];for(const B of h.children)if(B.type==="text")for(let P=0;P<B.text.length;P++)w.push({node:B,indexInNode:P,marks:B.marks||{}});let A=0,_=0;for(const[B,P]of v)if(B===0)A+=P.length,_+=P.length;else if(B===-1)I.delete(A,P.length);else if(B===1){for(let $=0;$<P.length;$++){const T=w[_+$];if(T){const C={...T.marks,proposalId:t};kt(I,A+$,P[$],C)}}A+=P.length,_+=P.length}}});const S=x.encodeStateAsUpdate(y,b);this.proposals.set(t,S),this.saveToLocalStorage(),this.notifyListeners();return}}function l(d){return d.children.filter(u=>u.type==="text").map(u=>u.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 _c(r,t,e,n){if(r.type==="list"){const c=new x.XmlElement("list");return c.setAttribute("id",t),c.setAttribute("variant",r.variant??"unordered"),r.startNumber!==void 0&&c.setAttribute("startNumber",String(r.startNumber)),r.numberingChainId&&c.setAttribute("numberingChainId",r.numberingChainId),r.children.forEach(l=>{const d=new x.XmlElement("list-item");cn(d,l),d.setAttribute("id",l.id||et()),l.checked!==void 0&&d.setAttribute("checked",String(l.checked)),typeof l.indentLevel=="number"&&l.indentLevel>0&&d.setAttribute("indentLevel",String(l.indentLevel)),l.direction!==void 0&&d.setAttribute("direction",l.direction);const u=new x.XmlText;let g=0;l.children.forEach(p=>{if(p.type==="text"){const h=p,f=Ni(h.marks,e);u.insert(g,h.text,f),g+=h.text.length}}),d.insert(0,[u]),c.push([d])}),c}if(r.type==="table"){const c=r,l=new x.XmlElement("table");l.setAttribute("id",t),c.columnWidths&&l.setAttribute("columnWidths",JSON.stringify(c.columnWidths)),c.hasHeader&&l.setAttribute("hasHeader","true"),c.tableWidth!==void 0&&l.setAttribute("tableWidth",String(c.tableWidth)),c.align&&l.setAttribute("align",c.align),c.borderColor&&l.setAttribute("borderColor",c.borderColor),c.borderWidth!==void 0&&l.setAttribute("borderWidth",String(c.borderWidth)),c.cellPadding!==void 0&&l.setAttribute("cellPadding",String(c.cellPadding));for(const d of c.children){const u=new x.XmlElement("table-row");u.setAttribute("id",d.id||et());for(const g of d.children){const p=new x.XmlElement("table-cell");p.setAttribute("id",g.id||et()),g.verticalAlign&&p.setAttribute("verticalAlign",g.verticalAlign),g.backgroundColor&&p.setAttribute("backgroundColor",g.backgroundColor);for(const h of g.children)if(h.type==="paragraph"){const f=h,m=new x.XmlElement("paragraph");m.setAttribute("id",f.id||et()),f.heading&&m.setAttribute("heading",String(f.heading)),f.align&&m.setAttribute("align",f.align);const y=new x.XmlText;let b=0;for(const k of f.children)if(k.type==="text"){const v=k,S=Ni(v.marks,e);kt(y,b,v.text,S),b+=v.text.length}m.insert(0,[y]),p.push([m])}u.push([p])}l.push([u])}return l}if(r.type==="code"){const c=r,l=new x.XmlElement("code");l.setAttribute("id",t),c.language&&l.setAttribute("language",c.language),c.renderDiagram!==void 0&&l.setAttribute("renderDiagram",String(c.renderDiagram)),c.showDiagramSource!==void 0&&l.setAttribute("showDiagramSource",String(c.showDiagramSource));const d=new x.XmlText;return l.insert(0,[d]),kt(d,0,c.content||""),l}if(r.type==="math"){const c=r,l=new x.XmlElement("math");l.setAttribute("id",t),c.displayMode&&l.setAttribute("displayMode",c.displayMode),c.align&&l.setAttribute("align",c.align);const d=new x.XmlText;return l.insert(0,[d]),kt(d,0,c.content||""),l}if(r.type==="image"){const c=r,l=new x.XmlElement("image");return l.setAttribute("id",t),l.setAttribute("src",c.src),c.sourceUrl&&l.setAttribute("sourceUrl",c.sourceUrl),l.setAttribute("width",String(c.width)),l.setAttribute("height",String(c.height)),c.alt&&l.setAttribute("alt",c.alt),c.align&&l.setAttribute("align",c.align),l}if(r.type==="page-break"){const c=new x.XmlElement("page-break");return c.setAttribute("id",t),c}if(r.type==="toc")return Ut({...r,id:t});if(r.type==="section-break"){const c=new x.XmlElement("section-break");return c.setAttribute("id",t),r.layout&&c.setAttribute("layout",JSON.stringify(r.layout)),r.breakType&&c.setAttribute("breakType",r.breakType),c}const o=new x.XmlElement("paragraph"),i=r;o.setAttribute("id",t),i.heading&&o.setAttribute("heading",String(i.heading)),i.align&&o.setAttribute("align",i.align);const s=new x.XmlText;let a=0;return i.children.forEach(c=>{if(c.type==="text"){const l=c,d=Ni(l.marks,e);kt(s,a,l.text,d),a+=l.text.length}}),o.insert(0,[s]),o}function Ni(r,t,e){return{...r||{},proposalId:t}}const Fi=new Map;function Cp(r,t){Fi.set(r,t)}const Pp=new Set(["Arial","Arial, sans-serif"]);function Ei(r){if(typeof r!="string")return;const t=r.trim();if(!(!t||Pp.has(t)))return t}function rr(r){const t={};for(const e of po)if(r[e]!==void 0)if(e==="fontFamily"){const n=Ei(r[e]);n&&(t[e]=n)}else(e==="color"||e==="backgroundColor")&&typeof r[e]=="string"&&/^#[0-9a-fA-F]{6}$/.test(r[e])?t[e]=r[e].toLowerCase():t[e]=r[e];return t}const Lc=Ts.filter(r=>!po.includes(r));function Sn(r){const t=rr(r);for(const e of Lc)r[e]!==void 0&&(t[e]=r[e]);return t}function Mp(r){const t=Nc(r);for(const e of Lc)r[e]!==void 0&&(t[e]=r[e]);return t}function Ri(r,t){return JSON.stringify(Sn(r||{}))===JSON.stringify(Sn(t||{}))}function Nc(r){const t=rr(r);t.docxRunPropertyResets=r.docxRunPropertyResets??null;for(const e of po)e in t||(t[e]=null);return t}function Di(r,t){const e=rr(r||{}),n=rr(t||{});return JSON.stringify(e)===JSON.stringify(n)}function Fc(r,t){for(const e of bo){const n=r[e],o=t[e];if(e==="link"||e==="backgroundColor"||e==="color"){const i=c=>typeof c=="string"&&/^#[0-9a-fA-F]{6}$/.test(c),s=i(n)?n.toLowerCase():n,a=i(o)?o.toLowerCase():o;if(s!==a)return!1}else if(e==="fontFamily"){if(Ei(n)!==Ei(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 Ec{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 De(r,t){return{...r,id:t}}function $p(r,t,e){const n=new Set(r),o=i=>{if(i){if(i.block.type==="table"&&i.block.id){n.add(i.block.id);return}for(let s=i.containerPath.length-1;s>=0;s--){const a=i.containerPath[s];if((e.get(a)?.block??t.get(a)?.block)?.type==="table"){n.add(a);break}}}};for(const i of r)o(e.get(i)),o(t.get(i));return n}function Rc(r){return JSON.stringify(r.children.map(t=>[t.id,t.children.map(e=>[e.id,e.rowSpan??1,e.colSpan??1])]))}function Dc(r){return JSON.stringify({...r,children:r.children.map(t=>({...t,children:t.children.map(e=>({...e,children:[]}))}))})}function Bp(r,t){return{...t,children:t.children.map((e,n)=>({...e,children:e.children.map((o,i)=>({...o,children:r.children[n].children[i].children}))}))}}function Oi(r,t,e){const n=e?.affectedBlockIds?new Set(Array.from(e.affectedBlockIds).filter(N=>typeof N=="string"&&N.length>0)):null,o=t.getYDoc(),i=Array.from(t.getPendingSuggestions().keys()),s=i.length>0?t.materializeWithSuggestions(i):o,a=e?.precomputedLiveDocSchema??Tt(o),c=e?.precomputedCurrentDocSchema??(s===o?a:Tt(s)),l=e?.precomputedFinalDocSchema??Tt(r),d=we(a),u=we(c),g=we(l),p=n?$p(n,u,g):null,h=new Set;for(const N of new Set([...d.keys(),...g.keys()])){const L=d.get(N)?.block,R=g.get(N)?.block;L?.type!=="table"&&R?.type!=="table"||(L?.type!=="table"||R?.type!=="table"||Rc(L)!==Rc(R)||ko(L,R))&&h.add(N)}if(p)for(const[N,L]of new Map([...d,...g]))L.containerPath.some(R=>p.has(R))&&p.add(N);const f=new Set(Array.from(e?.atomicReplaceBlockIds??[]).filter(N=>typeof N=="string"&&N.length>0)),m=new Map;for(const N of e?.replacementBlockMatches??[])typeof N?.currentBlockId!="string"||N.currentBlockId.length===0||typeof N?.finalBlockId!="string"||N.finalBlockId.length===0||m.set(N.finalBlockId,N.currentBlockId);const y=N=>{const L=m.get(N);return L&&d.has(L)?L:N},b=!!p&&p.size>0,k=t.getPendingSuggestions();if(b){const N=new Set;for(const L of p){const R=t.getSuggestionsForParagraph(L);for(const M of R)k.has(M)&&N.add(M)}for(const L of N)t.deleteSuggestion(L)}else for(const[N]of k)t.deleteSuggestion(N);const v=[],S=new Set,I=new Set,w=u;for(const[N,L]of d){const R=L.block;if(R.type!=="list"||g.has(N)||R.children.length===0||b&&!p.has(N)||L.containerPath.some(W=>h.has(W)))continue;const M=w.get(N)?.block,F=(e?.listUnwrapMemberIds?.get(N)??(M?.type==="list"?M.children:R.children).map(W=>W.id)).map(W=>g.get(W)).filter(W=>!!W),j=F[0];if(!j||F.some((W,ct)=>W.containerPath.join("/")!==L.containerPath.join("/")||ct>0&&W.indexInParent<=F[ct-1].indexInParent))continue;const D=j.containerPath.at(-1),O=D?g.get(D)?.block:null,H=(O&&"children"in O?O.children:l.children).slice(j.indexInParent,F.at(-1).indexInParent+1);if(H.some(W=>!W.id||d.has(W.id)))continue;const q=`prop_${et()}`;t.createSuggestion(q,W=>{const ct=ut(W,N);return ct?(ct.yParent.delete(ct.index,1),ct.yParent.insert(ct.index,H.map(vt=>Ut(vt))),[{kind:"replace",paragraphId:N,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:N,blocks:H},description:"AI: remove list markers"}),v.push(q),S.add(N),t.setSuggestionsForParagraph(N,[q]);for(const W of H)I.add(W.id),t.setSuggestionsForParagraph(W.id,[q])}const A=[],_=b?Array.from(p).filter(N=>g.has(N)):Array.from(g.keys());for(const N of _){const L=g.get(N);if(!L||I.has(N)||L.containerPath.some(D=>I.has(D)))continue;const R=L.block,M=m.get(N);if(R.type==="container"||R.type==="table-cell"||L.containerPath.some(D=>h.has(D)))continue;const F=M?d.get(M)??d.get(N):d.get(N),j=M&&F?.block.id===M&&M!==N?M:null;if(F?.block.id&&S.add(F.block.id),R.type==="paragraph"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type==="paragraph"){const O=F.block,H=zi(O),q=zi(D);if(H!==q||Hp(O,D)){if(f.has(N)){const ct=ji(t,D);ct&&(v.push(ct),D.id&&t.setSuggestionsForParagraph(D.id,[ct]));continue}const W=Oc(t,O,D);v.push(...W)}}else{const O=ji(t,D);O&&(v.push(O),D.id&&t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="list"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type==="list"){const O=F.block;if(Bs(O,D)){if(!Op(O,D)){const H=_p(t,O,D);H.length>0&&O.id&&(v.push(...H),t.setSuggestionsForParagraph(O.id,H))}}else{const H=qi(t,D);H&&O.id&&(v.push(H),t.setSuggestionsForParagraph(O.id,[H]))}}else{const O=qi(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="table"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type==="table"){const O=F.block,H=h.has(D.id);if(H||Dc(O)!==Dc(D)){const q=jc(t,H?D:Bp(O,D));q&&(v.push(q),t.setSuggestionsForParagraph(D.id,[q]))}}else{const O=jc(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="code"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type==="code"){const O=F.block;if(O.content!==D.content||O.language!==D.language){const H=Uc(t,D);H&&D.id&&(v.push(H),t.setSuggestionsForParagraph(D.id,[H]))}}else{const O=Uc(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="math"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type==="math"){const O=F.block;if(O.content!==D.content||O.displayMode!==D.displayMode||O.align!==D.align){const H=qc(t,D);H&&D.id&&(v.push(H),t.setSuggestionsForParagraph(D.id,[H]))}}else{const O=qc(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="image"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type==="image"){const O=F.block;if(O.src!==D.src||O.width!==D.width||O.height!==D.height||O.alt!==D.alt||O.align!==D.align){const H=zc(t,D);H&&D.id&&(v.push(H),t.setSuggestionsForParagraph(D.id,[H]))}}else{const O=zc(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="page-break"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type!=="page-break"){const O=Rp(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}else if(R.type==="toc"){const D=j!==null?De(R,j):R;if(!F)A.push({location:L});else if(F.block.type!=="toc"||F.block.levels!==D.levels||F.block.instr!==D.instr||F.block.fontFamily!==D.fontFamily||F.block.fontSize!==D.fontSize||F.block.color!==D.color||F.block.direction!==D.direction||F.block.align!==D.align){const O=Dp(t,D);O&&D.id&&(v.push(O),t.setSuggestionsForParagraph(D.id,[O]))}}}A.sort((N,L)=>{const R=N.location.containerPath,M=L.location.containerPath,F=Math.min(R.length,M.length);for(let j=0;j<F;j++)if(R[j]!==M[j])return R[j].localeCompare(M[j]);return R.length!==M.length?R.length-M.length:N.location.indexInParent-L.location.indexInParent});const B=N=>{const L=N.containerPath.at(-1),R=L?g.get(L)?.block:null;return R&&"children"in R?R.children:l.children},P=N=>{const L=B(N);for(let R=N.indexInParent-1;R>=0;R--){const M=L[R];if(M.id)return y(M.id)}return null},$=N=>{const L=B(N),R=(()=>{for(let F=N.indexInParent-1;F>=0;F--)if(L[F]?.id)return y(L[F].id);return null})(),M=(()=>{for(let F=N.indexInParent-1;F>=0;F--){const j=L[F]?.id;if(!j)continue;const D=y(j);if(d.has(D))return D}return null})();return Array.from(new Set([M,R].filter(F=>typeof F=="string"&&F.length>0)))},T=[];for(const N of A){const L=N.location,R=P(L),M=T[T.length-1];if(M&&M.afterId===R&&M.containerPath.join("/")===L.containerPath.join("/")&&M.blocks[M.blocks.length-1].location.indexInParent===L.indexInParent-1){M.blocks.push(N);continue}T.push({afterId:R,containerPath:L.containerPath,blocks:[N]})}for(const N of T){const L=N.afterId&&d.has(N.afterId);if(N.blocks.length===1&&L){const{location:R}=N.blocks[0],M=R.block,F=qp(t,M,N.afterId,a);F&&(v.push(F),M.id&&t.setSuggestionsForParagraph(M.id,[F]))}else for(let R=0;R<N.blocks.length;R++){const{location:M}=N.blocks[R],F=M.block;if(F.type!=="paragraph"&&F.type!=="list"&&F.type!=="table"&&F.type!=="code"&&F.type!=="math"&&F.type!=="image"&&F.type!=="page-break"&&F.type!=="toc"){console.warn("[SuggestionPlanner] Skipping unsupported block type for position-aware insertion:",F.type);continue}const j=$(M),D=t.createPositionAwareInsertion(F.id,F,j,B(M).slice(M.indexInParent+1).map(O=>O.id).filter(O=>!!O&&d.has(O)).slice(0,1),{authorType:"ai",description:`AI: insert_${F.type} (position-aware)`});D&&(v.push(D),t.setSuggestionsForParagraph(F.id,[D]))}}const C=b?Array.from(p).filter(N=>d.has(N)):Array.from(d.keys());for(const N of C){const L=d.get(N);if(!L||S.has(N))continue;const R=L.block,M=R.type==="container"&&b&&!!p?.has(N);if(!(R.type==="container"&&!M)&&R.type!=="table-cell"&&!L.containerPath.some(F=>h.has(F))&&(R.type==="paragraph"||R.type==="list"||R.type==="table"||R.type==="code"||R.type==="math"||R.type==="image"||R.type==="page-break"||R.type==="section-break"||R.type==="toc"||M)){const F=Up(t,R);F&&(v.push(F),t.setSuggestionsForParagraph(N,[F]))}}return v}function Oc(r,t,e){const n=[];if(!Mn(t,e)){const g=ji(r,e);if(g)return r.setSuggestionsForParagraph(e.id,[g]),[g]}const o=g=>{const p=[];return g.children.forEach((h,f)=>{if(h.type==="text"){const m=h;for(let y=0;y<m.text.length;y++)p.push({char:m.text[y],marks:m.marks||{},nodeIndex:f,charIndexInNode:y})}}),p},i=o(t),s=o(e),a=i.map(g=>g.char).join(""),c=s.map(g=>g.char).join(""),l=qo(a,c).diffs;let d=0,u=0;for(let g=0;g<l.length;g++){const[p,h]=l[g];if(p===0){const f=h.length;for(let m=0;m<f;m++){const y=i[d+m],b=s[u+m],k=y?.marks||{},v=b?.marks||{};if(!Fc(k,v)){const S=m;let I=m+1;for(;I<f;){const P=i[d+I]?.marks||{},$=s[u+I]?.marks||{};if(Fc(P,$)||!Ri($,v))break;I++}const w=h.substring(S,I),A=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_=Mp(v),B=r.createTextReplacement(A,e.id,d+S,I-S,w,_,w,{authorType:"ai",description:"AI: apply formatting"});B&&n.push(B),m=I-1}}d+=h.length,u+=h.length}else if(p===-1){const f=h.length,m=g+1<l.length?l[g+1]:null;if(m&&m[0]===1){const y=m[1];let b=!0;if(y.length>1){const k=u<s.length?s[u].marks:{};for(let v=1;v<y.length;v++){const S=u+v<s.length?s[u+v].marks:{};if(!Di(k,S)){b=!1;break}}}if(b){const k=u<s.length?s[u].marks:{},{...v}=k,S=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=r.createTextReplacement(S,e.id,d,f,y,v,h,{authorType:"ai",description:"AI: replace text"});I&&n.push(I)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,v=r.createSuggestion(k,S=>{const I=at(S,e.id);let w=null;if(I)for(let B=0;B<I.length;B++){const P=I.get(B);if(P instanceof x.XmlText){w=P;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting replacement`),[];w.delete(d,f);let A=d,_=0;for(;_<y.length;){const B=_,P=u+_,$=P<s.length?Sn(s[P].marks):{};let T=_+1;for(;T<y.length;){const N=u+T,L=N<s.length?Sn(s[N].marks):{};if(!Ri($,L))break;T++}const C=y.substring(B,T);kt(w,A,C,{...$,suggestionId:k}),A+=C.length,_=T}return[{kind:"replace",paragraphId:e.id,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(w,d,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(w,d+y.length,0)),text:y,oldText:h}]},{authorType:"ai",description:"AI: replace text"});v&&n.push(v)}g++,d+=f,u+=y.length}else{const y=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,b=r.createTextDeletion(y,e.id,d,f,h,{authorType:"ai",description:"AI: delete text"});b&&n.push(b),d+=f}}else if(p===1){const f=h,m=g>0?l[g-1]:null;if(m&&m[0]===-1)continue;const y=[];let b=0;for(;b<f.length;){const k=b,v=u+b,S=v<s.length?s[v].marks:{},I=Sn(S);let w=b+1;for(;w<f.length;){const _=u+w,B=_<s.length?s[_].marks:{};if(!Ri(I,B))break;w++}const A=f.substring(k,w);y.push({text:A,marks:I}),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)}`,v=r.createTextInsertion(k,e.id,d,f,{},{authorType:"ai",description:"AI: insert text"});v&&n.push(v)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,v=r.createSuggestion(k,S=>{const I=at(S,e.id);let w=null;if(I)for(let _=0;_<I.length;_++){const B=I.get(_);if(B instanceof x.XmlText){w=B;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting insertion`),[];let A=d;for(const _ of y){const B={..._.marks,suggestionId:k};kt(w,A,_.text,B),A+=_.text.length}return[{kind:"insert",paragraphId:e.id,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(w,d,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(w,d+f.length,0)),text:f}]},{authorType:"ai",description:"AI: insert text"});v&&n.push(v)}u+=f.length}}return e.id&&n.length>0&&r.setSuggestionsForParagraph(e.id,n),n}function ji(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};if(r.createBlockReplacementSuggestion){const n=r.createBlockReplacementSuggestion(t,e);if(n)return n}return r.createSuggestionFromToolCall(e,(n,o)=>{const i=ut(n,t.id);if(!i||i.yBlock.nodeName!=="paragraph")return ve(n,o);const s=xt(i.yBlock)?.toDelta().map(l=>typeof l.insert=="string"?l.insert:"").join("")??"";i.yParent.delete(i.index,1);const a=Ut(t);i.yParent.insert(i.index,[a]);const c=xt(a);return[{kind:"replace",paragraphId:t.id,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(c,0,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(c,c.length,0)),text:zi(t),oldText:s}]})}function _p(r,t,e){const n=[],o=t.children.map(b=>({item:b,text:tn(b),signature:Ui(b)})),i=e.children.map(b=>({item:b,text:tn(b),signature:Ui(b)})),{beforeKeys:s,afterKeys:a}=$c(t.children,e.children,Ui),c=Bi(s,a),l=[],d=(b,k,v)=>{const S=Math.min(b.length,k.length);for(let I=0;I<S;I++)l.push({kind:"replace",index:v+I,currentItem:b[I],finalItem:k[I]});for(let I=S;I<b.length;I++)l.push({kind:"delete",index:v+I,currentItem:b[I]});for(let I=k.length-1;I>=S;I--)l.push({kind:"insert",index:v+S,finalItem:k[I]})};let u=0,g=0;for(const b of c){let k=u;for(;k<o.length&&s[k]!==b;)k+=1;let v=g;for(;v<i.length&&a[v]!==b;)v+=1;d(o.slice(u,k),i.slice(g,v),u),u=k+1,g=v+1;const S=o[k],I=i[v];S&&I&&(S.signature!==I.signature||!Xc(S.item,I.item))&&l.push({kind:"replace",index:k,currentItem:S,finalItem:I})}d(o.slice(u),i.slice(g),u);const p=l.some(b=>b.kind!=="replace"?!0:b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text);if(l.length>0&&!p){const b=Lp(r,e);return b?[b]:[]}for(const b of l){if(b.kind==="insert"){const v=Np(r,t.id,b.finalItem.item,b.index,t.variant);v&&n.push(v);continue}if(b.kind==="delete"){const v=Fp(r,t.id,b.index,b.currentItem.text);v&&n.push(v);continue}const k=Ep(r,t.id,b.index,b.currentItem.item,b.finalItem.item,t.variant);k&&n.push(k)}const h=l.filter(b=>b.kind==="replace").length,f=l.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,i.length),y=m>0?n.length/m:0;if(h>0&&y>.7&&f){const b=qi(r,e);return b?[b]:[]}return n}function Lp(r,t){if(!t.id)return null;const e=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return r.createSuggestion(e,n=>{const o=at(n,t.id);if(!o||o.nodeName!=="list")return[];for(let i=0;i<t.children.length;i++){const s=o.get(i),a=t.children[i];if(!(s instanceof x.XmlElement)||!a)continue;const c=xt(s);if(!c)continue;let l=0;for(const d of a.children)d.type!=="text"||d.text.length===0||(It(c,l,d.text.length,Nc(d.marks||{})),l+=d.text.length)}return[{kind:"replace",paragraphId:t.id,text:t.children.map(tn).join(`
27
- `),oldText:t.children.map(tn).join(`
28
- `)}]},{authorType:"ai",description:"AI: apply list formatting"})}function Np(r,t,e,n,o){const i=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return r.createSuggestion(i,s=>{const a=at(s,t);if(!a||a.nodeName!=="list")return console.warn(`List ${t} not found for item insertion`),[];const c=new x.XmlElement("list-item");cn(c,e),c.setAttribute("id",e.id||et()),e.checked!==void 0&&c.setAttribute("checked",String(e.checked)),e.indentLevel&&c.setAttribute("indentLevel",String(e.indentLevel)),e.direction!==void 0&&c.setAttribute("direction",e.direction);const l=new x.XmlText;let d=0;e.children.forEach(g=>{if(g.type==="text"){const p=g,h={...p.marks||{},suggestionId:i,toolType:"list_item_insert"};l.insert(d,p.text,h),d+=p.text.length}}),c.insert(0,[l]);const u=Math.min(n,a.length);return a.insert(u,[c]),[{kind:"insert",paragraphId:t,text:tn(e)}]},{authorType:"ai",description:"AI: insert list item"})}function Fp(r,t,e,n){const o=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return r.createSuggestion(o,i=>{const s=at(i,t);return!s||s.nodeName!=="list"?(console.warn(`List ${t} not found for item deletion`),[]):e>=s.length?(console.warn(`Item index ${e} out of bounds for list ${t}`),[]):(s.delete(e,1),[{kind:"delete",paragraphId:t,text:n}])},{authorType:"ai",description:"AI: delete list item"})}function Ep(r,t,e,n,o,i){const s=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return r.createSuggestion(s,a=>{const c=at(a,t);if(!c||c.nodeName!=="list")return console.warn(`List ${t} not found for item replacement`),[];if(e>=c.length)return console.warn(`Item index ${e} out of bounds for list ${t}`),[];const l=c.get(e);if(!(l instanceof x.XmlElement))return console.warn(`Item at index ${e} is not an XmlElement`),[];cn(l,o),o.direction!==n.direction&&(o.direction!==void 0?l.setAttribute("direction",o.direction):l.removeAttribute("direction")),o.checked!==n.checked&&(o.checked!==void 0?l.setAttribute("checked",String(o.checked)):l.removeAttribute("checked")),o.indentLevel!==n.indentLevel&&(o.indentLevel?l.setAttribute("indentLevel",String(o.indentLevel)):l.removeAttribute("indentLevel"));let d=null;for(let p=0;p<l.length;p++){const h=l.get(p);if(h instanceof x.XmlText){d=h;break}}if(!d)return console.warn(`No content found in list item at index ${e}`),[];const u=d.length;u>0&&d.delete(0,u);let g=0;return o.children.forEach(p=>{if(p.type==="text"){const h=p,f={...Sn(h.marks||{}),suggestionId:s,toolType:"list_item_replace"};d.insert(g,h.text,f),g+=h.text.length}}),[{kind:"replace",paragraphId:t,text:tn(o),oldText:tn(n)}]},{authorType:"ai",description:"AI: replace list item"})}function tn(r){return r.children.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ui(r){return JSON.stringify({...Object.fromEntries(mo.map(t=>[t,r[t]])),direction:r.direction,checked:r.checked??!1,indentLevel:r.indentLevel??0,children:r.children.map(t=>t.type==="text"?{type:"text",text:t.text}:{type:t.type})})}function qi(r,t){const e={name:"replace_block",arguments:{id:t.id,content:jp(t)}};return r.createSuggestionFromToolCall(e,n=>{const o=ut(n,t.id);return o?(o.yParent.delete(o.index,1),o.yParent.insert(o.index,[Ut(t)]),[{kind:"replace",paragraphId:t.id,text:"List replaced",oldText:o.yBlock.nodeName==="list"?"List":"Paragraph"}]):[]})}function jc(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toInternalHtml({type:"doc",children:[t]})}};return r.createSuggestionFromToolCall(e,(n,o)=>ve(n,o))}function Uc(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return r.createSuggestionFromToolCall(e,(n,o)=>ve(n,o))}function qc(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return r.createSuggestionFromToolCall(e,(n,o)=>ve(n,o))}function zc(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toInternalImageHtml(t)}};return r.createSuggestionFromToolCall(e,(n,o)=>ve(n,o))}function Rp(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return r.createSuggestionFromToolCall(e,(n,o)=>ve(n,o))}function Dp(r,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return r.createSuggestionFromToolCall(e,(n,o)=>ve(n,o))}function Op(r,t){if(r.children.length!==t.children.length)return!1;for(let e=0;e<r.children.length;e++){const n=r.children[e],o=t.children[e];if(mo.some(a=>n[a]!==o[a])||n.direction!==o.direction||n.checked!==o.checked||n.indentLevel!==o.indentLevel)return!1;const i=n.children.filter(a=>a.type==="text").map(a=>a.text).join(""),s=o.children.filter(a=>a.type==="text").map(a=>a.text).join("");if(i!==s||!Xc(n,o))return!1}return!0}function Xc(r,t){if(r.children.length!==t.children.length)return!1;for(let e=0;e<r.children.length;e++){const n=r.children[e],o=t.children[e];if(n.type!==o.type||n.type==="text"&&o.type==="text"&&(n.text!==o.text||!Di(n.marks||{},o.marks||{})))return!1}return!0}function jp(r){return it.toInternalHtml({type:"doc",children:[r]})}function Up(r,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 r.createSuggestion(o,i=>{const s=ut(i,e);if(!s)return console.warn(`[SuggestionPlanner] Block ${e} not found for removal`),[];const{yBlock:a,yParent:c,index:l}=s,d=a.nodeName;let u;if(d==="list")u={kind:"delete",paragraphId:e,text:"List removed"};else{let g="";for(let p=0;p<a.length;p++){const h=a.get(p);if(h instanceof x.XmlText){const f=mt(h);for(const m of f)m.insert&&typeof m.insert=="string"&&(g+=m.insert)}}u={kind:"delete",paragraphId:e,text:g||"Block removed"}}return c.delete(l,1),[u]},{authorType:"ai",toolCallAction:n,description:"AI: remove_block"})}function qp(r,t,e,n){let o,i;e===null?n.children.length>0?(o=n.children[0].id,i="before"):(o=Rn,i="after"):(o=e,i="after");const s={name:"insert_block",arguments:{referenceId:o,position:i,content:[zp(t)]}};return zt(s,{stableId:t.id||et()}),r.createSuggestionFromToolCall(s,(a,c)=>ve(a,c))}function zp(r){return r.type==="paragraph"?Xp(r):r.type==="image"?it.toInternalImageHtml(r):r.type==="list"||r.type==="table"||r.type==="code"||r.type==="math"||r.type==="page-break"||r.type==="toc"?it.toInternalHtml({type:"doc",children:[r]}):""}function oe(r){return r.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Xp(r,t){const e=r.heading?`h${r.heading}`:"p",n=[];r.align&&n.push(`text-align: ${r.align}`);const o=n.length>0?` style="${n.join("; ")}"`:"";let i=`<${e}${o}>`;for(const s of r.children)if(s.type==="text"){let a=s.text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");if(s.marks?.bold&&(a=`<b>${a}</b>`),s.marks?.italic&&(a=`<i>${a}</i>`),s.marks?.underline&&(a=`<u>${a}</u>`),s.marks?.strikethrough&&(a=`<s>${a}</s>`),s.marks?.code&&(a=`<code>${a}</code>`),s.marks?.latex&&(a=`<latex-inline>${a}</latex-inline>`),s.marks?.superscript||s.marks?.footnoteRef){const u=s.marks?.footnotePendingBody!==void 0?` data-footnote="${oe(s.marks.footnotePendingBody)}"${s.marks?.footnotePendingKind==="endnote"?' data-note-kind="endnote"':""}`:"";a=s.marks?.footnoteRef?`<sup data-footnote-ref="${oe(s.marks.footnoteRef)}"${u}>${a}</sup>`:`<sup>${a}</sup>`}else s.marks?.subscript&&(a=`<sub>${a}</sub>`);const c=s.marks?.fontFamily,l=s.marks?.fontSize;if(c||l||s.marks?.color||s.marks?.doubleStrikethrough||s.marks?.smallCaps||s.marks?.allCaps||s.marks?.letterSpacing){const u=[];c&&u.push(`font-family: ${oe(c)}`),l&&u.push(`font-size: ${l}px`),s.marks?.color&&u.push(`color: ${oe(s.marks.color)}`),s.marks?.doubleStrikethrough&&u.push("text-decoration: line-through double"),s.marks?.smallCaps&&u.push("font-variant: small-caps"),s.marks?.allCaps&&u.push("text-transform: uppercase"),typeof s.marks?.letterSpacing=="number"&&Number.isFinite(s.marks.letterSpacing)&&s.marks.letterSpacing!==0&&u.push(`letter-spacing: ${s.marks.letterSpacing}px`),a=`<span style="${u.join("; ")}">${a}</span>`}s.marks?.hidden&&(a=`<span data-word-hidden="true">${a}</span>`),s.marks?.lang&&(a=`<span data-word-lang="${oe(s.marks.lang)}">${a}</span>`),s.marks?.bookmark&&(a=`<span data-bookmark="${oe(s.marks.bookmark)}">${a}</span>`),s.marks?.fieldInstr&&(a=`<span data-field-instr="${oe(s.marks.fieldInstr)}">${a}</span>`),s.marks?.field&&(a=`<span data-dynamic-field="${oe(s.marks.field)}">${a}</span>`),s.marks?.sdtInline&&(a=`<span data-sdt-inline="${oe(s.marks.sdtInline)}">${a}</span>`),s.marks?.aiGenerated&&(a=`<span data-ai-generated="true">${a}</span>`),s.marks?.__htmlClassName&&(a=`<span data-html-class="${oe(s.marks.__htmlClassName)}">${a}</span>`);const d=ue(s.marks?.backgroundColor);if(d&&(a=`<mark color="${oe(d)}">${a}</mark>`),s.marks?.link&&(a=`<a href="${oe(s.marks.link)}">${a}</a>`),s.marks?.comment)for(const u of s.marks.comment.split(",").map(g=>g.trim()).filter(Boolean).reverse())a=`<comment-thread id="${oe(u)}">${a}</comment-thread>`;i+=a}return i+=`</${e}>`,i}function zi(r){return r.children.filter(t=>t.type==="text").map(t=>t.type==="text"?t.text:"").join("")}function Hp(r,t){if(!Mn(r,t)||r.children.length!==t.children.length)return!0;for(let e=0;e<r.children.length;e++){const n=r.children[e],o=t.children[e];if(n.type!==o.type||n.type==="text"&&o.type==="text"&&(n.text!==o.text||!Di(n.marks||{},o.marks||{})))return!0}return!1}const Wp=Object.freeze(Object.defineProperty({__proto__:null,ToolCallHistory:Ec,createFlattenedSuggestions:Oi,createGranularSuggestionsForParagraph:Oc},Symbol.toStringTag,{value:"Module"}));class Xi{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=x.encodeStateAsUpdateV2(this.ydoc),this.ydoc.on("update",this.invalidateBaseUpdate)),this.cachedBaseUpdate}seedFork(){const t=new x.Doc;return x.applyUpdateV2(t,this.getBaseUpdate()),t}createForklessTextSuggestion(t){const e=at(this.ydoc,t.paragraphId),n=e?xt(e):null;if(!n||t.startOffset+t.deleteLength>n.length)return null;const o=t.kind==="delete"?t.startOffset+t.deleteLength:t.startOffset,i=x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(n,o,0)),s=x.encodeRelativePosition(x.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:i,to:s,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(),i=x.encodeStateVector(o);let s=[];o.transact(()=>{s=e(o)},"proposal-edit");const a=x.encodeStateAsUpdate(o,i);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:s,...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?at(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,i,s={}){return this.createForklessTextSuggestion({id:t,kind:"delete",paragraphId:e,startOffset:n,deleteLength:o,newText:"",marks:{},anchorText:i,metadata:{...s,id:t}})||this.createSuggestion(t,c=>{const l=at(c,e);if(!l)return[];const d=xt(l);return d?(d.delete(n,o),[{kind:"delete",paragraphId:e,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,n,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,n+o,0)),text:i}]):[]},{...s,id:t,inlinePreview:{startOffset:n,newText:"",marks:{}}})}createTextInsertion(t,e,n,o,i={},s={}){const a={...i,suggestionId:t};return this.createSuggestion(t,c=>{const l=at(c,e);if(!l)return[];const d=xt(l);return d?(kt(d,n,o,a),[{kind:"insert",paragraphId:e,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,n,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):[]},{...s,id:t})}createTextReplacement(t,e,n,o,i,s={},a,c={}){const l={...s,suggestionId:t};return this.createForklessTextSuggestion({id:t,kind:"replace",paragraphId:e,startOffset:n,deleteLength:o,newText:i,marks:l,anchorText:i,oldText:a,metadata:{...c,id:t}})||this.createSuggestion(t,u=>{const g=at(u,e);if(!g)return[];const p=xt(g);return p?(p.delete(n,o),kt(p,n,i,l),[{kind:"replace",paragraphId:e,from:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(p,n,0)),to:x.encodeRelativePosition(x.createRelativePositionFromTypeIndex(p,n+i.length,0)),text:i,oldText:a}]):[]},{...c,id:t,inlinePreview:{startOffset:n,newText:i,marks:l}})}createPositionAwareInsertion(t,e,n,o,i={}){const s=this.generateId();return this.suggestionMeta.set(s,{id:s,authorId:i.authorId||"system",authorType:i.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...i}),s}materializeWithSuggestion(t){const e=this.suggestionMeta.get(t);if(!e||e.status==="accepted")return null;const n=this.seedFork();if(e.blockPreview?.id){const i=ut(n,e.blockPreview.id);return i?(i.yParent.delete(i.index,1),i.yParent.insert(i.index,[Ut(e.blockPreview)]),n):null}if(e.insertionContext)return this.applyPositionAwareInsertion(n,t,e),n;const o=this.proposals.get(t);return o?(x.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 s=ut(e,o.blockPreview.id);s&&(s.yParent.delete(s.index,1),s.yParent.insert(s.index,[Ut(o.blockPreview)]));continue}const i=this.proposals.get(n);i&&x.applyUpdate(e,i)}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 i=o.from?x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(o.from),e):null,s=o.to?x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(o.to),e):null;return{kind:o.kind,paragraphId:o.paragraphId,fromIndex:i?.index??null,toIndex:s?.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 i=t.getXmlFragment("content");let s=0;for(let c=i.length-1;c>=0;c--){const l=i.get(c);if(!(l instanceof x.XmlElement))continue;const d=l.getAttribute("id");if(d&&o.mustBeAfter.includes(d)){s=c+1;break}}const a=Jp(o.content,o.paragraphId,e);i.insert(s,[a])}removeProposalFromParagraphs(t){for(const[e,n]of this.paragraphSuggestions){const o=n.filter(i=>i!==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[i,s]of n)s===t&&(n.delete(i),o=!0);o&&n.size===0&&this.tableCellSuggestions.delete(e)}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function Jp(r,t,e,n){if(r.type==="list"){const a=new x.XmlElement("list");return a.setAttribute("id",t),a.setAttribute("variant",r.variant??"unordered"),r.startNumber!==void 0&&a.setAttribute("startNumber",String(r.startNumber)),r.numberingChainId&&a.setAttribute("numberingChainId",r.numberingChainId),r.children.forEach(c=>{const l=new x.XmlElement("list-item");cn(l,c),l.setAttribute("id",c.id||et()),c.checked!==void 0&&l.setAttribute("checked",String(c.checked)),typeof c.indentLevel=="number"&&c.indentLevel>0&&l.setAttribute("indentLevel",String(c.indentLevel)),c.direction!==void 0&&l.setAttribute("direction",c.direction);const d=new x.XmlText;let u=0;c.children.forEach(g=>{if(g.type!=="text")return;const p=Hi(g.marks,e);d.insert(u,g.text,p),u+=g.text.length}),l.insert(0,[d]),a.push([l])}),a}if(r.type==="table")return Ut(Ps({...r,id:t},a=>({...a,marks:Hi(a.marks,e)})));if(r.type==="code"){const a=new x.XmlElement("code");a.setAttribute("id",t),r.language&&a.setAttribute("language",r.language),r.renderDiagram!==void 0&&a.setAttribute("renderDiagram",String(r.renderDiagram)),r.showDiagramSource!==void 0&&a.setAttribute("showDiagramSource",String(r.showDiagramSource));const c=new x.XmlText;return a.insert(0,[c]),kt(c,0,r.content||""),a}if(r.type==="math"){const a=new x.XmlElement("math");a.setAttribute("id",t),r.displayMode&&a.setAttribute("displayMode",r.displayMode),r.align&&a.setAttribute("align",r.align);const c=new x.XmlText;return a.insert(0,[c]),kt(c,0,r.content||""),a}if(r.type==="image"){const a=new x.XmlElement("image");return a.setAttribute("id",t),a.setAttribute("src",r.src),r.sourceUrl&&a.setAttribute("sourceUrl",r.sourceUrl),a.setAttribute("width",String(r.width)),a.setAttribute("height",String(r.height)),r.alt&&a.setAttribute("alt",r.alt),r.align&&a.setAttribute("align",r.align),a}if(r.type==="page-break"){const a=new x.XmlElement("page-break");return a.setAttribute("id",t),a}if(r.type==="toc")return Ut({...r,id:t});if(r.type==="section-break"){const a=new x.XmlElement("section-break");return a.setAttribute("id",t),r.layout&&a.setAttribute("layout",JSON.stringify(r.layout)),r.breakType&&a.setAttribute("breakType",r.breakType),a}const o=new x.XmlElement("paragraph");o.setAttribute("id",t),r.heading&&o.setAttribute("heading",String(r.heading)),r.align&&o.setAttribute("align",r.align);const i=new x.XmlText;let s=0;return r.children.forEach(a=>{if(a.type!=="text")return;const c=Hi(a.marks,e);kt(i,s,a.text,c),s+=a.text.length}),o.insert(0,[i]),o}function Hi(r,t,e){return{...r||{},suggestionId:t}}class lo{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"?Ae:this.host.defaultHumanAuthorName??js)}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()),i={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},s=()=>{this.host.liveSuggestionMetadataContext=i;try{return e()}finally{this.host.liveSuggestionMetadataContext=n}},a=t.batchHistory===!1?s():this.host.runWithUndoGroup(t.historyOrigin??`live-suggestions:${i.createdAt}`,s),c=this.getLiveSuggestionIds().filter(l=>!o.has(l));return{result:a,suggestionIds:c}}normalizeLiveSuggestionRecord(t){const e=this.host.liveSuggestionMetadataContext,n=t.source??e?.source??"manual",o=t.authorType??e?.authorType??(n==="agent"?"ai":"human"),i=t.createdAt??e?.createdAt??Date.now(),s=t.label??e?.label,a=this.resolveSuggestionAuthorName(o,t.agentName??e?.agentName),c=t.agentModel??e?.agentModel,l=t.commentThreadId??e?.commentThreadId,d=t.agentConversationId??e?.agentConversationId,u=t.agentRequestId??e?.agentRequestId,g=t.agentTurn??e?.agentTurn;return{...t,source:n,authorType:o,createdAt:i,label:s,...l?{commentThreadId:l}:{},agentName:a,...c?{agentModel:c}:{},...d?{agentConversationId:d}:{},...u!==void 0?{agentRequestId:u}:{},...g!==void 0?{agentTurn:g}:{}}}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;default:return null}}embedLiveSuggestionRecordInTree(t,e){const n=this.liveSuggestionRecordAnchorBlockId(t);if(!n||!this.host.ydoc)return;const o=e??at(this.host.ydoc,n);if(o instanceof x.XmlElement)try{if(t.type==="table-change"){let i=[];const s=o.getAttribute("structuralSuggestionRecords");if(typeof s=="string")try{const a=JSON.parse(s);Array.isArray(a)&&(i=a)}catch{}i=i.filter(a=>a?.id!==t.id),i.push(t),o.setAttribute("structuralSuggestionRecords",JSON.stringify(i))}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=at(this.host.ydoc,n);o instanceof x.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.liveSuggestionTreeRecordCache.has(t))return this.host.liveSuggestionTreeRecordCache.get(t)??null;let e=null;const n=o=>{for(const i of o.toArray()){if(e||!(i instanceof x.XmlElement))continue;const s=i.getAttribute("structuralSuggestionRecord");if(typeof s=="string"&&s.length>0)try{const c=JSON.parse(s);if(c&&c.id===t&&c.type){e=c;return}}catch{}const a=i.getAttribute("structuralSuggestionRecords");if(typeof a=="string"&&a.length>0)try{const c=JSON.parse(a),l=Array.isArray(c)?c.find(d=>d&&d.id===t&&!!d.type):void 0;if(l){e=l;return}}catch{}n(i)}};try{n(this.host.getYContentFragment()),n(this.host.getYNotesFragment())}catch{}return this.host.liveSuggestionTreeRecordCache.set(t,e),e}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 i of t){const s=this.findInlineSuggestionMetadataInValue(i,e);if(s)return s}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=fr(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=z(this.host.getDocument(),e.blockId)??void 0,o=this.host.getBlockDescription(n);return o?`Insert ${o}`: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??z(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 i=this.host.getBlockDescription(n)??this.host.getBlockDescription(e.beforeBlock);if(i&&e.label)return`${e.label} ${i}`;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 i=this.getInlineSuggestionMetadataFromDocument(o);if(i?.source)return i.source===t;if(t==="agent"&&i?.authorType==="ai")return!0;const s=this.getLiveSuggestion(o);return s?.source?s.source===t:t==="agent"&&s?.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"?Ae:js}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 i of this.getSuggestionIdsForBlock(o))e.add(i);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 i of t)this.indexInlineSuggestionFacts(i);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 i=e.marks?.deletion?"delete":e.marks?.insertion?"insert":e.marks?.formatChange?"format":null;i&&!this.host.inlineSuggestionKindCache.has(n)&&this.host.inlineSuggestionKindCache.set(n,i)}const o=fr(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 i=e.structuralSuggestionKind==="insert"||e.structuralSuggestionKind==="split"?"insert":e.structuralSuggestionKind==="delete"||e.structuralSuggestionKind==="merge"?"delete":e.structuralSuggestionKind==="change"?"format":null;i&&this.host.inlineSuggestionKindCache.set(e.structuralSuggestionId,i)}if(typeof e.suggestionId=="string"&&e.suggestionId.length>0&&!this.host.inlineSuggestionKindCache.has(e.suggestionId)){const i=e.diffState==="insert"?"insert":e.diffState==="delete"?"delete":null;i&&this.host.inlineSuggestionKindCache.set(e.suggestionId,i)}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=z(n,e.blockId);return o?this.host.isListItemBlockChangeRecord(e)?o.type==="list"&&o.children.some(i=>i.structuralSuggestionId===e.id):e.acceptedBlock?this.blockChangeTargetIsOwned(e):this.blockContainsSuggestionMarker(o,e.id):!1}case"table-change":{const o=z(n,e.tableId);return o?.type!=="table"||!this.blockContainsSuggestionMarker(o,e.id)?!1:e.tableRevision.operations.some(i=>i.kind==="row"?o.children.some(s=>s.id===i.rowId):i.kind==="cell"?o.children.some(s=>s.id===i.rowId&&s.children.some(a=>a.id===i.cellId)):i.kind==="geometry"?i.pendingRows.some(s=>o.children.some(a=>a.id===s.id)):i.kind==="grid"||i.target==="table"?!0:i.target==="row"||i.target==="row-exception"?o.children.some(s=>s.id===i.rowId):o.children.some(s=>s.children.some(a=>a.id===i.cellId)))}case"block-insert":{const o=z(n,e.blockId);return o&&this.blockContainsSuggestionMarker(o,e.id)?!0:this.host.collectStructuralInsertBlockIds(n,e.id).length>0}case"block-delete":{const o=z(n,e.blockId);return!!(o&&this.blockContainsSuggestionMarker(o,e.id))}case"paragraph-split":{const o=z(n,e.blockId),i=z(n,e.insertedBlockId);return!!(o&&i&&(this.blockContainsSuggestionMarker(o,e.id)||this.blockContainsSuggestionMarker(i,e.id)))}case"paragraph-merge":{const o=z(n,e.firstBlockId),i=z(n,e.secondBlockId);return!i||i.type!=="paragraph"?!1:o&&o.type==="paragraph"?this.blockContainsSuggestionMarker(o,e.id)||this.blockContainsSuggestionMarker(i,e.id):this.blockContainsSuggestionMarker(i,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=J(t,this.host.ydoc,e),o=this.createLiveSuggestionProjection("reject"),i=_i(n,o.ydoc);if(!i.anchor||!i.focus)return null;const s=qt(o.doc,i.anchor,i.focus)<=0;return{doc:o.doc,start:s?i.anchor:i.focus,end:s?i.focus:i.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=eo.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"),i=at(o.ydoc,t),s=i?xt(i):null,a=at(this.host.ydoc,t),c=a?xt(a):null;if(!s||!c||n>s.length)return null;const l=x.createRelativePositionFromTypeIndex(s,e,0),d=x.createRelativePositionFromTypeIndex(s,n,-1),u=x.createAbsolutePositionFromRelativePosition(l,this.host.ydoc),g=x.createAbsolutePositionFromRelativePosition(d,this.host.ydoc);return!u||!g||u.type!==c||g.type!==c||g.index<=u.index?null:{start:u.index,end:g.index}}blocksWithNotesAndChrome(t){return[...t.children,...t.notes??[],...t.chrome??[]]}collectSuggestionIdsFromBlockValue(t,e){lo.collectSuggestionIdsFromBlockValue(t,e)}static collectSuggestionIdsFromBlockValue(t,e){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const i of t)lo.collectSuggestionIdsFromBlockValue(i,e);return}const n=t;typeof n.suggestionId=="string"&&n.suggestionId.length&&e.add(n.suggestionId);const o=fr(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 i=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(i))for(const s of i)s&&typeof s.id=="string"&&s.id&&e.add(s.id)}catch{}n.marks&&typeof n.marks.suggestionId=="string"&&n.marks.suggestionId.length&&e.add(n.marks.suggestionId);for(const i of Object.values(n))i&&typeof i=="object"&&lo.collectSuggestionIdsFromBlockValue(i,e)}getSequenceReplacementMembers(t){const e=[],n=o=>{o.toArray().forEach((i,s)=>{i instanceof x.XmlElement&&(i.getAttribute("structuralSuggestionId")===t.id?e.push({yBlock:i,yParent:o,index:s}):n(i))})};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 i of e)this.setParagraphStructuralSuggestion(i,"change",void 0,t.id,"Paragraph");const n=this.getSequenceReplacementMembers(t),o={...t,blockId:n[0].yBlock.getAttribute("id"),sequenceBlockIds:n.map(({yBlock:i})=>i.getAttribute("id"))};this.saveLiveSuggestion(o,n[0].yBlock);for(const i of n.slice(1))this.embedLiveSuggestionRecordInTree(o,i.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 i=o.getAttribute("id");i&&t.add(i)}}}}resetLiveSuggestionsForBlocks(t,e){const n=new Set(t);this.expandPendingSequenceBlockIds(n);for(const u of this.getLiveSuggestionStore().values())if(u.type==="block-change"&&u.sequenceBlockIds&&this.liveSuggestionRecordTouchesAnyBlock(u,n)&&!this.applySuggestionRecordRejection(u))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 i=new Set,s=this.host.getDocument(),a=we(s),c=we(e),l=new Set(o);for(const[u,g]of this.getLiveSuggestionStore())this.liveSuggestionRecordTouchesAnyBlock(g,l)&&i.add(u);for(const u of o){const g=a.get(u)?.block??z(s,u);g&&this.collectSuggestionIdsFromBlockValue(g,i)}const d=this.getSuggestionMutationSelection();for(const u of o){const g=a.get(u)?.block??z(s,u),p=c.get(u)?.block??z(e,u);if(p){if(!g||g.type==="paragraph"&&p.type==="paragraph"&&JSON.stringify(g)===JSON.stringify(p))continue;this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(u,this.cloneSuggestionSnapshot(p),d,d));continue}g&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(u,d,d))}this.host.transact(()=>{for(const u of i)this.deleteLiveSuggestion(u)})}liveSuggestionRecordTouchesAnyBlock(t,e){const n=o=>e.has(o.getAttribute("id")??"")||o.toArray().some(i=>i instanceof x.XmlElement&&n(i));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(c=>{const l=this.getLiveSuggestion(c);return!l||l.type==="inline-text"||l.type==="inline-format"});if(o.length===n.length)return this.applyInlineSuggestionDecisions(new Set(o),e).size;let i=this.applyInlineSuggestionDecisions(new Set(o),e).size;const s=this.host.documentId==="live-suggestion-projection"?this.applySimpleProjectionBlockDecisions(n,e):new Set;i+=s.size;const a=new Set;for(const c of n){if(s.has(c))continue;const l=this.getLiveSuggestion(c);if(!l||l.type==="inline-text"||l.type==="inline-format")continue;const d=l?.type==="block-change"&&!this.host.isListItemBlockChangeRecord(l);if(d&&a.has(l.blockId)){this.deleteLiveSuggestion(c),i+=1;continue}(e==="accept"?this.acceptLiveSuggestionWithoutPruning(c):this.rejectLiveSuggestionWithoutPruning(c))&&(d&&a.add(l.blockId),i+=1)}return i}applySimpleProjectionBlockDecisions(t,e){const n=new Set,o=new Set,i=new Set,s=new Set;for(const c of t){const l=this.getLiveSuggestion(c);if(l){if(e==="accept"&&l.type==="block-delete"||e==="reject"&&l.type==="block-insert"){n.add(c),o.add(l.blockId),l.cleanupTrailingParagraphId&&o.add(l.cleanupTrailingParagraphId),s.add(c);continue}(e==="accept"&&(l.type==="block-insert"||l.type==="paragraph-split")||e==="reject"&&(l.type==="block-delete"||l.type==="paragraph-merge"))&&(i.add(c),s.add(c))}}if(s.size===0)return s;const a=c=>{const l=c.toArray();for(let d=l.length-1;d>=0;d-=1){const u=l[d];if(!(u instanceof x.XmlElement))continue;const g=u.getAttribute("id"),p=u.getAttribute("structuralSuggestionId"),h=u.getAttribute("suggestionId");if(typeof g=="string"&&o.has(g)||typeof p=="string"&&n.has(p)||typeof h=="string"&&n.has(h)){c.delete(d,1);continue}typeof p=="string"&&i.has(p)&&this.clearElementStructuralSuggestion(u),typeof h=="string"&&i.has(h)&&this.setDiffSuggestionAttributes(u,void 0,void 0),a(u)}};return this.host.transact(()=>{a(this.host.getYContentFragment()),a(this.host.getYNotesFragment());for(const c of s)this.deleteLiveSuggestion(c)}),s}applyLiveSuggestionDecisionScopeInternal(t){let e=0,n=[];const o=new Set,i=new Set,s=[];for(let a=0;a<hm;a+=1){const c=this.getNextSuggestionIdsForDecisionScope(t.scope,a);if(a===0&&(n=c),c.length===0)break;const l=c.join("\0");if(i.has(l))break;i.add(l);for(const u of c)o.add(u);const d=this.applyLiveSuggestionDecisionInternal(c,t.decision);if(s.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:s}}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 i=t.historyOrigin??this.getLiveSuggestionDecisionHistoryOrigin(t);return this.host.runWithUndoGroup(i,()=>{const s=this.applyLiveSuggestionDecisionScopeInternal(t),a=s.prunedSuggestions.concat(this.pruneUnresolvableLiveSuggestionsInternal());o={...s,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:Ct()}getSuggestionIdForSuggestedSelectionOverwrite(t,e,n){if(!this.host.suggestingMode||!n?.anchor||!n.focus||qt(t,n.anchor,n.focus)===0)return null;const[o,i]=qt(t,n.anchor,n.focus)<=0?[n.anchor,n.focus]:[n.focus,n.anchor];if(o.block!==e.block||i.block!==e.block)return null;const s=z(t,e.block);if(!s)return null;if(s.type==="paragraph")return i.offset>o.offset?Ct():null;if(s.type!=="list")return null;const a=this.host.getListCursorInfo(s,o),c=this.host.getListCursorInfo(s,i);return!a||!c||a.itemIndex!==c.itemIndex?null:(s.children[a.itemIndex],c.offsetInItem>a.offsetInItem?Ct():null)}getInlineInsertionSuggestionNodeInTextChildren(t,e){let n=0,o=null;for(const i of t){if(i.type!=="text")continue;const s=i.text.length,a=n+s,c=!!(i.marks?.insertion&&i.marks.suggestionId&&this.isOwnPendingSuggestionSpan(i.marks));if(e>=n&&e<=a&&c)return i;e===a&&c&&(o=i),n=a}return o}getInlineInsertionSuggestionIdInTextChildren(t,e){return this.getInlineInsertionSuggestionNodeInTextChildren(t,e)?.marks?.suggestionId??null}getInlineInsertionSuggestionNodeAtPosition(t,e){const n=z(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 i=n.children[o.itemIndex];return i?this.getInlineInsertionSuggestionNodeInTextChildren(i.children,o.offsetInItem):null}getInlineInsertionSuggestionIdAtPosition(t,e){return this.getInlineInsertionSuggestionNodeAtPosition(t,e)?.marks?.suggestionId??null}getStructuralInsertSuggestionIdAtPosition(t,e){const n=z(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 i=n.children[o.itemIndex];return i?.structuralSuggestionKind==="insert"&&i.structuralSuggestionId?i.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=z(t,e);for(;n;){const o=this.getBlockInsertSuggestionIdForBlock(n);if(o)return o;if(typeof n.id!="string")break;const i=ke(t,n.id);if(!i||!("id"in i)||typeof i.id!="string")break;n=i}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,i=o?.source??"manual",s=o?.authorType??(i==="agent"?"ai":"human");return{suggestionId:t,suggestionSource:i,suggestionAuthorType:s,suggestionCreatedAt:n??o?.createdAt??Date.now(),suggestionLabel:e??o?.label,...o?.commentThreadId?{suggestionCommentThreadId:o.commentThreadId}:{},suggestionAuthorName:this.resolveSuggestionAuthorName(s,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,i){const s=t?.suggestionId===e?t:i?.suggestionId===e?i:null;return this.recordStampedId("insertionIds",e),{...t||{},insertion:!0,...this.buildInlineSuggestionMetadataMarks(e,n,o),...this.pickInlineSuggestionMetadataMarks(s)}}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||It(t,e,n,{deletion:null})}findAdjacentDeletionSuggestionAttrs(t,e,n){if(n<=0)return null;const o=e+n,i=mt(t);let s=0,a=null,c=null;for(const l of i){if(typeof l.insert!="string")continue;const d=s,u=s+l.insert.length,g=l.attributes||{},p=g.deletion&&typeof g.suggestionId=="string"&&this.isOwnPendingSuggestionSpan(g);if(p&&u===e&&(a=g),p&&d===o){c=g;break}if(s=u,s>o)break}return a??c}findAdjacentDeletionSuggestionId(t,e,n){return this.findAdjacentDeletionSuggestionAttrs(t,e,n)?.suggestionId??null}applySuggestedDeletionToTextRange(t,e,n,o){const i=this.host.collectOverlappingTextSpans(t,e,n);if(i.length===0)return{retainedLength:0,changed:!1};const s=o?null:this.findAdjacentDeletionSuggestionAttrs(t,e,n),a=o??s?.suggestionId??Ct(),c={...this.buildInlineSuggestionMetadataMarks(a,"Delete"),...this.pickInlineSuggestionMetadataMarks(s?.suggestionId===a?s:null)};let l=0,d=!1;for(let u=i.length-1;u>=0;u--){const g=i[u],p=g.attributes||{};if(p.insertion){if(this.isOwnPendingSuggestionSpan(p)){t.delete(g.start,g.length),d=!0;continue}l+=g.length,this.recordStampedId("deletionIds",a),It(t,g.start,g.length,{deletion:!0,...c,layeredInsertion:JSON.stringify({id:p.suggestionId,source:p.suggestionSource,authorType:p.suggestionAuthorType,createdAt:p.suggestionCreatedAt,label:p.suggestionLabel,authorName:p.suggestionAuthorName,commentThreadId:p.suggestionCommentThreadId,agentModel:p.suggestionAgentModel,agentConversationId:p.suggestionAgentConversationId,agentRequestId:p.suggestionAgentRequestId,agentTurn:p.suggestionAgentTurn}),formatChange:null,suggestionPriorAttributes:null}),d=!0;continue}if(l+=g.length,p.deletion){o&&p.suggestionId!==o&&(this.recordStampedId("deletionIds",a),It(t,g.start,g.length,{...c,formatChange:null,suggestionPriorAttributes:null}),d=!0);continue}this.recordStampedId("deletionIds",a),It(t,g.start,g.length,{deletion:!0,...c,formatChange:null,suggestionPriorAttributes:null}),d=!0}return{retainedLength:l,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,i){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"),i?t.setAttribute("structuralSuggestionLabel",i):t.removeAttribute("structuralSuggestionLabel")}setParagraphStructuralSuggestion(t,e,n,o,i){this.setElementStructuralSuggestion(t,e,n,o,i)}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 i=this.cloneSuggestionSnapshot(t);return i.children=i.children.map(s=>e.has(s.id)?{...s,diffState:n,suggestionId:o,children:s.children.map(a=>({...a,diffState:n,suggestionId:o}))}:s),i}markTableSuggestionColumn(t,e,n,o){const i=this.cloneSuggestionSnapshot(t);return i.children=i.children.map(s=>({...s,children:s.children.map((a,c)=>c===e?{...a,diffState:n,suggestionId:o}:a)})),i}buildSuggestedTableChange(t,e,n){const o=(h,f,m)=>({id:n,type:"table-change",tableId:t.id,label:h,tableRevision:{version:1,suggestionKind:f,...m}}),i=t.children.map(h=>h.id),s=e.children.map(h=>h.id),a=h=>JSON.stringify(h,(f,m)=>{if(f!=="id"){if(f==="marks"&&m&&typeof m=="object"){const y={...m};return y.fontFamily===ae&&delete y.fontFamily,Object.keys(y).length?y:void 0}return m}}),c=a({...t,children:[]})===a({...e,children:[]}),l=(h,f)=>{let m=0;for(const y of f)y===h[m]&&m++;return m===h.length};if(e.children.length>t.children.length&&l(i,s)&&c&&t.children.every(h=>a(h)===a(e.children.find(f=>f.id===h.id)))){const h=new Set(i),f=e.children.map((b,k)=>({row:b,rowIndex:k})).filter(({row:b})=>!h.has(b.id)),m=new Set(f.map(({row:b})=>b.id)),y=f.length===1?"Insert table row":"Insert table rows";return{liveBlock:this.markTableSuggestionRows(e,m,"insert",n),label:y,record:o(y,"insert",{markers:f.map(({row:b,rowIndex:k})=>({kind:"row-insert",rowId:b.id,rowIndex:k})),operations:f.map(({row:b,rowIndex:k})=>({kind:"row",action:"insert",rowId:b.id,rowIndex:k,row:this.cloneSuggestionSnapshot(b)}))})}}if(e.children.length<t.children.length&&l(s,i)&&c&&e.children.every(h=>a(h)===a(t.children.find(f=>f.id===h.id)))){const h=new Set(s),f=t.children.map((v,S)=>({row:v,rowIndex:S})).filter(({row:v})=>!h.has(v.id)),m=new Set(f.map(({row:v})=>v.id)),y=new Map(e.children.map(v=>[v.id,v])),b=this.cloneSuggestionSnapshot(e);b.children=t.children.map(v=>y.get(v.id)??v);const k=f.length===1?"Delete table row":"Delete table rows";return{liveBlock:this.markTableSuggestionRows(b,m,"delete",n),label:k,record:o(k,"delete",{markers:f.map(({row:v,rowIndex:S})=>({kind:"row-delete",rowId:v.id,rowIndex:S})),operations:f.map(({row:v,rowIndex:S})=>({kind:"row",action:"delete",rowId:v.id,rowIndex:S,row:this.cloneSuggestionSnapshot(v)}))})}}const d=this.host.findSingleTableColumnDelta(t,e);if(d&&(a({...t,children:[],columnWidths:[]})!==a({...e,children:[],columnWidths:[]})||t.children.some((h,f)=>{const m=e.children[f];return a({...h,children:[]})!==a({...m,children:[]})?!0:h.children.some(y=>{const b=m.children.find(k=>k.id===y.id);return b&&a(y)!==a(b)})})))return null;if(d?.kind==="insert"){const h=[],f=[];for(let m=0;m<e.children.length;m++){const y=e.children[m],b=y.children[d.index];b&&(h.push({kind:"cell",action:"insert",rowId:y.id,cellId:b.id,cellIndex:d.index,cell:this.cloneSuggestionSnapshot(b)}),f.push({kind:"cell-insert",rowId:y.id,cellId:b.id,rowIndex:m,cellIndex:d.index,gridColumn:d.index}))}return h.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(e,d.index,"insert",n),label:"Insert table column",record:o("Insert table column","insert",{markers:f,operations:h})}}if(d?.kind==="delete"){const h=[],f=[];for(let m=0;m<t.children.length;m++){const y=t.children[m],b=y.children[d.index];b&&(h.push({kind:"cell",action:"delete",rowId:y.id,cellId:b.id,cellIndex:d.index,cell:this.cloneSuggestionSnapshot(b)}),f.push({kind:"cell-delete",rowId:y.id,cellId:b.id,rowIndex:m,cellIndex:d.index,gridColumn:d.index}))}return h.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(t,d.index,"delete",n),label:"Delete table column",record:o("Delete table column","delete",{markers:f,operations:h})}}const u=dn(t),g=dn(e);if(t.children.length===e.children.length&&u.rows===g.rows&&u.cols===g.cols&&t.children.every((h,f)=>h.id===e.children[f]?.id)){const h=u.cells.map(f=>{const m=g.byId.get(f.cell.id);return m?{before:f,after:m}:null}).filter(f=>!!f&&(f.before.rowSpan!==f.after.rowSpan||f.before.colSpan!==f.after.colSpan));if(h.length===1&&h[0].before.col===h[0].after.col&&h[0].before.row===h[0].after.row&&h[0].before.colSpan===h[0].after.colSpan&&h[0].before.rowSpan!==h[0].after.rowSpan){const f=h[0].before,m=h[0].after,y=m.rowSpan>f.rowSpan,b=y?f.row+f.rowSpan:m.row+m.rowSpan,k=y?m.row+m.rowSpan:f.row+f.rowSpan,v=[],S=new Set([t.children[f.row].id]);for(let _=b;_<k;_++){const B=e.children[_];B&&(S.add(B.id),v.push({kind:"cell-merge",rowId:B.id,rowIndex:_,gridColumn:m.col,...y?{vMerge:"cont"}:{vMergeOrig:"cont"}}))}const I=e.children.filter(_=>S.has(_.id)).map(_=>this.cloneSuggestionSnapshot(_)),w=t.children.filter(_=>S.has(_.id)).map(_=>this.cloneSuggestionSnapshot(_));if(!c||t.children.some(_=>!S.has(_.id)&&a(_)!==a(e.children.find(B=>B.id===_.id))))return null;const A=y?"Merge table cells":"Split table cells";return{liveBlock:this.cloneSuggestionSnapshot(e),label:A,record:o(A,"format",{markers:v,operations:[{kind:"geometry",pendingRows:I,acceptedRows:this.cloneSuggestionSnapshot(I),rejectedRows:w}]})}}}const p=h=>JSON.stringify(h.children,(f,m)=>{if(f!=="marks"||!m||typeof m!="object")return m;const y={...m};return y.fontFamily===ae&&delete y.fontFamily,Object.keys(y).length>0?y:void 0});if(t.children.length===e.children.length&&t.children.every((h,f)=>{const m=e.children[f];return m?.id===h.id&&h.children.length===m.children.length&&h.children.every((y,b)=>{const k=m.children[b];return k?.id===y.id&&y.colSpan===k.colSpan&&y.rowSpan===k.rowSpan&&p(y)===p(k)})})){const h=[],f=[],m=(b,k,v)=>{const S={},I={};for(const w of v){const A=b[w],_=k[w];JSON.stringify(A)!==JSON.stringify(_)&&(_!==void 0&&(S[w]=_),A!==void 0&&(I[w]=A))}return{current:S,prior:I}};JSON.stringify(t.columnWidths)!==JSON.stringify(e.columnWidths)&&h.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""});const y=m(t,e,["tableWidth","align","borderColor","borderWidth","borders","cellPadding"]);(Object.keys(y.current).length>0||Object.keys(y.prior).length>0)&&(f.push({kind:"table-properties"}),h.push({kind:"properties",target:"table",currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:y.current,priorAttributes:y.prior})),t.hasHeader!==e.hasHeader&&e.children[0]&&(f.push({kind:"row-properties",rowId:e.children[0].id,rowIndex:0}),h.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 b=0;b<e.children.length;b++){const k=t.children[b],v=e.children[b];for(let S=0;S<v.children.length;S++){const I=k.children[S],w=v.children[S],A=m(I,w,["verticalAlign","backgroundColor","borders","padding"]);if(Object.keys(A.current).length===0&&Object.keys(A.prior).length===0)continue;const _=g.byId.get(w.id);f.push({kind:"cell-properties",rowId:v.id,cellId:w.id,rowIndex:b,cellIndex:S,gridColumn:_?.col}),h.push({kind:"properties",target:"cell",rowId:v.id,cellId:w.id,currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:A.current,priorAttributes:A.prior})}}if(h.length>0)return{liveBlock:this.cloneSuggestionSnapshot(e),label:"Change table formatting",record:o("Change table formatting","format",{markers:f,operations:h})}}return null}hasSameTableGeometry(t,e){return t.children.length===e.children.length&&t.children.every((n,o)=>{const i=e.children[o];return i?.id===n.id&&n.children.length===i.children.length&&n.children.every((s,a)=>{const c=i.children[a];return c?.id===s.id&&c.colSpan===s.colSpan&&c.rowSpan===s.rowSpan})})}reconcileTableDescendantIds(t,e){const n=this.cloneSuggestionSnapshot(e),o=new Set(["id","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),i=b=>_n(JSON.parse(JSON.stringify(b,(k,v)=>o.has(k)?void 0:v))),s=t.children,a=n.children,c=new Set(s.map(b=>b.id)),l=new Set(a.map(b=>b.id)),d=new Set(s.flatMap(b=>b.children.map(k=>k.id))),u=new Set(a.flatMap(b=>b.children.map(k=>k.id))),g=new Map([...s,...a].map(b=>[b,i(b)])),p=(b,k)=>b.id===k.id?0:c.has(k.id)||l.has(b.id)?2.25:g.get(b)===g.get(k)?0:b.children.length===k.children.length&&b.children.every((v,S)=>{const I=k.children[S];return I?.colSpan===v.colSpan&&I?.rowSpan===v.rowSpan})?.75:2.25,h=Array.from({length:s.length+1},()=>Array(a.length+1).fill(0));for(let b=0;b<=s.length;b++)h[b][0]=b;for(let b=0;b<=a.length;b++)h[0][b]=b;for(let b=1;b<=s.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]+p(s[b-1],a[k-1]));const f=[];let m=s.length,y=a.length;for(;m>0&&y>0;){const b=p(s[m-1],a[y-1]);b<2&&Math.abs(h[m][y]-(h[m-1][y-1]+b))<1e-4?(f.push([s[m-1],a[y-1]]),m--,y--):h[m][y]===h[m-1][y]+1?m--:y--}for(const[b,k]of f)if(k.id=b.id,b.children.length===k.children.length)for(let v=0;v<b.children.length;v++){const S=b.children[v],I=k.children[v];S.colSpan!==I.colSpan||S.rowSpan!==I.rowSpan||S.id!==I.id&&(d.has(I.id)||u.has(S.id))||(I.id=S.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=(i,s)=>{!s.diffState&&i.diffState&&(s.diffState=i.diffState),!s.suggestionId&&i.suggestionId&&(s.suggestionId=i.suggestionId)};for(let i=0;i<t.children.length;i++){const s=t.children[i];let a=n.children.find(c=>c.id===s.id);if(!a&&s.diffState==="delete"){const c=t.children.slice(i+1).map(d=>d.id).find(d=>n.children.some(u=>u.id===d)),l=c?n.children.findIndex(d=>d.id===c):n.children.length;a=this.cloneSuggestionSnapshot(s),n.children.splice(l,0,a)}if(a){o(s,a);for(let c=0;c<s.children.length;c++){const l=s.children[c];let d=a.children.find(u=>u.id===l.id);if(!d&&l.diffState==="delete"){const u=s.children.slice(c+1).map(p=>p.id).find(p=>a.children.some(h=>h.id===p)),g=u?a.children.findIndex(p=>p.id===u):a.children.length;d=this.cloneSuggestionSnapshot(l),a.children.splice(g,0,d)}d&&o(l,d)}}}return n}getYTextForSuggestionSpan(t){const e=at(this.host.ydoc,t.blockId);if(!(e instanceof x.XmlElement))return null;if(t.itemIndex===void 0)return xt(e);const n=[];for(let i=0;i<e.length;i++){const s=e.get(i);s instanceof x.XmlElement&&s.nodeName==="list-item"&&n.push(s)}const o=n[t.itemIndex];return o?xt(o):null}stripInlineSuggestionMarks(t,e,n){It(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 i=this.host.collectOverlappingTextSpans(t,e,n),s=i.length>0?i:[{start:e,length:n,attributes:{}}];for(const a of s){const c={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},l=ss(a.attributes?.suggestionPriorAttributes)??o,d=new Set([...Object.keys(a.attributes||{}),...Object.keys(l||{})]);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 u of d)Object.prototype.hasOwnProperty.call(l,u)?c[u]=l[u]:c[u]=null;It(t,a.start,a.length,c)}}clearStructuralSuggestionById(t,e){for(const n of t.toArray()){if(!(n instanceof x.XmlElement))continue;n.getAttribute("structuralSuggestionId")===e&&this.clearElementStructuralSuggestion(n);const o=n.getAttribute("structuralSuggestionRecords");if(typeof o=="string"&&o.length>0)try{const i=JSON.parse(o);if(Array.isArray(i)){const s=i.filter(a=>a?.id!==e);s.length!==i.length&&(s.length>0?n.setAttribute("structuralSuggestionRecords",JSON.stringify(s)):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=z(this.host.getDocument(),t.blockId);return e?this.blockContainsSuggestionMarker(e,t.id)?!0:e.structuralSuggestionId?!1:Ud(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(i=>i?.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=z(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 i=o.filter(s=>s?.id!==e);i.length>0?n.structuralSuggestionRecords=JSON.stringify(i):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])),i=new Map(n.map(a=>[a.id,a])),s=new Set([...o.keys(),...i.keys()]);for(const a of s){const c=t.children.find(p=>p.id===a),l=o.get(a),d=i.get(a);if(!c||!l||!d)continue;const u=new Set(l.children.map(p=>p.id)),g=new Set(d.children.map(p=>p.id));c.children=c.children.filter(p=>!u.has(p.id)||g.has(p.id));for(let p=0;p<d.children.length;p++){const h=d.children[p],f=l.children.find(y=>y.id===h.id);let m=c.children.find(y=>y.id===h.id);if(!m&&!f&&(m=this.cloneSuggestionSnapshot(h),c.children.splice(Math.min(p,c.children.length),0,m)),!(!m||!f)){JSON.stringify(f.children)!==JSON.stringify(h.children)&&JSON.stringify(m.children)===JSON.stringify(f.children)&&(m.children=this.cloneSuggestionSnapshot(h.children));for(const y of["rowSpan","colSpan"])f[y]!==h[y]&&(h[y]===void 0?delete m[y]:m[y]=h[y])}}}}applyTableRevisionDecision(t,e){const n=z(this.host.getDocument(),t.tableId);if(!n||n.type!=="table")return!1;const o=this.cloneSuggestionSnapshot(n);let i={version:1};if(o.docxTablePropertyOverrides)try{const c=JSON.parse(o.docxTablePropertyOverrides);c?.version===1&&(i=c)}catch{}for(const c of t.tableRevision.operations){if(c.kind==="row"){const f=c.action==="insert"?e==="accept":e==="reject",m=o.children.findIndex(y=>y.id===c.rowId);f&&m<0?o.children.splice(Math.min(c.rowIndex,o.children.length),0,this.cloneSuggestionSnapshot(c.row)):!f&&m>=0&&o.children.splice(m,1);continue}if(c.kind==="cell"){const f=o.children.find(b=>b.id===c.rowId);if(!f)continue;const m=c.action==="insert"?e==="accept":e==="reject",y=f.children.findIndex(b=>b.id===c.cellId);m&&y<0?f.children.splice(Math.min(c.cellIndex,f.children.length),0,this.cloneSuggestionSnapshot(c.cell)):!m&&y>=0&&f.children.splice(y,1);continue}if(c.kind==="geometry"){this.applyTableGeometryRows(o,c.pendingRows,e==="accept"?c.acceptedRows:c.rejectedRows);continue}if(c.kind==="grid"){const f=e==="accept"?c.currentColumnWidths:c.priorColumnWidths,m=e==="accept"?c.currentGridXml:c.priorGridXml;o.columnWidths=[...f],m&&(i.grid={xml:m,columnWidths:[...f]});continue}const l=e==="accept"?c.currentAttributes:c.priorAttributes,d=e==="accept"?c.priorAttributes:c.currentAttributes;let u;if(c.target==="table"?u=o:c.target==="row"||c.target==="row-exception"?u=o.children.find(f=>f.id===c.rowId):u=o.children.flatMap(f=>f.children).find(f=>f.id===c.cellId),u)for(const f of new Set([...Object.keys(d??{}),...Object.keys(l??{})]))l&&Object.prototype.hasOwnProperty.call(l,f)&&l[f]!==void 0?u[f]=this.cloneSuggestionSnapshot(l[f]):delete u[f];const g=e==="accept"?c.currentTableAttributes:c.priorTableAttributes,p=e==="accept"?c.priorTableAttributes:c.currentTableAttributes;for(const f of new Set([...Object.keys(p??{}),...Object.keys(g??{})]))g&&Object.prototype.hasOwnProperty.call(g,f)&&g[f]!==void 0?o[f]=this.cloneSuggestionSnapshot(g[f]):delete o[f];const h=e==="accept"?c.currentPropertiesXml:c.priorPropertiesXml;c.target==="table"?i.table=h:c.target==="row-exception"&&c.rowId?(i.rowExceptions=i.rowExceptions??{},i.rowExceptions[c.rowId]=h):c.target==="row"&&c.rowId?(i.rows=i.rows??{},i.rows[c.rowId]=h):c.target==="cell"&&c.cellId&&(i.cells=i.cells??{},i.cells[c.cellId]=h)}(i.table||i.grid||Object.keys(i.rows??{}).length>0||Object.keys(i.rowExceptions??{}).length>0||Object.keys(i.cells??{}).length>0)&&(o.docxTablePropertyOverrides=JSON.stringify(i)),this.clearSuggestionMarkerFromValue(o,t.id);const s=this.getSuggestionMutationSelection(),a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.tableId,o,s,s));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,t.acceptedBlock,e,e));return o&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)),this.deleteLiveSuggestion(t.id)),o}const n=z(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=J(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=J(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}case"block-delete":{const n=this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.blockId,e,e));return n&&(t.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.cleanupTrailingParagraphId,e,e)),this.deleteLiveSuggestion(t.id)),n}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=J(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"paragraph-merge":{const n=this.host.getDocument(),o=z(n,t.secondBlockId);let i=z(n,t.firstBlockId),s=ke(n,t.firstBlockId);if(!i||i.type!=="paragraph"){const d=ke(n,t.secondBlockId),u=d?"children"in d?d.children:[]:n.children,g=u.findIndex(h=>h.id===t.secondBlockId),p=g>0?u[g-1]:null;p?.type==="paragraph"&&(i=p,s=d??n)}if(!i||!o||!s||i.type!=="paragraph"||o.type!=="paragraph")return!1;const a={block:i.id,offset:i.children.reduce((d,u)=>d+(u.type==="text"?u.text.length:0),0)},c={block:o.id,offset:0},l=this.runWithoutSuggesting(()=>this.host.mergeAdjacentParagraphs(i,o,a,c,s,e,e));return l&&this.deleteLiveSuggestion(t.id),l}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=J(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),i=o[0];return!i||o.some(s=>s.yParent!==i.yParent)?!1:(this.host.transact(()=>{for(const s of[...o].sort((a,c)=>c.index-a.index))s.yParent.delete(s.index,1);i.yParent.insert(i.index,[this.host.blockToYjsElement(this.cloneSuggestionSnapshot(t.beforeBlock))]),this.deleteLiveSuggestion(t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=J(e,this.host.ydoc,this.host.getDocument()),!0)}const n=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,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),i=o.length>0?Array.from(new Set(o)):[t.blockId];let s=!1;for(const a of[...i].reverse())s=this.runWithoutSuggesting(()=>this.host.deleteBlockById(a,e,e))||s;if(s){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 s}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=J(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"paragraph-split":{const n=this.host.getDocument();return!z(n,t.insertedBlockId)||!this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,t.beforeBlock,e,e))?!1:(this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.insertedBlockId,e,e)),this.deleteLiveSuggestion(t.id),!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=J(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=J(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;if(this.host.transact(()=>{const o=i=>{for(const s of i.toArray()){if(s instanceof x.XmlElement){const d=s.getAttribute("structuralSuggestionId");typeof d=="string"&&t.has(d)&&(this.clearElementStructuralSuggestion(s),n.add(d));const u=s.getAttribute("suggestionId");typeof u=="string"&&t.has(u)&&(this.setDiffSuggestionAttributes(s,void 0,void 0),n.add(u)),o(s);continue}if(!(s instanceof x.XmlText))continue;const a=mt(s),c=[];let l=0;for(const d of a)typeof d.insert=="string"&&(c.push({start:l,length:d.insert.length,attributes:d.attributes||{}}),l+=d.insert.length);for(let d=c.length-1;d>=0;d--){const u=c[d],g=typeof u.attributes.suggestionId=="string"?u.attributes.suggestionId:null,p=fr(u.attributes.layeredInsertion);if(g&&t.has(g)){e==="accept"?u.attributes.deletion?s.delete(u.start,u.length):this.stripInlineSuggestionMarks(s,u.start,u.length):u.attributes.deletion&&p?It(s,u.start,u.length,{deletion:null,layeredInsertion:null,insertion:!0,suggestionId:p.id,suggestionSource:p.source??null,suggestionAuthorType:p.authorType??null,suggestionCreatedAt:p.createdAt??null,suggestionLabel:p.label??"Insert",suggestionCommentThreadId:p.commentThreadId??null,suggestionAuthorName:p.authorName??null,suggestionAgentModel:p.agentModel??null,suggestionAgentConversationId:p.agentConversationId??null,suggestionAgentRequestId:p.agentRequestId??null,suggestionAgentTurn:p.agentTurn??null}):u.attributes.insertion?s.delete(u.start,u.length):u.attributes.formatChange&&ss(u.attributes.suggestionPriorAttributes)?this.restoreInlineSuggestionFormatting(s,u.start,u.length,ss(u.attributes.suggestionPriorAttributes)):this.stripInlineSuggestionMarks(s,u.start,u.length),n.add(g);continue}p&&t.has(p.id)&&(e==="accept"?It(s,u.start,u.length,{insertion:null,layeredInsertion:null}):s.delete(u.start,u.length),n.add(p.id))}}};o(this.host.getYContentFragment()),o(this.host.getYNotesFragment()),o(this.host.ydoc.getXmlFragment("chrome"))}),n.size>0){const o=this.getSuggestionMutationSelection();this.host.setSelectionAfterOperation(o),this.host.afterOperationRelativeSelection=J(o,this.host.ydoc,this.host.getDocument());for(const i of n)this.deleteLiveSuggestion(i)}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,i){const s=this.host.getDocument().children.slice(n,o+1);if(s.length<2||s.some(l=>l.type!=="paragraph"))return!1;const a=s.map((l,d)=>{const u=l,g=this.host.getParagraphTextLength(u),p=d===0?Math.min(t.offset,g):0,h=d===s.length-1?Math.min(e.offset,g):g;return{blockId:u.id,from:p,to:h}});if(!a.some(l=>l.to>l.from))return!1;const c=Ct();return this.host.transact(()=>{for(const l of a){if(l.to<=l.from)continue;const d=at(this.host.ydoc,l.blockId);if(!(d instanceof x.XmlElement))continue;const u=xt(d);u&&(this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),l.blockId)?u.delete(l.from,l.to-l.from):this.applySuggestedDeletionToTextRange(u,l.from,l.to-l.from,c).retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(u,l.from))}for(let l=0;l+1<s.length;l++){const d=s[l],u=s[l+1],g=at(this.host.ydoc,d.id),p=at(this.host.ydoc,u.id);if(!(g instanceof x.XmlElement)||!(p instanceof x.XmlElement)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),d.id)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),u.id))continue;const h=Ct();this.setParagraphStructuralSuggestion(g,"merge","before",h),this.setParagraphStructuralSuggestion(p,"merge","after",h),this.saveLiveSuggestion({id:h,type:"paragraph-merge",firstBlockId:d.id,secondBlockId:u.id})}}),this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=J(i,this.host.ydoc,this.host.getDocument()),!0}sanitizePreviewMarks(t){let e=pm(t);for(const n of As)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 i={...o};return delete i.diffState,delete i.suggestionId,delete i.proposalId,delete i.toolCallId,delete i.toolType,delete i.diffSegmentIndex,delete i.structuralSuggestionId,delete i.structuralSuggestionKind,delete i.structuralSuggestionRole,delete i.structuralSuggestionLabel,i};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(i=>e(i))}))});case"table":return n({...t,children:t.children.map(o=>n({...o,children:o.children.map(i=>n({...i,children:i.children.map(s=>this.sanitizePreviewBlock(s))}))}))});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===ae||o.fontFamily==="Arial"){const i={...o};return delete i.fontFamily,i}return o};return JSON.stringify({...Object.fromEntries(mo.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 Bi(n,o)}getListItemAlignmentKeysForSuggestionBridge(t,e){return $c(t,e,n=>this.getListItemSignatureForSuggestionBridge(n))}computeListSuggestionBridgeOperations(t,e){const n=[],o=this.computeListItemLcsForSuggestionBridge(t.children,e.children),{beforeKeys:i,afterKeys:s}=this.getListItemAlignmentKeysForSuggestionBridge(t.children,e.children),a=t.children.map(g=>this.getListItemSignatureForSuggestionBridge(g)),c=e.children.map(g=>this.getListItemSignatureForSuggestionBridge(g)),l=(g,p,h,f)=>{const m=Math.min(g.length,p.length);for(let y=0;y<m;y++)n.push({kind:"change",index:h+y,beforeItem:g[y],afterItem:p[y]});for(let y=m;y<g.length;y++)n.push({kind:"delete",index:h+y,beforeItem:g[y]});for(let y=m;y<p.length;y++)n.push({kind:"insert",index:h+y,afterIndex:f+y,afterItem:p[y]})};let d=0,u=0;for(const g of o){let p=d;for(;p<i.length&&i[p]!==g;)p+=1;let h=u;for(;h<s.length&&s[h]!==g;)h+=1;l(t.children.slice(d,p),e.children.slice(u,h),d,u),a[p]!==c[h]&&n.push({kind:"change",index:p,beforeItem:t.children[p],afterItem:e.children[h]}),d=p+1,u=h+1}return l(t.children.slice(d),e.children.slice(u),d,u),n}findListItemIndexForSuggestionBridge(t,e){if(!e)return-1;if(e.id){const o=t.findIndex(i=>i.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,i){const s=this.sanitizePreviewBlock(t),a=this.sanitizePreviewBlock(e),c=i?this.cloneSuggestionSnapshot(i):null;if(o.kind==="insert"){const u=this.cloneSuggestionSnapshot(c??s),g=this.cloneSuggestionSnapshot(o.afterItem),p=this.findListItemIndexForSuggestionBridge(u.children,a.children[o.afterIndex-1]),h=this.findListItemIndexForSuggestionBridge(u.children,a.children[o.afterIndex+1]);let f=Math.min(o.afterIndex,u.children.length);return o.afterIndex===0?f=0:p!==-1?f=p+1:h!==-1&&(f=h),u.children.splice(f,0,{...g,structuralSuggestionId:n,structuralSuggestionKind:"insert",structuralSuggestionLabel:"Insert"}),{liveBlock:u,label:"Insert",listItemSuggestion:{kind:"insert",afterItem:this.cloneSuggestionSnapshot(g)}}}if(o.kind==="delete"){const u=this.cloneSuggestionSnapshot(c??s),g=this.findListItemIndexForSuggestionBridge(u.children,o.beforeItem);if(g!==-1){const p=u.children[g];return u.children[g]={...p,structuralSuggestionId:n,structuralSuggestionKind:"delete",structuralSuggestionLabel:"Delete"},{liveBlock:u,acceptedBlock:this.cloneSuggestionSnapshot(a),label:"Delete",listItemSuggestion:{kind:"delete",beforeItem:this.cloneSuggestionSnapshot(o.beforeItem)}}}}if(o.kind!=="change")return null;const l=this.cloneSuggestionSnapshot(c??s),d=this.findListItemIndexForSuggestionBridge(l.children,o.beforeItem);return d!==-1?(l.children[d]={...this.cloneSuggestionSnapshot(o.afterItem),structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:"Change"},{liveBlock:l,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(!Bs(e,n))return!1;const o=this.computeListSuggestionBridgeOperations(e,n);if(o.length===0)return!1;let i=this.cloneSuggestionSnapshot(t.currentLiveBlock??e),s=!1;const a=[],c=[];for(let l=0;l<o.length;l++){const d=l===0?t.suggestionId:Ct(),u=o[l];if(u.kind==="change"&&this.host.canBridgeListItemChangeAsInline(u.beforeItem,u.afterItem)){const p=this.findListItemIndexForSuggestionBridge(i.children,u.beforeItem);if(p===-1)return!1;c.push({suggestionId:d,itemIndex:p,beforeItem:this.cloneSuggestionSnapshot(u.beforeItem),afterItem:this.cloneSuggestionSnapshot(u.afterItem),formatOnly:this.host.getListItemPlainText(u.beforeItem)===this.host.getListItemPlainText(u.afterItem)});continue}const g=this.buildListSuggestionChange(e,n,d,u,i);if(!g?.listItemSuggestion)return!1;i=g.liveBlock,s=!0,a.push({id:d,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:g.acceptedBlock?this.cloneSuggestionSnapshot(g.acceptedBlock):void 0,listItemSuggestion:{kind:g.listItemSuggestion.kind,beforeItem:g.listItemSuggestion.beforeItem?this.cloneSuggestionSnapshot(g.listItemSuggestion.beforeItem):void 0,afterItem:g.listItemSuggestion.afterItem?this.cloneSuggestionSnapshot(g.listItemSuggestion.afterItem):void 0},label:g.label,createdAt:t.createdAt})}if(s&&!this.host.replaceBlockByIdWithoutSelection(t.blockId,i))return!1;this.host.transact(()=>{for(const l of a)this.saveLiveSuggestion(l)});for(const l of c){const d=this.host.getListItemPlainText(l.afterItem);let u;if(l.formatOnly){const g=this.host.extractTextNodesForRange(l.afterItem,0,d.length);u=this.applyBridgeInlineFormatSuggestion({suggestionId:l.suggestionId,blockId:t.blockId,itemIndex:l.itemIndex,start:0,end:d.length,targetAttributes:{},targetTextNodes:g,createdAt:t.createdAt})}else{const g=this.host.getListItemPlainText(l.beforeItem),p=qo(g,d).diffs;let h=0,f=0;u=!0;for(let m=0;m<p.length&&u;m++){const[y,b]=p[m];if(y===0){u=this.applyBridgeInlineFormatSuggestion({suggestionId:Ct(),blockId:t.blockId,itemIndex:l.itemIndex,start:f,end:f+b.length,targetAttributes:{},targetTextNodes:this.host.extractTextNodesForRange(l.afterItem,h,h+b.length),createdAt:t.createdAt}),h+=b.length,f+=b.length;continue}if(y===-1){const k=p[m+1];if(k&&k[0]===1){const v=this.host.extractTextNodesForRange(l.afterItem,h,h+k[1].length);u=this.applyBridgeInlineTextSuggestion({suggestionId:l.suggestionId,blockId:t.blockId,itemIndex:l.itemIndex,start:f,deleteLength:b.length,insertNodes:v,label:"Replace",createdAt:t.createdAt}),f+=b.length+k[1].length,h+=k[1].length,m++}else u=this.applyBridgeInlineTextSuggestion({suggestionId:l.suggestionId,blockId:t.blockId,itemIndex:l.itemIndex,start:f,deleteLength:b.length,insertNodes:[],label:"Replace",createdAt:t.createdAt}),f+=b.length}else{const k=this.host.extractTextNodesForRange(l.afterItem,h,h+b.length);u=this.applyBridgeInlineTextSuggestion({suggestionId:l.suggestionId,blockId:t.blockId,itemIndex:l.itemIndex,start:f,deleteLength:0,insertNodes:k,label:"Replace",createdAt:t.createdAt}),f+=b.length,h+=b.length}}}if(!u)return!1}return a.length>0||c.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 s=this.applySuggestedDeletionToTextRange(e,t.start,t.deleteLength,t.suggestionId);o=t.start+s.retainedLength,n=n||s.changed}let i=o;for(const s of t.insertNodes){if(!s.text)continue;const a=this.buildSuggestionInsertionMarks(this.sanitizePreviewMarks(s.marks),t.suggestionId,t.label,t.createdAt);kt(e,i,s.text,a),i+=s.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,u)=>d+u.text.length,0)!==n)return!1;const i=[];let s=t.start;const a=t.targetTextNodes?t.targetTextNodes.map(d=>({length:d.text.length,marks:d.marks})):[{length:n,marks:t.targetAttributes}];let c=0;for(const d of a){const u=s+d.length;for(;c<o.length&&o[c].start+o[c].length<=s;)c++;for(let g=c;g<o.length&&o[g].start<u;g++){const p=o[g],h=Math.max(p.start,s),f=Math.min(p.start+p.length,u);if(f<=h)continue;const m=t.targetTextNodes?xa(p.attributes,d.marks):{...d.marks??{}};i.push({...p,start:h,length:f-h,targetAttributes:m})}s=u}const l=[];return this.host.transact(()=>{for(const d of i){const u={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(t.suggestionId,"Format",t.createdAt)},g=new Set([...Object.keys(d.attributes||{}),...Object.keys(d.targetAttributes)]);if(g.delete("insertion"),g.delete("deletion"),g.delete("suggestionId"),g.delete("formatChange"),g.delete("suggestionSource"),g.delete("suggestionAuthorType"),g.delete("suggestionCreatedAt"),g.delete("suggestionLabel"),g.delete("suggestionCommentThreadId"),g.delete("suggestionAuthorName"),g.delete("suggestionAgentModel"),g.delete("suggestionAgentConversationId"),g.delete("suggestionAgentRequestId"),g.delete("suggestionAgentTurn"),g.delete("suggestionPriorAttributes"),g.delete("layeredInsertion"),g.delete("proposalId"),g.delete("toolCallId"),g.delete("toolType"),![...g].every(p=>(d.attributes?.[p]??null)===(d.targetAttributes[p]??null))){l.push(d);for(const p of g)Object.prototype.hasOwnProperty.call(d.targetAttributes,p)?u[p]=d.targetAttributes[p]:u[p]=null;It(e,d.start,d.length,{...u,suggestionPriorAttributes:pr(d.attributes)})}}l.length!==0&&this.saveLiveSuggestion({id:t.suggestionId,type:"inline-format",spans:l.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||ut(this.host.ydoc,t.referenceId),o=t.referenceId===Rn;if(!n&&!o)return!1;const i=n?.yParent??this.host.getYContentFragment(),s=n?.index??0,a=this.sanitizePreviewBlock(t.block),c=a.id||et();let l=null;this.host.transact(()=>{const u=this.host.blockToYjsElement({...a,id:c});l=u,u.setAttribute("id",c),this.markInsertedBlockElement(u,t.suggestionId,t.label);const g=o?i.length:t.position==="before"?s:s+1;i.insert(g,[u]),t.batchInsertedBlocks?.set(c,{yBlock:u,yParent:i,index:g})});const d=this.host.ensureTrailingParagraph();return this.host.transact(()=>{this.saveLiveSuggestion({id:t.suggestionId,type:"block-insert",blockId:c,label:t.label,createdAt:t.createdAt,cleanupTrailingParagraphId:d??void 0},l??void 0)}),!0}applyBridgeBlockDeleteSuggestion(t){const e=at(this.host.ydoc,t.blockId);if(!(e instanceof x.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"?z(this.host.getDocument(),t.blockId):null;let i=this.markBlockForGenericSuggestionChange(n,t.suggestionId,t.label),s,a,c=t.label;if(e.type==="paragraph"&&n.type==="paragraph"&&ce(e)!==ce(n))i=this.host.buildParagraphReplacementLiveBlock(e,n,t.suggestionId,t.label),s=n;else if(e.type==="paragraph"&&n.type==="paragraph")s=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;i={...n,structuralSuggestionId:t.suggestionId,structuralSuggestionKind:"change",structuralSuggestionLabel:"List"},s=n,c="List"}else if(e.type==="table"&&n.type==="table"){const l=z(this.createLiveSuggestionProjection("accept").doc,t.blockId),d=l?.type==="table"?l:e,u=this.reconcileTableDescendantIds(d,n),g=ko(e,u),p=g?null:this.buildSuggestedTableChange(d,u,t.suggestionId);if(p)i=o?.type==="table"?this.mergePendingTableRevisionState(o,p.liveBlock):p.liveBlock,a=p.record,c=p.label;else if(!this.hasSameTableGeometry(d,u)||g||ko(d,u))i=this.markBlockForGenericSuggestionChange(u,t.suggestionId,"Table"),s=u,c="Change";else{if(o?.type==="table"&&this.collectNestedSuggestionIdsForBlock(t.blockId,t.suggestionId).length>0)return!0;i={...this.cloneSuggestionSnapshot(u),diffState:"insert",suggestionId:t.suggestionId}}}if(t.optimizeFormatting&&e.type==="paragraph"&&n.type==="paragraph"&&ce(e)===ce(n)){const l=this.batchYBlockLocationsById?.get(t.blockId)?.yBlock??at(this.host.ydoc,t.blockId),d=l?l._item:null,u=l?xt(l):null;if(l&&u&&!d?.deleted){const g=new Set(["insertion","deletion","suggestionId","formatChange","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","proposalId","toolCallId","toolType"]),p=[];let h=0,f=!1;for(const m of n.children){if(m.type!=="text"||m.text.length===0)continue;const y=this.sanitizePreviewMarks(m.marks)??{},b=this.host.collectOverlappingTextSpans(u,h,m.text.length);f||(f=b.some(k=>["insertion","deletion","suggestionId","formatChange"].some(v=>Object.prototype.hasOwnProperty.call(k.attributes,v)))),p.push({targetAttributes:y,spans:b}),h+=m.text.length}if(!f)return this.host.transact(()=>{yo(l,i);for(const{targetAttributes:m,spans:y}of p)for(const b of y){const k=new Set([...Object.keys(b.attributes??{}),...Object.keys(m)]),v={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(t.suggestionId,"Format",t.createdAt)};for(const S of k)g.has(S)||(v[S]=Object.prototype.hasOwnProperty.call(m,S)?m[S]:null);v.suggestionPriorAttributes=pr(b.attributes),It(u,b.start,b.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},l)}),!0}}if(e.type==="paragraph"&&n.type==="paragraph"&&JSON.stringify(e.children)===JSON.stringify(n.children)){const l=this.batchYBlockLocationsById?.get(t.blockId),d=l?l.yBlock._item:null;if(l&&!d?.deleted)return yo(l.yBlock,i),this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:this.cloneSuggestionSnapshot(n),label:c,createdAt:t.createdAt},l.yBlock),!0}return this.host.replaceBlockByIdWithoutSelection(t.blockId,i,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:s?this.cloneSuggestionSnapshot(s):void 0,label:c,createdAt:t.createdAt})}),!0):!1}sortBlockSuggestionPlansByDependency(t){if(t.length<=1)return t;const e=[],n=new Set,o=[...t],i=new Set(o.flatMap(s=>[s.blockId,...s.producedBlockIds??[]]).filter(s=>!!s));for(;o.length>0;){let s=!1;for(let a=0;a<o.length;a++){const c=o[a],l=c.insertReferenceId;if(!(l&&i.has(l)&&!n.has(l))){e.push(c),c.blockId&&n.add(c.blockId),c.producedBlockIds?.forEach(d=>n.add(d)),o.splice(a,1),s=!0;break}}if(!s){e.push(...o);break}}return e}buildAgentSuggestionPlanFromProposal(t,e,n,o,i,s,a,c=!1,l=!1){const d=e.getSuggestion(t);if(!d)return null;const u=i??d.createdAt;if(d.blockSequencePreview){const{blockId:S,blocks:I}=d.blockSequencePreview,w=z(n,S);return!w||I.length===0?null:{proposalId:t,category:"block",blockId:S,producedBlockIds:I.map(A=>A.id),apply:()=>{const A=ut(this.host.ydoc,S);if(!A)return!1;const _=I.map(B=>this.sanitizePreviewBlock(B));return this.host.transact(()=>{A.yParent.delete(A.index,1);const B=_.map($=>this.host.blockToYjsElement($));A.yParent.insert(A.index,B);for(const $ of B)this.setElementStructuralSuggestion($,"change",void 0,t,"Paragraph");const P=this.normalizeLiveSuggestionRecord({id:t,type:"block-change",blockId:_[0].id,beforeBlock:this.cloneSuggestionSnapshot(w),sequenceBlockIds:_.map($=>$.id),label:"Paragraph",createdAt:u});this.saveLiveSuggestion(P,B[0]);for(const $ of B.slice(1))this.embedLiveSuggestionRecordInTree(P,$)}),!0}}}if(d.blockPreview?.id){const S=z(n,d.blockPreview.id);if(!S)return null;const I=d.blockPreview;return{proposalId:t,category:"block",blockId:S.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:S.id,beforeBlock:S,afterBlock:I,optimizeFormatting:c,label:S.type==="paragraph"&&I.type==="paragraph"?ce(S)===ce(I)?"Format":"Replace":S.type==="table"?"Table":S.type==="list"?"List":"Change",createdAt:u})}}if(d.toolCallAction?.name==="insert_block"){const S=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,I=typeof S?.referenceId=="string"?S.referenceId:null,w=S?.position==="before"||S?.position==="after"?S.position:null,A=typeof S?.content=="string"?S.content:Array.isArray(S?.content)&&typeof S?.content[0]=="string"?S?.content[0]:null;if(!I||!w||!A)return null;const _=Ro(d.toolCallAction),B=(_&&s?z(s,_):null)??it.fromAgentHtml(A,{existingDocument:n}).children[0];if(!B)return null;const P={...B,id:_||B.id||et()};return{proposalId:t,category:"block",blockId:P.id,insertReferenceId:I,apply:()=>this.insertBlockRelativeWithSuggestion({block:P,referenceId:I,position:w,suggestionId:t,label:"Insert",createdAt:u,batchInsertedBlocks:a})}}if(d.insertionContext){const S=this.host.resolvePositionAwareInsertionReference({baseDoc:n,mustBeAfter:d.insertionContext.mustBeAfter,mustBeBefore:d.insertionContext.mustBeBefore});return S?{proposalId:t,category:"block",blockId:d.insertionContext.paragraphId,insertReferenceId:S.referenceId,apply:()=>this.insertBlockRelativeWithSuggestion({block:{...this.cloneSuggestionSnapshot(d.insertionContext.content),id:d.insertionContext.content.id||d.insertionContext.paragraphId||et()},referenceId:S.referenceId,position:S.position,suggestionId:t,label:"Insert",createdAt:u,batchInsertedBlocks:a})}:null}const g=e.resolveAnchorsAgainstDoc(t,o),p=d.anchors?.[0]?.paragraphId??null,h=d.inlinePreview&&!d.toolCallAction?d.inlinePreview:null,f=h?{resolvedPreview:(d.anchors??[]).map(S=>({kind:S.kind,paragraphId:S.paragraphId,fromIndex:h.startOffset,toIndex:h.startOffset+h.newText.length,text:S.text})),previewAnchorBlock:null}:e.withMaterializedSuggestion(t,S=>({resolvedPreview:e.resolveAnchorsAgainstDoc(t,S),previewAnchorBlock:p?qd(S,p):null}));if(!f)return null;const{resolvedPreview:m,previewAnchorBlock:y}=f;if(d.toolCallAction?.name==="remove_block"){const S=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,I=typeof S?.id=="string"?S.id:null,w=I?z(n,I):null;return!I||!w?null:{proposalId:t,category:"block",blockId:I,apply:()=>this.applyBridgeBlockDeleteSuggestion({suggestionId:t,blockId:I,beforeBlock:w,label:"Delete",createdAt:u})}}const b=d.anchors?.[0],k=g[0],v=m[0];if(b?.paragraphId){const S=z(n,b.paragraphId);let I=S?.type==="table"&&s?z(s,S.id):null;S?.type==="table"&&I?.type==="table"&&this.hasSameTableGeometry(S,I)&&!ko(S,I)&&(I={...I,children:I.children.map((B,P)=>({...B,children:B.children.map(($,T)=>({...$,children:S.children[P].children[T].children}))}))});const w=I??y;if(d.toolCallAction?.name==="replace_block"&&S&&w&&(S.type!=="paragraph"||w.type!=="paragraph"||this.host.paragraphReplaceShouldStayAtomic(S,w)))return{proposalId:t,category:"block",blockId:S.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:S.id,beforeBlock:S,afterBlock:w,optimizeFormatting:c,label:S.type==="paragraph"&&w.type==="paragraph"?ce(S)===ce(w)?"Format":"Replace":S.type==="table"?"Table":S.type==="list"?"List":"Change",createdAt:u})};if(S?.type==="paragraph"){const B=k?.fromIndex??k?.toIndex,P=b.previewStartOffset??v?.fromIndex??v?.toIndex;if(b.kind==="delete"){const $=B??P??0,T=b.text?.length??Math.max(0,(k?.toIndex??$)-$),C=Math.max(0,$-T);return{proposalId:t,category:"inline",blockId:S.id,start:C,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:S.id,start:C,deleteLength:T,insertNodes:[],label:"Delete",createdAt:u})}}if(b.kind==="insert"&&(h||w?.type==="paragraph")){const $=P??B??0,T=P??$,C=b.previewStartOffset!==void 0?T+(b.text?.length??0):v?.toIndex??T+(b.text?.length??0),N=b.previewTextNodes?b.previewTextNodes.map(L=>({...L,marks:L.marks?{...L.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(w,T,C);return{proposalId:t,category:"inline",blockId:S.id,start:$,inlinePriority:0,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:S.id,start:$,deleteLength:0,insertNodes:N,label:"Insert",createdAt:u})}}if(b.kind==="replace"&&(h||w?.type==="paragraph")){const $=P??B??0,T=P??$,C=b.previewStartOffset!==void 0?T+(b.text?.length??0):v?.toIndex??T+(b.text?.length??0),N=b.previewTextNodes?b.previewTextNodes.map(L=>({...L,marks:L.marks?{...L.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(w,T,C);return b.oldText===b.text?{proposalId:t,category:"inline",blockId:S.id,start:$,inlinePriority:1,apply:()=>this.applyBridgeInlineFormatSuggestion({suggestionId:t,blockId:S.id,start:$,end:$+(b.text?.length??0),targetAttributes:{},targetTextNodes:N,createdAt:u})}:{proposalId:t,category:"inline",blockId:S.id,start:$,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:S.id,start:$,deleteLength:b.oldText?.length??0,insertNodes:N,label:"Replace",createdAt:u})}}}if(S?.type==="list"&&w?.type==="list")return{proposalId:t,category:"block",blockId:S.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:S.id,beforeBlock:S,afterBlock:w,optimizeFormatting:!l&&(c||b.oldText===b.text),label:"List",createdAt:u})};const A=S?.type,_=w?.type;if(A==="list-item"&&_==="list-item"){const B=S,P=w,$=ke(n,B.id)?.children.find(T=>T?.type!=="list"?!1:T.children.some(C=>C.id===B.id));if($?.id){const T=$.children.findIndex(C=>C.id===B.id);if(T!==-1){const C=this.cloneSuggestionSnapshot($),N=this.cloneSuggestionSnapshot($);return N.children[T]=this.cloneSuggestionSnapshot(P),{proposalId:t,category:"block",blockId:$.id,apply:()=>{const L=z(this.host.getDocument(),$.id);return this.applyGranularListSuggestionChanges({blockId:$.id,before:C,after:N,suggestionId:t,currentLiveBlock:L?.type==="list"?L:void 0,createdAt:u})}}}}}if(S&&w)return{proposalId:t,category:"block",blockId:S.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:S.id,beforeBlock:S,afterBlock:w,optimizeFormatting:c,label:S.type==="table"?"Table":S.type==="paragraph"?"Format":"Change",createdAt:u})}}return null}describeAgentSuggestionApplyFailure(t,e,n,o){const i=e.getSuggestion(t.proposalId),s=(v,S)=>{const I=z(v,S);if(!I||I.id===S)return I;if(I.type==="list"){const w=I.children.find(A=>A.id===S);if(w)return w}return I},a=i?.toolCallAction,c=a?.arguments&&typeof a.arguments=="object"?a.arguments:null,l=typeof c?.id=="string"&&c.id.length>0?c.id:t.blockId,d=o?.find(v=>{const S=v.arguments&&typeof v.arguments=="object"?v.arguments:null,I=typeof S?.id=="string"&&S.id.length>0?S.id:null,w=I?s(n,I):null;if(!w)return!1;if(I===l)return!0;const A=typeof S?.find=="string"?S.find:"";return A.length>0&&ce(w).includes(A)})??a,u=d?.name??"agent change",g=d?.arguments&&typeof d.arguments=="object"?d.arguments:null,p=typeof g?.id=="string"&&g.id.length>0?g.id:t.blockId,h=this.host.getDocument(),f=p?s(h,p):null,m=p?s(n,p):null,y=f??m,b=y?y.type:null,k=p?`'${p}'${typeof b=="string"?` (${b})`:""}`:"the requested target";return!f&&m?`Could not apply ${t.category} suggestion for ${u} 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 ${u} 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 ${u}: the target block is unavailable at replay time. The attempted change was rolled back; re-read the document and retry.`}applyValidatedAgentActionsAsSuggestions(t){const e=this.host.tryCancelInsertedBlockForRemoveAction(t.processedActions,t.docBeforeToolCall);if(e)return e;const n=!!t.processedActions?.length&&t.processedActions.every(P=>P.name==="style_blocks"),o=new Xi(t.baseFork,n),i=new Map;for(const{block:P}of we(t.docBeforeToolCall).values())P.type==="list"&&P.id&&i.set(P.id,P.children.map($=>$.id));for(const P of this.getLiveSuggestionIds()){const $=this.getLiveSuggestion(P);$?.type==="block-change"&&$.sequenceBlockIds&&$.beforeBlock.id&&i.set($.beforeBlock.id,this.getSequenceReplacementMembers($).map(({yBlock:T})=>T.getAttribute("id")))}const s=Oi(t.validationFork,o,{...t.flattenOptions,precomputedLiveDocSchema:t.baseDocForSuggestions,precomputedCurrentDocSchema:t.baseDocForSuggestions,listUnwrapMemberIds:i,precomputedFinalDocSchema:t.docAfterToolCall}),a=t.validationAnchorsByAction.flat().filter(P=>P.kind==="replace"&&P.previewStartOffset!==void 0&&!!P.paragraphId);for(const P of a){const $=s.filter(T=>(o.getSuggestion(T)?.anchors??[]).some(C=>C.kind==="replace"&&C.paragraphId===P.paragraphId&&(C.oldText??"").includes(P.oldText??"")&&(C.text??"").includes(P.text??"")));if($.length===1){const T=o.getSuggestion($[0]),C=P.sourceFrom?x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(P.sourceFrom),t.baseFork):null,N=P.paragraphId?at(t.baseFork,P.paragraphId):null,L=N?xt(N):null,R=L?mt(L).map(M=>typeof M.insert=="string"?M.insert:"").join(""):"";T&&C&&C.type===L&&R.slice(C.index,C.index+(P.oldText?.length??0))===(P.oldText??"")&&(T.anchors=[{...P,previewStartOffset:C.index}])}}const c=s.length>=100,l=Date.now(),d=P=>{c&&(`${s.length}${P}`,Date.now()-l)};if(d("flattened"),s.length===0)return this.tryRejectRevertedPendingSuggestions({actions:t.processedActions,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 u=t.baseDocForSuggestions,g=(t.processedActions??[]).map((P,$)=>{const T=P.arguments&&typeof P.arguments=="object"?P.arguments:null,C=typeof T?.comment=="string"?T.comment.trim():"";return{action:P,comment:C,anchors:t.validationAnchorsByAction[$]??[]}}).filter(({action:P,comment:$})=>(P.name==="replace"||P.name==="replace_all")&&$.length>0),p=new Map;for(const P of g){const $=P.anchors.flatMap(T=>{if(!T.from||!T.to||!T.paragraphId)return[];const C=x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(T.from),t.validationFork),N=x.createAbsolutePositionFromRelativePosition(x.decodeRelativePosition(T.to),t.validationFork);if(!C||!N||C.type!==N.type)return[];const L=T.oldText??"",R=T.text??"";let M=0;for(;M<L.length&&M<R.length&&L[M]===R[M];)M++;let F=0;for(;F<L.length-M&&F<R.length-M&&L[L.length-1-F]===R[R.length-1-F];)F++;const j=L.length>R.length&&M+F===R.length?C.index+M:null;return[{paragraphId:T.paragraphId,start:C.index,end:N.index,deletionPoint:j}]});p.set(P,$)}const h=new Map,f=s.map(P=>this.buildAgentSuggestionPlanFromProposal(P,o,u,t.baseFork,void 0,t.docAfterToolCall,h,t.optimizeStyleFormatting===!0,g.length>0)).filter(P=>!!P);if(d("built plans"),f.length!==s.length)return{success:!1,error:"Could not translate one or more agent changes into live suggestions."};const m=this.sortBlockSuggestionPlansByDependency(f.filter(P=>P.category==="block")),y=new Map(s.map((P,$)=>[P,$])),b=f.filter(P=>P.category==="inline").sort((P,$)=>{if(P.blockId&&$.blockId&&P.blockId===$.blockId){const T=($.start??0)-(P.start??0);if(T!==0)return T;const C=($.inlinePriority??0)-(P.inlinePriority??0);if(C!==0)return C}return(y.get(P.proposalId)??0)-(y.get($.proposalId)??0)});let k=[];const v=this.host.beginRollbackScope();let S=null;try{d("applying plans"),k=this.withSuggestionMetadata({source:"agent",authorType:"ai",label:`${t.agentName??Ae} revision`,agentName:t.agentName??Ae,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,historyOrigin:`live-suggestions:${t.toolCallId}`},()=>this.host.transact(()=>{const P=new Set(Array.from(t.flattenOptions?.affectedBlockIds??[]));for(const C of f)C.blockId&&P.add(C.blockId);S=m[0]??b[0]??null,this.resetLiveSuggestionsForBlocks(P,u),this.batchYBlockLocationsById=new Map;const $=new Map;for(const C of m){if(!C.blockId)continue;const N=at(this.host.ydoc,C.blockId);N&&$.set(N,C.blockId)}const T=new Map;for(const[C,N]of $){const L=C.parent;if(!(L instanceof x.XmlElement||L instanceof x.XmlFragment))continue;const R=T.get(L)??new Map;R.set(C,N),T.set(L,R)}for(const[C,N]of T)C.toArray().forEach((L,R)=>{if(!(L instanceof x.XmlElement))return;const M=N.get(L);M&&this.batchYBlockLocationsById.set(M,{yBlock:L,yParent:C,index:R})});try{for(const C of m)if(S=C,!C.apply())throw new Error("suggestion application returned false");for(const C of b)if(S=C,!C.apply())throw new Error("suggestion application returned false")}finally{this.batchYBlockLocationsById=null}d("finished plan loop"),S=null})).suggestionIds,d("applied plans"),v.dispose()}catch(P){v.revert();const $=P instanceof Error?P.message:"suggestion application failed",T=$==="suggestion application returned false"?null:$,C=S?this.describeAgentSuggestionApplyFailure(S,o,u,t.originalActions):null;return{success:!1,error:C?`${C}${T?` Detail: ${T}`:""}`:T??"Could not apply the requested edit."}}this.host.relinkCommentSuggestionIds();const I=g.length?this.host.getSuggestionCommentRanges(k):[],w=[],A=[];let _=0;for(const[P,$]of p){const T=I.flatMap(R=>$.flatMap(M=>{if(R.structural){if(M.paragraphId!==R.blockId)return[];const F=Math.max(R.projectedStart,M.start),j=Math.min(R.projectedEnd,M.end);return j<F||j===F&&M.start!==M.end?[]:[{...R,start:R.start+F-R.projectedStart,end:R.start+j-R.projectedStart}]}return(()=>{if(M.paragraphId!==R.blockId)return!1;const F=R.projectedStart,j=R.projectedEnd;return F===j&&M.start===M.end?F===M.start:F===j?M.deletionPoint===F||M.start<F&&F<M.end:M.start===M.end?F<M.start&&M.start<j:F<M.end&&M.start<j})()?[R]:[]})),C=Array.from(new Set(T.map(R=>R.suggestionId)));if(C.length===0){_++;for(const R of k)w.includes(R)||w.push(R);continue}for(const R of C)w.includes(R)||w.push(R);const N={author:t.agentName??Ae,authorType:"ai",agentName:t.agentName??Ae,agentModel:t.agentModel,suggestionId:C[0],...C.length>1?{relatedSuggestionIds:C}:{}},L=T.every(R=>R.structural&&R.start===R.end)?this.host.addBlockComment(T[0].blockId,P.comment,N):this.host.addCommentToRanges(T.map(({blockId:R,start:M,end:F})=>({blockId:R,start:M,end:F})),P.comment,N);L?A.push(L):_++}const B=Sm(t.agentFeedback,t.originalActions,s,t.docBeforeToolCall,t.docAfterToolCall);return{success:k.length>0,planningSuggestionIds:s,suggestionIds:k,commentedSuggestionIds:w,attachedCommentIds:A,commentAttachmentFailureCount:_,agentFeedback:k.length>0?B:void 0,error:k.length===0?"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content.":void 0}}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)}),zd(this.host.ydoc,t.doc),this.host.transact(()=>{const o=this.getLiveSuggestionStore();for(const i of Array.from(o.keys()))o.delete(i);for(const[i,s]of t.liveSuggestions)o.set(i,this.cloneSuggestionSnapshot(s))}),this.host.cachedDoc=this.cloneSuggestionSnapshot(t.doc),Mo(this.host.ydoc,this.host.cachedDoc),this.host.invalidateDerivedDocumentState()}tryRejectRevertedPendingSuggestions(t){const e=this.host.getActionTargetBlockIds(t.actions,t.baseDoc);if(e.length===0)return null;const n=this.host.getDocument(),o=new Set,i=[];for(const a of e){const c=z(n,a);c&&this.collectSuggestionIdsFromBlockValue(c,o);const l=z(t.baseDoc,a),d=z(t.docAfterToolCall,a);l&&d&&JSON.stringify(l)===JSON.stringify(d)&&i.push(a)}if(o.size===0||i.length===0||this.rejectLiveSuggestions(Array.from(o))===0)return null;const s=i.length===1?`block ${i[0]}`:`${i.length} blocks`;return{success:!0,planningSuggestionIds:[],suggestionIds:[],agentFeedback:`Rejected pending suggestion changes for ${s}.`}}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 Xi(this.host.cloneYDoc(this.host.ydoc));return this.rebuildDetachedSuggestionsFromSnapshotWithStore(t,e)}rebuildDetachedSuggestionsFromSnapshotWithStore(t,e){const n=$n(t);return Oi(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),Li.clearAllStoredSuggestions(this.host.documentId)}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){const e=this.host.cloneYDoc(this.host.ydoc),n=new Xi(e);if(this.hasSerializedDetachedSuggestions(t.serverDetachedSuggestions)){const d=this.host.cloneYDoc(this.host.ydoc),u=new Li(d,`${this.host.documentId}-legacy-proposal-materialization`,!0,t.conversationId);u.loadFromServerData(t.serverDetachedSuggestions);const g=Array.from(u.getPendingSuggestions().keys());if(g.length>0){const p=Tt(u.materializeWithSuggestions(g));this.rebuildDetachedSuggestionsFromSnapshotWithStore(p,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 i=Tt(e),s=o.map(d=>this.buildAgentSuggestionPlanFromProposal(d,n,i,e,t.legacyCreatedAt)).filter(d=>!!d);if(s.length!==o.length)return{success:!1,migratedSuggestionCount:0,error:"Could not translate one or more legacy proposals into live suggestions."};const a=this.sortBlockSuggestionPlansByDependency(s.filter(d=>d.category==="block")),c=s.filter(d=>d.category==="inline").sort((d,u)=>d.blockId&&u.blockId&&d.blockId===u.blockId?(u.start??0)-(d.start??0):o.indexOf(d.proposalId)-o.indexOf(u.proposalId));let l=[];try{l=this.withSuggestionMetadata({source:"agent",authorType:"ai",createdAt:t.legacyCreatedAt,label:"Agent revision",agentName:Ae,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 c)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:l.length>0,suggestionIds:l,migratedSuggestionCount:o.length,error:l.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 i=this.rebuildDetachedSuggestionsFromSnapshot(e.proposedDocument);return(i.length>0||o<=0)&&this.host.rebuiltMigrationSnapshotConversations.add(t),i.length}catch(i){return console.error("[DocumentMutator] Failed rebuilding detached changes from migration snapshot:",i),o<=0&&this.host.rebuiltMigrationSnapshotConversations.add(t),0}}setOnDetachedSuggestionsChanged(t){this.host.detachedSuggestionStore.setOnSuggestionsChanged(t)}}class Yp{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 i=0;i<n.yContext.yBlock.length;i++){const s=n.yContext.yBlock.get(i);s instanceof x.XmlElement&&s.nodeName==="list-item"&&o.push(s)}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(),i=z(o,t);if(!i||i.type!=="paragraph")return!1;const s=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(i):null,a=this.host.suggestingMode?Ct():null,c=ut(this.host.ydoc,t);if(!c)return!1;const{yBlock:l,yParent:d,index:u}=c;this.host.transact(()=>{if(!(l instanceof x.XmlElement))return;const h=new x.XmlElement("list"),f=l.getAttribute("id")||et();h.setAttribute("id",f),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(f,n)):e==="ordered"?(h.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(f,1)):this.host.listStartNumberCache.delete(f);let m,y;for(let I=0;I<l.length;I++){const w=l.get(I);if(w instanceof x.XmlText){y=w;break}}if(y&&y.length>0){const I=mt(y);for(const w of I)if(w.attributes?.fontFamily){m=w.attributes.fontFamily;break}}if(!m&&i.type==="paragraph"){for(const I of i.children)if(I.type==="text"&&I.marks?.fontFamily){m=I.marks.fontFamily;break}}const b=[],k=[],v=(I,w)=>{k.push({ops:I,plain:w})};if(y&&y.length>0){const I=mt(y);let w=[],A="";const _=()=>{v(w,A),w=[],A=""};I.forEach(B=>{if(typeof B.insert=="string"){let P=B.insert;for(;P.length>0;){const $=P.indexOf(`
29
- `);if($===-1)P.length>0&&(w.push({insert:P,attributes:B.attributes&&Object.keys(B.attributes).length>0?{...B.attributes}:void 0}),A+=P),P="";else{const T=P.slice(0,$);T.length>0&&(w.push({insert:T,attributes:B.attributes&&Object.keys(B.attributes).length>0?{...B.attributes}:void 0}),A+=T),_(),P=P.slice($+1)}}}else if(B.insert!==void 0&&B.insert!==null){let P=null;if(typeof B.insert=="string")P=B.insert;else try{P=JSON.stringify(B.insert)}catch{P=String(B.insert)}P&&P.length>0&&(w.push({insert:P,attributes:B.attributes&&Object.keys(B.attributes).length>0?{...B.attributes}:void 0}),A+=P)}}),_()}else k.push({ops:[],plain:""});k.length===0&&k.push({ops:[],plain:""});const S=bt(l,"direction");k.forEach(I=>{const w=new x.XmlElement("list-item");w.setAttribute("id",et()),e==="todo"&&w.setAttribute("checked","false"),(S==="rtl"||S==="ltr")&&w.setAttribute("direction",S);const A=new x.XmlText;if(k.length===1&&(e==="unordered"&&(I.plain==="-"||I.plain==="*")||e==="ordered"&&/^\d+\.$/.test(I.plain.trim())||e==="todo"&&(I.plain==="[]"||I.plain.trim()==="[]"))){const _=[...I.ops].reverse().find(P=>P.insert.length>0)?.attributes,B={...Ue(_)??{}};B.fontFamily||(B.fontFamily=m||ae),w.setAttribute("_emptyTextMarks",JSON.stringify(B))}else{let _=0;I.ops.forEach(({insert:B,attributes:P})=>{if(B.length===0)return;const $=P?{...P}:{};$.fontFamily||(m||console.warn("[DocumentMutator] convertParagraphToList: No font found, defaulting to Arial. This may indicate a bug."),$.fontFamily=m||ae),A.insert(_,B,$),_+=B.length})}w.insert(0,[A]),b.push(w)}),h.insert(0,b),d.delete(u,1),d.insert(u,[h]),this.host.suggestingMode&&a&&s&&this.host.suggestionEngine.saveLiveSuggestion({id:a,type:"block-change",blockId:t,beforeBlock:s,label:"List"})});const g={block:l.getAttribute("id")||t,offset:0};this.host.setSelectionAfterOperation({anchor:g,focus:g});const p=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(p),!0}setListDirectionById(t,e){const n=ut(this.host.ydoc,t);if(!n)return!1;const{yBlock:o}=n;return!(o instanceof x.XmlElement)||o.nodeName!=="list"?!1:(this.host.transact(()=>{for(let i=0;i<o.length;i++){const s=o.get(i);!(s instanceof x.XmlElement)||s.nodeName!=="list-item"||(e===null?rt(s,"direction"):s.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 i=[];for(let s=t;s<=e;s++){const a=o.children[s];if(!a)return!1;if(a.type==="paragraph")i.push({type:"paragraph",node:a});else if(a.type==="list")i.push({type:"list",node:a});else return!1}return i.length===0?!1:(this.host.transact(()=>{const s=this.host.getYContentFragment(),a=s.get(t),c=a instanceof x.XmlElement?a.getAttribute("id"):void 0,l=new x.XmlElement("list"),d=c||et();l.setAttribute("id",d),l.setAttribute("variant",n),n==="ordered"?(l.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(d,1)):this.host.listStartNumberCache.delete(d);const u=[];let g;for(const f of i){if(f.type==="paragraph"){for(const m of f.node.children)if(m.type==="text"&&m.marks?.fontFamily){g=m.marks.fontFamily;break}}else if(f.type==="list")for(const m of f.node.children){for(const y of m.children)if(y.type==="text"&&y.marks?.fontFamily){g=y.marks.fontFamily;break}if(g)break}if(g)break}let p=!1;const h=(f,m)=>{const y=new x.XmlElement("list-item");y.setAttribute("id",et()),n==="todo"&&y.setAttribute("checked",String(m?.checked??!1)),(m?.direction==="rtl"||m?.direction==="ltr")&&y.setAttribute("direction",m.direction);const b=new x.XmlText;let k=f;if((n==="unordered"&&(f==="-"||f==="*")||n==="ordered"&&/^\d+\.$/.test(f)||n==="todo"&&f==="[]")&&(k=""),k){const S=m?.fontFamily||g;S||console.warn("[DocumentMutator] convertParagraphRangeToList: No font found for list item, defaulting to Arial. This may indicate a bug."),b.insert(0,k,{fontFamily:S||ae})}const v=m?.indentLevel;typeof v=="number"&&v>0&&y.setAttribute("indentLevel",String(v)),y.insert(0,[b]),u.push(y),p=!0};i.forEach(f=>{if(f.type==="paragraph"){const m=f.node.children.filter(b=>b.type==="text").map(b=>b.text).join("");let y;for(const b of f.node.children)if(b.type==="text"&&b.marks?.fontFamily){y=b.marks.fontFamily;break}(m.length>0?m.split(`
30
- `):[""]).forEach(b=>{h(b,{fontFamily:y,direction:f.node.direction})})}else{const m=f.node;m.children.forEach(y=>{const b=this.getListItemPlainText(y),k=m.variant==="todo"?y.checked??!1:void 0;let v;for(const S of y.children)if(S.type==="text"&&S.marks?.fontFamily){v=S.marks.fontFamily;break}h(b,{checked:k,indentLevel:y.indentLevel,fontFamily:v,direction:y.direction})})}}),p||h(""),l.insert(0,u),s.delete(t,e-t+1),s.insert(t,[l])}),!0)}convertListToParagraph(t){const e=this.host.getDocument().children[t];if(!e||e.type!=="list")return!1;const n=e;this.host.suggestingMode&&this.host.suggestionEngine.cloneSuggestionSnapshot(n);const o=this.host.suggestingMode?Ct():null;n.id&&this.host.listStartNumberCache.delete(n.id),this.host.transact(()=>{const a=this.host.getYContentFragment(),c=a.get(t);if(!(c instanceof x.XmlElement))return;const l=[];for(let p=0;p<c.length;p++){const h=c.get(p);if(h instanceof x.XmlElement&&h.nodeName==="list-item"){let f=null;for(let m=0;m<h.length;m++){const y=h.get(m);if(y instanceof x.XmlText){f=y;break}}f?l.push({delta:mt(f)}):l.push({delta:[]})}}const d=new x.XmlElement("paragraph");d.setAttribute("id",c.getAttribute("id")||et());{const p=n.children[0]?.direction;(p==="rtl"||p==="ltr")&&d.setAttribute("direction",p)}o&&this.host.suggestionEngine.setParagraphStructuralSuggestion(d,"change",void 0,o,"Paragraph");const u=new x.XmlText;let g=0;l.forEach((p,h)=>{p.delta.forEach(f=>{typeof f.insert=="string"&&(f.attributes&&Object.keys(f.attributes).length>0?u.insert(g,f.insert,f.attributes):u.insert(g,f.insert),g+=f.insert.length)}),h<l.length-1&&(u.insert(g,`
31
- `),g+=1)}),d.insert(0,[u]),a.delete(t,1),a.insert(t,[d])});const i=this.host.getDocument(),s=i.children[t]?.id?this.host.cursorAtBlock(t,0,i):null;return s&&(this.host.setSelectionAfterOperation({anchor:s,focus:s}),this.host.updateAfterOperationRelativeSelection(i)),!0}updateListVariant(t,e,n){const o=this.host.getDocument().children[t];if(!o||o.type!=="list")return!1;const i=o,s=i.id||String(t),a=i.startNumber;return this.host.transact(()=>{const c=this.host.getYContentFragment().get(t);if(c instanceof x.XmlElement){if(c.setAttribute("variant",e),e==="ordered"){const l=c.getAttribute("startNumber"),d=l?parseInt(l,10):void 0,u=this.host.listStartNumberCache.get(s),g=n??a??d??u??1;c.setAttribute("startNumber",String(g)),this.host.listStartNumberCache.set(s,g)}else a!==void 0&&this.host.listStartNumberCache.set(s,a),c.removeAttribute("startNumber");for(let l=0;l<c.length;l++){const d=c.get(l);d instanceof x.XmlElement&&d.nodeName==="list-item"&&(e==="todo"?d.getAttribute("checked")===void 0&&d.setAttribute("checked","false"):d.removeAttribute("checked"))}}}),!0}convertListToParagraphById(t){const e=this.host.getDocument(),n=z(e,t);if(!n||n.type!=="list")return!1;const o=n,i=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(o):null,s=this.host.suggestingMode?Ct():null;o.id&&this.host.listStartNumberCache.delete(o.id);const a=ut(this.host.ydoc,t);if(!a)return!1;const{yBlock:c,yParent:l,index:d}=a;this.host.transact(()=>{if(!(c instanceof x.XmlElement))return;const p=[];for(let y=0;y<c.length;y++){const b=c.get(y);if(b instanceof x.XmlElement&&b.nodeName==="list-item"){let k=null;for(let v=0;v<b.length;v++){const S=b.get(v);if(S instanceof x.XmlText){k=S;break}}k?p.push({delta:mt(k)}):p.push({delta:[]})}}const h=new x.XmlElement("paragraph");h.setAttribute("id",c.getAttribute("id")||et());{const y=o.children[0]?.direction;(y==="rtl"||y==="ltr")&&h.setAttribute("direction",y)}s&&this.host.suggestionEngine.setParagraphStructuralSuggestion(h,"change",void 0,s,"Paragraph");const f=new x.XmlText;let m=0;p.forEach((y,b)=>{y.delta.forEach(k=>{typeof k.insert=="string"&&(k.attributes&&Object.keys(k.attributes).length>0?f.insert(m,k.insert,k.attributes):f.insert(m,k.insert),m+=k.insert.length)}),b<p.length-1&&(f.insert(m,`
32
- `),m+=1)}),h.insert(0,[f]),l.delete(d,1),l.insert(d,[h]),this.host.suggestingMode&&s&&i&&this.host.suggestionEngine.saveLiveSuggestion({id:s,type:"block-change",blockId:t,beforeBlock:i,label:"Paragraph"})});const u={block:c.getAttribute("id")||t,offset:0};this.host.setSelectionAfterOperation({anchor:u,focus:u});const g=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(g),!0}updateListVariantById(t,e,n){const o=this.host.getDocument(),i=z(o,t);if(!i||i.type!=="list")return!1;const s=i,a=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(s):null,c=s.id||t,l=s.startNumber,d=this.host.suggestingMode?Ct():null,u=ut(this.host.ydoc,t);if(!u)return!1;const{yBlock:g}=u;return this.host.transact(()=>{if(g instanceof x.XmlElement){if(g.setAttribute("variant",e),d&&(this.host.suggestionEngine.clearElementStructuralSuggestion(g),this.host.suggestionEngine.setElementStructuralSuggestion(g,"change",void 0,d,"List")),e==="ordered"){const p=g.getAttribute("startNumber"),h=p?parseInt(p,10):void 0,f=this.host.listStartNumberCache.get(c),m=n??l??h??f??1;g.setAttribute("startNumber",String(m)),this.host.listStartNumberCache.set(c,m)}else l!==void 0&&this.host.listStartNumberCache.set(c,l),g.removeAttribute("startNumber");for(let p=0;p<g.length;p++){const h=g.get(p);h instanceof x.XmlElement&&h.nodeName==="list-item"&&(e==="todo"?h.getAttribute("checked")===void 0&&h.setAttribute("checked","false"):h.removeAttribute("checked"))}this.host.suggestingMode&&d&&a&&this.host.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:t,beforeBlock:a,label:"List"})}}),!0}continueListFromPrevious(t){const e=this.host.getDocument(),n=z(e,t);if(!n||n.type!=="list"||n.variant!=="ordered")return!1;const o=[],i=u=>{for(const g of u)if(g.type==="list")o.push(g);else if(g.type==="container"||g.type==="footnote")i(g.children);else if(g.type==="table")for(const p of g.children)for(const h of p.children)i(h.children)};i(e.children);const s=o.findIndex(u=>u.id===t);let a;for(let u=s-1;u>=0;u--)if(o[u].variant==="ordered"){a=o[u];break}if(s<0||!a)return!1;const c=ut(this.host.ydoc,t)?.yBlock,l=ut(this.host.ydoc,a.id)?.yBlock;if(!(c instanceof x.XmlElement)||!(l instanceof x.XmlElement))return!1;const d=a.numberingChainId??et();return this.host.transact(()=>{a.numberingChainId||l.setAttribute("numberingChainId",d),c.setAttribute("numberingChainId",d),c.removeAttribute("startNumber")}),!0}restartListNumberingAt(t,e,n=0){const o=this.host.getDocument(),i=z(o,t);if(!i||i.type!=="list"||i.variant!=="ordered"||!Number.isFinite(e)||e<1)return null;const s=i,a=Math.max(0,Math.min(Math.floor(n),s.children.length-1)),c=Math.floor(e),l=ut(this.host.ydoc,t);if(!l)return null;const{yBlock:d,yParent:u,index:g}=l;if(!(d instanceof x.XmlElement))return null;if(a===0)return this.host.transact(()=>{d.setAttribute("startNumber",String(c))}),this.host.listStartNumberCache.set(s.id,c),s.id;const p=et();return this.host.transact(()=>{const h=new x.XmlElement("list");h.setAttribute("id",p),h.setAttribute("variant",s.variant);const f=s.numberingChainId;f&&h.setAttribute("numberingChainId",f),s.numberingFormat&&h.setAttribute("numberingFormat",s.numberingFormat),h.setAttribute("startNumber",String(c)),s.lineSpacing!==void 0&&h.setAttribute("lineSpacing",String(s.lineSpacing)),h.insert(0,this.cloneYListItemRange(d,a)),d.delete(a,d.length-a),u.insert(g+1,[h])}),this.host.listStartNumberCache.set(p,c),p}cloneYListItemRange(t,e){const n=[];for(let o=e;o<t.length;o++){const i=t.get(o);if(!(i instanceof x.XmlElement)||i.nodeName!=="list-item")continue;const s=new x.XmlElement("list-item");s.setAttribute("id",i.getAttribute("id")||et());const a=i.getAttribute("checked");a!==void 0&&s.setAttribute("checked",a);const c=i.getAttribute("indentLevel");c!==void 0&&s.setAttribute("indentLevel",c);const l=bt(i,"direction");l!==void 0&&s.setAttribute("direction",l);let d=null;for(let g=0;g<i.length;g++){const p=i.get(g);if(p instanceof x.XmlText){d=p;break}}const u=new x.XmlText;if(d&&d.length>0){const g=mt(d);let p=0;g.forEach(h=>{typeof h.insert=="string"&&(u.insert(p,h.insert,h.attributes||{}),p+=h.insert.length)})}s.insert(0,[u]),n.push(s)}return n}splitListItem(t,e){this.host.beforeOperationSelection=e;const n=this.host.getDocument(),o=z(n,t.block);if(!o||o.type!=="list")return null;const i=o,s=Re(t,this.host.ydoc,n);if(!s)return null;const a=x.createAbsolutePositionFromRelativePosition(s.textOffset,this.host.ydoc);if(!a||!(a.type instanceof x.XmlText))return null;const c=a.type,l=a.index,d=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(i):null,u=this.host.suggestingMode?Ct():null;let g=null,p=null,h=!0;if(this.host.transact(()=>{const f=ut(this.host.ydoc,i.id);if(!f)return;const{yBlock:m,yParent:y,index:b}=f;if(!(m instanceof x.XmlElement))return;const k=[];for(let M=0;M<m.length;M++){const F=m.get(M);F instanceof x.XmlElement&&F.nodeName==="list-item"&&k.push(F)}let v=-1;for(let M=0;M<k.length;M++){const F=k[M];for(let j=0;j<F.length;j++){const D=F.get(j);if(D instanceof x.XmlText&&D===c){v=M;break}}if(v!==-1)break}if(v===-1||v>=i.children.length)return;const S=k[v],I=i.children[v],w=I.children.map(M=>M.type==="text"?M.text:"").join(""),A=this.host.suggestingMode&&l<w.length&&(()=>{let M=0,F=!1;for(const j of I.children){if(j.type!=="text")continue;const D=M+j.text.length;if(D>l&&j.text.length>0&&(F=!0,!j.marks?.deletion))return!1;M=D}return F})();if(w.trim().length===0&&i.children.length===1){const M=new x.XmlElement("paragraph");g=et(),M.setAttribute("id",g),(I.direction==="rtl"||I.direction==="ltr")&&M.setAttribute("direction",I.direction),h=!1;let F;for(const D of I.children)if(D.type==="text"&&D.marks?.fontFamily){F=D.marks.fontFamily;break}F||(F=this.host.resolveFontFamilyForList(i)),F&&M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:F}));const j=new x.XmlText;M.insert(0,[j]),y.delete(b,1),y.insert(b,[M]);return}if(w.trim().length===0&&i.children.length>1){const M=v===i.children.length-1,F=v===0;if(F||M){m.delete(v,1);const j=new x.XmlElement("paragraph");g=et(),j.setAttribute("id",g),(I.direction==="rtl"||I.direction==="ltr")&&j.setAttribute("direction",I.direction),h=!1;let D;for(const H of I.children)if(H.type==="text"&&H.marks?.fontFamily){D=H.marks.fontFamily;break}D||(D=this.host.resolveFontFamilyForList(i)),D&&j.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:D}));const O=new x.XmlText;j.insert(0,[O]),F?y.insert(b,[j]):y.insert(b+1,[j])}else{const j=i.children.length-v-1,D=new x.XmlElement("list");if(D.setAttribute("id",et()),D.setAttribute("variant",i.variant),i.variant==="ordered"){const ct=i.numberingChainId??et();i.numberingChainId||m.setAttribute("numberingChainId",ct),D.setAttribute("numberingChainId",ct),i.numberingFormat&&D.setAttribute("numberingFormat",i.numberingFormat)}const O=new x.XmlElement("paragraph");g=et(),O.setAttribute("id",g),(I.direction==="rtl"||I.direction==="ltr")&&O.setAttribute("direction",I.direction),h=!1;let H;for(const ct of I.children)if(ct.type==="text"&&ct.marks?.fontFamily){H=ct.marks.fontFamily;break}H||(H=this.host.resolveFontFamilyForList(i)),H&&O.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:H}));const q=new x.XmlText;O.insert(0,[q]);const W=[];for(let ct=v+1;ct<k.length;ct++){const vt=k[ct],Dt=new x.XmlElement("list-item");Dt.setAttribute("id",vt.getAttribute("id")||et());const Qt=vt.getAttribute("checked");Qt!==void 0&&Dt.setAttribute("checked",Qt);const Vt=vt.getAttribute("indentLevel");Vt!==void 0&&Dt.setAttribute("indentLevel",Vt);const G=bt(vt,"direction");G!==void 0&&Dt.setAttribute("direction",G);let gt=null;for(let Q=0;Q<vt.length;Q++){const wt=vt.get(Q);if(wt instanceof x.XmlText){gt=wt;break}}const yt=new x.XmlText;if(gt&&gt.length>0){const Q=mt(gt);let wt=0;Q.forEach(ft=>{if(typeof ft.insert=="string"){const dt=ft.attributes||{};yt.insert(wt,ft.insert,dt),wt+=ft.insert.length}})}Dt.insert(0,[yt]),W.push(Dt)}D.insert(0,W),m.delete(v,j+1),y.insert(b+1,[O,D])}return}if(l===0){const M=new x.XmlElement("list-item"),F=et();M.setAttribute("id",F),g=F,i.variant==="todo"&&M.setAttribute("checked","false");const j=I.indentLevel??0;j>0&&M.setAttribute("indentLevel",String(j)),(I.direction==="rtl"||I.direction==="ltr")&&M.setAttribute("direction",I.direction);let D;for(const H of I.children)if(H.type==="text"&&H.marks?.fontFamily){D=H.marks.fontFamily;break}D||(D=this.host.resolveFontFamilyForList(i));const O=new x.XmlText;M.insert(0,[O]),D?M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:D})):M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:ae})),u&&(this.host.suggestionEngine.clearElementStructuralSuggestion(M),this.host.suggestionEngine.setElementStructuralSuggestion(M,"insert",void 0,u,"Insert")),m.insert(v,[M]),g=I.id??null,p=v+1;return}if(l>=w.length||A){const M=new x.XmlElement("list-item");g=et(),M.setAttribute("id",g),p=v+1,i.variant==="todo"&&M.setAttribute("checked","false");const F=I.indentLevel??0;F>0&&M.setAttribute("indentLevel",String(F)),(I.direction==="rtl"||I.direction==="ltr")&&M.setAttribute("direction",I.direction);let j=this.host.getFontAtOffsetInListItem(I,l);j||(j=this.host.resolveFontFamilyForList(i));const D=new x.XmlText;M.insert(0,[D]),j?M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:j})):M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:ae})),u&&(this.host.suggestionEngine.clearElementStructuralSuggestion(M),this.host.suggestionEngine.setElementStructuralSuggestion(M,"insert",void 0,u,"Insert")),m.insert(v+1,[M]);return}let _=null;for(let M=0;M<S.length;M++){const F=S.get(M);if(F instanceof x.XmlText){_=F;break}}if(!_)return;const B=mt(_);let P=0;const $=[];for(const M of B)if(M.insert&&typeof M.insert=="string"){const F=M.insert.length;if(P+F<=l)P+=F;else if(P>=l)$.push(M);else{const j=l-P,D=M.insert.slice(j);D&&$.push({insert:D,...M.attributes&&{attributes:M.attributes}}),P=l}}l<_.length&&_.delete(l,_.length-l);const T=new x.XmlElement("list-item");g=et(),T.setAttribute("id",g),p=v+1,i.variant==="todo"&&T.setAttribute("checked","false");const C=I.indentLevel??0;C>0&&T.setAttribute("indentLevel",String(C)),(I.direction==="rtl"||I.direction==="ltr")&&T.setAttribute("direction",I.direction);const N=this.host.getFontAtOffsetInListItem(I,l),L=new x.XmlText;let R=0;if($.length>0){for(const M of $)if(M.insert&&typeof M.insert=="string"){const F=M.attributes&&Object.keys(M.attributes).length>0?{...M.attributes}:{};F.fontFamily||(N||console.warn("[DocumentMutator] splitListItem: No font found for new list item, defaulting to Arial. This may indicate a bug."),F.fontFamily=N||ae),L.insert(R,M.insert,F),R+=M.insert.length}}else{const M=N||this.host.resolveFontFamilyForList(i)||ae;T.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:M}))}u&&(this.host.suggestionEngine.clearElementStructuralSuggestion(S),this.host.suggestionEngine.clearElementStructuralSuggestion(T),this.host.suggestionEngine.setElementStructuralSuggestion(S,"split","before",u,"Split"),this.host.suggestionEngine.setElementStructuralSuggestion(T,"split","after",u,"Split")),T.insert(0,[L]),m.insert(v+1,[T])}),h){const f=this.host.getDocument(),m=z(f,i.id);if(!m||m.type!=="list"||p===null)return null;const y=m;let b=0;for(let S=0;S<p;S++){const I=y.children[S];for(const w of I.children)w.type==="text"&&(b+=w.text.length);S<p-1&&(b+=1)}p>0&&(b+=1);const k={block:y.id,offset:b},v={anchor:k,focus:k};return this.host.suggestingMode&&u&&d&&this.host.suggestionEngine.saveLiveSuggestion({id:u,type:"block-change",blockId:i.id,beforeBlock:d,label:"List"}),this.host.setSelectionAfterOperation(v),this.host.afterOperationRelativeSelection=J(v,this.host.ydoc,f),k}else{if(!g)return null;const f={block:g,offset:0},m={anchor:f,focus:f};return this.host.setSelectionAfterOperation(m),this.host.afterOperationRelativeSelection=J(m,this.host.ydoc,this.host.getDocument()),f}}insertTextInListItem(t,e,n,o){const i=this.resolveListContext(t);if(!i)return null;const{doc:s}=i,a=Re(t,this.host.ydoc,s);if(!a)return null;const c=x.createAbsolutePositionFromRelativePosition(a.textOffset,this.host.ydoc);if(!c||!(c.type instanceof x.XmlText))return null;const l=c.type,d=c.index;let u=null;if(o?.anchor&&o.focus&&qt(i.doc,o.anchor,o.focus)!==0){const w=Re(o.anchor,this.host.ydoc,i.doc),A=Re(o.focus,this.host.ydoc,i.doc),_=w?x.createAbsolutePositionFromRelativePosition(w.textOffset,this.host.ydoc):null,B=A?x.createAbsolutePositionFromRelativePosition(A.textOffset,this.host.ydoc):null;_?.type instanceof x.XmlText&&B?.type instanceof x.XmlText&&_.type===B.type&&_.type===l&&(u={yText:l,startOffset:Math.min(_.index,B.index),endOffset:Math.max(_.index,B.index)})}const g={},p=[],h=Rs(s,t),f=Er(s,t),m=Rr(s,t),y=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(s,t.block),b=y?null:this.host.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(s,t),k=b?.marks?.suggestionId??null,v=this.host.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(s,t,o);{const w=!y&&(this.host.suggestingMode||k)&&e.length>0,A=Ti({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:h?.marks,exitingLink:f,exitingComment:m,suggestionMarks:w?this.host.suggestionEngine.buildSuggestionInsertionMarks(void 0,v??k??this.host.suggestionEngine.getSuggestionIdFromInheritedMarks(h?.marks),void 0,void 0,b?.marks??h?.marks):void 0});Object.assign(g,A.marksToApply),p.push(...A.marksToRemove)}let S=u?.startOffset??d;this.host.transact(()=>{if(u&&u.endOffset>u.startOffset){const w=u.endOffset-u.startOffset;if(this.host.suggestingMode&&!y){const A=this.host.suggestionEngine.applySuggestedDeletionToTextRange(u.yText,u.startOffset,w,v??void 0);S=u.startOffset+A.retainedLength}else u.yText.delete(u.startOffset,w),S=u.startOffset}vc(l,S,e,{marksToApply:g,marksToRemove:p}),!y&&(this.host.suggestingMode||k)&&e.length>0&&this.host.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(l,S,e.length)});const I=x.createRelativePositionFromTypeIndex(l,S+e.length);return or({blockId:a.blockId,textOffset:I},this.host.ydoc)}insertTextInList(t,e,n,o){this.host.beforeOperationSelection=n;const i=this.insertTextInListItem(t,e,null,n);if(i){const s={anchor:i,focus:i};return this.host.setSelectionAfterOperation(s),this.host.afterOperationRelativeSelection=J(s,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(o),this.host.afterOperationRelativeSelection=J(o,this.host.ydoc,this.host.getDocument()),!0}insertFormattedTextInList(t,e,n,o,i){this.host.beforeOperationSelection=o;const s=this.insertTextInListItem(t,e,n,o);if(s){const a={anchor:s,focus:s};return this.host.setSelectionAfterOperation(a),this.host.afterOperationRelativeSelection=J(a,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=J(i,this.host.ydoc,this.host.getDocument()),!0}deleteTextInList(t,e,n,o){const i=this.resolveListContext(t);if(!i)return!1;const s=Re(t,this.host.ydoc,i.doc);if(!s)return!1;const a=x.createAbsolutePositionFromRelativePosition(s.textOffset,this.host.ydoc);if(!a||!(a.type instanceof x.XmlText))return!1;const c=a.type,l=a.index,d=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i.doc,t.block);return this.host.transact(()=>{const u=c.length,g=Math.min(e,u-l);if(g>0)if(this.host.suggestingMode&&!d){const p=this.host.suggestionEngine.applySuggestedDeletionToTextRange(c,l,g);g>1&&p.retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(c,l)}else c.delete(l,g)}),this.host.setSelectionAfterOperation(o),this.host.afterOperationRelativeSelection=J(o,this.host.ydoc,this.host.getDocument()),!0}tryApplyParagraphListTrigger(t,e,n){if(n!==" "||!t.id)return null;const o=this.host.getParagraphPlainText(t);return e.offset!==o.length?null:o==="-"||o==="*"?this.convertParagraphToListById(t.id,"unordered"):/^\d+\.$/.test(o)?this.convertParagraphToListById(t.id,"ordered",parseInt(o,10)):o==="[]"?this.convertParagraphToListById(t.id,"todo"):null}mergeAdjacentListsOnDelete(t,e,n,o,i,s,a){if(o!==n+1||!this.isCursorAtEndOfList(t,i)||!this.isCursorAtStartOfList(e,s))return!1;const c=this.host.getYContentFragment(),l=c.get(n),d=c.get(o);if(!(l instanceof x.XmlElement)||!(d instanceof x.XmlElement))return!1;let u=!1;return this.host.transact(()=>{const g=[];for(let h=0;h<d.length;h++){const f=d.get(h);if(f instanceof x.XmlElement&&f.nodeName==="list-item"){const m=new x.XmlElement("list-item");m.setAttribute("id",et());const y=f.getAttribute("checked");t.variant==="todo"&&m.setAttribute("checked",y??"false");const b=f.getAttribute("indentLevel");b!==void 0&&m.setAttribute("indentLevel",b);const k=bt(f,"direction");k!==void 0&&m.setAttribute("direction",k);const v=new x.XmlText;for(let S=0;S<f.length;S++){const I=f.get(S);if(I instanceof x.XmlText){const w=mt(I);let A=0;w.forEach(_=>{typeof _.insert=="string"&&(v.insert(A,_.insert,_.attributes||{}),A+=_.insert.length)});break}}m.insert(0,[v]),g.push(m)}}g.length>0&&l.insert(l.length,g),c.delete(o,1);const p=d.getAttribute("id")||e.id;p&&this.host.listStartNumberCache.delete(p),u=!0}),u?(this.host.setSelectionAfterOperation(a),!0):!1}isCursorAtStartOfList(t,e){return e.offset===0}isCursorAtEndOfList(t,e){if(t.children.length===0)return!0;let n=0;for(let o=0;o<t.children.length;o++){const i=t.children[o];n+=i.children.filter(s=>s.type==="text").reduce((s,a)=>s+a.text.length,0),o<t.children.length-1&&(n+=1)}return e.offset>=n}getListCursorInfo(t,e){const n=t;if(n.type!=="list")return null;let o=e.offset,i=0;for(let l=0;l<n.children.length;l++){const d=n.children[l].children.filter(u=>u.type==="text").reduce((u,g)=>u+g.text.length,0);if(o<=d){i=l;break}if(o-=d,l<n.children.length-1){if(o===0){i=l+1;break}o-=1}}if(i<0||i>=t.children.length)return null;const s=t.children[i],a=this.getListItemTextLength(s),c=Math.max(0,Math.min(o,a));return{itemIndex:i,offsetInItem:c,itemLength:a}}getListItemTextLength(t){return t.children.reduce((e,n)=>n.type==="text"?e+n.text.length:e,0)}setListItemIndent(t,e,n,o,i){const s=this.host.getDocument();if(!t||t.type!=="list"||e<0||e>=t.children.length)return!1;const a=t,c=a.children[e].indentLevel??0,l=Math.max(0,Math.min(2,Math.floor(n)));if(l===c)return!1;const d=l-c;if(d>0&&(e===0||(a.children[e-1].indentLevel??0)<l-1))return!1;const u=[],g=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(a):null,p=this.host.suggestingMode?Ct():null;if(d!==0)for(let m=e+1;m<a.children.length;m++){const y=a.children[m].indentLevel??0;if(y<=c)break;if(d>0&&y+d>2)return!1;const b=Math.max(0,Math.min(2,y+d));u.push({index:m,newIndent:b})}this.host.beforeOperationSelection=o;const h=$e().getHandlerForBlock(t);this.host.beforeOperationRelativeSelection=h?.allowsInternalCursor()?J(o,this.host.ydoc,s):null;const f=at(this.host.ydoc,t.id??"");return!f||!(f instanceof x.XmlElement)?!1:(this.host.transact(()=>{const m=[];for(let b=0;b<f.length;b++){const k=f.get(b);k instanceof x.XmlElement&&k.nodeName==="list-item"&&m.push(k)}const y=m[e];y&&(l>0?y.setAttribute("indentLevel",String(l)):y.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(y),this.host.suggestionEngine.setElementStructuralSuggestion(y,"change",void 0,p,d>0?"Indent":"Outdent")),u.forEach(({index:b,newIndent:k})=>{const v=m[b];v&&(k>0?v.setAttribute("indentLevel",String(k)):v.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(v),this.host.suggestionEngine.setElementStructuralSuggestion(v,"change",void 0,p,d>0?"Indent":"Outdent")))}),this.host.suggestingMode&&p&&g&&this.host.suggestionEngine.saveLiveSuggestion({id:p,type:"block-change",blockId:t.id,beforeBlock:g,label:d>0?"Indent":"Outdent"}))}),this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=h?.allowsInternalCursor()?J(i,this.host.ydoc,this.host.getDocument()):null,!0)}}function Kp(r,t){const e=mt(r).map(c=>typeof c.insert=="string"?c.insert:"").join(""),n=t.map(c=>c.text).join("");let o=0;for(const[c,l]of e===n?[]:qo(e,n).diffs)c===-1?r.delete(o,l.length):(c===1&&kt(r,o,l),o+=l.length);const i=mt(r);let s=0,a=0;o=0;for(const c of i){if(typeof c.insert!="string")continue;let l=c.insert.length;for(;l>0;){for(;s<t.length&&a===t[s].text.length;)s++,a=0;const d=t[s],u=Math.min(l,d.text.length-a),g=d.marks??{},p=c.attributes??{},h={};for(const f of new Set([...Object.keys(g),...Object.keys(p)])){const m=g[f];JSON.stringify(m)!==JSON.stringify(p[f])&&(h[f]=m??null)}Object.keys(h).length&&It(r,o,u,h),o+=u,a+=u,l-=u}}}function Wi(r,t){const e=r.toArray().filter(l=>l instanceof x.XmlElement),n=e.map(l=>String(l.getAttribute("id"))),o=t.children.map(l=>l.id),i=new Map;let s=0,a=0;for(const l of Bi(n,o)){for(;n[s]!==l;)s++;for(;o[a]!==l;)a++;i.set(a++,e[s++])}const c=new Set(i.values());yo(r,t);for(let l=r.length-1;l>=0;l--){const d=r.get(l);(!(d instanceof x.XmlElement)||!c.has(d))&&r.delete(l,1)}t.children.forEach((l,d)=>{const u=i.get(d);if(!u){r.insert(d,[Ut(l)]);return}yo(u,l);const g=u.toArray().find(h=>h instanceof x.XmlText);g&&Kp(g,l.children);const p=l.children.every(h=>h.text.length===0)?l.children.find(h=>h.marks&&Object.keys(h.marks).length)?.marks:void 0;if(p){const h=JSON.stringify(p);bt(u,"_emptyTextMarks")!==h&&u.setAttribute("_emptyTextMarks",h)}else rt(u,"_emptyTextMarks")})}const Vp=300;function Gp(r){return Array.from(r).slice(0,Vp).join("")}function Zp(r){return r.children.every(t=>t.type==="paragraph"&&t.children.every(e=>e.type==="text"&&e.text.trim().length===0))}class Ji extends Error{constructor(t,e,n){super(n instanceof Error?n.message:String(n)),this.actionIndex=t,this.action=e,this.originalError=n,this.name="PreprocessActionError"}}class ir{constructor(){this.afterIdChain=new Map,this.currentTurnId=""}startNewTurn(){const t="turn_"+Date.now();this.afterIdChain.clear(),this.currentTurnId=t}getChainedAfterId(t){return t?this.afterIdChain.get(t)||t:null}updateChain(t,e){this.afterIdChain.set(t,e)}hasChain(t){return this.afterIdChain.has(t)}getCurrentTurnId(){return this.currentTurnId}reset(){this.afterIdChain.clear(),this.currentTurnId=""}}function Hc(r){return r.replace(/\s+id="[^"]*"/g,"")}function Wc(r){const t=Hc(r),e=t.match(/^<p\b([^>]*)>([\s\S]*)<\/p>$/i);return e?e[1].trim().length>0?t:e[2]:t}function Jc(r){return it.toInternalHtml({type:"doc",children:[r]})}function Qp(r,t,e,n){if(!r.actions)return r;const o=r.actions.map((l,d)=>{const u=y=>{throw new Ji(d,l,new Error(y))};if(l.name==="replace_block"&&(typeof l.arguments.id!="string"||!l.arguments.id.trim())&&u('replace_block id is required. Read the target block and use its current ID. To write into a blank document, use insert_block with referenceId="" and position="after".'),l.name!=="insert_block")return l;const{referenceId:g,position:p}=l.arguments;if(p!=="before"&&p!=="after"&&u("insert_block position must be before or after."),typeof g=="string"&&g.trim())return l;if(!n||!Zp(n))return u("insert_block referenceId is required for a document with content. Read the target location and use a current block ID. Use an empty referenceId only for a blank document.");const h=p==="before"?n.children[0]:n.children.at(-1),f={...l,arguments:{...l.arguments,referenceId:h?.id??Rn}},m=ne(l);return m&&zt(f,m),f}),i=e||new ir;`${r.actions.length}${t}${i.getCurrentTurnId()}`;const s=[],a=n?it.createParsingContext(n):void 0,c=(l,d,u)=>{try{const g=d.name==="insert_block"?d.arguments.referenceId:d.name==="replace_block"?d.arguments.id:void 0,p=typeof g=="string"&&n?z(n,g):null,h=p?.type==="list"?p.children.find(f=>f.id===g):void 0;return it.fromAgentHtml(l,{existingDocument:n,parsingContext:a,preserveImageReferenceIds:!0,listItemBaseIndent:h?h.indentLevel??0:void 0})}catch(g){throw new Ji(u,d,g)}};for(const[l,d]of o.entries()){const u=ne(d);if(d.name==="insert_block"){const{referenceId:g,position:p,content:h}=d.arguments;let f=g;const m=p;if(p==="after"&&i.hasChain(g)){const k=i.getChainedAfterId(g);k&&(f=k)}const y=it.coalesceAdjacentBareListFragments(Array.isArray(h)?h:[h]),b=[];for(const k of y){const v=c(k,d,l);if(v.children.length!==0)if(v.children.length===1){const S=et();zt(d,{stableId:S});const I=v.children[0];let w;I.type==="list"||I.type==="table"||I.type==="page-break"||I.type,w=Hc(it.toInternalHtml(v)),b.push({content:w,id:S})}else for(let S=0;S<v.children.length;S++){const I=v.children[S],w=Jc(I);let A;I.type==="list"||I.type==="table"||I.type==="page-break"||I.type==="toc"?A=w:A=Wc(w);const _=et();b.push({content:A,id:_})}}for(let k=0;k<b.length;k++){const{content:v,id:S}=b[k],I={name:"insert_block",arguments:{}};k===0?(I.arguments.referenceId=f,I.arguments.position=m,zt(I,{stableId:b[k].id})):(I.arguments.referenceId=b[k-1].id,I.arguments.position="after"),I.arguments.content=[v],zt(I,{...u,stableId:S}),s.push(I)}if(p==="after"&&b.length>0){const k=b[b.length-1].id;i.updateChain(g,k)}}else if(d.name==="replace_block"){const{id:g,content:p,count:h}=d.arguments,f=it.coalesceAdjacentBareListFragments(Array.isArray(p)?p:[p]),m=[];for(const y of f){const b=c(y,d,l);if(b.children.length===0)m.push({content:y,id:g,type:"paragraph"});else for(const k of b.children){const v=Jc(k),S=m.length===0?g:et();m.push({content:v,id:S,type:k.type})}}if(m.length<=1){const y={...d,arguments:{...d.arguments,content:m.length>0?[m[0].content]:f}};u&&zt(y,u),s.push(y)}else{const y={name:"replace_block",arguments:{id:g,...typeof h=="number"?{count:h}:{},content:[m[0].content]}};zt(y,{...u,allowNoopContinuation:!0,splitReplacementGroup:m[0].id,multiBlockReplace:{replacementBlockIds:m.map(b=>b.id),replacedCount:typeof h=="number"?h:1}}),s.push(y);for(let b=1;b<m.length;b++){const{content:k,id:v,type:S}=m[b];let I;S==="list"||S==="table"||S==="code"||S==="page-break"||S==="toc"?I=k:I=Wc(k);const w={name:"insert_block",arguments:{referenceId:b===1?g:m[b-1].id,position:"after",content:[I]}};zt(w,{...u,stableId:v,splitReplacementGroup:m[0].id}),s.push(w)}m.length>1&&i.updateChain(g,m[m.length-1].id)}}else s.push(d)}return{...r,actions:s}}const tf=Math.floor,ef=(r,t)=>r<t?r:t,nf=(r,t)=>r>t?r:t,Yc=128,sr=127,of=Number.MAX_SAFE_INTEGER,rf=r=>{const t=unescape(encodeURIComponent(r)),e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.codePointAt(o);return n},Xn=typeof TextEncoder<"u"?new TextEncoder:null,sf=r=>Xn.encode(r),af=Xn?sf:rf;let Hn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Hn&&Hn.decode(new Uint8Array).length===1&&(Hn=null);const ar=(r,t)=>{const e=r.cbuf.length;r.cpos===e&&(r.bufs.push(r.cbuf),r.cbuf=new Uint8Array(e*2),r.cpos=0),r.cbuf[r.cpos++]=t},cr=(r,t)=>{for(;t>sr;)ar(r,Yc|sr&t),t=tf(t/128);ar(r,sr&t)},Yi=new Uint8Array(3e4),cf=Yi.length/3,lf=(r,t)=>{if(t.length<cf){const e=Xn.encodeInto(t,Yi).written||0;cr(r,e);for(let n=0;n<e;n++)ar(r,Yi[n])}else hf(r,af(t))},df=(r,t)=>{const e=unescape(encodeURIComponent(t)),n=e.length;cr(r,n);for(let o=0;o<n;o++)ar(r,e.codePointAt(o))},uf=Xn&&Xn.encodeInto?lf:df,gf=(r,t)=>{const e=r.cbuf.length,n=r.cpos,o=ef(e-n,t.length),i=t.length-o;r.cbuf.set(t.subarray(0,o),n),r.cpos+=o,i>0&&(r.bufs.push(r.cbuf),r.cbuf=new Uint8Array(nf(e*2,i)),r.cbuf.set(t.subarray(o)),r.cpos=i)},hf=(r,t)=>{cr(r,t.byteLength),gf(r,t)},Kc=r=>new Error(r),pf=Kc("Unexpected end of array"),ff=Kc("Integer out of Range"),mf=(r,t)=>{const e=new Uint8Array(r.arr.buffer,r.pos+r.arr.byteOffset,t);return r.pos+=t,e},bf=r=>mf(r,Ki(r)),Vc=r=>r.arr[r.pos++],Ki=r=>{let t=0,e=1;const n=r.arr.length;for(;r.pos<n;){const o=r.arr[r.pos++];if(t=t+(o&sr)*e,e*=128,o<Yc)return t;if(t>of)throw ff}throw pf},yf=r=>{let t=Ki(r);if(t===0)return"";{let e=String.fromCodePoint(Vc(r));if(--t<100)for(;t--;)e+=String.fromCodePoint(Vc(r));else for(;t>0;){const n=t<1e4?t:1e4,o=r.arr.subarray(r.pos,r.pos+n);r.pos+=n,e+=String.fromCodePoint.apply(null,o),t-=n}return decodeURIComponent(escape(e))}},kf=r=>Hn.decode(bf(r)),Gc=Hn?kf:yf;var Wn;(function(r){r[r.Token=0]="Token",r[r.PermissionDenied=1]="PermissionDenied",r[r.Authenticated=2]="Authenticated"})(Wn||(Wn={}));const Sf=(r,t)=>{cr(r,Wn.Token),uf(r,t)},If=(r,t,e)=>{switch(Ki(r)){case Wn.PermissionDenied:{t(Gc(r));break}case Wn.Authenticated:{e(Gc(r));break}}},Zc=r=>Array.from(r.entries()).map(([t,e])=>({clientId:t,...e}));var Vi;(function(r){r[r.Connecting=0]="Connecting",r[r.Open=1]="Open",r[r.Closing=2]="Closing",r[r.Closed=3]="Closed"})(Vi||(Vi={}));function vf(r){return r||(r={}),{delay:r.delay===void 0?200:r.delay,initialDelay:r.initialDelay===void 0?0:r.initialDelay,minDelay:r.minDelay===void 0?0:r.minDelay,maxDelay:r.maxDelay===void 0?0:r.maxDelay,factor:r.factor===void 0?0:r.factor,maxAttempts:r.maxAttempts===void 0?3:r.maxAttempts,timeout:r.timeout===void 0?0:r.timeout,jitter:r.jitter===!0,initialJitter:r.initialJitter===!0,handleError:r.handleError===void 0?null:r.handleError,handleTimeout:r.handleTimeout===void 0?null:r.handleTimeout,beforeAttempt:r.beforeAttempt===void 0?null:r.beforeAttempt,calculateDelay:r.calculateDelay===void 0?null:r.calculateDelay}}async function Gi(r){return new Promise(t=>setTimeout(t,r))}function xf(r,t){let e=t.delay;if(e===0)return 0;if(t.factor&&(e*=Math.pow(t.factor,r.attemptNum-1),t.maxDelay!==0&&(e=Math.min(e,t.maxDelay))),t.jitter){const n=Math.ceil(t.minDelay),o=Math.floor(e);e=Math.floor(Math.random()*(o-n+1))+n}return Math.round(e)}async function wf(r,t){const e=vf(t);for(const a of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const c=e[a];if(!Number.isInteger(c)||c<0)throw new Error(`Value for ${a} must be an integer greater than or equal to 0`)}if(e.factor.constructor!==Number||e.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(e.delay<e.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${e.delay}, minDelay: ${e.minDelay}`);const n={attemptNum:0,attemptsRemaining:e.maxAttempts?e.maxAttempts:-1,aborted:!1,abort(){n.aborted=!0}},o=e.calculateDelay||xf;async function i(){if(e.beforeAttempt&&e.beforeAttempt(n,e),n.aborted){const c=new Error("Attempt aborted");throw c.code="ATTEMPT_ABORTED",c}const a=async c=>{if(e.handleError&&await e.handleError(c,n,e),n.aborted||n.attemptsRemaining===0)throw c;n.attemptNum++;const l=o(n,e);return l&&await Gi(l),i()};return n.attemptsRemaining>0&&n.attemptsRemaining--,e.timeout?new Promise((c,l)=>{const d=setTimeout(()=>{if(e.handleTimeout)try{c(e.handleTimeout(n,e))}catch(u){l(u)}else{const u=new Error(`Retry timeout (attemptNum: ${n.attemptNum}, timeout: ${e.timeout})`);u.code="ATTEMPT_TIMEOUT",l(u)}},e.timeout);r(n,e).then(u=>{clearTimeout(d),c(u)}).catch(u=>{clearTimeout(d),a(u).then(c).catch(l)})}):r(n,e).catch(a)}const s=e.calculateDelay?e.calculateDelay(n,e):e.initialDelay;if(s&&await Gi(s),n.attemptNum<1&&e.initialJitter){const a=o(n,e);a&&await Gi(a)}return i()}const Qc=Math.floor,Af=(r,t)=>r<t?r:t,Tf=(r,t)=>r>t?r:t,Cf=64,lr=128,Pf=63,Jn=127,tl=Number.MAX_SAFE_INTEGER,Mf=()=>new Set,$f=Array.from,Bf=r=>{const t=unescape(encodeURIComponent(r)),e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.codePointAt(o);return n},Yn=typeof TextEncoder<"u"?new TextEncoder:null,_f=r=>Yn.encode(r),Lf=Yn?_f:Bf;let Kn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Kn&&Kn.decode(new Uint8Array).length===1&&(Kn=null);class Nf{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Zi=()=>new Nf,el=r=>{let t=r.cpos;for(let e=0;e<r.bufs.length;e++)t+=r.bufs[e].length;return t},Qi=r=>{const t=new Uint8Array(el(r));let e=0;for(let n=0;n<r.bufs.length;n++){const o=r.bufs[n];t.set(o,e),e+=o.length}return t.set(new Uint8Array(r.cbuf.buffer,0,r.cpos),e),t},dr=(r,t)=>{const e=r.cbuf.length;r.cpos===e&&(r.bufs.push(r.cbuf),r.cbuf=new Uint8Array(e*2),r.cpos=0),r.cbuf[r.cpos++]=t},Yt=(r,t)=>{for(;t>Jn;)dr(r,lr|Jn&t),t=Qc(t/128);dr(r,Jn&t)},ts=new Uint8Array(3e4),Ff=ts.length/3,Ef=(r,t)=>{if(t.length<Ff){const e=Yn.encodeInto(t,ts).written||0;Yt(r,e);for(let n=0;n<e;n++)dr(r,ts[n])}else In(r,Lf(t))},Rf=(r,t)=>{const e=unescape(encodeURIComponent(t)),n=e.length;Yt(r,n);for(let o=0;o<n;o++)dr(r,e.codePointAt(o))},Ce=Yn&&Yn.encodeInto?Ef:Rf,Df=(r,t)=>{const e=r.cbuf.length,n=r.cpos,o=Af(e-n,t.length),i=t.length-o;r.cbuf.set(t.subarray(0,o),n),r.cpos+=o,i>0&&(r.bufs.push(r.cbuf),r.cbuf=new Uint8Array(Tf(e*2,i)),r.cbuf.set(t.subarray(o)),r.cpos=i)},In=(r,t)=>{Yt(r,t.byteLength),Df(r,t)},nl=r=>new Error(r),ol=nl("Unexpected end of array"),rl=nl("Integer out of Range");class Of{constructor(t){this.arr=t,this.pos=0}}const il=r=>new Of(r),jf=(r,t)=>{const e=new Uint8Array(r.arr.buffer,r.pos+r.arr.byteOffset,t);return r.pos+=t,e},ur=r=>jf(r,en(r)),sl=r=>r.arr[r.pos++],en=r=>{let t=0,e=1;const n=r.arr.length;for(;r.pos<n;){const o=r.arr[r.pos++];if(t=t+(o&Jn)*e,e*=128,o<lr)return t;if(t>tl)throw rl}throw ol},Uf=r=>{let t=r.arr[r.pos++],e=t&Pf,n=64;const o=(t&Cf)>0?-1:1;if((t&lr)===0)return o*e;const i=r.arr.length;for(;r.pos<i;){if(t=r.arr[r.pos++],e=e+(t&Jn)*n,n*=128,t<lr)return o*e;if(e>tl)throw rl}throw ol},qf=r=>{let t=en(r);if(t===0)return"";{let e=String.fromCodePoint(sl(r));if(--t<100)for(;t--;)e+=String.fromCodePoint(sl(r));else for(;t>0;){const n=t<1e4?t:1e4,o=r.arr.subarray(r.pos,r.pos+n);r.pos+=n,e+=String.fromCodePoint.apply(null,o),t-=n}return decodeURIComponent(escape(e))}},zf=r=>Kn.decode(ur(r)),Vn=Kn?zf:qf,Xf=r=>{const t=r.pos,e=Vn(r);return r.pos=t,e},vn=Date.now,es=()=>new Map,Hf=(r,t,e)=>{let n=r.get(t);return n===void 0&&r.set(t,n=e()),n};class Wf{constructor(){this._observers=es()}on(t,e){Hf(this._observers,t,Mf).add(e)}once(t,e){const n=(...o)=>{this.off(t,n),e(...o)};this.on(t,n)}off(t,e){const n=this._observers.get(t);n!==void 0&&(n.delete(e),n.size===0&&this._observers.delete(t))}emit(t,e){return $f((this._observers.get(t)||es()).values()).forEach(n=>n(...e))}destroy(){this._observers=es()}}const Jf=Object.keys,al=r=>Jf(r).length,Yf=(r,t)=>Object.prototype.hasOwnProperty.call(r,t),Kf=(r,t)=>r===t,Gn=(r,t)=>{if(r==null||t==null)return Kf(r,t);if(r.constructor!==t.constructor)return!1;if(r===t)return!0;switch(r.constructor){case ArrayBuffer:r=new Uint8Array(r),t=new Uint8Array(t);case Uint8Array:{if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==t[e])return!1;break}case Set:{if(r.size!==t.size)return!1;for(const e of r)if(!t.has(e))return!1;break}case Map:{if(r.size!==t.size)return!1;for(const e of r.keys())if(!t.has(e)||!Gn(r.get(e),t.get(e)))return!1;break}case Object:if(al(r)!==al(t))return!1;for(const e in r)if(!Yf(r,e)||!Gn(r[e],t[e]))return!1;break;case Array:if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(!Gn(r[e],t[e]))return!1;break;default:return!1}return!0},ns=3e4;class Vf extends Wf{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=vn();this.getLocalState()!==null&&ns/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const n=[];this.meta.forEach((o,i)=>{i!==this.clientID&&ns<=e-o.lastUpdated&&this.states.has(i)&&n.push(i)}),n.length>0&&gr(this,n,"timeout")},Qc(ns/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const e=this.clientID,n=this.meta.get(e),o=n===void 0?0:n.clock+1,i=this.states.get(e);t===null?this.states.delete(e):this.states.set(e,t),this.meta.set(e,{clock:o,lastUpdated:vn()});const s=[],a=[],c=[],l=[];t===null?l.push(e):i==null?t!=null&&s.push(e):(a.push(e),Gn(i,t)||c.push(e)),(s.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:s,updated:c,removed:l},"local"]),this.emit("update",[{added:s,updated:a,removed:l},"local"])}setLocalStateField(t,e){const n=this.getLocalState();n!==null&&this.setLocalState({...n,[t]:e})}getStates(){return this.states}}const gr=(r,t,e)=>{const n=[];for(let o=0;o<t.length;o++){const i=t[o];if(r.states.has(i)){if(r.states.delete(i),i===r.clientID){const s=r.meta.get(i);r.meta.set(i,{clock:s.clock+1,lastUpdated:vn()})}n.push(i)}}n.length>0&&(r.emit("change",[{added:[],updated:[],removed:n},e]),r.emit("update",[{added:[],updated:[],removed:n},e]))},os=(r,t,e=r.states)=>{const n=t.length,o=Zi();Yt(o,n);for(let i=0;i<n;i++){const s=t[i],a=e.get(s)||null,c=r.meta.get(s).clock;Yt(o,s),Yt(o,c),Ce(o,JSON.stringify(a))}return Qi(o)},Gf=(r,t,e)=>{const n=il(t),o=vn(),i=[],s=[],a=[],c=[],l=en(n);for(let d=0;d<l;d++){const u=en(n);let g=en(n);const p=JSON.parse(Vn(n)),h=r.meta.get(u),f=r.states.get(u),m=h===void 0?0:h.clock;(m<g||m===g&&p===null&&r.states.has(u))&&(p===null?u===r.clientID&&r.getLocalState()!=null?g++:r.states.delete(u):r.states.set(u,p),r.meta.set(u,{clock:g,lastUpdated:o}),h===void 0&&p!==null?i.push(u):h!==void 0&&p===null?c.push(u):p!==null&&(Gn(p,f)||a.push(u),s.push(u)))}(i.length>0||a.length>0||c.length>0)&&r.emit("change",[{added:i,updated:a,removed:c},e]),(i.length>0||s.length>0||c.length>0)&&r.emit("update",[{added:i,updated:s,removed:c},e])};class cl{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(o=>o.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(o=>o!==e):delete this.callbacks[t]),this}removeAllListeners(){this.callbacks={}}}class rs{constructor(t){this.data=t,this.encoder=Zi(),this.decoder=il(new Uint8Array(this.data))}peekVarString(){return Xf(this.decoder)}readVarUint(){return en(this.decoder)}readVarString(){return Vn(this.decoder)}readVarUint8Array(){return ur(this.decoder)}writeVarUint(t){return Yt(this.encoder,t)}writeVarString(t){return Ce(this.encoder,t)}writeVarUint8Array(t){return In(this.encoder,t)}length(){return el(this.encoder)}}var Xt;(function(r){r[r.Sync=0]="Sync",r[r.Awareness=1]="Awareness",r[r.Auth=2]="Auth",r[r.QueryAwareness=3]="QueryAwareness",r[r.Stateless=5]="Stateless",r[r.CLOSE=7]="CLOSE",r[r.SyncStatus=8]="SyncStatus"})(Xt||(Xt={}));var re;(function(r){r.Connecting="connecting",r.Connected="connected",r.Disconnected="disconnected"})(re||(re={}));class nn{constructor(){this.encoder=Zi()}get(t){return t.encoder}toUint8Array(){return Qi(this.encoder)}}class Zf extends nn{constructor(){super(...arguments),this.type=Xt.CLOSE,this.description="Ask the server to close the connection"}get(t){return Ce(this.encoder,t.documentName),Yt(this.encoder,this.type),this.encoder}}class Qf extends cl{constructor(t){super(),this.messageQueue=[],this.configuration={url:"",document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=re.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(t),this.configuration.WebSocketPolyfill=t.WebSocketPolyfill?t.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(t){this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=t}attach(t){this.configuration.providerMap.set(t.configuration.name,t),this.status===re.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===re.Connected&&t.onOpen(this.receivedOnOpenPayload)}detach(t){this.configuration.providerMap.has(t.configuration.name)&&(t.send(Zf,{documentName:t.configuration.name}),this.configuration.providerMap.delete(t.configuration.name))}setConfiguration(t={}){this.configuration={...this.configuration,...t}}async connect(){if(this.status===re.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const t=()=>{let o=!1;return{retryPromise:wf(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,beforeAttempt:i=>{(!this.shouldConnect||o)&&i.abort()}}).catch(i=>{if(i&&i.code!=="ATTEMPT_ABORTED")throw i}),cancelFunc:()=>{o=!0}}},{retryPromise:e,cancelFunc:n}=t();return this.cancelWebsocketRetry=n,e}attachWebSocketListeners(t,e){const{identifier:n}=t,o=l=>this.emit("message",l),i=l=>this.emit("close",{event:l}),s=l=>this.emit("open",l),a=l=>{e(l)};this.webSocketHandlers[n]={message:o,close:i,open:s,error:a};const c=this.webSocketHandlers[t.identifier];Object.keys(c).forEach(l=>{t.addEventListener(l,c[l])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:t}=this.webSocket,e=this.webSocketHandlers[t];Object.keys(e).forEach(n=>{var o;(o=this.webSocket)===null||o===void 0||o.removeEventListener(n,e[n]),delete this.webSocketHandlers[t]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((t,e)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,e),this.webSocket=n,this.status=re.Connecting,this.emit("status",{status:re.Connecting}),this.connectionAttempt={resolve:t,reject:e}})}onMessage(t){var e;this.resolveConnectionAttempt(),this.lastMessageReceived=vn();const n=new rs(t.data).peekVarString();(e=this.configuration.providerMap.get(n))===null||e===void 0||e.onMessage(t)}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=re.Connected,this.emit("status",{status:re.Connected}),this.emit("connect"),this.messageQueue.forEach(t=>this.send(t)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){var t;(t=this.connectionAttempt)===null||t===void 0||t.reject(),this.connectionAttempt=null}checkConnection(){var t;this.status===re.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=vn()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):((t=this.webSocket)===null||t===void 0||t.close(),this.messageQueue=[])))}get serverUrl(){for(;this.configuration.url[this.configuration.url.length-1]==="/";)return this.configuration.url.slice(0,this.configuration.url.length-1);return this.configuration.url}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,this.webSocket!==null)try{this.webSocket.close(),this.messageQueue=[]}catch(t){console.error(t)}}send(t){var e;((e=this.webSocket)===null||e===void 0?void 0:e.readyState)===Vi.Open?this.webSocket.send(t):this.messageQueue.push(t)}onClose({event:t}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=re.Disconnected,this.emit("status",{status:re.Disconnected}),this.emit("disconnect",{event:t}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}}const ll=0,is=1,dl=2,tm=(r,t)=>{Yt(r,ll);const e=x.encodeStateVector(t);In(r,e)},em=(r,t,e)=>{Yt(r,is),In(r,x.encodeStateAsUpdate(t,e))},nm=(r,t,e)=>em(t,e,ur(r)),ul=(r,t,e)=>{try{x.applyUpdate(t,ur(r),e)}catch(n){console.error("Caught error while handling a Yjs update",n)}},om=(r,t)=>{Yt(r,dl),In(r,t)},rm=ul,im=(r,t,e,n)=>{const o=en(r);switch(o){case ll:nm(r,t,e);break;case is:ul(r,e,n);break;case dl:rm(r,e,n);break;default:throw new Error("Unknown message type")}return o};class sm{constructor(t){this.message=t}apply(t,e){const{message:n}=this,o=n.readVarUint(),i=n.length();switch(o){case Xt.Sync:this.applySyncMessage(t,e);break;case Xt.Awareness:this.applyAwarenessMessage(t);break;case Xt.Auth:this.applyAuthMessage(t);break;case Xt.QueryAwareness:this.applyQueryAwarenessMessage(t);break;case Xt.Stateless:t.receiveStateless(Vn(n.decoder));break;case Xt.SyncStatus:this.applySyncStatusMessage(t,Uf(n.decoder)===1);break;case Xt.CLOSE:const s={code:1e3,reason:Vn(n.decoder),target:t.configuration.websocketProvider.webSocket,type:"close"};t.onClose(),t.configuration.onClose({event:s}),t.forwardClose(s);break;default:throw new Error(`Can’t apply message of unknown type: ${o}`)}n.length()>i+1&&t.send(nn,{encoder:n.encoder})}applySyncMessage(t,e){const{message:n}=this;n.writeVarUint(Xt.Sync);const o=im(n.decoder,n.encoder,t.document,t);e&&o===is&&(t.synced=!0)}applySyncStatusMessage(t,e){e&&t.decrementUnsyncedChanges()}applyAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;Gf(t.awareness,e.readVarUint8Array(),t)}applyAuthMessage(t){const{message:e}=this;If(e.decoder,t.permissionDeniedHandler.bind(t),t.authenticatedHandler.bind(t))}applyQueryAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;e.writeVarUint(Xt.Awareness),e.writeVarUint8Array(os(t.awareness,Array.from(t.awareness.getStates().keys())))}}class am{constructor(t,e={}){this.message=new t,this.encoder=this.message.get(e)}create(){return Qi(this.encoder)}send(t){t?.send(this.create())}}class cm extends nn{constructor(){super(...arguments),this.type=Xt.Auth,this.description="Authentication"}get(t){if(typeof t.token>"u")throw new Error("The authentication message requires `token` as an argument.");return Ce(this.encoder,t.documentName),Yt(this.encoder,this.type),Sf(this.encoder,t.token),this.encoder}}class gl extends nn{constructor(){super(...arguments),this.type=Xt.Awareness,this.description="Awareness states update"}get(t){if(typeof t.awareness>"u")throw new Error("The awareness message requires awareness as an argument");if(typeof t.clients>"u")throw new Error("The awareness message requires clients as an argument");Ce(this.encoder,t.documentName),Yt(this.encoder,this.type);let e;return t.states===void 0?e=os(t.awareness,t.clients):e=os(t.awareness,t.clients,t.states),In(this.encoder,e),this.encoder}}class lm extends nn{constructor(){super(...arguments),this.type=Xt.Stateless,this.description="A stateless message"}get(t){var e;return Ce(this.encoder,t.documentName),Yt(this.encoder,this.type),Ce(this.encoder,(e=t.payload)!==null&&e!==void 0?e:""),this.encoder}}class hl extends nn{constructor(){super(...arguments),this.type=Xt.Sync,this.description="First sync step"}get(t){if(typeof t.document>"u")throw new Error("The sync step one message requires document as an argument");return Ce(this.encoder,t.documentName),Yt(this.encoder,this.type),tm(this.encoder,t.document),this.encoder}}class dm extends nn{constructor(){super(...arguments),this.type=Xt.Sync,this.description="A document update"}get(t){return Ce(this.encoder,t.documentName),Yt(this.encoder,this.type),om(this.encoder,t.update),this.encoder}}class um extends Error{constructor(){super(...arguments),this.code=1001}}class gm extends cl{constructor(t){var e,n,o;super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,forceSyncInterval:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=i=>this.emit("connect",i),this.forwardClose=i=>this.emit("close",i),this.forwardDisconnect=i=>this.emit("disconnect",i),this.forwardDestroy=i=>this.emit("destroy",i),this.setConfiguration(t),this.configuration.document=t.document?t.document:new x.Doc,this.configuration.awareness=t.awareness!==void 0?t.awareness:new Vf(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),(e=this.awareness)===null||e===void 0||e.on("update",()=>{this.emit("awarenessUpdate",{states:Zc(this.awareness.getStates())})}),(n=this.awareness)===null||n===void 0||n.on("change",()=>{this.emit("awarenessChange",{states:Zc(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),(o=this.awareness)===null||o===void 0||o.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&typeof this.configuration.forceSyncInterval=="number"&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(t={}){if(!t.websocketProvider){const e=t;this.manageSocket=!0,this.configuration.websocketProvider=new Qf({url:e.url})}this.configuration={...this.configuration,...t}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),this.unsyncedChanges===0&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(hl,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&gr(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){typeof window>"u"||!("addEventListener"in window)||window.addEventListener("pagehide",this.boundPageHide)}sendStateless(t){this.send(lm,{documentName:this.configuration.name,payload:t})}documentUpdateHandler(t,e){e!==this&&(this.incrementUnsyncedChanges(),this.send(dm,{update:t,documentName:this.configuration.name}))}awarenessUpdateHandler({added:t,updated:e,removed:n},o){const i=t.concat(e).concat(n);this.send(gl,{awareness:this.awareness,clients:i,documentName:this.configuration.name})}get synced(){return this.isSynced}set synced(t){this.isSynced!==t&&(this.isSynced=t,t&&this.emit("synced",{state:t}))}receiveStateless(t){this.emit("stateless",{payload:t})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect();console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}async onOpen(t){this.isAuthenticated=!1,this.emit("open",{event:t});let e;try{e=await this.getToken()}catch(n){this.permissionDeniedHandler(`Failed to get token: ${n}`);return}this.send(cm,{token:e??"",documentName:this.configuration.name}),this.startSync()}async getToken(){return typeof this.configuration.token=="function"?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(hl,{document:this.document,documentName:this.configuration.name}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(gl,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(t,e){if(!this._isAttached)return;const n=new am(t,e);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(t){const e=new rs(t.data),n=e.readVarString();e.writeVarString(n),this.emit("message",{event:t,message:new rs(t.data)}),new sm(e).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&gr(this.awareness,Array.from(this.awareness.getStates().keys()).filter(t=>t!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(gr(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),!(typeof window>"u"||!("removeEventListener"in window))&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(t){this.emit("authenticationFailed",{reason:t}),this.isAuthenticated=!1}authenticatedHandler(t){this.isAuthenticated=!0,this.authorizedScope=t,this.emit("authenticated",{scope:t})}setAwarenessField(t,e){if(!this.awareness)throw new um(`Cannot set awareness field "${t}" to ${JSON.stringify(e)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(t,e)}}const hm=10,hr=(r,t,e)=>Math.max(t,Math.min(e,r));function pr(r){const t={};for(const[e,n]of Object.entries(r??{}))Ai.has(e)&&e!=="aiGenerated"&&e!=="__htmlClassName"||n==null||(t[e]=n);return JSON.stringify(t)}function fr(r){if(typeof r!="string"||r.length===0)return null;try{const t=JSON.parse(r);return t&&typeof t=="object"&&typeof t.id=="string"?t:null}catch{return null}}function ss(r){if(typeof r!="string"||r.length===0)return null;try{const t=JSON.parse(r);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function pm(r,t){if(!r)return;const e={},n=!!r.footnoteRef;for(const[o,i]of Object.entries(r))i===void 0||i===!1||i===null||Ai.has(o)||o!=="footnoteRef"&&(o==="superscript"&&n||(e[o]=i));return Object.keys(e).length>0?e:void 0}const pl=["spaceBefore","spaceAfter","contextualSpacing"];function Zn(r,t){t.spaceBefore!==void 0&&r.setAttribute("spaceBefore",String(t.spaceBefore)),t.spaceAfter!==void 0&&r.setAttribute("spaceAfter",String(t.spaceAfter)),t.contextualSpacing!==void 0&&r.setAttribute("contextualSpacing",String(t.contextualSpacing))}function fm(r,t,e=!1){for(const n of pl){const o=bt(r,n);o!=null?t.setAttribute(n,o):e&&rt(t,n)}}function fl(r){if(!r)return{};if(typeof r=="string")try{return JSON.parse(r)}catch{return{}}return typeof r=="object"?{...r}:{}}function ml(r){const t=fl(r.getAttribute("_emptyTextMarks"));if(Object.keys(t).length===0)return!1;for(const e of Gs)delete t[e];return Object.keys(t).length===0?r.removeAttribute("_emptyTextMarks"):r.setAttribute("_emptyTextMarks",JSON.stringify(t)),!0}function bl(r,t,e,n){const o=r.getAttribute("_emptyTextMarks"),i=o!=null,s=e==null||e===!1;if(!i&&!n&&!s)return!1;const a=fl(o),c=Object.prototype.hasOwnProperty.call(a,t);if(s){if(!c)return!1;delete a[t]}else{if(a[t]===e)return!1;a[t]=e}return Object.keys(a).length===0?r.removeAttribute("_emptyTextMarks"):r.setAttribute("_emptyTextMarks",JSON.stringify(a)),!0}function mr(r,t){t&&Object.keys(t).length>0?r.setAttribute("_emptyTextMarks",JSON.stringify(t)):r.removeAttribute("_emptyTextMarks")}function br(r){return r.children.some(t=>t.type==="text"&&t.text.length>0)}function Qn(r,t,e,n){if(!br(t))return Ue(n);if(e.offset<=0){const i=t.children.find(s=>s.type==="text"&&s.text.length>0);return Ue(i?.marks)}const o=Rs(r,e);return Ue(o?.marks)}const to=r=>r?.type==="code"||r?.type==="math",xn=r=>{if(!r||r.type!=="code")return!1;const t=r.language?.trim().toLowerCase();return t==="latex"||t==="latex-inline"},ae="Arial, sans-serif";function yl(r){if(r==null)return;const t=Number.parseFloat(r);return Number.isFinite(t)?t:void 0}function kl(r,t){for(const e of r.toArray())if(e instanceof x.XmlElement){if(e.nodeName==="paragraph"){t(e);continue}(e.nodeName==="container"||e.nodeName==="table"||e.nodeName==="table-row"||e.nodeName==="table-cell")&&kl(e,t)}}const Sl=r=>r.name==="set_title"||r.name==="set_notes"||r.name==="set_page_layout"||r.name==="set_header_footer",mm=r=>`${r} ${r===1?"proposal":"proposals"}`;function ce(r){if(!r||typeof r!="object")return"";if(r.type==="text"&&typeof r.text=="string")return r.text;if((r.type==="code"||r.type==="math")&&typeof r.content=="string")return r.content;if(Array.isArray(r.children)){const t=r.type==="paragraph"||r.type==="list-item"?"":" ";return r.children.map(e=>ce(e)).filter(e=>e.length>0).join(t)}return""}function Il(r){const t=r.replace(/\s+/g," ").trim();return t.length===0?[]:t.split(" ")}function bm(r,t){if(r.length===0||t.length===0)return 0;const e=new Array(t.length+1).fill(0),n=new Array(t.length+1).fill(0);for(let o=1;o<=r.length;o++){for(let i=1;i<=t.length;i++)n[i]=r[o-1]===t[i-1]?e[i-1]+1:Math.max(e[i],n[i-1]);for(let i=0;i<=t.length;i++)e[i]=n[i],n[i]=0}return e[t.length]}function ym(r,t){const e=Il(r),n=Il(t),o=Math.max(e.length,n.length);if(o===0)return null;const i=bm(e,n),s=Math.max(0,o-i);return Math.round(s/o*100)}function km(r,t,e){const n=z(r,e),o=z(t,e);if(!n||!o)return null;const i=ce(n),s=ce(o);return ym(i,s)}function Sm(r,t,e,n,o){if(!r||!t||e.length===0)return r;const i=t.filter(u=>!Sl(u));if(i.length!==1||i[0].name!=="replace_block")return r;const s=i[0].arguments&&typeof i[0].arguments=="object"?i[0].arguments:void 0,a=typeof s?.id=="string"&&s.id.trim().length>0?s.id.trim():null;if(!a||(typeof s?.count=="number"&&Number.isFinite(s.count)?Math.max(1,Math.floor(s.count)):1)!==1)return r;const c=[mm(e.length)],l=km(n,o,a);l!==null&&c.push(`~${l}% words changed`);const d=r.trim();return d.endsWith(".")?`${d.slice(0,-1)} (${c.join("; ")}).`:`${d} (${c.join("; ")}).`}function Im(r,t,e){if(e<=0)return[];const n=we(r).get(t);if(!n)return[];const o=n.parentContainer?n.parentContainer.children:r.children,i=[];for(let s=n.indexInParent;s<o.length&&i.length<e;s+=1){const a=o[s];if(!a?.id)break;i.push(a.id)}return i}function vm(r,t){if(!t||t.length===0)return[];const e=[];for(const n of t){if(n.name!=="replace_block")continue;const o=sg(n);if(!o||o.replacementBlockIds.length<=1||o.replacedCount<=1)continue;const i=n.arguments&&typeof n.arguments=="object"?n.arguments:void 0,s=typeof i?.id=="string"&&i.id.trim().length>0?i.id.trim():null;if(!s)continue;const a=Im(r,s,o.replacedCount),c=a.length===o.replacedCount&&o.replacementBlockIds.length===o.replacedCount?o.replacedCount:1;for(let l=0;l<c;l+=1){const d=a[l],u=o.replacementBlockIds[l];!d||!u||e.push({currentBlockId:d,finalBlockId:u})}}return e}const vl=(r,t,e)=>{if(!r||!t)return;const n=r.filter(a=>!Sl(a));if(n.length!==1){if(n.length===0){const a=r.some(u=>u.name==="set_title"),c=r.some(u=>u.name==="set_notes"),l=r.some(u=>u.name==="set_page_layout");if(a&&c&&l)return"Updated title, notes, and page layout.";if(a&&c)return"Updated title and notes.";if(l&&a)return"Updated page layout and title.";if(l&&c)return"Updated page layout and notes.";if(a){const u=r.find(g=>g.name==="set_title")?.arguments?.title;return u?`Title set to "${u}".`:"Title set."}if(c)return"Notes updated.";if(l)return"Page layout updated.";const d=r.find(u=>u.name==="set_header_footer");if(d){const u=d.arguments?.side==="footer"?"Footer":"Header";return d.arguments?.clear?`${u} removed.`:`${u} updated.`}}return}const o=n[0],i=e?.[0]??[],s=a=>{if(typeof a=="string"&&a.trim().length>0)return a.trim();if(Array.isArray(a)){const c=Array.from(new Set(a.filter(l=>typeof l=="string").map(l=>l.trim()).filter(l=>l.length>0)));return c.length===0?"the target blocks":c.length===1?c[0]:`${c.length} blocks (${c.join(", ")})`}return"the target blocks"};if(o.name==="insert_block"){const a=t.filter(u=>u.name==="insert_block").map(u=>Ro(u)).filter(u=>typeof u=="string"&&u.length>0);if(a.length===0)return;const c=a.length,l=a[0],d=a[a.length-1];return c===1?`Inserted block ${l}.`:`Inserted ${c} blocks; first inserted block ID was ${l}; last inserted block ID was ${d}.`}if(o.name==="replace_block"){const a=t.find(g=>g.name==="replace_block"),c=a&&"id"in a.arguments?a.arguments.id:void 0;if(!c)return;const l=t.filter(g=>g.name==="insert_block").map(g=>Ro(g)).filter(g=>typeof g=="string"&&g.length>0),d=1+l.length,u=l.length>0?l[l.length-1]:c;return d===1?`Replaced block ${c}.`:`Inserted ${d} blocks; first inserted block ID was ${c}; last inserted block ID was ${u}.`}if(o.name==="remove_block"){const{id:a,count:c=1}=o.arguments,l=i.length>0?i.length:c;return`Removed ${l} ${l===1?"block":"blocks"} starting at block ID ${a}.`}if(o.name==="set_block_attribute"){const{id:a,attribute:c,operation:l="set"}=o.arguments,d=s(a);return l==="toggle"?`Toggled ${c} on ${d}.`:l==="remove"?`Removed ${c} from ${d}.`:`Updated ${c} on ${d}.`}if(o.name==="clear_formatting"){const{id:a}=o.arguments;return`Cleared removable formatting on ${s(a)}. Font family, font size, text color, and paragraph attributes were intentionally preserved.`}if(o.name==="replace"||o.name==="replace_all"){const{id:a}=o.arguments,c=i.length>0?i.length:1;return`Replaced ${c} ${c===1?"occurrence":"occurrences"} in block ${a}.`}if(o.name==="append_to_paragraph"){const{id:a}=o.arguments,c=i.map(l=>l.text?.length??0).reduce((l,d)=>l+d,0);return c>0?`Appended ${c} characters to block ${a}.`:`Appended content to block ${a}.`}if(o.name==="break_paragraph"){const{id:a}=o.arguments,c=i.find(l=>l.kind==="insert"&&l.paragraphId!==a);return c?.paragraphId?`Split block ${a}; new block ID ${c.paragraphId}.`:`Split block ${a}.`}if(o.name==="join_paragraphs"){const{firstId:a,secondId:c}=o.arguments;return`Joined adjacent blocks ${a} and ${c}; preserved block ${a}.`}if(o.name==="insert_table_row"){const{tableId:a,referenceIndex:c,referenceRowId:l,position:d}=o.arguments,u=i.find(g=>g.kind==="insert"&&g.paragraphId===a);return u?.text?`${u.text} in table ${a}.`:`Inserted 1 row ${d} row ${l??c} in table ${a}.`}if(o.name==="remove_table_row"){const{tableId:a,rowIndex:c}=o.arguments;return`Removed row ${c} from table ${a}.`}if(o.name==="insert_table_column"){const{tableId:a,referenceIndex:c,position:l}=o.arguments;return`Inserted 1 column ${l} column ${c} in table ${a}.`}if(o.name==="remove_table_column"){const{tableId:a,columnIndex:c}=o.arguments;return`Removed column ${c} from table ${a}.`}},xl=class sn{constructor(t,e=()=>{},n,o,i,s,a,c){this.cachedDoc=null,this.incrementalRefreshPending=!1,this.derivedDocumentRevision=0,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache=new Map,this.inlineSuggestionMetadataCache=new Map,this.inlineSuggestionKindCache=new Map,this.canResolveLiveSuggestionCache=new Map,this.liveSuggestionProjectionCache=new Map,this.suggestionIdsByBlockCache=new WeakMap,this.documentSuggestionIdsCache=null,this.afterOperationSelection=null,this.beforeOperationSelection=null,this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null,this.origin="local-user",this.trackedUndoOrigins=new Set([null,"local-user"]),this.remoteOrigins=new Set,this.isRedoing=!1,this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.rebuiltMigrationSnapshotConversations=new Set,this.listStartNumberCache=new Map,this.batchingUpdates=!1,this.pendingUpdate=null,this.disposed=!1,this.handleYDocUpdate=(f,m,y,b)=>{if(this.disposed)return;m!==_s&&m!==kc&&this.canRepairIdentity()&&(this.classifyTransactionOrigin(m)==="local"?this.repairDocumentIdentity(b,m):this.scheduleDeferredIdentityRepair());const k=this.ydoc.share.get("agent-presence"),v=k&&b.changedParentTypes.size>0&&[...b.changedParentTypes.keys()].every(I=>I===k),S=this.classifyTransactionOrigin(m);v||(this.invalidateDerivedDocumentState(),this.cachedDoc=null,this.incrementalRefreshPending=!0),this.batchingUpdates?this.pendingUpdate=()=>this.onDocumentChange(this.getDocument(),{origin:S}):this.onDocumentChange(this.getDocument(),{origin:S})},this.suggestingMode=!1,this.liveSuggestionMetadataContext=null,this.defaultHumanAuthorName=null,this.liveSuggestionTreeRecordCache=new Map,this.lastPrunedUnresolvableLiveSuggestions=[],this.listOperations=new Yp(this),this.suggestionEngine=new lo(this),this.cachedKernel=null,this.strandedObservers=!1,this.strandedCheck=null,this.identityRepairedOnConstruct=!1,this.deferredIdentityRepair=null,this.ydoc=o||$n(t),yc(this.ydoc,wi),this.canRepairIdentity=c?.canRepairIdentity??(()=>!0),!c?.deferIdentityRepair&&this.canRepairIdentity()&&this.repairDocumentIdentity()&&(this.identityRepairedOnConstruct=!0,t=Tt(this.ydoc)),this.documentId=i||"default",this.onDocumentChange=e,this.onTitleChange=n,this.detachedSuggestionStore=new Li(this.ydoc,this.documentId,s),this.toolCallHistory=new Ec,this.preprocessorSession=a||new ir,this.ensureParagraphIndentStorageUsesUnits(),this.cachedDoc=t,Mo(this.ydoc,t),this.documentSuggestionIdsCache=this.suggestionEngine.createDocumentSuggestionIdsCache(t);const l=this.ydoc.getXmlFragment("content"),d=this.ydoc.getXmlFragment("chrome"),u=this.ydoc.getXmlFragment("notes"),g=this.ydoc.getArray("annotations"),p=this.suggestionEngine.getLiveSuggestionStore(),h=this.ydoc.getMap("comments");this.undoManager=new x.UndoManager([l,d,u,g,p,h],{captureTimeout:1e3,trackedOrigins:this.trackedUndoOrigins}),this.ydoc.on("update",this.handleYDocUpdate),this.undoManager.on("stack-item-added",f=>{this.isRedoing?(this.currentSelectionBeforeRedo&&f.stackItem.meta.set("beforeSelection",this.currentSelectionBeforeRedo),this.afterSelectionForRedo&&f.stackItem.meta.set("afterSelection",this.afterSelectionForRedo),this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.isRedoing=!1):(this.beforeOperationRelativeSelection?f.stackItem.meta.set("beforeSelection",this.beforeOperationRelativeSelection):this.beforeOperationSelection&&f.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection),this.afterOperationRelativeSelection&&f.stackItem.meta.set("afterSelection",this.afterOperationRelativeSelection),this.beforeOperationSelection&&f.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection)),this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null}),this.undoManager.on("stack-item-popped",f=>{if(f.type==="undo"){const m=this.undoManager.redoStack;if(m.length>0&&f.stackItem.meta.size>0){const y=m[m.length-1];f.stackItem.meta.forEach((b,k)=>{y.meta.set(k,b)})}}})}invalidateDerivedDocumentState(){this.derivedDocumentRevision+=1,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache.clear(),this.inlineSuggestionMetadataCache.clear(),this.inlineSuggestionKindCache.clear(),this.canResolveLiveSuggestionCache.clear();for(const t of this.liveSuggestionProjectionCache.values())t.projection.ydoc.destroy();this.liveSuggestionProjectionCache.clear(),this.documentSuggestionIdsCache=null,this.liveSuggestionTreeRecordCache.clear()}getTopLevelIndexFromPath(t){return!t||t.length===0?null:t.length>0?t[0]:0}getTopLevelIndexFromPosition(t){if(!t)return null;const e=this.getBlockContextById(this.getDocument(),t.block);return e?e.topLevelIndex:null}getBlockContextById(t,e){const n=z(t,e);if(!n)return null;const o=Xe(t,e);if(!o||o.length===0)return Ls(t,e)?{block:n,blockPath:[-1],topLevelIndex:-1}:null;const i=o[0];return{block:n,blockPath:o,topLevelIndex:i}}cursorAtBlock(t,e,n=this.getDocument()){const o=n.children[t];return o?.id?{block:o.id,offset:e}:null}resolveFontFamilyForList(t){for(const e of t.children)for(const n of e.children)if(n.type==="text"&&n.marks?.fontFamily)return n.marks.fontFamily}getFontAtOffsetInListItem(t,e){if(e<=0){for(const i of t.children)if(i.type==="text"&&i.marks?.fontFamily)return i.marks.fontFamily;return}let n=0,o;for(const i of t.children)if(i.type==="text"){const s=i.text.length;if(i.marks?.fontFamily&&(o=i.marks.fontFamily),n+s>=e)return i.marks?.fontFamily||o;n+=s}return o}registerTrackedUndoOrigin(t){t!==void 0&&this.trackedUndoOrigins.add(t)}registerRemoteOrigin(t){if(t==null)throw new Error("A collaboration provider must apply updates with a non-null transaction origin");this.remoteOrigins.add(t),this.trackedUndoOrigins.delete(t)}unregisterRemoteOrigin(t){this.remoteOrigins.delete(t)}classifyTransactionOrigin(t){return t===this.origin||this.trackedUndoOrigins.has(t)?"local":this.remoteOrigins.has(t)||t instanceof gm?"remote":"unknown"}runWithUndoGroup(t,e){const n=this.origin;this.registerTrackedUndoOrigin(t),this.undoManager.stopCapturing(),this.beginGroup(t),this.origin=t;try{return e()}finally{this.origin=n,this.endGroup()}}getTextMarksAtBlockOffset(t,e,n){const o=z(this.getDocument(),t);if(!o)return;const i=o.type==="paragraph"?o.children:o.type==="list"&&e!==void 0?o.children[e]?.children:void 0;if(!i)return;let s=0;for(const a of i){if(a.type!=="text")continue;const c=s+a.text.length;if(n<c||a.text.length===0&&n===s)return a.marks;s=c}return[...i].reverse().find(a=>a.type==="text")?.marks}getFormattingDescriptionFromMarkKey(t){switch(t){case"bold":return"Bold";case"italic":return"Italic";case"underline":return"Underline";case"strikethrough":return"Strikethrough";case"doubleStrikethrough":return"Double Strikethrough";case"smallCaps":return"Small Caps";case"allCaps":return"All Caps";case"letterSpacing":return"Letter Spacing";case"code":return"Code";case"latex":return"LaTeX";case"superscript":return"Superscript";case"subscript":return"Subscript";case"backgroundColor":return"Highlight";case"fontSize":return"Font Size";case"color":return"Text Color";case"fontFamily":return"Font";case"link":return"Link";default:return"Format"}}getNaturalFormatCategoryFromMarkKey(t){switch(t){case"bold":return"bold";case"italic":return"italic";case"underline":return"underline";case"strikethrough":return"strikethrough";case"doubleStrikethrough":return"double strikethrough";case"smallCaps":return"small caps";case"allCaps":return"all caps";case"letterSpacing":return"letter spacing";case"superscript":return"superscript";case"subscript":return"subscript";case"fontSize":return"font size";case"color":return"text color";case"fontFamily":return"font";case"backgroundColor":return"highlight";case"link":return"link";case"code":return"code style";case"latex":return"LaTeX";default:return"formatting"}}getNaturalFormatCategoryFromDescription(t){return t.trim().toLowerCase()||"formatting"}buildNaturalFormatChangeDescription(t){const e=t.filter((o,i)=>t.indexOf(o)===i);if(e.length===0)return"Formatting";const n=e.join(", ");return n.charAt(0).toUpperCase()+n.slice(1)}getInlineFormatDescription(t){const e=new Set,n=new Set,o=["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","letterSpacing","code","latex","superscript","subscript","fontFamily","fontSize","color","backgroundColor","link"];for(const i of t.spans){const s=this.getTextMarksAtBlockOffset(i.blockId,i.itemIndex,i.start);for(const a of o){const c=i.attributes[a],l=s?.[a];a==="fontFamily"&&(c??void 0)===void 0&&l===ae||(c??void 0)!==(l??void 0)&&(e.add(a),(l??void 0)===void 0||l===!1?n.add(a):n.delete(a))}}if(e.size>0){const i=Array.from(e).map(s=>{const a=this.getNaturalFormatCategoryFromMarkKey(s);return n.has(s)?`remove ${a}`:a});return this.buildNaturalFormatChangeDescription(i)}return t.label&&t.label!=="Format"?this.buildNaturalFormatChangeDescription([this.getNaturalFormatCategoryFromDescription(t.label)]):null}getBlockDescription(t){if(!t)return null;switch(t.type){case"image":return"Image";case"table":return"Table";case"code":return t.language==="latex"?"LaTeX Block":t.renderDiagram?"Diagram":"Code Block";case"math":return"LaTeX Block";case"page-break":return"Page Break";case"section-break":return"Section Break";case"placeholder":return"Placeholder";case"toc":return"Table of Contents";case"container":return"Container";case"paragraph":case"list":return null;default:return null}}getTableDimensionDescription(t,e,n){if(!t||t!=="Row"&&t!=="Column"||e?.type!=="table"||n?.type!=="table")return null;const o=t==="Row"?e.children.length:e.columnWidths.length,i=t==="Row"?n.children.length:n.columnWidths.length;return i>o?`Insert Table ${t}`:i<o?`Delete Table ${t}`:`Change Table ${t}`}getTextFormattingChangeKeys(t,e){const n=new Set,o=t.map(a=>a.text).join(""),i=e.map(a=>a.text).join("");if(o!==i)return[];const s=Math.max(o.length,i.length);for(let a=0;a<s;a++){const c=this.getTextMarksAtOffset(t,a),l=this.getTextMarksAtOffset(e,a);for(const d of bo)this.formattingMarkValuesEqual(c?.[d],l?.[d])||n.add(d)}if(s===0){const a=t[0]?.marks,c=e[0]?.marks;for(const l of bo)this.formattingMarkValuesEqual(a?.[l],c?.[l])||n.add(l)}return bo.filter(a=>n.has(a))}getTextMarksAtOffset(t,e){let n=0;for(const o of t){const i=n+o.text.length;if(e<i)return o.marks;n=i}return t[t.length-1]?.marks}formattingMarkValuesEqual(t,e){const n=t??void 0,o=e??void 0;return n===o?!0:typeof n=="string"&&typeof o=="string"&&/^#[0-9a-fA-F]{6}$/.test(n)&&/^#[0-9a-fA-F]{6}$/.test(o)?n.toLowerCase()===o.toLowerCase():!1}getBlockFormatDescription(t,e){const n=[],o=i=>{n.includes(i)||n.push(i)};if(t?.type==="paragraph"&&e?.type==="paragraph"&&(t.heading!==e.heading&&o("heading"),t.align!==e.align&&o("alignment"),t.lineSpacing!==e.lineSpacing&&o("line spacing"),(t.leftIndent!==e.leftIndent||t.firstLineIndent!==e.firstLineIndent)&&o("indent"),n.length===0))for(const i of this.getTextFormattingChangeKeys(t.children,e.children))o(this.getNaturalFormatCategoryFromMarkKey(i));if(t?.type==="list"&&e?.type==="list"){t.lineSpacing!==e.lineSpacing&&o("line spacing");const i=Math.max(t.children.length,e.children.length);if(n.length===0)for(let s=0;s<i;s++){const a=t.children[s],c=e.children[s];if(!(!a||!c))for(const l of this.getTextFormattingChangeKeys(a.children,c.children))o(this.getNaturalFormatCategoryFromMarkKey(l))}}return this.buildNaturalFormatChangeDescription(n)}inlineFormatRecordHasLiveMarker(t){return t.spans.some(e=>{const n=this.suggestionEngine.getYTextForSuggestionSpan(e);return n?this.collectOverlappingTextSpans(n,e.start,e.end-e.start).some(o=>o.attributes.suggestionId===t.id&&!!o.attributes.formatChange):!1})}cloneYDoc(t){const e=new x.Doc;return x.applyUpdate(e,x.encodeStateAsUpdate(t)),e}collapseAffectedBlockIds(t,e){const n=Array.from(new Set(Array.from(t).filter(d=>typeof d=="string"&&d.length>0))),o=new Set(n),i=this.getDocument(),s=we(i),a=we(e),c=new Map;for(const d of[s,a])for(const{block:u}of d.values())if(u.type==="list")for(const g of u.children)c.set(g.id,u.id);const l=(d,u)=>{let g=ke(d,u);for(;g&&g.type!=="doc";){if(g.id)return g.id;g=ke(d,g.id)}return null};return n.filter(d=>{const u=c.get(d);if(u&&o.has(u))return!1;const g=[s.get(d),a.get(d)];let p=!1;for(const f of g)if(f&&(p=!0,f.containerPath.some(m=>m!==d&&o.has(m))))return!1;if(p)return!0;let h=d;for(;h;){const f=l(i,h)??l(e,h);if(!f)break;if(o.has(f))return!1;h=f}return!0})}collectOverlappingTextSpans(t,e,n){if(n<=0)return[];const o=[],i=e+n,s=mt(t);let a=0;for(const c of s){if(typeof c.insert!="string")continue;const l=a,d=a+c.insert.length,u=Math.max(e,l),g=Math.min(i,d);if(u<g&&o.push({start:u,length:g-u,attributes:{...c.attributes||{}}}),a=d,a>=i)break}return o}normalizeAdjacentManualReplacementOrder(t,e){const n=[];let o=0;for(const h of mt(t)){if(typeof h.insert!="string"||h.insert.length===0){o+=typeof h.insert=="string"?h.insert.length:1;continue}const f=o,m=f+h.insert.length;n.push({start:f,end:m,text:h.insert,attributes:{...h.attributes||{}}}),o=m}const i=n.findIndex(h=>h.start===e&&h.attributes.deletion);if(i<=0)return null;let s=i-1;if(n[s].end!==e||!n[s].attributes.insertion)return null;for(;s>0&&n[s-1].end===n[s].start&&n[s-1].attributes.insertion;)s-=1;let a=i;for(;a+1<n.length&&n[a].end===n[a+1].start&&n[a+1].attributes.deletion;)a+=1;const c=n.slice(s,a+1);if(c.some(h=>!h.attributes.insertion&&!h.attributes.deletion))return null;const l=c.filter(h=>h.attributes.insertion),d=c.filter(h=>h.attributes.deletion);if(l.length===0||d.length===0)return null;const u=c[0].start,g=c[c.length-1].end-u;t.delete(u,g);let p=u;for(const h of[...d,...l])kt(t,p,h.text,h.attributes),p+=h.text.length;return{regionStart:u,insertionLength:l.reduce((h,f)=>h+f.text.length,0),deletionLength:d.reduce((h,f)=>h+f.text.length,0)}}static remapOffsetAcrossReplacementNormalization(t,e){const{regionStart:n,insertionLength:o,deletionLength:i}=e,s=n+o+i;return t<=n||t>s?t:t<=n+o?t+i:t-o}findSingleTableColumnDelta(t,e){if(t.children.length===0||t.children.length!==e.children.length)return null;let n=null,o=null;for(let i=0;i<t.children.length;i++){const s=t.children[i].children,a=e.children[i].children,c=a.length-s.length;if(Math.abs(c)!==1)return null;const l=c>0?"insert":"delete",d=c>0?a:s,u=c>0?s:a;let g=0;for(;g<u.length&&d[g]?.id===u[g]?.id;)g++;for(let p=g;p<u.length;p++)if(d[p+1]?.id!==u[p]?.id)return null;if(n!==null&&n!==l||o!==null&&o!==g)return null;n=l,o=g}return n!==null&&o!==null?{kind:n,index:o}:null}getTrailingCleanupParagraphIdForTopLevelBlock(t,e){const n=t.children.findIndex(i=>i.id===e);if(n===-1||n!==t.children.length-2)return;const o=t.children[n+1];if(!(!o||o.type!=="paragraph"||o.children.some(i=>i.type!=="text"||i.text.length>0)))return o.id}collectStructuralInsertBlockIds(t,e,n=[]){if("id"in t&&typeof t.id=="string"&&"structuralSuggestionKind"in t&&t.structuralSuggestionKind==="insert"&&"structuralSuggestionId"in t&&t.structuralSuggestionId===e&&n.push(t.id),t.type==="doc"&&Array.isArray(t.notes))for(const o of t.notes)this.collectStructuralInsertBlockIds(o,e,n);if(!("children"in t)||!Array.isArray(t.children))return n;for(const o of t.children)o&&typeof o=="object"&&this.collectStructuralInsertBlockIds(o,e,n);return n}replaceAnyBlockById(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();if(!z(i,t))return!1;const s=ut(this.ydoc,t);return s?(this.beforeOperationRelativeSelection=J(n,this.ydoc,i),this.transact(()=>{this.replaceBlockByIdWithoutSelection(t,e,s)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0):!1}isListItemBlockChangeRecord(t){return!!(t.beforeBlock.type==="list"&&t.listItemSuggestion)}applyListItemBlockChangeDecision(t,e,n){const o=z(this.getDocument(),t.blockId);if(!o||o.type!=="list")return!1;const i=this.suggestionEngine.cloneSuggestionSnapshot(o),s=i.children.findIndex(g=>g.structuralSuggestionId===t.id);if(s===-1)return!1;const a=this.suggestionEngine.cloneSuggestionSnapshot(i);if(a.structuralSuggestionRecord)try{JSON.parse(a.structuralSuggestionRecord).id===t.id&&delete a.structuralSuggestionRecord}catch{}const{kind:c,beforeItem:l,afterItem:d}=t.listItemSuggestion;if(c==="insert")e==="accept"?a.children[s]=this.suggestionEngine.cloneSuggestionSnapshot(d??a.children[s]):a.children.splice(s,1);else if(c==="delete")e==="accept"?a.children.splice(s,1):a.children[s]=this.suggestionEngine.cloneSuggestionSnapshot(l??a.children[s]);else{const g=e==="accept"?d??a.children[s]:l;if(!g)return!1;a.children[s]=this.suggestionEngine.cloneSuggestionSnapshot(g)}const u=this.suggestionEngine.runWithoutSuggesting(()=>this.replaceAnyBlockById(t.blockId,a,n,n));return u&&this.suggestionEngine.deleteLiveSuggestion(t.id),u}arePathsEqual(t,e){return!t||!e||t.length!==e.length?!1:t.every((n,o)=>n===e[o])}getParagraphContextForPosition(t,e){const n=e??this.getDocument(),o=this.getBlockContextById(n,t.block);return!o||o.block.type!=="paragraph"?null:{paragraph:o.block,paragraphPath:o.blockPath,topLevelIndex:o.topLevelIndex}}getParagraphOffsetForPosition(t,e){const n=e??this.getDocument(),o=this.getParagraphContextForPosition(t,n);return o?{...o,offset:t.offset}:null}getParagraphTextLength(t){return t.children.reduce((e,n)=>e+(n.type==="text"?n.text.length:0),0)}getCancelableParagraphSplitRecord(t,e){const n=t.structuralSuggestionId;if(!n||n!==e.structuralSuggestionId||t.structuralSuggestionKind!=="split"||e.structuralSuggestionKind!=="split")return null;const o=this.suggestionEngine.getLiveSuggestion(n);if(!o||o.type!=="paragraph-split")return null;const i=new Set([o.blockId,o.insertedBlockId]);return!i.has(t.id)||!i.has(e.id)?null:o}getCancelableParagraphMergeRecord(t,e){const n=t.structuralSuggestionId;if(!n||t.structuralSuggestionKind!=="merge"||!t.structuralSuggestionRole)return null;const o=this.getParagraphTextLength(t);if(!(t.structuralSuggestionRole==="before"&&e===o||t.structuralSuggestionRole==="after"&&e===0))return null;const i=this.suggestionEngine.getLiveSuggestion(n);return!i||i.type!=="paragraph-merge"||i.firstBlockId!==t.id&&i.secondBlockId!==t.id?null:i}isPlainEmptyParagraph(t){return!t.structuralSuggestionId&&!t.structuralSuggestionKind&&this.getParagraphTextLength(t)===0}isInsertedParagraph(t){return t.structuralSuggestionKind==="insert"&&typeof t.structuralSuggestionId=="string"&&t.structuralSuggestionId.length>0}cursorFromParagraphOffset(t,e,n){let o=0;for(const s of e.children)s.type==="text"&&(o+=s.text.length);const i=Math.min(Math.max(0,n),o);return{block:e.id,offset:i}}arePositionsInSameEditableBlock(t,e,n){return e.block===n.block}getYContentFragment(){return Pn(this.ydoc)}getYChromeFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("chrome")}getYNotesFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("notes")}getYBlockContext(t,e){if(!t.length)return null;const n=this.getYContentFragment(),o=t[0];if(o<0||o>=n.length)return null;const i=n.get(o);return i instanceof x.XmlElement?{parent:n,index:o,yBlock:i}:null}getYParagraphContext(t,e){const n=this.getYBlockContext(t,e);if(!n)return null;for(let o=0;o<n.yBlock.length;o++){const i=n.yBlock.get(o);if(i instanceof x.XmlText)return{yBlock:n.yBlock,yText:i}}return null}getEmptyTextMarksForParagraph(t){const e=this.getYBlockContext(t);if(!e)return;const n=e.yBlock.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(o){console.warn("Failed to parse _emptyTextMarks",o);return}}getEmptyTextMarksForBlockId(t){const e=at(this.ydoc,t);if(!e)return;const n=e.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(o){console.warn("Failed to parse _emptyTextMarks",o);return}}resolveEditableContext(t,e){const n=e??this.getDocument(),o=this.getBlockContextById(n,t.block);if(!o)return null;const i={block:o.block,blockPath:o.blockPath},s=ut(this.ydoc,o.block.id),a=s?{parent:s.yParent,index:s.index,yBlock:s.yBlock}:null;return{doc:n,editable:i,yContext:a}}dispose(){this.disposed||(this.disposed=!0,this.ydoc.off("update",this.handleYDocUpdate),this.strandedCheck&&clearTimeout(this.strandedCheck),this.strandedCheck=null,this.deferredIdentityRepair&&clearTimeout(this.deferredIdentityRepair),this.deferredIdentityRepair=null,this.detachedSuggestionStore.destroy(),this.undoManager.destroy(),this.pendingUpdate=null,this.onDocumentChange=()=>{},this.onTitleChange=void 0,this.remoteOrigins.clear(),this.trackedUndoOrigins.clear(),this.toolCallHistory.clear(),this.invalidateDerivedDocumentState())}setSelectionAfterOperation(t){this.afterOperationSelection=t,this.updateAfterOperationRelativeSelection(this.getDocument())}updateAfterOperationRelativeSelection(t){const e=this.afterOperationSelection;this.afterOperationRelativeSelection=e?J(e,this.ydoc,t):null}getDocument(){return this.cachedDoc||(this.cachedDoc=this.incrementalRefreshPending?Ie(this.ydoc):Tt(this.ydoc),this.incrementalRefreshPending=!1),this.cachedDoc}mergeAdjacentListItemsSnapshot(t,e,n){if(e<0||e>=t.children.length-1)return null;const o=this.suggestionEngine.cloneSuggestionSnapshot(t),i=o.children[e],s=o.children[e+1];if(!i||!s)return null;const a=this.suggestionEngine.cloneSuggestionSnapshot(i.children),c=this.suggestionEngine.cloneSuggestionSnapshot(s.children),l=a[a.length-1],d=c[0];return l?.type==="text"&&d?.type==="text"&&JSON.stringify(l.marks||{})===JSON.stringify(d.marks||{})&&(l.text+=d.text,c.shift()),i.children=[...a,...c],n&&(i.structuralSuggestionId=n,i.structuralSuggestionKind="change",i.structuralSuggestionLabel="Join",delete i.structuralSuggestionRole),o.children.splice(e+1,1),o}collectInlineFormattingRanges(t,e,n,o){const i=[],s=qt(o,t,e)<=0,a=s?t:e,c=s?e:t;if(a.block===c.block)return this.collectSingleBlockFormattingRange(a,c,o);{const g=Ls(o,a.block)?.block??(o.notes??[]).find(p=>p.children.some(h=>h.id===a.block));if(g){const p=g.children.map(m=>m.id),h=p.indexOf(a.block),f=p.indexOf(c.block);if(h!==-1&&f!==-1){const[m,y]=h<=f?[h,f]:[f,h],b=[];for(let k=m;k<=y;k++){const v=g.children[k];if(!v.id)continue;const S=k===h?a:{block:v.id,offset:0},I=k===f?c:{block:v.id,offset:Number.MAX_SAFE_INTEGER};b.push(...this.collectSingleBlockFormattingRange({block:v.id,offset:k===h?S.offset:0},{block:v.id,offset:k===f?I.offset:Number.MAX_SAFE_INTEGER},o))}return b}}}const l=Xe(o,a.block),d=Xe(o,c.block);if(!l||!d){if(a.block===c.block)return this.collectSingleBlockFormattingRange(a,c,o);const g=this.collectSingleBlockFormattingRange(a,a,o),p=this.collectSingleBlockFormattingRange(c,c,o);return[...g,...p]}let u=!0;for(const{block:g,path:p}of Ds(o)){const h=ln(p,l),f=ln(p,d);if(h<0)continue;if(f>0)break;const m=f===0,y=ut(this.ydoc,g.id);if(!y){u=!1;continue}const b=y.yBlock;if(g.type==="paragraph"){const k=xt(b);if(!k){u=!1;continue}let v=0,S=k.length;u&&a.block===g.id&&(v=a.offset),m&&c.block===g.id&&(S=c.offset),v=hr(v,0,k.length),S=hr(S,0,k.length);const I=Math.min(v,S),w=Math.max(v,S);w>I&&i.push({yText:k,start:I,end:w,blockId:g.id}),u=!1;continue}if(g.type==="list"){const k=g,v=[];for(let B=0;B<b.length;B++){const P=b.get(B);P instanceof x.XmlElement&&P.nodeName==="list-item"&&v.push(P)}const S=Math.min(k.children.length,v.length);if(S===0){u=!1;continue}let I=0,w=S-1,A=0,_=Number.MAX_SAFE_INTEGER;if(u&&a.block===g.id){const B=this.listOperations.getListCursorInfo(k,a);B&&(I=Math.min(B.itemIndex,S-1),A=B.offsetInItem)}if(m&&c.block===g.id){const B=this.listOperations.getListCursorInfo(k,c);B&&(w=Math.min(B.itemIndex,S-1),_=B.offsetInItem)}for(let B=I;B<=w;B++){const P=v[B];if(!P)continue;const $=xt(P);if(!$||$.length===0)continue;let T=0,C=$.length;B===I&&(T=Math.min(A,$.length)),B===w&&(C=Math.min(_,$.length)),C>T&&i.push({yText:$,start:T,end:C})}u=!1}}return i}collectSingleBlockFormattingRange(t,e,n){const o=[],i=z(n,t.block);if(!i)return o;const s=ut(this.ydoc,t.block);if(!s)return o;const a=s.yBlock;if(i.type==="paragraph"){const c=xt(a);if(!c)return o;let l=t.offset,d=e.offset;l=hr(l,0,c.length),d=hr(d,0,c.length);const u=Math.min(l,d),g=Math.max(l,d);g>u&&o.push({yText:c,start:u,end:g,blockId:i.id})}else if(i.type==="list"){const c=i,l=[];for(let y=0;y<a.length;y++){const b=a.get(y);b instanceof x.XmlElement&&b.nodeName==="list-item"&&l.push(b)}const d=Math.min(c.children.length,l.length);if(d===0)return o;const u=this.listOperations.getListCursorInfo(c,t),g=this.listOperations.getListCursorInfo(c,e);if(!u||!g)return o;let p=Math.min(u.itemIndex,d-1),h=Math.min(g.itemIndex,d-1),f=u.offsetInItem,m=g.offsetInItem;p>h&&([p,h]=[h,p],[f,m]=[m,f]);for(let y=p;y<=h;y++){const b=l[y];if(!b)continue;const k=xt(b);if(!k||k.length===0)continue;let v=0,S=k.length;y===p&&(v=Math.min(f,k.length)),y===h&&(S=Math.min(m,k.length)),S>v&&o.push({yText:k,start:v,end:S,blockId:i.id,itemIndex:y})}}return o}collectParagraphBlockIdsInRange(t,e,n){const o=[],i=new Set,s=g=>{const p=z(n,g);p?.type==="paragraph"&&p.id&&!i.has(p.id)&&(i.add(p.id),o.push(p.id))},a=qt(n,t,e)<=0,c=a?t:e,l=a?e:t,d=Xe(n,c.block),u=Xe(n,l.block);if(!d||!u)return s(c.block),s(l.block),o;for(const{block:g,path:p}of Ds(n)){const h=ln(p,d),f=ln(p,u);if(!(h<0)){if(f>0)break;g.type==="paragraph"&&g.id&&!i.has(g.id)&&(i.add(g.id),o.push(g.id))}}return o.length===0&&s(c.block),o}clearFormattingEmptyMarksAtPosition(t,e){const n=z(e,t.block);if(!n)return!1;if(n.type==="paragraph"){const l=ut(this.ydoc,n.id);return l?ml(l.yBlock):!1}if(n.type!=="list")return!1;const o=n;this.suggestingMode&&this.suggestionEngine.cloneSuggestionSnapshot(o),this.suggestingMode&&Ct();const i=ut(this.ydoc,n.id);if(!i)return!1;const s=this.listOperations.getListCursorInfo(o,t);if(!s)return!1;const a=[];for(let l=0;l<i.yBlock.length;l++){const d=i.yBlock.get(l);d instanceof x.XmlElement&&d.nodeName==="list-item"&&a.push(d)}const c=a[s.itemIndex];return c?ml(c):!1}updateEmptyTextMarksAtPosition(t,e,n,o){const i=z(o,t.block);if(!i)return!1;if(i.type==="paragraph"){const u=ut(this.ydoc,i.id);if(!u)return!1;const g=i.children.some(p=>p.type==="text"&&p.text.length>0);return bl(u.yBlock,e,n,!g)}if(i.type!=="list")return!1;const s=i,a=ut(this.ydoc,i.id);if(!a)return!1;const c=this.listOperations.getListCursorInfo(s,t);if(!c)return!1;const l=[];for(let u=0;u<a.yBlock.length;u++){const g=a.yBlock.get(u);g instanceof x.XmlElement&&g.nodeName==="list-item"&&l.push(g)}const d=l[c.itemIndex];return d?bl(d,e,n,c.itemLength===0):!1}updateBackgroundColorEmptyMarksAtPosition(t,e,n){return this.updateEmptyTextMarksAtPosition(t,"backgroundColor",e,n)}insertTextInCodeBlock(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument(),s=z(i,t.block);if(!to(s))return!1;const a=at(this.ydoc,t.block);if(!a)return!1;let c=null;for(let g=0;g<a.length;g++){const p=a.get(g);if(p instanceof x.XmlText){c=p;break}}if(!c)return!1;const l=Math.min(t.offset,c.length);this.transact(()=>{c.insert(l,e)});const d={block:t.block,offset:l+e.length},u={anchor:d,focus:d};return this.setSelectionAfterOperation(u),this.afterOperationRelativeSelection=J(u,this.ydoc,this.getDocument()),!0}deleteTextInCodeBlock(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();this.beforeOperationRelativeSelection=J(n,this.ydoc,i);const s=z(i,t.block);if(!to(s))return!1;const a=at(this.ydoc,t.block);if(!a)return!1;let c=null;for(let u=0;u<a.length;u++){const g=a.get(u);if(g instanceof x.XmlText){c=g;break}}if(!c)return!1;const l=c.length-t.offset,d=Math.min(e,l);return this.transact(()=>{c.delete(t.offset,d)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}getYDoc(){return this.ydoc}getAfterOperationSelection(){return this.afterOperationSelection}captureSelectionBeforeOperation(t){if(!t){this.beforeOperationSelection=null,this.beforeOperationRelativeSelection=null;return}const e=o=>o?{block:o.block,offset:o.offset}:null;this.beforeOperationSelection={anchor:e(t.anchor),focus:e(t.focus)};const n=this.getDocument();this.beforeOperationRelativeSelection=J(t,this.ydoc,n)}setAfterOperationSelectionFromEditor(t){if(t){const n=o=>o?{block:o.block,offset:o.offset}:null;this.setSelectionAfterOperation({anchor:n(t.anchor),focus:n(t.focus)})}else this.setSelectionAfterOperation(null);if(!t){this.afterOperationRelativeSelection=null;return}const e=this.getDocument();this.afterOperationRelativeSelection=J(t,this.ydoc,e)}ensureParagraphIndentStorageUsesUnits(){const t=this.ydoc.getMap("metadata");if(t.get(Me.paragraphIndentStorageVersion)===Mr)return;const e=this.ydoc.getXmlFragment("content");if(e.length===0&&an(this.ydoc))return;const n=t.get(Me.indentStepPx),o=be({indentStepPx:typeof n=="number"?n:void 0}).indentStepPx;this.ydoc.transact(()=>{e.length>0&&kl(e,i=>{const s=Fs(yl(bt(i,"leftIndent")),{indentStepPx:o,storedAsUnits:!1}),a=Fs(yl(bt(i,"firstLineIndent")),{indentStepPx:o,storedAsUnits:!1,firstLine:!0});s===void 0?rt(i,"leftIndent"):i.setAttribute("leftIndent",String(s)),a===void 0?rt(i,"firstLineIndent"):i.setAttribute("firstLineIndent",String(a))}),t.set(Me.paragraphIndentStorageVersion,Mr)},"indent-storage-migration")}setTitle(t){const e=Gp(t);this.transact(()=>{this.ydoc.getMap("metadata").set("title",e)}),this.onTitleChange&&this.onTitleChange(e)}setNotes(t){const e=typeof t=="string"?t:String(t??"");this.transact(()=>{const n=this.ydoc.getMap("metadata");e.length===0?n.delete("notes"):n.set("notes",e)})}getDocumentNotes(){const t=this.ydoc.getMap("metadata").get("notes");return typeof t=="string"?t:""}updateSectionBreakLayout(t,e){const n=this.getYContentFragment();let o=null;for(const i of n.toArray())if(i instanceof x.XmlElement&&i.nodeName==="section-break"&&i.getAttribute("id")===t){o=i;break}return o?(this.transact(()=>{o.setAttribute("layout",JSON.stringify(e))}),!0):!1}pinInheritedPageNumbering(t){const e=be(this.getPageLayoutSettings()),n=this.getDocument().children.filter(s=>s.type==="section-break"),o=t.pageNumberFormat!==void 0&&t.pageNumberFormat!==e.pageNumberFormat,i=t.pageNumberStart!==void 0&&t.pageNumberStart!==e.pageNumberStart;n.forEach((s,a)=>{const c=s.layout,l={...o&&c?.pageNumberFormat===void 0?{pageNumberFormat:e.pageNumberFormat}:{},...i&&a===0&&c?.pageNumberStart===void 0?{pageNumberStart:e.pageNumberStart}:{}};Object.keys(l).length>0&&this.updateSectionBreakLayout(s.id,{...c??{},...l})})}applyLayoutToAllSectionBreaks(t){const e=this.getYContentFragment();this.transact(()=>{for(const n of e.toArray())if(n instanceof x.XmlElement&&n.nodeName==="section-break"){let o={};try{const s=n.getAttribute("layout");o=typeof s=="string"?JSON.parse(s):{}}catch{o={}}const i={...o.oxmlSectPr!==void 0?{oxmlSectPr:o.oxmlSectPr}:{},...o.pageBorders!==void 0?{pageBorders:o.pageBorders}:{},...o.pageNumberStart!==void 0?{pageNumberStart:o.pageNumberStart}:{},...o.pageNumberFormat!==void 0?{pageNumberFormat:o.pageNumberFormat}:{}};n.setAttribute("layout",JSON.stringify(Ns(i,t)??t))}})}applySetHeaderFooterAction(t){const e=t.side==="footer"?"footer":"header",n=t.slot==="first"||t.slot==="even"?t.slot:"default";return{changed:op(this.kernel,e,n,{left:t.left,center:t.center,right:t.right},t.clear===!0),side:e,slot:n}}applySetPageLayoutAction(t){const e=t.clearPageBorders===!0?null:Xd(t.pageBorders);if(t.pageBorders!==void 0&&e===void 0)throw new Error("Invalid pageBorders: use supported side styles, #RRGGBB colors, widthPt 0.25–12 and spacePt 0–31, or null to remove.");const n=this.getPageLayoutSettings(),o=this.getDocument().children.filter($=>$.type==="section-break"),i=o.length+1,s=typeof t.sectionIndex=="number"&&Number.isInteger(t.sectionIndex)&&t.sectionIndex>=1&&t.sectionIndex<=i?t.sectionIndex:void 0;if(t.sectionIndex!=null&&s===void 0){const $=typeof t.sectionIndex=="number"&&Number.isInteger(t.sectionIndex)?`sectionIndex ${t.sectionIndex} is out of range: document has ${i} section${i===1?"":"s"}`:`sectionIndex must be an integer between 1 and ${i}, got ${JSON.stringify(t.sectionIndex)}`;return{settings:n,pageless:this.getPagelessMode(),error:$}}if(t.pageNumberFormat!=null&&!_r(t.pageNumberFormat))return{settings:n,pageless:this.getPagelessMode(),error:`pageNumberFormat must be one of ${Hd.join(", ")}, got ${JSON.stringify(t.pageNumberFormat)}`};const a=s?o[s-1]:void 0,c=a?Cs(n,a.layout):n,l=this.getPagelessMode(),d=Wd(t.preset)?Jd(t.preset):void 0,u={...d?.pageLayout??{}},g={...c,...d?.pageLayout??{}};Yd(t.pageSize)&&(g.pageSize=t.pageSize,u.pageSize=t.pageSize),(t.orientation==="portrait"||t.orientation==="landscape")&&(g.orientation=t.orientation,u.orientation=t.orientation);const p=ye(t.margin);p!==void 0&&(g.marginTopPx=p,g.marginRightPx=p,g.marginBottomPx=p,g.marginLeftPx=p,u.marginTopPx=p,u.marginRightPx=p,u.marginBottomPx=p,u.marginLeftPx=p);const h=ye(t.marginTop);h!==void 0&&(g.marginTopPx=h,u.marginTopPx=h);const f=ye(t.marginRight);f!==void 0&&(g.marginRightPx=f,u.marginRightPx=f);const m=ye(t.marginBottom);m!==void 0&&(g.marginBottomPx=m,u.marginBottomPx=m);const y=ye(t.marginLeft);y!==void 0&&(g.marginLeftPx=y,u.marginLeftPx=y);const b=ye(t.indentStep);b!==void 0&&(g.indentStepPx=b,u.indentStepPx=b);const k=ye(t.blockSpacing);k!==void 0&&(g.blockSpacingPx=k,u.blockSpacingPx=k),Kd(t.columnCount)&&(g.columnCount=t.columnCount,u.columnCount=t.columnCount);const v=ye(t.columnGap);if(v!==void 0){const $=Math.max(0,nu(v));g.columnGapTwips=$,u.columnGapTwips=$}if((t.noteMode==="footnotes"||t.noteMode==="endnotes")&&this.convertAllNoteKinds(t.noteMode==="endnotes"?"endnote":"footnote"),typeof t.showPageNumbers=="boolean"||Lr(t.pageNumberPosition)){const $=Lr(t.pageNumberPosition)?t.pageNumberPosition:this.ydoc.getMap("metadata").get(Me.pageNumberPosition)??"bottom-right",T=typeof t.showPageNumbers=="boolean"?t.showPageNumbers:!0;this.setPageNumberSlot(T,$)}if(typeof t.showPageNumbers=="boolean"&&(g.showPageNumbers=!1),Lr(t.pageNumberPosition)&&(g.pageNumberPosition=t.pageNumberPosition),typeof t.pageNumberStart=="number"?(g.pageNumberStart=t.pageNumberStart,u.pageNumberStart=t.pageNumberStart):t.pageNumberRestart===!0&&(u.pageNumberStart=a?.layout?.pageNumberStart??1),_r(t.pageNumberFormat)&&(g.pageNumberFormat=t.pageNumberFormat,u.pageNumberFormat=t.pageNumberFormat),!a){const $=s===i&&i>1;t.pageNumberRestart===!0||$&&typeof t.pageNumberStart=="number"&&t.pageNumberRestart!==!1?g.pageNumberRestart=!0:t.pageNumberRestart===!1&&delete g.pageNumberRestart}if((t.pageBorders!==void 0||t.clearPageBorders===!0)&&(g.pageBorders=e,u.pageBorders=e),t.lineNumbering!==void 0){const $=Vd(t.lineNumbering);$?g.lineNumbering=$:delete g.lineNumbering,u.lineNumbering=Gd($)??""}const S=ye(t.pageWidth),I=ye(t.pageHeight);if(S!==void 0&&I!==void 0){const $=Zd(S,I);$&&(g.pageSize=$.pageSize,g.orientation=$.orientation,u.pageSize=$.pageSize,u.orientation=$.orientation)}if(t.watermark!==void 0){const $=Ys(t.watermark);this.transact(()=>{const T=this.ydoc.getMap("metadata");$?T.set("watermark",$):T.delete("watermark")})}const w=be(g),A=typeof t.pageless=="boolean"?t.pageless:d?.pageless??l,_=t.pageNumberRestart===!1&&typeof t.pageNumberStart!="number",B=$=>{const T=Ns($,u)??{...u};if(!_)return T;const{pageNumberStart:C,...N}=T;return N},P=Object.keys(u).length>0||_;if(s&&a)P&&this.updateSectionBreakLayout(a.id,B(a.layout));else if(s===i){if(t.pageBorders!==void 0||t.clearPageBorders===!0)for(const $ of o)$.layout?.pageBorders!==void 0||/<w:pgBorders\b/.test($.layout?.oxmlSectPr??"")||this.updateSectionBreakLayout($.id,{...$.layout,pageBorders:n.pageBorders??null});this.pinInheritedPageNumbering({..._r(t.pageNumberFormat)?{pageNumberFormat:t.pageNumberFormat}:{},...typeof t.pageNumberStart=="number"?{pageNumberStart:t.pageNumberStart}:{}}),this.setPageLayoutSettings(w)}else{if(P)for(const $ of o)this.updateSectionBreakLayout($.id,B($.layout));this.setPageLayoutSettings(w)}return this.setPagelessMode(A),{settings:w,pageless:A}}setPagelessMode(t){this.transact(()=>{this.ydoc.getMap("metadata").set("pageless",t)})}getPagelessMode(){return!!this.ydoc.getMap("metadata").get("pageless")}convertParagraphToList(t,e,n){return this.listOperations.convertParagraphToList(t,e,n)}convertParagraphToListById(t,e,n){return this.listOperations.convertParagraphToListById(t,e,n)}getListItemPlainText(t){return this.listOperations.getListItemPlainText(t)}convertParagraphRangeToList(t,e,n){return this.listOperations.convertParagraphRangeToList(t,e,n)}updateListVariant(t,e,n){return this.listOperations.updateListVariant(t,e,n)}convertListToParagraphById(t){return this.listOperations.convertListToParagraphById(t)}updateListVariantById(t,e,n){return this.listOperations.updateListVariantById(t,e,n)}continueListFromPrevious(t){return this.listOperations.continueListFromPrevious(t)}restartListNumberingAt(t,e,n){return this.listOperations.restartListNumberingAt(t,e,n)}splitListItem(t,e){return this.listOperations.splitListItem(t,e)}insertTextInListItem(t,e,n,o){return this.listOperations.insertTextInListItem(t,e,n,o)}insertTextInList(t,e,n,o){return this.listOperations.insertTextInList(t,e,n,o)}insertFormattedTextInList(t,e,n,o,i){return this.listOperations.insertFormattedTextInList(t,e,n,o,i)}getListCursorInfo(t,e){return this.listOperations.getListCursorInfo(t,e)}getListItemTextLength(t){return this.listOperations.getListItemTextLength(t)}setListItemIndent(t,e,n,o,i){return this.listOperations.setListItemIndent(t,e,n,o,i)}setSuggestingMode(t){this.suggestionEngine.setSuggestingMode(t)}isSuggestingMode(){return this.suggestionEngine.isSuggestingMode()}getLiveSuggestionStore(){return this.suggestionEngine.getLiveSuggestionStore()}setDefaultSuggestionAuthorName(t){this.suggestionEngine.setDefaultSuggestionAuthorName(t)}withSuggestionMetadata(t,e){return this.suggestionEngine.withSuggestionMetadata(t,e)}saveLiveSuggestion(t){this.suggestionEngine.saveLiveSuggestion(t)}backfillLiveSuggestionTreeRecords(){this.suggestionEngine.backfillLiveSuggestionTreeRecords()}getLiveSuggestion(t){return this.suggestionEngine.getLiveSuggestion(t)}getInlineSuggestionMetadataFromDocument(t){return this.suggestionEngine.getInlineSuggestionMetadataFromDocument(t)}getLiveSuggestionTooltipDescription(t){return this.suggestionEngine.getLiveSuggestionTooltipDescription(t)}deleteLiveSuggestion(t){this.suggestionEngine.deleteLiveSuggestion(t)}getLiveSuggestionIds(){return this.suggestionEngine.getLiveSuggestionIds()}completeInternalTextMove(t,e,n){const o=new Set(t),i=new Set(e),s=[],a=[],c=[],l=p=>{if(p instanceof x.XmlText){let h=0;for(const f of mt(p)){const m=typeof f.insert=="string"?f.insert.length:1,y=f.attributes??{};y.deletion&&o.has(y.suggestionId)?s.push({text:p,start:h,length:m,attributes:y}):y.insertion&&i.has(y.suggestionId)&&a.push({text:p,start:h,length:m,attributes:y}),h+=m}}if(p instanceof x.XmlFragment||p instanceof x.XmlElement){p instanceof x.XmlElement&&(o.has(p.getAttribute("structuralSuggestionId"))||i.has(p.getAttribute("structuralSuggestionId")))&&c.push(p);for(let h=0;h<p.length;h++){const f=p.get(h);f instanceof x.AbstractType&&l(f)}}};if(l(this.getYContentFragment()),s.length===0||a.length===0)return!1;const d=1e7+Math.floor(Math.random()*9e7),u=`reviseMove-${n}`,g=(p,h,f)=>{const m=JSON.stringify({version:1,name:u,role:h,rangeId:`${d}${f}`,wrapperId:`${d+1}${f}`,fallbackSuggestionId:p[0].attributes.suggestionId,...p[0].attributes.suggestionAuthorName?{rangeAuthor:p[0].attributes.suggestionAuthorName}:{},...typeof p[0].attributes.suggestionCreatedAt=="number"?{rangeCreatedAt:p[0].attributes.suggestionCreatedAt}:{}});for(const y of p)It(y.text,y.start,y.length,{suggestionId:n,suggestionLabel:"Move",docxMove:m})};return this.transact(()=>{g(s,"from","1"),g(a,"to","2");for(const p of c)p.setAttribute("structuralSuggestionId",n)}),!0}recordStampedSuggestionIds(t){return this.suggestionEngine.recordStampedSuggestionIds(t)}runTrackedMovePaste(t,e,n,o){return this.runWithUndoGroup("tracked-move-paste",()=>{const{result:i,stamped:s}=this.recordStampedSuggestionIds(n);return o(i)&&this.completeInternalTextMove(e,[...s.insertionIds,...s.structuralInsertIds,t],t),i})}getLiveSuggestionIdsBySource(t){return this.suggestionEngine.getLiveSuggestionIdsBySource(t)}getLiveSuggestionIdsByCommentThread(t){return this.suggestionEngine.getLiveSuggestionIdsByCommentThread(t)}getLiveSuggestionAuthorName(t){return this.suggestionEngine.getLiveSuggestionAuthorName(t)}getLiveSuggestionKind(t){return this.suggestionEngine.getLiveSuggestionKind(t)}getLiveSuggestionIdsForBlock(t){return this.suggestionEngine.getLiveSuggestionIdsForBlock(t)}canResolveLiveSuggestion(t){return this.suggestionEngine.canResolveLiveSuggestion(t)}getUnresolvableLiveSuggestionRecords(){return this.suggestionEngine.getUnresolvableLiveSuggestionRecords()}takeLastPrunedUnresolvableLiveSuggestions(){return this.suggestionEngine.takeLastPrunedUnresolvableLiveSuggestions()}getDocumentWithAcceptedSuggestions(){return this.suggestionEngine.getDocumentWithAcceptedSuggestions()}mapAcceptedSuggestionRangeToLiveRange(t,e,n){return this.suggestionEngine.mapAcceptedSuggestionRangeToLiveRange(t,e,n)}getDocumentWithRejectedSuggestions(){return this.suggestionEngine.getDocumentWithRejectedSuggestions()}sanitizeBlocksForClipboard(t){return t.map(e=>this.suggestionEngine.sanitizePreviewBlock(e))}getSelectionInRejectedSuggestionProjection(t){return this.suggestionEngine.getSelectionInRejectedSuggestionProjection(t)}static materializeAcceptedSuggestions(t){const e=o=>{if(!o||typeof o!="object")return!1;if(Array.isArray(o))return o.some(e);const i=o;return typeof i.suggestionId=="string"&&i.suggestionId||typeof i.structuralSuggestionId=="string"&&i.structuralSuggestionId||i.marks&&typeof i.marks.suggestionId=="string"&&i.marks.suggestionId?!0:e(i.children)};if(!t.children.some(e))return t;const n=$n(t);try{const o=sn.createSuggestionProjectionFromYDoc(n,"accept");try{return{...t,children:o.doc.children}}finally{o.ydoc.destroy()}}finally{n.destroy()}}static createSuggestionProjectionFromYDoc(t,e,n){const o=new x.Doc;x.applyUpdate(o,x.encodeStateAsUpdate(t));const i=new sn(Tt(o),()=>{},void 0,o,"live-suggestion-projection",!0,new ir,{canRepairIdentity:()=>!1}),s=n?Array.from(new Set(n.filter(a=>typeof a=="string"&&a.length>0))):i.getLiveSuggestionIds();try{return e==="accept"?i.suggestionEngine.applyLiveSuggestionDecisionInternal(s,"accept"):i.suggestionEngine.applyLiveSuggestionDecisionInternal(s,"reject"),t.getXmlFragment("notes").length>0&&i.reconcileFootnotes(),{ydoc:o,doc:i.getDocument()}}finally{i.dispose()}}decideLiveSuggestions(t){return this.suggestionEngine.decideLiveSuggestions(t)}acceptLiveSuggestions(t){return this.suggestionEngine.acceptLiveSuggestions(t)}acceptLiveSuggestionsBySource(t){return this.suggestionEngine.acceptLiveSuggestionsBySource(t)}acceptLiveSuggestionsByAuthor(t){return this.suggestionEngine.acceptLiveSuggestionsByAuthor(t)}rejectLiveSuggestionsByAuthor(t){return this.suggestionEngine.rejectLiveSuggestionsByAuthor(t)}acceptLiveSuggestionsByKind(t){return this.suggestionEngine.acceptLiveSuggestionsByKind(t)}rejectLiveSuggestionsByKind(t){return this.suggestionEngine.rejectLiveSuggestionsByKind(t)}rejectLiveSuggestions(t){return this.suggestionEngine.rejectLiveSuggestions(t)}rejectLiveSuggestionsBySource(t){return this.suggestionEngine.rejectLiveSuggestionsBySource(t)}setElementStructuralSuggestion(t,e,n,o,i){this.suggestionEngine.setElementStructuralSuggestion(t,e,n,o,i)}setDiffSuggestionAttributes(t,e,n){this.suggestionEngine.setDiffSuggestionAttributes(t,e,n)}acceptLiveSuggestion(t){return this.suggestionEngine.acceptLiveSuggestion(t)}rejectLiveSuggestion(t){return this.suggestionEngine.rejectLiveSuggestion(t)}applyBridgeBlockChangeSuggestion(t){return this.suggestionEngine.applyBridgeBlockChangeSuggestion(t)}resetToolCallHistory(){return this.suggestionEngine.resetToolCallHistory()}setToolCallHistory(t){return this.suggestionEngine.setToolCallHistory(t)}getDetachedSuggestionStore(){return this.suggestionEngine.getDetachedSuggestionStore()}setDetachedSuggestionConversation(t,e){this.suggestionEngine.setDetachedSuggestionConversation(t,e)}clearLegacyDetachedSuggestionState(){this.suggestionEngine.clearLegacyDetachedSuggestionState()}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){return this.suggestionEngine.migrateLegacyDetachedSuggestionsToLiveSuggestions(t)}get kernel(){return this.cachedKernel||(this.cachedKernel={ydoc:this.ydoc,transact:t=>this.transact(t),getYContentFragment:()=>this.getYContentFragment(),getYChromeFragment:()=>this.getYChromeFragment(),getYNotesFragment:()=>this.getYNotesFragment(),blockToYjsElement:t=>this.blockToYjsElement(t),getDocument:()=>this.getDocument(),insertTextNodes:(t,e,n)=>this.insertTextNodes(t,e,n),suggestions:{isSuggesting:()=>this.suggestingMode,buildInlineMetadataMarks:(t,e,n)=>this.suggestionEngine.buildInlineSuggestionMetadataMarks(t,e,n),setElementStructuralSuggestion:(t,e,n,o,i)=>this.suggestionEngine.setElementStructuralSuggestion(t,e,n,o,i)}}),this.cachedKernel}setHeadersAndFooters(t,e){nr(this.kernel,t,e)}ensureHeaderFooterBlock(t,e){return wc(this.kernel,t,e)}migrateLegacyHeaderFooterMetadata(){Qh(this.kernel)}migrateNotesOutOfContent(){mp(this.kernel)}migrateChromeOutOfContent(){Zh(this.kernel)}getHeadersAndFooters(){return Ci(this.kernel)}setSectionHeadersAndFooters(t,e,n){Vh(this.kernel,t,e,n)}getSectionHeadersAndFooters(t){return Gh(this.kernel,t)}setPageNumberSlot(t,e="bottom-right"){tp(this.kernel,t,e)}migrateLegacyPageNumbers(){ep(this.kernel)}setPageLayoutSettings(t){this.ensureParagraphIndentStorageUsesUnits(),this.transact(()=>{Qd(this.ydoc.getMap("metadata"),t)})}setWatermark(t){const e=Ys(t);this.transact(()=>{const n=this.ydoc.getMap("metadata");e?n.set("watermark",e):n.delete("watermark")})}getWatermarkRaw(){const t=this.ydoc.getMap("metadata").get("watermark");return typeof t=="string"&&t.trim()!==""?t:void 0}getPageLayoutSettings(){return xs(this.ydoc.getMap("metadata"))??be(void 0)}getIndentStepPx(){return this.getPageLayoutSettings().indentStepPx??0}getTitle(){return this.ydoc.getMap("metadata").get("title")}transact(t){return this.assertObserversNotStranded(),this.incrementalRefreshPending=!1,this.cachedDoc=null,this.invalidateDerivedDocumentState(),this.ydoc.transact(t,this.origin)}assertObserversNotStranded(){if(this.strandedObservers)throw new Error("The editor lost sync with the document. Reload the page to continue editing.");this.hasQueuedCleanupsOutsideTransaction()&&!this.strandedCheck&&(this.strandedCheck=setTimeout(()=>{this.strandedCheck=null,!(this.disposed||!this.hasQueuedCleanupsOutsideTransaction())&&(this.strandedObservers=!0,wi(new Error(`Refusing further writes: ${this.ydoc._transactionCleanups.length} stranded transaction cleanups`),"transact"))},0))}hasQueuedCleanupsOutsideTransaction(){const t=this.ydoc;return t._transaction===null&&t._transactionCleanups.length>0}scheduleDeferredIdentityRepair(){this.deferredIdentityRepair||(this.deferredIdentityRepair=setTimeout(()=>{this.deferredIdentityRepair=null,!(this.disposed||!this.canRepairIdentity())&&this.repairDocumentIdentity()&&this.onDocumentChange(this.getDocument(),{origin:"local"})},sn.DEFERRED_IDENTITY_REPAIR_MS))}repairDocumentIdentity(t,e){const n=t!==void 0&&e===this.undoManager,o=this.ydoc.clientID,i=t?.beforeState.get(o)??0,s=n?l=>{const d=l._item?.id;return d!==void 0&&d.client===o&&d.clock>=i}:void 0,a=tu(this.ydoc,{transaction:t,shouldDrop:s});if(n&&a.droppedIds.length>0){const l=new Set(a.droppedIds),d=this.suggestionEngine.getLiveSuggestionStore(),u=[];for(const[g,p]of d._map){if(p.deleted||p.id.client!==o||p.id.clock<i)continue;const h=d.get(g);h&&this.suggestionEngine.liveSuggestionRecordTouchesAnyBlock(h,l)&&u.push(g)}u.length>0&&this.ydoc.transact(()=>{for(const g of u)this.suggestionEngine.deleteLiveSuggestion(g)},_s)}const c=Hh(this.ydoc,t,n?"strip":"recover");return a.duplicatesFound===0&&c===0?!1:(this.cachedDoc=null,this.incrementalRefreshPending=!1,Mo(this.ydoc,Tt(this.ydoc)),!0)}get localOrigin(){return this.origin}beginRollbackScope(){const t=new x.UndoManager([this.ydoc.getXmlFragment("content"),this.ydoc.getXmlFragment("chrome"),this.ydoc.getXmlFragment("notes"),this.ydoc.getArray("annotations"),this.suggestionEngine.getLiveSuggestionStore(),this.ydoc.getMap("comments")],{captureTimeout:0,trackedOrigins:this.trackedUndoOrigins}),e=this.undoManager.undoStack.length,n=this.undoManager.redoStack.length;let o=!1;const i=()=>{o||(o=!0,t.destroy())};return{revert:()=>{if(!o){for(;t.canUndo();)t.undo();this.undoManager.undoStack.length=Math.min(this.undoManager.undoStack.length,e),this.undoManager.redoStack.length=Math.min(this.undoManager.redoStack.length,n),this.cachedDoc=null,this.incrementalRefreshPending=!1,this.invalidateDerivedDocumentState(),i()}},dispose:i}}canUndo(){return this.undoManager.canUndo()}canRedo(){return this.undoManager.canRedo()}undo(){try{const t=this.undoManager.undoStack;if(t.length===0)return null;const e=t[t.length-1],n=e.meta.get("beforeSelection"),o=e.meta.get("beforeSelectionAbsolute");return this.undoManager.undo(),n?_i(n,this.ydoc):o||null}catch(t){return console.error("Error during undo:",t),t instanceof Error&&t.message.includes("forEach")&&(console.warn("Clearing undo history due to corrupted state"),this.undoManager.clear()),null}}redo(t){try{const e=this.undoManager.redoStack;if(e.length===0)return null;const n=e[e.length-1].meta.get("afterSelection"),o=this.getDocument();return this.currentSelectionBeforeRedo=t?J(t,this.ydoc,o):null,this.afterSelectionForRedo=n||null,this.isRedoing=!0,this.undoManager.redo(),n?_i(n,this.ydoc):null}catch(e){return console.error("Error during redo:",e),this.isRedoing=!1,this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,e instanceof Error&&e.message.includes("forEach")&&(console.warn("Clearing undo history due to corrupted state"),this.undoManager.clear()),null}}getParagraphPlainText(t){return t.children.map(e=>e.text).join("")}insertText(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();try{this.beforeOperationRelativeSelection=J(n,this.ydoc,i)}catch{this.beforeOperationRelativeSelection=null}const s=this.resolveEditableContext(t,i);if(!s)return!1;const{editable:a}=s,c=a.block;if(c.type==="list")return this.listOperations.insertTextInList(t,e,n,o);if(to(c))return this.insertTextInCodeBlock(t,e,n,o);if(c.type!=="paragraph")return!1;const l=c,d=this.listOperations.tryApplyParagraphListTrigger(l,t,e);if(d!==null)return d;const u={type:"text",text:e},g={},p=Er(i,t),h=Rr(i,t),f=Dr(i,t,n),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(i,t),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i,t.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(i,t,n),v=!b&&(this.suggestingMode||y)&&e.length>0,S=Ti({inheritedMarks:f?.marks,emptyParagraphMarks:br(l)?void 0:this.getEmptyTextMarksForBlockId(t.block),exitingLink:p,exitingComment:h,suggestionMarks:v?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(f?.marks),void 0,void 0,m?.marks??f?.marks):void 0});Object.assign(g,S.marksToApply),Object.keys(g).length>0&&(u.marks=g);const I=this.insertTextNodes(t,[u],n,k??void 0);if(I){const w={anchor:I,focus:I};this.setSelectionAfterOperation(w),this.afterOperationRelativeSelection=J(w,this.ydoc,this.getDocument())}return I!==null}insertFormattedText(t,e,n,o,i,s){this.beforeOperationSelection=o;const a=this.getDocument();this.beforeOperationRelativeSelection=J(o,this.ydoc,a);const c=z(a,t.block);if(!c)return!1;if(c.type==="list")return this.listOperations.insertFormattedTextInList(t,e,n,o,i);if(to(c))return this.insertTextInCodeBlock(t,e,o,i);if(c.type!=="paragraph")return!1;const l=c,d=this.listOperations.tryApplyParagraphListTrigger(l,t,e);if(d!==null)return d;const u=Re(t,this.ydoc,a);if(!u)return!1;const g=x.createAbsolutePositionFromRelativePosition(u.textOffset,this.ydoc);if(!g||!(g.type instanceof x.XmlText))return!1;const p=g.type,h=g.index,f=Dr(a,t,o),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(a,t),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,t.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(a,t,o),v=Er(a,t),S=Rr(a,t),I=!b&&(this.suggestingMode||y)&&e.length>0,{marksToApply:w,marksToRemove:A}=Ti({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:f?.marks,emptyParagraphMarks:br(l)?void 0:this.getEmptyTextMarksForBlockId(t.block),exitingLink:v,exitingComment:S,noteBodyFontSize:this.isBlockInsideFootnote(a,t.block)?ze:void 0,suggestionMarks:I?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,s??k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(f?.marks),void 0,void 0,m?.marks??f?.marks):void 0});let _=h;this.transact(()=>{if(o&&o.anchor&&o.focus&&qt(a,o.anchor,o.focus)!==0){const[$,T]=qt(a,o.anchor,o.focus)===-1?[o.anchor,o.focus]:[o.focus,o.anchor];if($.block===t.block&&T.block===t.block)if(this.suggestingMode&&!b){const{retainedLength:C}=this.suggestionEngine.applySuggestedDeletionToTextRange(p,$.offset,T.offset-$.offset,k??void 0);_=$.offset+C}else p.delete($.offset,T.offset-$.offset),_=$.offset}vc(p,_,e,{marksToApply:w,marksToRemove:A}),!b&&(this.suggestingMode||y)&&e.length>0&&this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(p,_,e.length)});const B=x.createRelativePositionFromTypeIndex(p,_+e.length),P=or({blockId:u.blockId,textOffset:B},this.ydoc);if(P){const $={anchor:P,focus:P};return this.setSelectionAfterOperation($),this.afterOperationRelativeSelection=J($,this.ydoc,this.getDocument()),!0}return this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=J(i,this.ydoc,this.getDocument()),!0}insertTextNodes(t,e,n,o){if(e.length===0)return null;const i=this.getDocument(),s=at(this.ydoc,t.block);if(!s)return null;const a=xt(s);if(!a)return null;const c=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i,t.block),l=c?e.map(h=>({...h,marks:this.suggestionEngine.stripSuggestionMarksFromTextMark(h.marks)})):e;let d=t.offset,u=0;const g=[];this.transact(()=>{if(n&&n.anchor&&n.focus&&qt(i,n.anchor,n.focus)!==0){const[f,m]=qt(i,n.anchor,n.focus)===-1?[n.anchor,n.focus]:[n.focus,n.anchor];if(f.block===t.block&&m.block===t.block)if(this.suggestingMode&&!c){const{retainedLength:y}=this.suggestionEngine.applySuggestedDeletionToTextRange(a,f.offset,m.offset-f.offset,o);d=f.offset+y}else a.delete(f.offset,m.offset-f.offset),d=f.offset}let h=d;for(const f of l)if(f.text.length>0){const m={...f.marks||{}};kt(a,h,f.text,m),m.insertion&&g.push({start:h,length:f.text.length}),h+=f.text.length,u+=f.text.length}for(const f of g)this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(a,f.start,f.length);s.getAttribute("_emptyTextMarks")&&s.removeAttribute("_emptyTextMarks")});const p=d+u;return{block:t.block,offset:p}}insertParagraphInternal(t,e,n=this.getYContentFragment()){if(t<0||t>n.length)return!1;const o=new x.XmlElement("paragraph");o.setAttribute("id",e.id||et()),e.heading&&o.setAttribute("heading",String(e.heading)),e.align&&o.setAttribute("align",e.align),e.lineSpacing!==void 0&&o.setAttribute("lineSpacing",String(e.lineSpacing)),Zn(o,e);const i=xe(e);i!==void 0&&o.setAttribute("pagination",i),e.styleId!==void 0&&o.setAttribute("styleId",e.styleId),e.direction!==void 0&&o.setAttribute("direction",e.direction),e.tabStops!==void 0&&o.setAttribute("tabStops",e.tabStops),e.borders!==void 0&&o.setAttribute("borders",e.borders),e.shading!==void 0&&o.setAttribute("shading",e.shading),e.oxmlAttrs!==void 0&&o.setAttribute("oxmlAttrs",e.oxmlAttrs),e.oxmlPPr!==void 0&&o.setAttribute("oxmlPPr",e.oxmlPPr);const s=le(e.leftIndent);s!==void 0&&o.setAttribute("leftIndent",String(s));const a=de(e.firstLineIndent);a!==void 0&&o.setAttribute("firstLineIndent",String(a));const c=new x.XmlText;n.insert(t,[o]),o.insert(0,[c]);let l=0;return e.children.forEach(d=>{if(d.type==="text"&&d.text.length>0){const u={...d.marks||{}};kt(c,l,d.text,u),l+=d.text.length}}),!0}insertParagraph(t,e){const n=this.getYContentFragment();return t<0||t>n.length?!1:(this.transact(()=>{this.insertParagraphInternal(t,e)}),!0)}deleteText(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();this.beforeOperationRelativeSelection=J(n,this.ydoc,i);const s=z(i,t.block);if(!s)return!1;if(s.type==="list")return this.listOperations.deleteTextInList(t,e,n,o);if(to(s))return this.deleteTextInCodeBlock(t,e,n,o);if(s.type!=="paragraph")return!1;const a=s,c=this.getEmptyTextMarksForBlockId(t.block),l=Qn(i,a,t,c);let d=0;for(const k of a.children)k.type==="text"&&(d+=k.text.length);let u=t.offset,g=t.offset+e,p=!1;{let k=0;for(const v of a.children){if(v.type!=="text")continue;const S=k+v.text.length;v.marks?.footnoteRef&&k<g&&S>u&&(p=!0,u=Math.min(u,k),g=Math.max(g,S)),k=S}}p&&(t={...t,offset:u},e=g-u);const h=d-t.offset,f=Math.min(e,h),m=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i,t.block);let y=null;this.transact(()=>{const k=at(this.ydoc,t.block);if(!k)return;const v=xt(k);if(v){if(this.suggestingMode&&!m){const S=this.suggestionEngine.applySuggestedDeletionToTextRange(v,t.offset,f);f>1&&S.retainedLength>0&&(y=this.normalizeAdjacentManualReplacementOrder(v,t.offset))}else v.delete(t.offset,f);v.length===0&&mr(k,l)}});const b=y?wl(o,t.block,y):o;return this.setSelectionAfterOperation(b),this.afterOperationRelativeSelection=J(b,this.ydoc,this.getDocument()),p&&!this.suggestingMode&&this.reconcileFootnotes(),!0}deleteSelection(t,e,n,o){this.beforeOperationSelection||(this.beforeOperationSelection=n);const i=this.getDocument();this.beforeOperationRelativeSelection||(this.beforeOperationRelativeSelection=J(n,this.ydoc,i));let s=ee(i,t.block),a=ee(i,e.block);if(s===-1||a===-1){const p=h=>{const f=(i.chrome??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));if(f!==-1)return i.children.length+f;const m=(i.notes??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));return m!==-1?i.children.length+(i.chrome?.length??0)+m:-1};if(s=p(t.block),a=p(e.block),s===-1||a===-1||t.block!==e.block&&(i.chrome??[]).some(h=>h.children.some(f=>f.id===t.block)))return!1}const c=t.block===e.block;if(c){const p=z(i,t.block);if(!p)return!1;if(this.suggestingMode&&p.type==="paragraph")return this.deleteSingleParagraphSelection(t,e,n,o);if(this.suggestingMode&&p.type==="list"){const f=p,m=this.listOperations.getListCursorInfo(f,t),y=this.listOperations.getListCursorInfo(f,e);if(m&&y&&m.itemIndex+1===y.itemIndex&&m.offsetInItem===this.listOperations.getListItemPlainText(f.children[m.itemIndex]).length&&y.offsetInItem===0){const b=Ct(),k=this.mergeAdjacentListItemsSnapshot(f,m.itemIndex,b);if(k){const v=this.suggestionEngine.runWithoutSuggesting(()=>this.updateBlockById(f.id,k,n,o));return v&&this.suggestionEngine.saveLiveSuggestion({id:b,type:"block-change",blockId:f.id,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(f),label:"Join"}),v}}}const h=$e().getHandlerForBlock(p);if(h&&h.handleDeleteSelection){const f=at(this.ydoc,p.id);if(!f)return!1;let m=!1;if(this.transact(()=>{m=!h.handleDeleteSelection(p,f,t,e),p.type==="paragraph"&&t.offset===0&&e.offset>=p.children.reduce((y,b)=>y+(b.type==="text"?b.text.length:0),0)&&br(p)&&mr(f,Qn(i,p,t))}),m){const y=gu(i,t.block),b=hu(i,t.block);let k;if(y&&y.id){const S=Ou(i,y.id);S?k=S:k={block:y.id,offset:0}}else if(b&&b.id)k={block:b.id,offset:0};else return!1;const v={anchor:k,focus:k};return this.deleteBlockById(t.block,n,v)}return this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}return p.type==="paragraph"?this.deleteSingleParagraphSelection(t,e,n,o):this.deleteBlockById(t.block,n,o)}if(this.suggestingMode&&!c&&this.suggestionEngine.deleteMultiParagraphSelectionAsSuggestion(t,e,s,a,o))return!0;const l=ke(i,t.block),d=ke(i,e.block),u=z(i,t.block),g=z(i,e.block);return l&&d&&l===d&&u?.type==="paragraph"&&g?.type==="paragraph"?this.mergeAdjacentParagraphs(u,g,t,e,l,n,o):this.deleteMultiBlockSelection(t,e,i,n,o)}mergeAdjacentParagraphs(t,e,n,o,i,s,a){const c=at(this.ydoc,t.id),l=at(this.ydoc,e.id);if(!c||!l)return console.error("[mergeAdjacentParagraphs] Could not find Y.js blocks"),!1;let d=null,u=null;for(let y=0;y<c.length;y++){const b=c.get(y);if(b instanceof x.XmlText){d=b;break}}for(let y=0;y<l.length;y++){const b=l.get(y);if(b instanceof x.XmlText){u=b;break}}if(!d||!u)return console.error("[mergeAdjacentParagraphs] Could not find Y.XmlText"),!1;const g=n.offset===d.length&&o.offset===0;if(g){const y=this.isPlainEmptyParagraph(t),b=this.isPlainEmptyParagraph(e),k=this.isInsertedParagraph(t),v=this.isInsertedParagraph(e);if(y&&v||k&&b){const S=y?t:e,I=y?e:t,w=y?0:this.getParagraphTextLength(I),A={block:I.id,offset:w},_={anchor:A,focus:A};return this.deleteBlockById(S.id,s,_)}}if(this.suggestingMode&&g){const y=this.getCancelableParagraphSplitRecord(t,e);if(y){const k=this.suggestionEngine.rejectLiveSuggestion(y.id);if(k){const v={block:y.blockId,offset:this.getParagraphTextLength(t)},S={anchor:v,focus:v};this.setSelectionAfterOperation(S),this.afterOperationRelativeSelection=J(S,this.ydoc,this.getDocument())}return k}const b=Ct();return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(c),this.suggestionEngine.clearParagraphStructuralSuggestion(l),this.suggestionEngine.setParagraphStructuralSuggestion(c,"merge","before",b),this.suggestionEngine.setParagraphStructuralSuggestion(l,"merge","after",b),this.suggestionEngine.saveLiveSuggestion({id:b,type:"paragraph-merge",firstBlockId:t.id,secondBlockId:e.id})}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=J(a,this.ydoc,this.getDocument()),!0}const p=ut(this.ydoc,t.id),h=ut(this.ydoc,e.id);if(!p||!h)return console.error("[mergeAdjacentParagraphs] Could not find Y.js parent"),!1;if(p.yParent!==h.yParent)return console.error("[mergeAdjacentParagraphs] Paragraphs have different Y.js parents"),!1;const f=p.index,m=h.index;return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(c);const y=d.length;n.offset<y&&d.delete(n.offset,y-n.offset);const b=mt(u).slice(0);let k=[],v=0;for(const w of b)if(typeof w.insert=="string"){const A=w.insert;if(v+A.length<=o.offset)v+=A.length;else if(v>=o.offset)k.push(w);else{const _=o.offset-v,B=A.slice(_);B.length>0&&k.push({...w,insert:B}),v+=A.length}}for(const w of k)typeof w.insert=="string"&&d.insert(d.length,w.insert,w.attributes||{});const{yParent:S}=p,I=m-f;I>0&&S.delete(f+1,I)}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=J(a,this.ydoc,this.getDocument()),!0}deleteMultiBlockSelection(t,e,n,o,i){const s=Xe(n,t.block),a=Xe(n,e.block);if(!s||!a)return!1;const c=z(n,t.block),l=z(n,e.block);if(!c||!l)return!1;const d=[];for(const{block:w,path:A}of pu(n)){const _=ln(A,s),B=ln(A,a);if(!(_<0)){if(B>0)break;d.push({block:w,path:A,isFirst:_===0,isLast:B===0})}}if(d.length===0)return!1;const u=s[0],g=a[0],p=n.children[u],h=n.children[g];if(u!==g&&p?.type==="list"&&h?.type==="list"&&this.listOperations.mergeAdjacentListsOnDelete(p,h,u,g,t,e,i))return!0;const f=d[0],m=d[d.length-1],y=f.block.type==="paragraph",b=m.block.type==="paragraph",k=ut(this.ydoc,f.block.id),v=ut(this.ydoc,m.block.id);if(!k||!v)return!1;const S=k.yBlock,I=v.yBlock;return this.transact(()=>{let w=null,A=null;y&&(w=xt(S)),b&&(A=xt(I));const _=y?t.offset:0,B=b?e.offset:0,P=d.length===2&&y&&b&&w!==null&&_===w.length&&B===0;let $="";const T={};if(b&&A){const C=mt(A);let N=0;for(const L of C)if(L.insert&&typeof L.insert=="string"){const R=L.insert.length;N>=B?($+=L.insert,L.attributes&&Object.assign(T,L.attributes)):N+R>B&&($+=L.insert.slice(B-N),L.attributes&&Object.assign(T,L.attributes)),N+=R}}if(y&&w&&_<w.length&&w.delete(_,w.length-_),P&&S instanceof x.XmlElement&&I instanceof x.XmlElement){const C=I.getAttribute("heading");C?S.setAttribute("heading",C):S.removeAttribute("heading");const N=bt(I,"align");N&&S.setAttribute("align",N);const L=bt(I,"lineSpacing");L?S.setAttribute("lineSpacing",L):rt(S,"lineSpacing"),fm(I,S,!0);const R=bt(I,"pagination");R?S.setAttribute("pagination",R):rt(S,"pagination");const M=bt(I,"tabStops");M?S.setAttribute("tabStops",M):rt(S,"tabStops");for(const D of["oxmlAttrs","oxmlPPr"]){const O=bt(I,D);O?S.setAttribute(D,O):rt(S,D)}const F=bt(I,"leftIndent");F?S.setAttribute("leftIndent",F):rt(S,"leftIndent");const j=bt(I,"firstLineIndent");j?S.setAttribute("firstLineIndent",j):rt(S,"firstLineIndent")}y&&w&&$?kt(w,w.length,$,T):!y&&b&&A&&B>0&&A.delete(0,Math.min(B,A.length));for(let C=d.length-1;C>=0;C--){const N=d[C],L=N.isFirst&&y,R=!y&&N.isLast&&b;if(L||R)continue;const M=ut(this.ydoc,N.block.id);if(M){const{yBlock:F,yParent:j,index:D}=M;if(j.length===1){if(N.block.type==="paragraph"){const O=ke(n,N.block.id);if(O?.type==="container"&&O.id){const q=ut(this.ydoc,O.id);if(q&&q.yParent.length>1){q.yParent.delete(q.index,1);continue}}const H=xt(F);H&&H.length>0&&H.delete(0,H.length)}else{j.delete(D,1);const O=new x.XmlElement("paragraph");O.setAttribute("id",et());const H=new x.XmlText;O.insert(0,[H]),j.insert(0,[O])}continue}j.delete(D,1)}}}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=J(i,this.ydoc,this.getDocument()),!0}deleteSingleParagraphSelection(t,e,n,o){const i=this.getDocument(),s=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i,t.block),a=this.getParagraphOffsetForPosition(t,i),c=this.getParagraphOffsetForPosition(e,i);if(!a||!c||!this.arePathsEqual(a.paragraphPath,c.paragraphPath))return!1;const l=this.getEmptyTextMarksForBlockId(t.block),d=Qn(i,a.paragraph,t,l);let u=null;this.transact(()=>{const p=at(this.ydoc,t.block);if(!(p instanceof x.XmlElement))return;let h=null;for(let f=0;f<p.length;f++){const m=p.get(f);if(m instanceof x.XmlText){h=m;break}}!h||a.paragraph.type!=="paragraph"||(this.suggestingMode&&!s?this.suggestionEngine.applySuggestedDeletionToTextRange(h,a.offset,c.offset-a.offset).retainedLength>0&&(u=this.normalizeAdjacentManualReplacementOrder(h,a.offset)):h.delete(a.offset,c.offset-a.offset),h.length===0&&mr(p,d))});const g=u?wl(o,t.block,u):o;return this.setSelectionAfterOperation(g),this.afterOperationRelativeSelection=J(g,this.ydoc,this.getDocument()),!0}deleteBlock(t,e,n){this.beforeOperationSelection=e;const o=this.getDocument();return o.children.length<=1?!1:(this.beforeOperationRelativeSelection=J(e,this.ydoc,o),this.transact(()=>{const i=this.getYContentFragment();t<i.length&&i.delete(t,1)}),this.afterOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),!0)}deleteBlockById(t,e,n){this.beforeOperationSelection=e;const o=this.getDocument(),i=z(o,t);if(!i)return!1;const s=ut(this.ydoc,t);if(!s)return!1;const{yBlock:a,yParent:c,index:l}=s;if(this.suggestingMode&&a instanceof x.XmlElement){const d=(i.type==="paragraph"||i.type==="list"?i.structuralSuggestionKind==="insert"?i.structuralSuggestionId:void 0:"diffState"in i&&i.diffState==="insert"&&"suggestionId"in i?i.suggestionId:void 0)??void 0;if(d&&this.suggestionEngine.getLiveSuggestion(d)?.type==="block-insert")return this.suggestionEngine.rejectLiveSuggestion(d);if(i.type==="paragraph"){const u=xt(a),g=u?.length??0;if(u&&g>0)return this.beforeOperationRelativeSelection=J(e,this.ydoc,o),this.transact(()=>{this.suggestionEngine.applySuggestedDeletionToTextRange(u,0,g)}),this.afterOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),!0}else{const u=Ct(),g=this.getTrailingCleanupParagraphIdForTopLevelBlock(o,t);return this.beforeOperationRelativeSelection=J(e,this.ydoc,o),this.transact(()=>{this.suggestionEngine.markDeletedBlockElement(a,u),this.suggestionEngine.saveLiveSuggestion({id:u,type:"block-delete",blockId:t,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(i),label:"Delete",cleanupTrailingParagraphId:g})}),this.afterOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),!0}}if(c.length===1){if(i.type==="paragraph"){const g=xt(a);return g&&g.length>0?(this.beforeOperationRelativeSelection=J(e,this.ydoc,o),this.transact(()=>{g.delete(0,g.length)}),this.afterOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),!0):!1}this.beforeOperationRelativeSelection=J(e,this.ydoc,o);const d=et();this.transact(()=>{c.delete(l,1);const g=new x.XmlElement("paragraph");g.setAttribute("id",d);const p=new x.XmlText;g.insert(0,[p]),c.insert(0,[g])});const u={anchor:{block:d,offset:0},focus:{block:d,offset:0}};return this.afterOperationRelativeSelection=J(u,this.ydoc,this.getDocument()),this.setSelectionAfterOperation(u),!0}return this.beforeOperationRelativeSelection=J(e,this.ydoc,o),this.transact(()=>{c.delete(l,1)}),this.afterOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),this.ensureTrailingParagraph(),!0}static splitBordersAttr(t){try{const e=JSON.parse(t),n=o=>{const i={};for(const s of o)e[s]!==void 0&&(i[s]=e[s]);return Object.keys(i).length>0?JSON.stringify(i):null};return{upper:n(["top","left","right"]),lower:n(["bottom","left","right"])}}catch{return{upper:t,lower:t}}}static isTailFullyDeletionMarked(t,e){if(!("children"in t)||!Array.isArray(t.children))return!1;let n=0,o=!1;for(const i of t.children){if(i.type!=="text")continue;const s=n+i.text.length;if(s>e&&i.text.length>0&&(o=!0,!i.marks?.deletion))return!1;n=s}return o}splitParagraph(t,e){this.beforeOperationSelection=e;const n=this.getDocument();this.beforeOperationRelativeSelection=J(e,this.ydoc,n);const o=z(n,t.block);if(!o)return null;let i=null;if(o.type==="list")return this.listOperations.splitListItem(t,e);if(o.type!=="paragraph")return null;if(this.suggestingMode){const B=this.getCancelableParagraphMergeRecord(o,t.offset);if(B&&this.suggestionEngine.rejectLiveSuggestion(B.id)){const P={anchor:t,focus:t};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=J(P,this.ydoc,this.getDocument()),t}}const s=ut(this.ydoc,t.block);if(!s)return null;const{yBlock:a,yParent:c,index:l}=s,d=o.structuralSuggestionId?this.suggestionEngine.getLiveSuggestion(o.structuralSuggestionId):void 0,u=d?.type==="block-change"&&d.sequenceBlockIds?d:null,g=this.getEmptyTextMarksForBlockId(t.block),p=t.offset,h=this.suggestionEngine.getStructuralInsertSuggestionIdAtPosition(n,t),f=o.children.reduce((B,P)=>P.type==="text"?B+P.text.length:B,0),m=this.suggestingMode&&p>0&&p<f&&sn.isTailFullyDeletionMarked(o,p),y=typeof h=="string"&&(p===0||p===f),b=typeof h=="string"&&p>0&&p<f,k=typeof h=="string",v=u?null:b?h:this.suggestingMode&&!y?Ct():null,S=b||this.suggestingMode&&!y&&(f===0||p===0||p===f||m),I=p===0&&!(S&&f===0),w=this.suggestingMode&&!k&&v;if(p===0){if(this.transact(()=>{i=et();const $=new x.XmlElement("paragraph");$.setAttribute("id",i);const T=a.getAttribute("heading"),C=a.getAttribute("styleId"),N=T!=null?!0:typeof C=="string"&&/^heading\d/i.test(C);Sc(a,$);const L=bt(a,"direction");if((L==="rtl"||L==="ltr")&&$.setAttribute("direction",L),!N){const j=bt(a,"align");j&&$.setAttribute("align",j);const D=a.getAttribute("styleId");D!=null&&$.setAttribute("styleId",D)}const R=bt(a,"borders");if(R!=null){const{upper:j,lower:D}=sn.splitBordersAttr(R);j?$.setAttribute("borders",j):rt($,"borders"),D?a.setAttribute("borders",D):rt(a,"borders")}const M=new x.XmlText,F=N?null:Qn(n,o,t,g);F&&$.setAttribute("_emptyTextMarks",JSON.stringify(F)),this.suggestionEngine.clearParagraphStructuralSuggestion(a),this.suggestionEngine.clearParagraphStructuralSuggestion($),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),v&&(S?this.suggestionEngine.setParagraphStructuralSuggestion($,"insert",void 0,v,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion($,"split","before",v),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","after",v))),$.insert(0,[M]),c.insert(I?l:l+1,[$]),u&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(u,[a,$]),N&&i&&this.applyStylesheetHeadingDefaults($,{type:"paragraph",id:i,heading:o.heading,styleId:o.styleId,children:[]},n,void 0)}),!i)return null;w&&v&&this.suggestionEngine.saveLiveSuggestion({id:v,type:"block-insert",blockId:i,label:"Insert"});const B={block:k?t.block:this.suggestingMode&&S?i:t.block,offset:0},P={anchor:B,focus:B};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=J(P,this.ydoc,this.getDocument()),B}if(this.transact(()=>{let B=null;for(let H=0;H<a.length;H++){const q=a.get(H);if(q instanceof x.XmlText){B=q;break}}if(!B||o.type!=="paragraph")return;const P=mt(B);let $=0;const T=[];if(!m){for(const H of P)if(H.insert&&typeof H.insert=="string"){const q=H.insert.length;if($+q<=p)$+=q;else if($>=p)T.push(H);else{const W=p-$,ct=H.insert.slice(W);ct&&T.push({insert:ct,...H.attributes&&{attributes:H.attributes}}),$=p}}p<B.length&&B.delete(p,B.length-p)}this.suggestionEngine.clearParagraphStructuralSuggestion(a),i=et();const C=new x.XmlElement("paragraph");C.setAttribute("id",i),Sc(a,C);const N=bt(a,"align");N&&C.setAttribute("align",N);const L=a.getAttribute("styleId");L!=null&&C.setAttribute("styleId",L);const R=bt(a,"direction");(R==="rtl"||R==="ltr")&&C.setAttribute("direction",R);const M=bt(a,"borders");if(M!=null){const{upper:H,lower:q}=sn.splitBordersAttr(M);q?C.setAttribute("borders",q):rt(C,"borders"),H?a.setAttribute("borders",H):rt(a,"borders")}const F=new x.XmlText,j=Qn(n,o,t,g),D=o.heading!==void 0&&Us(n.stylesheet)!==void 0;let O=null;if(D&&T.length>0){const H=n.stylesheet,q=(o.styleId?qs(H,o.styleId):void 0)??jr(H,o.heading),W=Us(H);O=zs(q?.runMarks,W?.runMarks)}if(T.length>0){let H=0;for(const q of T)if(q.insert&&typeof q.insert=="string"){let W=q.attributes||{};if(O){W={...W};for(const[ct,vt]of Object.entries(O))vt===!1||vt===void 0?delete W[ct]:W[ct]=vt}kt(F,H,q.insert,W),H+=q.insert.length}}else j&&C.setAttribute("_emptyTextMarks",JSON.stringify(j));this.suggestionEngine.clearParagraphStructuralSuggestion(C),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),v&&(S?this.suggestionEngine.setParagraphStructuralSuggestion(C,"insert",void 0,v,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(C,"split","after",v),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","before",v))),C.insert(0,[F]),c.insert(l+1,[C]),u&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(u,[a,C]),D&&i&&(this.applyStylesheetHeadingDefaults(C,{type:"paragraph",id:i,heading:o.heading,styleId:o.styleId,children:[]},n,void 0),T.length>0&&C.removeAttribute("_emptyTextMarks"))}),!i)return null;w&&v&&(S?this.suggestionEngine.saveLiveSuggestion({id:v,type:"block-insert",blockId:i,label:"Insert"}):this.suggestionEngine.saveLiveSuggestion({id:v,type:"paragraph-split",blockId:o.id,insertedBlockId:i,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(o)}));const A={block:i,offset:0},_={anchor:A,focus:A};return this.setSelectionAfterOperation(_),this.afterOperationRelativeSelection=J(_,this.ydoc,this.getDocument()),A}applyFormatting(t,e,n,o,i){this.beforeOperationSelection=o;const s=this.getDocument();this.beforeOperationRelativeSelection=J(o,this.ydoc,s);let a=!1,c=null;const l=[];return this.transact(()=>{const d=this.getYContentFragment(),u=this.collectInlineFormattingRanges(t,e,d,s);if(u.length===0)return;const g=this.suggestingMode?(()=>{let p=null;for(const h of u){if(!h.blockId)return null;const f=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(s,h.blockId);if(!f)return null;if(!p){p=f;continue}if(p!==f)return null}return p})():null;c=this.suggestingMode&&!g?Ct():null;t:for(const{yText:p,start:h,end:f}of u){const m=mt(p);let y=0;for(const b of m)if(b.insert&&typeof b.insert=="string"){const k=b.insert.length,v=y+k;if(y<f&&v>h&&!(b.attributes||{})[n]){a=!0;break t}y+=k}}for(const{yText:p,start:h,end:f,blockId:m,itemIndex:y}of u){const b=Math.max(0,f-h),k=this.suggestingMode&&c&&b>0?this.collectOverlappingTextSpans(p,h,b):[];if(this.suggestingMode&&c&&b>0&&m)for(const S of k)S.attributes?.insertion||S.attributes?.deletion||l.push({blockId:m,itemIndex:y,start:S.start,end:S.start+S.length,attributes:S.attributes});const v=n==="superscript"&&a?{superscript:!0,subscript:!1}:n==="subscript"&&a?{subscript:!0,superscript:!1}:{[n]:a};if(this.suggestingMode&&c&&b>0){const S=this.suggestionEngine.buildInlineSuggestionMetadataMarks(c,this.getFormattingDescriptionFromMarkKey(n));for(const I of k)I.attributes?.deletion||(It(p,I.start,I.length,v),!I.attributes?.insertion&&It(p,I.start,I.length,{formatChange:!0,...S,suggestionPriorAttributes:pr(I.attributes)}))}else It(p,h,b,v)}this.suggestingMode&&c&&l.length>0&&this.suggestionEngine.saveLiveSuggestion({id:c,type:"inline-format",label:this.getFormattingDescriptionFromMarkKey(n),spans:l})}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=J(i,this.ydoc,this.getDocument()),!0}formatRangesWithValue(t,e,n){if(!this.suggestingMode){for(const{yText:a,start:c,end:l}of t){const d=Math.max(0,l-c);d>0&&It(a,c,d,e)}return}const o=Ct(),i=this.suggestionEngine.buildInlineSuggestionMetadataMarks(o,n),s=[];for(const{yText:a,start:c,end:l,blockId:d,itemIndex:u}of t){const g=Math.max(0,l-c);if(g===0)continue;const p=this.collectOverlappingTextSpans(a,c,g);for(const h of p)h.attributes?.deletion||!Object.entries(e).some(([f,m])=>{const y=h.attributes?.[f];return m===!1||m===null?y!=null&&y!==!1:y!==m})||(It(a,h.start,h.length,e),!h.attributes?.insertion&&(It(a,h.start,h.length,{formatChange:!0,...i,suggestionPriorAttributes:pr(h.attributes)}),d&&s.push({blockId:d,itemIndex:u,start:h.start,end:h.start+h.length,attributes:h.attributes??{}})))}s.length>0&&this.suggestionEngine.saveLiveSuggestion({id:o,type:"inline-format",label:n,spans:s})}setFontFamily(t,e,n,o){this.beforeOperationSelection=o;const i=this.getDocument();return this.beforeOperationRelativeSelection=J(o,this.ydoc,i),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,s,i),c=qt(i,t,e)===0;if(a.length===0){c&&this.updateEmptyTextMarksAtPosition(t,"fontFamily",n,i);return}this.formatRangesWithValue(a,{fontFamily:n??!1},"Font"),c&&this.updateEmptyTextMarksAtPosition(t,"fontFamily",n,i)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}setFontSize(t,e,n,o){this.beforeOperationSelection=o;const i=this.getDocument();return this.beforeOperationRelativeSelection=J(o,this.ydoc,i),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,s,i),c=qt(i,t,e)===0;if(a.length===0){c&&this.updateEmptyTextMarksAtPosition(t,"fontSize",n,i);return}this.formatRangesWithValue(a,{fontSize:n??!1},"Font Size"),c&&this.updateEmptyTextMarksAtPosition(t,"fontSize",n,i)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}setLetterSpacing(t,e,n,o){this.beforeOperationSelection=o;const i=this.getDocument();return this.beforeOperationRelativeSelection=J(o,this.ydoc,i),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,s,i),c=qt(i,t,e)===0;if(a.length===0){c&&this.updateEmptyTextMarksAtPosition(t,"letterSpacing",n,i);return}this.formatRangesWithValue(a,{letterSpacing:n??!1},"Letter Spacing"),c&&this.updateEmptyTextMarksAtPosition(t,"letterSpacing",n,i)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}setTextColor(t,e,n,o){this.beforeOperationSelection=o;const i=this.getDocument();return this.beforeOperationRelativeSelection=J(o,this.ydoc,i),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,s,i),c=qt(i,t,e)===0;if(a.length===0){c&&this.updateEmptyTextMarksAtPosition(t,"color",n,i);return}this.formatRangesWithValue(a,{color:n??!1},"Text Color"),c&&this.updateEmptyTextMarksAtPosition(t,"color",n,i)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}setBackgroundColor(t,e,n,o){const i=Lu(n);this.beforeOperationSelection=o;const s=this.getDocument();return this.beforeOperationRelativeSelection=J(o,this.ydoc,s),this.transact(()=>{const a=this.getYContentFragment(),c=this.collectInlineFormattingRanges(t,e,a,s),l=qt(s,t,e)===0;if(c.length===0){l&&this.updateBackgroundColorEmptyMarksAtPosition(t,i,s);return}this.formatRangesWithValue(c,{backgroundColor:i??null},"Highlight"),l&&this.updateBackgroundColorEmptyMarksAtPosition(t,i,s)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}clearFormatting(t,e,n){this.beforeOperationSelection=n;const o=this.getDocument();this.beforeOperationRelativeSelection=J(n,this.ydoc,o);let i=!1;return this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,s,o),c=this.collectParagraphBlockIdsInRange(t,e,o);a.some(({start:l,end:d})=>d>l)&&(this.formatRangesWithValue(a,Vs,"Clear Formatting"),i=!0);for(const l of c){const d=at(this.ydoc,l);if(d)for(const u of Ks)bt(d,u)!==void 0&&(rt(d,u),i=!0)}qt(o,t,e)===0&&this.clearFormattingEmptyMarksAtPosition(t,o)&&(i=!0)}),this.setSelectionAfterOperation(n),this.afterOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),i}setLink(t,e,n,o){this.beforeOperationSelection=o;const i=this.getDocument();return this.beforeOperationRelativeSelection=J(o,this.ydoc,i),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,s,i);if(a.length===0)return;if(!this.suggestingMode){for(const{yText:l,start:d,end:u}of a){const g=Math.max(0,u-d);n?It(l,d,g,{link:n}):It(l,d,g,{link:!1})}return}const c=this.getPendingLinkSuggestionIdForRanges(a);if(c){if(!n&&!this.pendingLinkSuggestionHadPriorLink(a)){this.suggestionEngine.rejectLiveSuggestion(c);return}for(const{yText:l,start:d,end:u}of a){const g=Math.max(0,u-d);g!==0&&It(l,d,g,{link:n??!1})}return}this.formatRangesWithValue(a,{link:n??!1},"Link")}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}getPendingLinkSuggestionIdForRanges(t){let e=null;for(const{yText:n,start:o,end:i}of t){const s=Math.max(0,i-o);if(s!==0)for(const a of this.collectOverlappingTextSpans(n,o,s)){const c=a.attributes?.suggestionId;if(!a.attributes?.formatChange||!c)return null;const l=this.suggestionEngine.getLiveSuggestion(c);if(l?.type!=="inline-format"||l.label!=="Link"||e&&e!==c)return null;e=c}}return e}pendingLinkSuggestionHadPriorLink(t){for(const{yText:e,start:n,end:o}of t){const i=Math.max(0,o-n);if(i!==0)for(const s of this.collectOverlappingTextSpans(e,n,i)){const a=s.attributes?.suggestionPriorAttributes;if(typeof a=="string")try{if(JSON.parse(a).link)return!0}catch{}}}return!1}setCodeBlockLanguage(t,e){const n=this.getDocument(),o=z(n,t);if(!o||o.type!=="code")return!1;const i=n.children.findIndex(s=>s.id===t);return i===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(i);s instanceof x.XmlElement&&s.nodeName==="code"&&(e?(s.setAttribute("language",e),Nu(e)&&(s.getAttribute("renderDiagram")===null&&s.setAttribute("renderDiagram","true"),s.getAttribute("showDiagramSource")===null&&s.setAttribute("showDiagramSource","true"))):s.removeAttribute("language"))}),!0)}setCodeBlockRenderDiagram(t,e){const n=this.getDocument(),o=z(n,t);if(!o||o.type!=="code")return!1;const i=n.children.findIndex(s=>s.id===t);return i===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(i);s instanceof x.XmlElement&&s.nodeName==="code"&&(s.setAttribute("renderDiagram",String(e)),e&&s.getAttribute("showDiagramSource")===null&&s.setAttribute("showDiagramSource","true"))}),!0)}setCodeBlockShowDiagramSource(t,e){const n=this.getDocument(),o=z(n,t);if(!o||o.type!=="code")return!1;const i=n.children.findIndex(s=>s.id===t);return i===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(i);s instanceof x.XmlElement&&s.nodeName==="code"&&s.setAttribute("showDiagramSource",String(e))}),!0)}setMathBlockContent(t,e){const n=this.getDocument(),o=z(n,t);if(!o||o.type!=="math"&&!xn(o))return!1;const i=ut(this.ydoc,t);return i?(this.transact(()=>{const s=i.yBlock;if(!(s instanceof x.XmlElement))return;const a=xn(o)?"code":"math";if(s.nodeName!==a)return;let c=s.get(0);c instanceof x.XmlText||(c=new x.XmlText,s.insert(0,[c]));const l=c.length;l>0&&c.delete(0,l),c.insert(0,e)}),!0):!1}setMathBlockDisplayMode(t,e){const n=this.getDocument(),o=z(n,t);if(!o||o.type!=="math"&&!xn(o))return!1;const i=ut(this.ydoc,t);return i?(this.transact(()=>{const s=i.yBlock;if(s instanceof x.XmlElement){if(xn(o)&&s.nodeName==="code"){const a=e==="inline"?"latex-inline":"latex";s.setAttribute("language",a),s.getAttribute("renderDiagram")===null&&s.setAttribute("renderDiagram","true"),s.getAttribute("showDiagramSource")===null&&s.setAttribute("showDiagramSource","true");return}s.nodeName==="math"&&s.setAttribute("displayMode",e)}}),!0):!1}setMathBlockAlign(t,e){const n=this.getDocument(),o=z(n,t);if(!o||o.type!=="math"&&!xn(o))return!1;if(xn(o))return!0;const i=n.children.findIndex(s=>s.id===t);return i===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(i);s instanceof x.XmlElement&&s.nodeName==="math"&&s.setAttribute("align",e)}),!0)}replaceParagraph(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();return this.beforeOperationRelativeSelection=J(n,this.ydoc,i),t<0||t>=i.children.length?!1:(i.children[t],this.transact(()=>{const s=this.getYContentFragment(),a=s.get(t),c=a instanceof x.XmlElement?a.getAttribute("id"):void 0,l=new x.XmlElement("paragraph");l.setAttribute("id",e.id||c||et()),e.heading&&l.setAttribute("heading",String(e.heading)),e.align&&l.setAttribute("align",e.align),e.lineSpacing!==void 0&&l.setAttribute("lineSpacing",String(e.lineSpacing)),Zn(l,e);{const h=xe(e);h!==void 0&&l.setAttribute("pagination",h)}e.styleId!==void 0&&l.setAttribute("styleId",e.styleId),e.direction!==void 0&&l.setAttribute("direction",e.direction),e.tabStops!==void 0&&l.setAttribute("tabStops",e.tabStops),e.borders!==void 0&&l.setAttribute("borders",e.borders),e.shading!==void 0&&l.setAttribute("shading",e.shading),e.oxmlAttrs!==void 0&&l.setAttribute("oxmlAttrs",e.oxmlAttrs),e.oxmlPPr!==void 0&&l.setAttribute("oxmlPPr",e.oxmlPPr);const d=le(e.leftIndent);d!==void 0&&l.setAttribute("leftIndent",String(d));const u=de(e.firstLineIndent);u!==void 0&&l.setAttribute("firstLineIndent",String(u));const g=new x.XmlText;let p=0;e.children.forEach(h=>{if(h.type==="text"){const f={...h.marks||{}};kt(g,p,h.text,f),p+=h.text.length}}),l.insert(0,[g]),s.delete(t,1),s.insert(t,[l])}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0)}pasteParagraphsAsSuggestions(t,e,n,o){let i={block:t.block,offset:t.offset},s={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null},a=!1;const c=()=>{const d=this.getAfterOperationSelection();return d?.focus?{block:d.focus.block,offset:d.focus.offset}:null};let l=null;if(this.transact(()=>{for(let d=0;d<e.length;d++){if(d>0){const u=this.splitParagraph(i,{anchor:i,focus:i});if(!u)return;i=u,s={anchor:i,focus:i}}for(const u of e[d].children){if(u.type!=="text"||u.text.length===0)continue;const g=this.suggestionEngine.stripSuggestionMarksFromTextMark(u.marks)??{};if(!this.insertFormattedText(i,u.text,g,s,{anchor:i,focus:i},o))return;a=!0;const p=c();p&&(i=p),s={anchor:i,focus:i}}}l=i}),!a&&!l)return null;if(l){const d={anchor:l,focus:l};this.setSelectionAfterOperation(d),this.afterOperationRelativeSelection=J(d,this.ydoc,this.getDocument())}return l}pasteParagraphs(t,e,n,o={}){if(e.length===0||!e.some(b=>b.children.some(k=>k.type==="text"&&k.text.length>0)))return null;const i=Ue(Dr(this.getDocument(),t,n)?.marks);if(i?.fontFamily===ae&&delete i.fontFamily,i&&(e=e.map(b=>b.type==="paragraph"?{...b,children:b.children.map(k=>k.type==="text"?{...k,marks:{...i,...k.marks??{}}}:k)}:b)),this.suggestingMode)return this.pasteParagraphsAsSuggestions(t,e,n,o.suggestionIdOverride);this.beforeOperationSelection={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null};const s=this.getDocument();this.beforeOperationRelativeSelection=J(n,this.ydoc,s);let a=null;const c=o.preserveStructure===!0&&e.length>1;let l,d=null,u=null,g=null,p=!1,h=null,f=null;const m=b=>{if(!b.id)return null;let k=0;for(const v of b.children)v.type==="text"&&(k+=v.text.length);return{block:b.id,offset:k}},y=b=>b.id?b:{...b,id:et()};try{this.transact(()=>{const k=n.anchor&&n.focus&&qt(s,n.anchor,n.focus)!==0;let v={block:t.block,offset:t.offset};if(k&&n.anchor&&n.focus){const O={block:t.block,offset:t.offset},H=n.anchor.block===O.block&&n.anchor.offset===O.offset,q=n.focus.block===O.block&&n.focus.offset===O.offset,W=O,ct=H?{block:n.focus.block,offset:n.focus.offset}:q?{block:n.anchor.block,offset:n.anchor.offset}:qt(s,n.anchor,n.focus)<=0?{block:n.focus.block,offset:n.focus.offset}:{block:n.anchor.block,offset:n.anchor.offset},vt=this.getParagraphOffsetForPosition(W,s),Dt=this.getParagraphOffsetForPosition(ct,s);vt&&Dt&&this.arePathsEqual(vt.paragraphPath,Dt.paragraphPath)&&(d=Dt.offset);const Qt=vt?.offset??W.offset;this.deleteSelection({block:W.block,offset:W.offset},{block:ct.block,offset:ct.offset},{anchor:n.anchor?{block:n.anchor.block,offset:n.anchor.offset}:null,focus:n.focus?{block:n.focus.block,offset:n.focus.offset}:null},{anchor:{block:W.block,offset:W.offset},focus:{block:W.block,offset:W.offset}});const Vt=this.getDocument(),G=z(Vt,W.block);(G?.type==="paragraph"||G?.type==="list")&&G.id&&(v={block:G.id,offset:Qt})}const S=d!==null?s:this.getDocument(),I=this.getBlockContextById(S,v.block);if(!I){a=null;return}if(I.block.type==="list"){const O=e[0],H=O.children.filter(q=>q.type==="text").map(q=>q.text).join("");if(H){const q=O.children.find(ct=>ct.type==="text")?.marks||null,W=this.listOperations.insertTextInListItem(v,H,q);W&&(a=W)}return}if(I.block.type!=="paragraph"){a=null;return}const w=I.block;if(!w||w.type!=="paragraph"){a=null;return}const A=[],_=this.getParagraphOffsetForPosition(v,S)?.offset??0,B=d??_;let P=0;for(let O=0;O<w.children.length;O++){const H=w.children[O];if(H.type==="text"){const q=P;if(P+H.text.length>B){const W=Math.max(0,B-q);W<H.text.length&&A.push({type:"text",text:H.text.substring(W),marks:H.marks})}P+=H.text.length}}const $=A.length>0&&A.some(O=>O.text.length>0);if(p=$,$){let O=0;for(const q of w.children)q.type==="text"&&(O+=q.text.length);const H={block:w.id,offset:O};this.deleteSelection(v,H,{anchor:v,focus:H},{anchor:v,focus:v})}const T=e[0],C=at(this.ydoc,v.block);if(!C){a=null;return}const N=xt(C);if(!N){a=null;return}if(N.length===0&&T.type==="paragraph"){T.heading!==void 0?C.setAttribute("heading",String(T.heading)):C.removeAttribute("heading"),T.align?C.setAttribute("align",T.align):rt(C,"align"),T.lineSpacing!==void 0?C.setAttribute("lineSpacing",String(T.lineSpacing)):rt(C,"lineSpacing");for(const q of pl)rt(C,q);Zn(C,T);{const q=xe(T);q!==void 0?C.setAttribute("pagination",q):rt(C,"pagination")}T.styleId!==void 0?C.setAttribute("styleId",T.styleId):C.removeAttribute("styleId"),T.direction!==void 0?C.setAttribute("direction",T.direction):rt(C,"direction"),T.tabStops!==void 0?C.setAttribute("tabStops",T.tabStops):rt(C,"tabStops"),T.borders!==void 0?C.setAttribute("borders",T.borders):rt(C,"borders"),T.shading!==void 0?C.setAttribute("shading",T.shading):rt(C,"shading");const O=le(T.leftIndent);O!==void 0?C.setAttribute("leftIndent",String(O)):rt(C,"leftIndent");const H=de(T.firstLineIndent);H!==void 0?C.setAttribute("firstLineIndent",String(H)):rt(C,"firstLineIndent")}const L=T.children.filter(O=>O.type==="text"),R=this.insertTextNodes(v,L);if(!R){a=null;return}if(u=R,a=R,e.length===1&&!$){g=R.block;return}const M=ut(this.ydoc,v.block);if(!M)return;const F=M.yParent;let j=M.index+1;if(c){const O=[];let H=null;for(let q=1;q<e.length;q++){const W=y(e[q]);this.insertParagraphInternal(j,W,F),O.push(W.id),j++}if($){const q={type:"paragraph",id:et(),children:A.map(vt=>({type:"text",text:vt.text,marks:vt.marks?{...vt.marks}:void 0}))};w.heading!==void 0&&(q.heading=w.heading),w.align&&(q.align=w.align),w.direction!==void 0&&(q.direction=w.direction),w.tabStops!==void 0&&(q.tabStops=w.tabStops),w.lineSpacing!==void 0&&(q.lineSpacing=w.lineSpacing),w.spaceBefore!==void 0&&(q.spaceBefore=w.spaceBefore),w.spaceAfter!==void 0&&(q.spaceAfter=w.spaceAfter),w.contextualSpacing!==void 0&&(q.contextualSpacing=w.contextualSpacing),w.keepNext!==void 0&&(q.keepNext=w.keepNext),w.keepLines!==void 0&&(q.keepLines=w.keepLines),w.widowControl!==void 0&&(q.widowControl=w.widowControl);const W=le(w.leftIndent);W!==void 0&&(q.leftIndent=W);const ct=de(w.firstLineIndent);ct!==void 0&&(q.firstLineIndent=ct),this.insertParagraphInternal(j,q,F),H=q.id,j++}l={insertedParagraphIds:O,remainderParagraphId:H};return}let D=v.block;for(let O=1;O<e.length;O++){const H=y(e[O]);this.insertParagraphInternal(j,H,F),D=H.id,j++}if(g=D,$){const O=e.length>1?F.get(j-1):C;if(O instanceof x.XmlElement){let H=null;for(let q=0;q<O.length;q++){const W=O.get(q);if(W instanceof x.XmlText){H=W;break}}if(H){let q=H.length;h=q,f=D;for(const W of A){if(!W.text.length)continue;const ct={...W.marks||{}};H.insert(q,W.text,ct),q+=W.text.length}}}}});const b=this.getDocument();if(c&&l){const{insertedParagraphIds:k,remainderParagraphId:v}=l;if(k.length>0){const S=k[k.length-1],I=z(b,S);I&&I.type==="paragraph"?a=m(I):a={block:S,offset:0}}else if(v!==null){const S=z(b,v);S&&S.type==="paragraph"?a=m(S):a={block:v,offset:0}}else u&&(a=u)}else if(!c)if(p&&f!==null&&h!==null)a={block:f,offset:h};else if(p&&u)a=u;else if(g!==null){const k=z(b,g);k&&k.type==="paragraph"?a=m(k):u?a=u:a={block:g,offset:0}}else u&&(a=u);!a&&u&&(a=u)}catch(b){return console.error("Error in pasteParagraphs:",b),null}return a||(a=u??t),a&&(a=this.normalizeCursorPosition(a),this.setSelectionAfterOperation({anchor:a,focus:a}),this.updateAfterOperationRelativeSelection(this.getDocument())),a}normalizeCursorPosition(t){return this.getDocument().children.length,t}replaceDocument(t){return this.undoManager.stopCapturing(),this.transact(()=>{const e=this.getYContentFragment();e.length>0&&e.delete(0,e.length),t.children.forEach(n=>{if(n.type==="placeholder"){const o=new x.XmlElement("placeholder");o.setAttribute("id",n.id||et()),o.setAttribute("height",String(n.height)),e.push([o])}else if(n.type==="image"){const o=n,i=new x.XmlElement("image");i.setAttribute("id",n.id||et()),i.setAttribute("src",o.src),o.sourceUrl&&i.setAttribute("sourceUrl",o.sourceUrl),i.setAttribute("width",String(o.width)),i.setAttribute("height",String(o.height)),o.alt&&i.setAttribute("alt",o.alt),e.push([i])}else if(n.type==="paragraph"){const o=new x.XmlElement("paragraph");o.setAttribute("id",n.id||et()),n.heading&&o.setAttribute("heading",String(n.heading)),n.align&&o.setAttribute("align",n.align),n.lineSpacing!==void 0&&o.setAttribute("lineSpacing",String(n.lineSpacing)),Zn(o,n);{const l=xe(n);l!==void 0&&o.setAttribute("pagination",l)}n.styleId!==void 0&&o.setAttribute("styleId",n.styleId),n.direction!==void 0&&o.setAttribute("direction",n.direction),n.tabStops!==void 0&&o.setAttribute("tabStops",n.tabStops),n.borders!==void 0&&o.setAttribute("borders",n.borders),n.shading!==void 0&&o.setAttribute("shading",n.shading);const i=le(n.leftIndent);i!==void 0&&o.setAttribute("leftIndent",String(i));const s=de(n.firstLineIndent);s!==void 0&&o.setAttribute("firstLineIndent",String(s));const a=new x.XmlText;let c=0;n.children.forEach(l=>{if(l.type==="text"){const d={...l.marks||{}};kt(a,c,l.text,d),c+=l.text.length}}),o.insert(0,[a]),e.push([o])}else if(n.type==="list"){const o=n,i=new x.XmlElement("list");i.setAttribute("id",n.id||et()),i.setAttribute("variant",o.variant),o.startNumber!==void 0&&i.setAttribute("startNumber",String(o.startNumber)),o.numberingChainId&&i.setAttribute("numberingChainId",o.numberingChainId),o.numberingFormat&&i.setAttribute("numberingFormat",o.numberingFormat),o.children.forEach(s=>{const a=new x.XmlElement("list-item");cn(a,s),a.setAttribute("id",s.id||et()),o.variant==="todo"&&a.setAttribute("checked",String(s.checked??!1)),s.indentLevel!==void 0&&s.indentLevel>0&&a.setAttribute("indentLevel",String(s.indentLevel)),s.direction!==void 0&&a.setAttribute("direction",s.direction);const c=new x.XmlText;let l=0;s.children.forEach(d=>{if(d.type==="text"){const u={...d.marks||{}};c.insert(l,d.text,u),l+=d.text.length}}),a.insert(0,[c]),i.push([a])}),e.push([i])}})}),this.undoManager.clear(),!0}alignNormalizationDirection(t,e){const n=t?.type==="paragraph"?t:void 0,o=Object.prototype.hasOwnProperty.call(e,"direction")?e.direction??void 0:n?.direction;let i="";if(n)for(const s of n.children)i+=s.text??"";return Fu(o,i)}updateParagraphAttributes(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();if(this.beforeOperationRelativeSelection=J(n,this.ydoc,i),t<0||t>=i.children.length)return!1;(Object.prototype.hasOwnProperty.call(e,"leftIndent")||Object.prototype.hasOwnProperty.call(e,"firstLineIndent"))&&this.ensureParagraphIndentStorageUsesUnits();const s=this.alignNormalizationDirection(i.children[t],e);return this.transact(()=>{const a=this.getYContentFragment().get(t);if(a instanceof x.XmlElement){if(Object.prototype.hasOwnProperty.call(e,"align")&&(e.align===void 0||e.align==="left"&&s==="ltr"?rt(a,"align"):a.setAttribute("align",e.align)),Object.prototype.hasOwnProperty.call(e,"heading")){e.heading===void 0?a.removeAttribute("heading"):a.setAttribute("heading",String(e.heading));const c=i.children[t];c&&!this.applyStylesheetHeadingDefaults(a,c,i,e.heading)&&this.clearFontSizeMarksForHeadingChange(c,i)}if(Object.prototype.hasOwnProperty.call(e,"lineSpacing")&&(e.lineSpacing===void 0?rt(a,"lineSpacing"):a.setAttribute("lineSpacing",String(e.lineSpacing))),Object.prototype.hasOwnProperty.call(e,"styleId")&&(e.styleId===null||e.styleId===void 0?a.removeAttribute("styleId"):a.setAttribute("styleId",e.styleId)),Object.prototype.hasOwnProperty.call(e,"direction")&&(e.direction===null||e.direction===void 0?rt(a,"direction"):a.setAttribute("direction",e.direction)),Object.prototype.hasOwnProperty.call(e,"tabStops")&&(e.tabStops===null||e.tabStops===void 0?rt(a,"tabStops"):a.setAttribute("tabStops",e.tabStops)),Object.prototype.hasOwnProperty.call(e,"borders")&&(e.borders===null||e.borders===void 0?rt(a,"borders"):a.setAttribute("borders",e.borders)),Object.prototype.hasOwnProperty.call(e,"shading")&&(e.shading===null||e.shading===void 0?rt(a,"shading"):a.setAttribute("shading",e.shading)),Object.prototype.hasOwnProperty.call(e,"keepNext")||Object.prototype.hasOwnProperty.call(e,"keepLines")||Object.prototype.hasOwnProperty.call(e,"widowControl")){const c={};Nr(c,bt(a,"pagination"));for(const d of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(e,d)&&(e[d]===void 0?delete c[d]:c[d]=e[d]);const l=xe(c);l===void 0?rt(a,"pagination"):a.setAttribute("pagination",l)}if(Object.prototype.hasOwnProperty.call(e,"leftIndent")){const c=le(e.leftIndent);c===void 0?rt(a,"leftIndent"):a.setAttribute("leftIndent",String(c))}if(Object.prototype.hasOwnProperty.call(e,"firstLineIndent")){const c=de(e.firstLineIndent);c===void 0?rt(a,"firstLineIndent"):a.setAttribute("firstLineIndent",String(c))}}}),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}applyStylesheetHeadingDefaults(t,e,n,o){if(e.type!=="paragraph"||!e.id)return!1;const i=n.stylesheet,s=jr(i,o);if(!i||!s)return!1;const a=(e.styleId?qs(i,e.styleId):void 0)??jr(i,e.heading);o!==void 0&&s.styleId.toLowerCase()!=="normal"?t.setAttribute("styleId",s.styleId):t.removeAttribute("styleId");const c=a?.paragraphAttrs??{},l=s.paragraphAttrs??{},d=(f,m)=>Object.prototype.hasOwnProperty.call(f,m),u=["align","lineSpacing","spaceBefore","spaceAfter","contextualSpacing","leftIndent","firstLineIndent","direction","borders","shading","tabStops"];(d(l,"leftIndent")||d(l,"firstLineIndent"))&&(l.leftIndent!==void 0||l.firstLineIndent!==void 0)&&this.ensureParagraphIndentStorageUsesUnits();for(const f of u){if(!d(c,f)&&!d(l,f))continue;const m=l[f];m===void 0||m===!1?rt(t,f):t.setAttribute(f,String(m))}const g=["keepNext","keepLines","widowControl"];if(g.some(f=>d(c,f)||d(l,f))){const f={};Nr(f,bt(t,"pagination"));for(const y of g)!d(c,y)&&!d(l,y)||(l[y]===void 0?delete f[y]:f[y]=l[y]);const m=xe(f);m===void 0?rt(t,"pagination"):t.setAttribute("pagination",m)}const p=zs(a?.runMarks,s.runMarks),h=e.children.reduce((f,m)=>m.type==="text"?f+m.text.length:f,0);if(h>0){const f=this.getYContentFragment(),m=this.collectInlineFormattingRanges({block:e.id,offset:0},{block:e.id,offset:h},f,n);for(const{yText:y,start:b,end:k}of m){const v=Math.max(0,k-b);v>0&&It(y,b,v,p)}}else mr(t,s.runMarks);return!0}clearFontSizeMarksForHeadingChange(t,e){if(t.type!=="paragraph"||!t.id)return;const n=t.children.reduce((s,a)=>a.type==="text"?s+a.text.length:s,0);if(!t.children.some(s=>s.type==="text"&&s.marks?.fontSize!==void 0))return;if(n===0){this.updateEmptyTextMarksAtPosition({block:t.id,offset:0},"fontSize",void 0,e);return}const o=this.getYContentFragment(),i=this.collectInlineFormattingRanges({block:t.id,offset:0},{block:t.id,offset:n},o,e);for(const{yText:s,start:a,end:c}of i){const l=Math.max(0,c-a);l>0&&It(s,a,l,{fontSize:!1})}}updateParagraphAttributesById(t,e,n,o){const i=z(this.getDocument(),t);if(!i||i.type!=="paragraph"&&i.type!=="list")return!1;const s=at(this.ydoc,t);if(!s)return!1;this.beforeOperationSelection=n;const a=this.getDocument();this.beforeOperationRelativeSelection=J(n,this.ydoc,a);const c=Object.prototype.hasOwnProperty.call(e,"leftIndent")||Object.prototype.hasOwnProperty.call(e,"firstLineIndent"),l=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,t),d=this.suggestingMode&&!l?Ct():null;c&&this.ensureParagraphIndentStorageUsesUnits();const u=this.alignNormalizationDirection(z(a,t)??void 0,e);return this.transact(()=>{if(Object.prototype.hasOwnProperty.call(e,"align")&&(e.align===void 0||e.align==="left"&&u==="ltr"?rt(s,"align"):s.setAttribute("align",e.align)),Object.prototype.hasOwnProperty.call(e,"heading")&&(e.heading===void 0?s.removeAttribute("heading"):s.setAttribute("heading",String(e.heading)),this.applyStylesheetHeadingDefaults(s,i,a,e.heading)||this.clearFontSizeMarksForHeadingChange(i,a)),Object.prototype.hasOwnProperty.call(e,"lineSpacing")&&(e.lineSpacing===void 0?rt(s,"lineSpacing"):s.setAttribute("lineSpacing",String(e.lineSpacing))),Object.prototype.hasOwnProperty.call(e,"styleId")&&(e.styleId===null||e.styleId===void 0?s.removeAttribute("styleId"):s.setAttribute("styleId",e.styleId)),Object.prototype.hasOwnProperty.call(e,"direction")&&(e.direction===null||e.direction===void 0?rt(s,"direction"):s.setAttribute("direction",e.direction)),Object.prototype.hasOwnProperty.call(e,"tabStops")&&(e.tabStops===null||e.tabStops===void 0?rt(s,"tabStops"):s.setAttribute("tabStops",e.tabStops)),Object.prototype.hasOwnProperty.call(e,"borders")&&(e.borders===null||e.borders===void 0?rt(s,"borders"):s.setAttribute("borders",e.borders)),Object.prototype.hasOwnProperty.call(e,"shading")&&(e.shading===null||e.shading===void 0?rt(s,"shading"):s.setAttribute("shading",e.shading)),Object.prototype.hasOwnProperty.call(e,"keepNext")||Object.prototype.hasOwnProperty.call(e,"keepLines")||Object.prototype.hasOwnProperty.call(e,"widowControl")){const g={};Nr(g,bt(s,"pagination"));for(const h of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(e,h)&&(e[h]===void 0?delete g[h]:g[h]=e[h]);const p=xe(g);p===void 0?rt(s,"pagination"):s.setAttribute("pagination",p)}if(Object.prototype.hasOwnProperty.call(e,"leftIndent")){const g=le(e.leftIndent);g===void 0?rt(s,"leftIndent"):s.setAttribute("leftIndent",String(g))}if(Object.prototype.hasOwnProperty.call(e,"firstLineIndent")){const g=de(e.firstLineIndent);g===void 0?rt(s,"firstLineIndent"):s.setAttribute("firstLineIndent",String(g))}this.suggestingMode&&d&&(this.suggestionEngine.clearElementStructuralSuggestion(s),this.suggestionEngine.setElementStructuralSuggestion(s,"change",void 0,d,"Format"),this.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:t,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(i),label:"Format"}))}),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}updateTocAttributesById(t,e,n,o){const i=z(this.getDocument(),t);if(!i||i.type!=="toc")return!1;const s=at(this.ydoc,t);return s?(this.beforeOperationSelection=n,this.beforeOperationRelativeSelection=J(n,this.ydoc,this.getDocument()),this.transact(()=>{Object.prototype.hasOwnProperty.call(e,"fontFamily")&&(e.fontFamily==null||e.fontFamily===""?s.removeAttribute("fontFamily"):s.setAttribute("fontFamily",e.fontFamily)),Object.prototype.hasOwnProperty.call(e,"fontSize")&&(e.fontSize==null?s.removeAttribute("fontSize"):s.setAttribute("fontSize",String(e.fontSize))),Object.prototype.hasOwnProperty.call(e,"color")&&(e.color==null||e.color===""?s.removeAttribute("color"):s.setAttribute("color",e.color))}),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0):!1}beginGroup(t){this.batchingUpdates=!0,this.pendingUpdate=null}endGroup(){if(this.undoManager.stopCapturing(),this.batchingUpdates=!1,this.pendingUpdate){const t=this.pendingUpdate;this.pendingUpdate=null,t()}}getHistoryInfo(){return{undoStackSize:this.undoManager.undoStack.length,redoStackSize:this.undoManager.redoStack.length}}clearHistory(){this.undoManager.clear()}extractTextNodesForRange(t,e,n){if(n<=e)return[];const o=[];let i=0;for(const s of t.children){if(s.type!=="text")continue;const a=i,c=i+s.text.length,l=Math.max(e,a),d=Math.min(n,c);if(l<d&&o.push({type:"text",text:s.text.slice(l-a,d-a),marks:this.suggestionEngine.sanitizePreviewMarks(s.marks)}),i=c,i>=n)break}return o}buildParagraphReplacementLiveBlock(t,e,n,o){const i=(u,g)=>u.map(p=>{const h=this.suggestionEngine.sanitizePreviewMarks(p.marks)??{};return delete h.deletion,delete h.insertion,delete h.formatChange,{type:"text",text:p.text,marks:{...h,[g]:!0,suggestionId:n}}}),s=i(t.children,"deletion"),a=i(e.children,"insertion"),c=s.map(u=>u.text).join(""),l=a.map(u=>u.text).join(""),d=c.length>0&&l.length>0&&!/\s$/.test(c)&&!/^\s/.test(l);return{...e,children:[...s,...d?[{type:"text",text:" "}]:[],...a],structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:o}}canBridgeListItemChangeAsInline(t,e){return mo.every(n=>t[n]===e[n])&&t.direction===e.direction&&(t.checked??!1)===(e.checked??!1)&&(t.indentLevel??0)===(e.indentLevel??0)}replaceBlockByIdWithoutSelection(t,e,n){const o=n?n.yBlock._item:null,i=n&&!o?.deleted&&n.yParent.get(n.index)===n.yBlock,s=i?null:ut(this.ydoc,t),a=i?n.yParent:s?.yParent,c=i?n.index:s?.index;return!a||c===void 0?!1:(this.transact(()=>{const l=a.get(c);if(e.type==="list"&&l instanceof x.XmlElement&&l.nodeName==="list"){Wi(l,e);return}const d=this.blockToYjsElement(e);a.delete(c,1),a.insert(c,[d])}),!0)}paragraphReplaceShouldStayAtomic(t,e){return!Mn(t,e)}resolvePositionAwareInsertionReference(t){const e=[...t.mustBeAfter].reverse().find(i=>typeof i=="string"&&i.length>0);if(e)return{referenceId:e,position:"after"};const n=t.mustBeBefore.find(i=>typeof i=="string"&&i.length>0);if(n)return{referenceId:n,position:"before"};const o=t.baseDoc.children[0]?.id;return o?{referenceId:o,position:"before"}:t.baseDoc.children.length===0?{referenceId:Rn,position:"after"}:null}tryCancelInsertedBlockForRemoveAction(t,e){if(!t?.length)return null;const n=t.length===1?t[0]:void 0,o=n?.arguments;if(n?.name==="remove_block"&&typeof o?.count=="number"&&Number.isInteger(o.count)&&o.count>1){const l=e.children.findIndex(d=>d.id===o.id);if(l<0||l+o.count>e.children.length)return null;t=e.children.slice(l,l+o.count).map(d=>({name:"remove_block",arguments:{id:d.id}}))}const i=this.getDocument(),s=new Set,a=new Set,c=new Set;for(const l of t){if(l.name!=="remove_block")return null;const d=l.arguments;if(typeof d?.id!="string"||d.count!==void 0&&d.count!==1)return null;const u=z(i,d.id)??z(e,d.id),g=this.suggestionEngine.getBlockInsertSuggestionIdForBlock(u),p=g?this.suggestionEngine.getLiveSuggestion(g):void 0;if(!u)return null;if(s.add(d.id),!g){c.add(d.id);continue}if(p?.type!=="block-insert")return null;a.add(g)}for(const l of a){const d=this.suggestionEngine.getLiveSuggestion(l);d?.type==="block-insert"&&d.cleanupTrailingParagraphId&&c.delete(d.cleanupTrailingParagraphId)}if(c.size>0||a.size===0)return null;for(const l of a)if(this.collectStructuralInsertBlockIds(i,l).some(d=>!s.has(d)))return null;return this.suggestionEngine.rejectLiveSuggestions([...a])===0?null:{success:!0,planningSuggestionIds:[],agentFeedback:`Removed pending inserted block${s.size===1?"":"s"} ${[...s].join(", ")}.`}}getActionTargetBlockIds(t,e){if(!t)return[];const n=new Set;for(const o of t){const i=o.arguments&&typeof o.arguments=="object"?o.arguments:null;if(!i||typeof i.id!="string"||i.id.length===0)continue;const s=i.id;if(n.add(s),o.name!=="replace_block")continue;const a=typeof i.count=="number"&&Number.isFinite(i.count)?Math.max(1,Math.floor(i.count)):1;if(a<=1)continue;const c=ee(e,s);if(!(c<0))for(let l=c+1;l<Math.min(e.children.length,c+a);l++){const d=e.children[l]?.id;d&&n.add(d)}}return Array.from(n)}applyAgentActions(t,e,n){e||(e="default-"+Date.now());const o=(t.actions??[]).filter(a=>a.name==="insert_footnote");if(o.length>0){const a=[];for(const d of o){const u=d.arguments??{},g=u.id??"";let p;try{p=tg(this,g,u.find??"")}catch(f){return{success:!1,error:f instanceof Error?f.message:String(f),failure:Ln(f)}}const h=this.suggestingMode;this.suggestingMode=!0;try{const{result:f}=this.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:u.kind==="endnote"?"Insert endnote":"Insert footnote",agentName:t.agentName??Ae,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,historyOrigin:`live-suggestions:${e}`},()=>this.insertFootnote(p,u.text??"",{anchor:p,focus:p},u.kind==="endnote"?"endnote":"footnote"));if(!f)return{success:!1,error:"insert_footnote: failed to insert"};f.suggestionId&&a.push(f.suggestionId)}finally{this.suggestingMode=h}}const c={...t,actions:(t.actions??[]).filter(d=>d.name!=="insert_footnote")};if(c.actions.length===0)return{success:!0,suggestionIds:a};const l=this.applyAgentActions(c,e,n);return l.success&&(l.suggestionIds=[...l.suggestionIds??[],...a]),l}this.detachedSuggestionStore.getPendingSuggestions().size===0&&this.toolCallHistory.getAllToolCalls().length>0&&this.toolCallHistory.clear();let i;try{i=Qp(t,e,this.preprocessorSession,this.getDocument())}catch(a){const c=a instanceof Ji?a:void 0,l=c?ne(c.action):void 0;return{success:!1,failure:Ln(c?.originalError??a),error:a instanceof Error?a.message:String(a),...c?{failedActions:[{actionIndex:c.actionIndex,actionName:c.action.name,error:c.message,failure:Ln(c.originalError),sourceEditIndex:l?.sourceEditIndex,sourceEditType:l?.sourceEditType}]}:{}}}if(n?.maxPreprocessedActions!==void 0&&(i.actions?.length??0)>n.maxPreprocessedActions)return{success:!1,error:`This edit expands to ${i.actions.length} tracked changes, above the per-call limit of ${n.maxPreprocessedActions}. Split it into smaller edits, or use replace_document_content/import_document when replacing most of a document.`};const s=vl(t.actions,i.actions);if(i.actions){for(const u of i.actions)if(u.name==="set_title")this.setTitle(u.arguments.title),u.arguments.title;else if(u.name==="set_notes"){const g=u.arguments?.notes,p=typeof g=="string"?g:g==null?"":String(g);this.setNotes(p)}else if(u.name==="set_page_layout"){const g=this.applySetPageLayoutAction(u.arguments??{});if(g.error)return{success:!1,error:`set_page_layout: ${g.error}`}}else u.name==="set_header_footer"&&this.applySetHeaderFooterAction(u.arguments??{});const a={...i,actions:i.actions.filter(u=>u.name!=="set_title"&&u.name!=="set_notes"&&u.name!=="set_page_layout"&&u.name!=="set_header_footer")},c=a.actions.length>=100,l=Date.now(),d=u=>{c&&(`${a.actions.length}${u}`,Date.now()-l)};if(d("preprocessed"),a.actions.length>0){const u=this.suggestionEngine.getLiveSuggestionIds().length>0;let g,p,h,f;if(u){const T=this.suggestionEngine.createLiveSuggestionProjection("accept"),C=this.suggestionEngine.createLiveSuggestionProjection("reject");g=T.doc,p=C.doc,h=this.cloneYDoc(T.ydoc),f=this.cloneYDoc(C.ydoc)}else g=this.getDocument(),p=g,h=this.cloneYDoc(this.ydoc),f=this.cloneYDoc(this.ydoc);const m=g,y=this.tryCancelInsertedBlockForRemoveAction(a.actions,m);if(y)return y;const{anchorsByAction:b,failures:k,alreadySatisfied:v}=Uh(h,a.actions,e,m,{rejectUnchangedAction:!0,continueAfterError:!0,canonicalDocument:()=>Tt(h),skipContextForFirstAction:!0});d("validated");const S=a.actions.length===1?ne(a.actions[0])?.styleEffects:void 0;if(k.length>0){const T=C=>`${C.actionName}: ${C.error}`;return k.length===1?{success:!1,error:`Failed operation: ${T(k[0])}`,failedActions:k,failure:k[0]?.failure}:{success:!1,error:`Failed operations: ${k.map(T).join("; ")}`,failedActions:k,failure:k[0]?.failure}}if(v)return h.destroy(),f.destroy(),{success:!0,resultCode:"already_satisfied",styleEffects:S,suggestionIds:[],planningSuggestionIds:[],agentFeedback:(a.actions.length===1?ci(a.actions[0]):void 0)??"Verified that the requested state is already satisfied; no document change was needed."};this.toolCallHistory.addToolCalls(a,e);const I=(a.actions.length===1?ci(a.actions[0]):void 0)??vl(t.actions,i.actions,b)??s,w=Tt(h);d("materialized validation document");const A=new Set,_=T=>{if(!T)return;A.add(T);const C=z(m,T)??z(w,T);C?.id&&A.add(C.id)};for(const T of b)for(const C of T)typeof C?.paragraphId=="string"&&C.paragraphId.length>0&&_(C.paragraphId);for(const T of a.actions){const C=T?.name,N=T?.arguments;(C==="replace"||C==="replace_all"||C==="replace_many"||C==="replace_block"||C==="remove_block"||C==="set_block_attribute"||C==="clear_block_formatting")&&typeof N?.id=="string"&&N.id.length>0&&_(N.id),typeof N?.referenceId=="string"&&N.referenceId.length>0&&_(N.referenceId),typeof N?.tableId=="string"&&N.tableId.length>0&&_(N.tableId)}const B=vm(m,a.actions);for(const T of B)A.add(T.currentBlockId),A.add(T.finalBlockId);this.suggestionEngine.expandPendingSequenceBlockIds(A);const P=A.size>0||B.length>0?{...A.size>0?{affectedBlockIds:Array.from(A)}:{},...B.length>0?{replacementBlockMatches:B}:{}}:void 0,$=this.suggestionEngine.applyValidatedAgentActionsAsSuggestions({validationFork:h,baseFork:f,flattenOptions:P,toolCallId:e,originalActions:t.actions,processedActions:i.actions,validationAnchorsByAction:b,docBeforeToolCall:m,docAfterToolCall:w,baseDocForSuggestions:p,agentFeedback:I,agentName:t.agentName,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,optimizeStyleFormatting:n?.optimizeStyleFormatting});return d("applied live suggestions"),this.materializePendingFootnoteBodies(),{...$,styleEffects:S}}}return{success:!0,planningSuggestionIds:[],agentFeedback:s}}getAllOperations(){return[]}onRemoteDocumentChange(t){}insertBlock(t,e,n,o){this.beforeOperationSelection=n;const i=this.suggestingMode?Ct():null,s=t.id||et(),a=this.getDocument();if(e<0||e>a.children.length)return!1;const c=$e().getHandlerForBlock(t);this.beforeOperationRelativeSelection=c.allowsInternalCursor()?J(n,this.ydoc,a):null,this.transact(()=>{const d=this.getYContentFragment(),u={...t,id:s};let g;if(u.type==="list"){const p=u,h=new x.XmlElement("list");h.setAttribute("variant",p.variant),p.id&&h.setAttribute("id",p.id),p.startNumber!==void 0&&h.setAttribute("startNumber",String(p.startNumber)),p.numberingChainId&&h.setAttribute("numberingChainId",p.numberingChainId),p.numberingFormat&&h.setAttribute("numberingFormat",p.numberingFormat);const f=[];p.children.forEach(m=>{const y=new x.XmlElement("list-item");cn(y,m),m.id&&y.setAttribute("id",m.id),m.checked!==void 0&&y.setAttribute("checked",String(m.checked)),m.indentLevel!==void 0&&y.setAttribute("indentLevel",String(m.indentLevel)),m.direction!==void 0&&y.setAttribute("direction",m.direction);const b=new x.XmlText;let k=0;m.children.forEach(v=>{if(v.type==="text"){const S=v.marks?{...v.marks}:void 0;kt(b,k,v.text,S),k+=v.text.length}}),y.insert(0,[b]),f.push(y)}),h.insert(0,f),g=h}else g=c.toYjs(u,this.ydoc);i&&g instanceof x.XmlElement&&(g.setAttribute("id",s),this.suggestionEngine.markInsertedBlockElement(g,i)),d.insert(e,[g])}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=c.allowsInternalCursor()?J(o,this.ydoc,this.getDocument()):null;const l=this.ensureTrailingParagraph();return i&&this.suggestionEngine.saveLiveSuggestion({id:i,type:"block-insert",blockId:s,label:"Insert",cleanupTrailingParagraphId:l??void 0}),!0}ensureTrailingParagraph(){const t=this.getYContentFragment();if(t.length===0)return null;const e=t.get(t.length-1);if(e instanceof x.XmlElement&&e.nodeName==="paragraph")return null;const n=new x.XmlElement("paragraph"),o=et();n.setAttribute("id",o);const i=new x.XmlText;return n.insert(0,[i]),this.transact(()=>{t.insert(t.length,[n])}),o}getComments(){return rp(this.kernel)}addComment(t,e,n,o,i){return ap(this.kernel,t,e,n,o,i)}addCommentToRanges(t,e,n){return Mi(this.kernel,t,e,n)}addBlockComment(t,e,n){return Cc(this.kernel,t,e,n)}addCommentForSuggestion(t,e,n){return this.addCommentForSuggestions([t],e,n)}getSuggestionCommentRanges(t){return ip(this.kernel,t)}addCommentForSuggestions(t,e,n){const o=Array.from(new Set(t)).filter(a=>typeof a=="string"&&a.length>0);if(o.length===0)return null;const i=this.getSuggestionCommentRanges(o).map(({blockId:a,start:c,end:l})=>({blockId:a,start:c,end:l})),s={...n,suggestionId:o[0],...o.length>1?{relatedSuggestionIds:o}:{}};if(i.length>0)return Mi(this.kernel,i,e,s);for(const a of o){const c=this.getLiveSuggestion(a),l=c&&"blockId"in c?c.blockId:c&&"firstBlockId"in c?c.firstBlockId:void 0;if(l)return Cc(this.kernel,l,e,s)}return null}replyToComment(t,e,n){return cp(this.kernel,t,e,n)}relinkCommentSuggestionIds(){return up(this.kernel,t=>this.suggestionEngine.canResolveLiveSuggestion(t))}resolveCommentsForSettledSuggestions(t){return dp(this.kernel,t,e=>this.suggestionEngine.canResolveLiveSuggestion(e))}setCommentResolved(t,e){return lp(this.kernel,t,e)}deleteComment(t){return gp(this.kernel,t)}isBlockInsideFootnote(t,e){return hp(t,e)}getFootnotes(){return pp(this.kernel)}renumberFootnotes(){return Ze(this.kernel)}materializePendingFootnoteBodies(){return Mc(this.kernel)}addPastedFootnoteBodies(t){const e=this.getYNotesFragment();e.insert(e.length,t.map(n=>this.kernel.blockToYjsElement(n))),this.reconcileFootnotes()}reconcileFootnotes(){fp(this.kernel)}insertFootnote(t,e,n,o="footnote"){return bp(this.kernel,t,e,n,o)}setFootnoteBodyText(t,e){return yp(this.kernel,t,e)}replaceFootnoteBodyText(t,e,n,o=!1){return kp(this.kernel,t,e,n,o)}convertAllNoteKinds(t){return Sp(this.kernel,t)}removeFootnote(t){return Ip(this.kernel,t)}blockToYjsElement(t){const e={...t,id:t.id||et()};return e.type==="list"?Ut(e):$e().getHandlerForBlock(e).toYjs(e,this.ydoc)}insertBlockAfterId(t,e,n,o){const i=ut(this.ydoc,e);if(!i)return!1;const{yParent:s,index:a}=i;this.beforeOperationSelection=n;const c=this.suggestingMode?Ct():null,l=t.id||et();this.transact(()=>{const u=this.blockToYjsElement(t);c&&u instanceof x.XmlElement&&(u.setAttribute("id",l),this.suggestionEngine.markInsertedBlockElement(u,c)),s.insert(a+1,[u])}),this.setSelectionAfterOperation(o),this.updateAfterOperationRelativeSelection(this.getDocument());const d=this.ensureTrailingParagraph();return c&&this.suggestionEngine.saveLiveSuggestion({id:c,type:"block-insert",blockId:l,label:"Insert",cleanupTrailingParagraphId:d??void 0}),!0}insertBlockBeforeId(t,e,n,o){const i=ut(this.ydoc,e);if(!i)return!1;const{yParent:s,index:a}=i;this.beforeOperationSelection=n;const c=this.suggestingMode?Ct():null,l=t.id||et();this.transact(()=>{const u=this.blockToYjsElement(t);c&&u instanceof x.XmlElement&&(u.setAttribute("id",l),this.suggestionEngine.markInsertedBlockElement(u,c)),s.insert(a,[u])}),this.setSelectionAfterOperation(o),this.updateAfterOperationRelativeSelection(this.getDocument());const d=this.ensureTrailingParagraph();return c&&this.suggestionEngine.saveLiveSuggestion({id:c,type:"block-insert",blockId:l,label:"Insert",cleanupTrailingParagraphId:d??void 0}),!0}insertBlockIntoParent(t,e,n,o){const i=ut(this.ydoc,e);if(!i)return!1;const{yBlock:s}=i;if(!(s instanceof x.XmlElement))return!1;const a=s.nodeName;if(!(a==="container"||a==="table-cell"))return!1;this.beforeOperationSelection=n;const c=this.suggestingMode?Ct():null,l=t.id||et();return this.transact(()=>{const d=this.blockToYjsElement(t);c&&d instanceof x.XmlElement&&(d.setAttribute("id",l),this.suggestionEngine.markInsertedBlockElement(d,c)),s.insert(0,[d])}),this.setSelectionAfterOperation(o),this.updateAfterOperationRelativeSelection(this.getDocument()),c&&this.suggestionEngine.saveLiveSuggestion({id:c,type:"block-insert",blockId:l,label:"Insert"}),!0}insertBlockAtStart(t,e,n){return this.insertBlock(t,0,e,n)}insertBlockAtEnd(t,e,n){const o=this.getDocument();return this.insertBlock(t,o.children.length,e,n)}updateBlock(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();if(t<0||t>=i.children.length)return!1;const s=i.children[t];if(s.type!==e.type)return console.warn(`[DocumentMutator] updateBlock type mismatch: ${s.type} -> ${e.type}`),!1;const a=$e().getHandlerForBlock(e);return this.beforeOperationRelativeSelection=a.allowsInternalCursor()?J(n,this.ydoc,i):null,an(this.ydoc)&&eu(this.ydoc),this.transact(()=>{const c=this.getYContentFragment();if(t<0||t>=c.length)return;const l={...e,id:e.id||s.id||et()},d=c.get(t);if(e.type==="list"&&d instanceof x.XmlElement&&d.nodeName==="list")Wi(d,l);else{const u=l.type==="list"?Ut(l):a.toYjs(l,this.ydoc);c.delete(t,1),c.insert(t,[u])}}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=a.allowsInternalCursor()?J(o,this.ydoc,this.getDocument()):null,!0}updateBlockById(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument(),s=z(i,t);if(!s)return!1;if(s.type!==e.type)return console.warn(`[DocumentMutator] updateBlockById type mismatch: ${s.type} -> ${e.type}`),!1;const a=ut(this.ydoc,t);if(!a)return!1;const{yParent:c,index:l}=a,d=$e().getHandlerForBlock(e),u=this.suggestingMode?Ct():null;let g=e,p=null;if(this.suggestingMode&&u&&s.type==="table"&&e.type==="table"){const h=this.suggestionEngine.buildSuggestedTableChange(s,e,u);if(h)g=h.liveBlock,p=h.record;else if(!this.suggestionEngine.hasSameTableGeometry(s,e))return!1}return this.beforeOperationRelativeSelection=d.allowsInternalCursor()?J(n,this.ydoc,i):null,this.transact(()=>{const h={...g,id:g.id||s.id||et()},f=c.get(l);if(g.type==="list"&&f instanceof x.XmlElement&&f.nodeName==="list")Wi(f,h);else{const m=h.type==="list"?Ut(h):d.toYjs(h,this.ydoc);c.delete(l,1),c.insert(l,[m])}p&&this.suggestionEngine.saveLiveSuggestion(p)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=d.allowsInternalCursor()?J(o,this.ydoc,this.getDocument()):null,!0}replaceParagraphById(t,e,n,o){this.beforeOperationSelection=n;const i=this.getDocument();if(!z(i,t))return!1;const s=ut(this.ydoc,t);if(!s)return!1;const{yBlock:a,yParent:c,index:l}=s;return this.beforeOperationRelativeSelection=J(n,this.ydoc,i),this.transact(()=>{const d=a instanceof x.XmlElement?a.getAttribute("id"):void 0,u=new x.XmlElement("paragraph");u.setAttribute("id",e.id||d||et()),e.heading&&u.setAttribute("heading",String(e.heading)),e.align&&u.setAttribute("align",e.align),e.lineSpacing!==void 0&&u.setAttribute("lineSpacing",String(e.lineSpacing)),Zn(u,e);{const m=xe(e);m!==void 0&&u.setAttribute("pagination",m)}e.styleId!==void 0&&u.setAttribute("styleId",e.styleId),e.direction!==void 0&&u.setAttribute("direction",e.direction),e.tabStops!==void 0&&u.setAttribute("tabStops",e.tabStops),e.borders!==void 0&&u.setAttribute("borders",e.borders),e.shading!==void 0&&u.setAttribute("shading",e.shading),e.oxmlAttrs!==void 0&&u.setAttribute("oxmlAttrs",e.oxmlAttrs),e.oxmlPPr!==void 0&&u.setAttribute("oxmlPPr",e.oxmlPPr);const g=le(e.leftIndent);g!==void 0&&u.setAttribute("leftIndent",String(g));const p=de(e.firstLineIndent);p!==void 0&&u.setAttribute("firstLineIndent",String(p));const h=new x.XmlText;let f=0;e.children.forEach(m=>{if(m.type==="text"){const y={...m.marks||{}};kt(h,f,m.text,y),f+=m.text.length}}),u.insert(0,[h]),c.delete(l,1),c.insert(l,[u])}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=J(o,this.ydoc,this.getDocument()),!0}toggleTodoItem(t,e,n,o,i){const s=this.getDocument(),a=s.children[t];if(!a||a.type!=="list"||a.variant!=="todo"||e<0||e>=a.children.length)return!1;this.beforeOperationSelection=o;const c=$e().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=c?.allowsInternalCursor()?J(o,this.ydoc,s):null,this.transact(()=>{const l=this.getYContentFragment().get(t);if(!(l instanceof x.XmlElement))return;let d=0;for(let u=0;u<l.length;u++){const g=l.get(u);if(g instanceof x.XmlElement&&g.nodeName==="list-item"){if(d===e){n?g.setAttribute("checked","true"):g.removeAttribute("checked");return}d++}}}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=c?.allowsInternalCursor()?J(i,this.ydoc,this.getDocument()):null,!0}toggleTodoItemById(t,e,n,o,i){const s=this.getDocument(),a=z(s,t);if(!a||a.type!=="list"||a.variant!=="todo"||e<0||e>=a.children.length)return!1;const c=ut(this.ydoc,t);if(!c)return!1;const{yBlock:l}=c;this.beforeOperationSelection=o;const d=$e().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=d?.allowsInternalCursor()?J(o,this.ydoc,s):null,this.transact(()=>{if(!(l instanceof x.XmlElement))return;let u=0;for(let g=0;g<l.length;g++){const p=l.get(g);if(p instanceof x.XmlElement&&p.nodeName==="list-item"){if(u===e){n?p.setAttribute("checked","true"):p.removeAttribute("checked");return}u++}}}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=d?.allowsInternalCursor()?J(i,this.ydoc,this.getDocument()):null,!0}};xl.DEFERRED_IDENTITY_REPAIR_MS=1500;let eo=xl;function wl(r,t,e){const n=o=>o&&o.block===t?{...o,offset:eo.remapOffsetAcrossReplacementNormalization(o.offset,e)}:o;return{anchor:n(r.anchor),focus:n(r.focus)}}class xm{constructor(t=50){this.tasks=new Map,this.intervalId=null,this.tickMs=t}schedule(t,e,n){const o=Date.now();this.tasks.set(t,{id:t,callback:n,delay:e,lastScheduledAt:o}),this.intervalId===null&&(this.intervalId=window.setInterval(()=>this.tick(),this.tickMs))}cancel(t){this.tasks.delete(t)&&this.tasks.size===0&&this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)}tick(){const t=Date.now();for(const e of this.tasks.values())if(t-e.lastScheduledAt>=e.delay){this.tasks.delete(e.id);try{e.callback()}catch(n){console.error("[DebouncedTaskScheduler] Task error",n)}}this.tasks.size===0&&this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)}}const wm=new xm;function Am(r,t,e){wm.schedule(r,t,e)}function Al(r){if(typeof atob=="function"){const t=atob(r),e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}return Uint8Array.from(Buffer.from(r,"base64"))}function Tl(r,t){const e=x;if(typeof e.applyUpdateV2=="function")try{e.applyUpdateV2(r,t)}catch(n){console.warn("[historyReplay] Failed to apply V2 update:",n)}}function Cl(r,t){try{x.applyUpdate(r,t),ou(r)||Tl(r,t)}catch{Tl(r,t)}}function Tm(r,t,e=-1){const n=new x.Doc({gc:!1});Cl(n,Al(r));const o=e<0?t.length:e;for(let i=0;i<o&&i<t.length;i++)Cl(n,Al(t[i]));return n}class Cm{constructor(){this.worker=null,this.workerFailed=!1,this.nextRequestId=1,this.pendingRequests=new Map}async init(){if(!(this.worker||this.workerFailed))try{if(typeof window>"u"||typeof Worker>"u"){this.workerFailed=!0;return}this.worker=new Worker(new URL(""+new URL("../assets/historyMaterializeWorker-CoAX9ZAi.js",import.meta.url).href,import.meta.url)),this.worker.onmessage=t=>{const e=t.data,n=this.pendingRequests.get(e.id);if(n){if(this.pendingRequests.delete(e.id),!e.success){n.reject(new Error(e.error||"Worker request failed"));return}e.kind==="filterDistinct"?n.resolve(e.distinctIds??[]):e.doc?n.resolve(e.doc):n.reject(new Error("Materialization failed"))}},this.worker.onerror=t=>{console.warn("[HistoryMaterializer] Worker error:",t);for(const[e,n]of this.pendingRequests)n.reject(new Error("Worker error")),this.pendingRequests.delete(e);this.workerFailed=!0,this.worker?.terminate(),this.worker=null}}catch(t){console.warn("[HistoryMaterializer] Failed to create worker:",t),this.workerFailed=!0}}async materialize(t,e,n=-1){if(await this.init(),this.worker&&!this.workerFailed)try{return await this.materializeViaWorker(t,e,n)}catch(o){console.warn("[HistoryMaterializer] Worker materialization failed, falling back:",o)}return this.materializeSync(t,e,n)}async computeDistinctContentIds(t,e){if(e.length===0)return[];if(await this.init(),!this.worker||this.workerFailed)return null;try{return await new Promise((n,o)=>{if(!this.worker){o(new Error("Worker not available"));return}const i=this.nextRequestId++;this.pendingRequests.set(i,{resolve:n,reject:o});const s={id:i,kind:"filterDistinct",segments:t,candidateIds:e};this.worker.postMessage(s),setTimeout(()=>{this.pendingRequests.has(i)&&(this.pendingRequests.delete(i),o(new Error("Worker timeout")))},6e4)})}catch(n){return console.warn("[HistoryMaterializer] Distinct-frame filtering failed:",n),null}}materializeToYDoc(t,e,n=-1){return Tm(t,e,n)}materializeViaWorker(t,e,n){return new Promise((o,i)=>{if(!this.worker){i(new Error("Worker not available"));return}const s=this.nextRequestId++;this.pendingRequests.set(s,{resolve:o,reject:i});const a={id:s,snapshotB64:t,updatesB64:e,uptoIndex:n};this.worker.postMessage(a),setTimeout(()=>{this.pendingRequests.has(s)&&(this.pendingRequests.delete(s),i(new Error("Worker timeout")))},3e4)})}materializeSync(t,e,n){const o=this.materializeToYDoc(t,e,n);try{return Tt(o)}finally{o.destroy()}}dispose(){for(const[,t]of this.pendingRequests)t.reject(new Error("Materializer disposed"));this.pendingRequests.clear(),this.worker?.terminate(),this.worker=null}isWorkerAvailable(){return this.worker!==null&&!this.workerFailed}}const yr=new Cm,as="https://app-api.revise-sdk.invalid";class Pm{constructor(t=20){this.cache=new Map,this.maxSize=t}get(t){const e=this.cache.get(t);return e&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.size>=this.maxSize&&!this.cache.has(t)){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.delete(t),this.cache.set(t,e)}clear(){this.cache.clear()}}class Mm{constructor(t,e,n){this.tailDebounceMs=1200,this.docCache=new Pm,this.totalUpdates=0,this.segments=[],this.loaded=!1,this.maxEndLoaded=0,this.loadLock=null,this.targetLocks=new Map,this.blobLocks=new Map,this.abortController=null,this.contentIds=[],this.updateTimestamps=new Map,this.contentTimestamps=[],this.chunkEndUpdateIds=[],this.chunkSegIdx=[],this.distinctContentIds=null,this.distinctSignature=null,this.changeObservers=[],this.disposed=!1,this.documentId=t,this.authToken=n?.authToken,this.tailTaskId=`history-tail-${Math.random().toString(36).slice(2)}`,this.abortController=new AbortController}onChange(t){return this.changeObservers.push(t),()=>{const e=this.changeObservers.indexOf(t);e>=0&&this.changeObservers.splice(e,1)}}async ensureLoaded(){if(this.loaded)return!0;if(this.disposed)return!1;if(!this.supportsServerHistory())return this.loaded=!0,!0;try{const t=`${as}/documents/${this.documentId}/history`,e=await this.fetchJson(t);return this.totalUpdates=this.readTotalUpdates(e),this.segments=this.parseFrames(e.frames),this.loaded=!0,this.recomputeDerivedData(),this.notifyChange(),!0}catch(t){return console.error("[UpdateHistoryManager] Failed to load update history:",{documentId:this.documentId,error:t instanceof Error?t.message:String(t)}),!1}}notifyDocUpdated(){this.disposed||!this.loaded||Am(this.tailTaskId,this.tailDebounceMs,()=>{this.refreshNewSegments()})}dispose(){this.disposed=!0,this.abortController?.abort(),this.abortController=null,this.changeObservers=[],this.docCache.clear(),this.segments=[],this.updateTimestamps.clear()}getTotalUpdates(){const t=this.segments[this.segments.length-1],e=this.contentIds[this.contentIds.length-1]??0;return Math.max(this.totalUpdates,t?.endUpdateId??0,e)}getContentCount(){return this.contentIds.length}getContentUpdateIds(){return this.contentIds.slice()}getDistinctContentUpdateIds(){return this.distinctContentIds&&this.distinctSignature===this.contentIdsSignature()?this.distinctContentIds.slice():null}contentIdsSignature(){const t=this.contentIds;return`${t.length}:${t[t.length-1]??0}`}async ensureDistinctFramesComputed(){}getWorkChunkCount(){return this.chunkEndUpdateIds.length}getWorkChunkEndUpdateIds(){return this.chunkEndUpdateIds.slice()}getTimestampForUpdateId(t){const e=this.updateTimestamps.get(Math.floor(t));return e&&Number.isFinite(e)&&e>0?e:null}getContentTimeline(){return{count:this.contentIds.length,timestamps:this.contentTimestamps.slice()}}getTimeAxisTicks(){let t;if(this.contentTimestamps.length>0?t=this.contentTimestamps.filter(h=>Number.isFinite(h)&&h>0):(t=Array.from(this.updateTimestamps.values()).filter(h=>Number.isFinite(h)&&h>0),t.sort((h,f)=>h-f)),t.length===0)return null;const e=t[0],n=t[t.length-1],o=n-e;if(o<=0)return{startTs:e,endTs:n,ticksTs:[]};const i=6e4,s=60*i,a=24*s,c=7*a;let l;o<s?l=5*i:o<a?l=s:o<30*a?l=a:l=c;const d=Math.floor(e/l)*l,u=[];let g=0,p=0;for(let h=d+l;h<n;h+=l){const f=h-l;for(;g<t.length&&t[g]<=f;)g++;for(p=Math.max(p,g);p<t.length&&t[p]<=h;)p++;p>g&&h>e&&u.push(h)}return{startTs:e,endTs:n,ticksTs:u}}getPauseMarkersForContent(t,e=10){const n=this.contentTimestamps;if(n.length<=1)return[];const o=Math.max(0,n[n.length-1]-n[0]);if(o<=0||t<=0)return[];const i=o*Math.max(1,e)/Math.max(1,t),s=[];let a=-1/0;for(let c=0;c<n.length-1;c++)n[c+1]-n[c]>=i&&n[c]-a>=i&&(s.push(c+1),a=n[c]);return s}async findLatestUpdateIdBeforeTimestamp(t){if(!await this.ensureLoaded()||!Number.isFinite(t)||t<=0||this.updateTimestamps.size===0)return null;const e=Array.from(this.updateTimestamps.entries()).filter(([,s])=>s>0).sort((s,a)=>s[1]-a[1]);if(e.length===0)return null;let n=0,o=e.length-1,i=null;for(;n<=o;){const s=n+o>>1;e[s][1]<=t?(i=e[s][0],n=s+1):o=s-1}return i??e[0][0]}async materializeAtContentIndex(t,e){if(!await this.ensureLoaded()||this.contentIds.length===0)return null;const n=Math.max(1,Math.min(this.contentIds.length,t));return this.materializeAt(this.contentIds[n-1],e)}async materializeAt(t,e){if(!await this.ensureLoaded()||this.segments.length===0)return null;const n=e?.excludePendingSuggestions===!0;t=Math.max(1,Math.min(this.getTotalUpdates(),t));const o=n?`update-${t}-accepted-only`:`update-${t}`,i=this.docCache.get(o);if(i)return i;await this.ensureHasSegmentFor(t);let s=this.getPlanForUpdateId(t);if(!s)return null;if(await this.ensureBlobsForSegmentStart(s.seg.startUpdateId),s=this.getPlanForUpdateId(t),!s?.seg.snapshotB64)return console.warn("[UpdateHistoryManager] Missing snapshot for segment",s?.seg.startUpdateId),null;const{seg:a}=s;try{const c=Math.min(a.updatesB64.length,a.frameOnly?a.updatesB64.length:t-a.startUpdateId+1);let l;if(n){const d=yr.materializeToYDoc(a.snapshotB64,a.updatesB64,c);try{const u=eo.createSuggestionProjectionFromYDoc(d,"reject");try{l=u.doc}finally{u.ydoc.destroy()}}finally{d.destroy()}}else l=await yr.materialize(a.snapshotB64,a.updatesB64,c);return l&&this.docCache.set(o,l),l}catch(c){return console.error("[UpdateHistoryManager] Materialize failed:",{updateId:t,segmentRange:`${a.startUpdateId}-${a.endUpdateId}`,error:c instanceof Error?c.message:String(c)}),null}}async materializeChunkEnd(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const n=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),o=e?.excludePendingSuggestions===!0?`chunk-end-${t}-accepted-only`:`chunk-end-${t}`,i=this.docCache.get(o);if(i)return i;const s=this.segments[this.chunkSegIdx[n]];await this.ensureBlobsForSegmentStart(s.startUpdateId);const a=await this.materializeAt(s.endUpdateId,e);return a&&this.docCache.set(o,a),a}async materializeChunkSnapshot(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const n=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),o=this.segments[this.chunkSegIdx[n]];if(await this.ensureBlobsForSegmentStart(o.startUpdateId),!o.snapshotB64)return null;if(e?.excludePendingSuggestions){const i=yr.materializeToYDoc(o.snapshotB64,[],0);try{const s=eo.createSuggestionProjectionFromYDoc(i,"reject");try{return s.doc}finally{s.ydoc.destroy()}}finally{i.destroy()}}return yr.materialize(o.snapshotB64,[],0)}async materializeChunkPair(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const n=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),o=this.segments[this.chunkSegIdx[n]];await this.ensureBlobsForSegmentStart(o.startUpdateId);const i=await this.materializeAt(o.endUpdateId,e);if(!i)return null;if(n>0){const a=this.segments[this.chunkSegIdx[n-1]];await this.ensureBlobsForSegmentStart(a.startUpdateId);const c=await this.materializeAt(a.endUpdateId,e);if(c)return{base:c,target:i}}if(!o.snapshotB64)return null;const s=await this.materializeChunkSnapshot(t,e);return s?{base:s,target:i}:null}__getPlanForTest(t){return this.getPlanForUpdateId(t)}supportsServerHistory(){return this.documentId.length>8}async fetchJson(t){if(this.disposed)throw new Error("Manager disposed");const e={};this.authToken&&(e.Authorization=`Bearer ${this.authToken}`);const n=await fetch(t,{headers:e,credentials:"omit",signal:this.abortController?.signal});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.json()}readTotalUpdates(t){const e=Number(t.totalUpdates);return!Number.isFinite(e)||e<=0?this.totalUpdates:e}parseFrames(t){return t?t.filter(e=>Number.isFinite(e.updateId)&&Number.isFinite(e.sourceId)&&(e.source==="legacy"||e.source==="delta")).map(e=>({startUpdateId:Number(e.updateId),endUpdateId:Number(e.updateId),snapshotB64:"",updatesB64:[],meta:[{ts:Number(e.timestamp||0),content:!0,userId:e.userId??null,agentName:e.agentName??null}],frameSource:e.source,frameSourceId:Number(e.sourceId),frameOnly:!0})).sort((e,n)=>e.startUpdateId-n.startUpdateId):[]}async refreshNewSegments(){!this.supportsServerHistory()||this.disposed||!this.loaded||await this.withLoadLock(async()=>{const t=`${as}/documents/${this.documentId}/history`;try{const e=await this.fetchJson(t);this.totalUpdates=this.readTotalUpdates(e),this.segments=this.parseFrames(e.frames),this.recomputeDerivedData(),this.notifyChange()}catch(e){e.name!=="AbortError"&&console.warn("[UpdateHistoryManager] Failed to refresh segments:",e)}})}async ensureHasSegmentFor(t){if(!this.supportsServerHistory()||this.disposed||this.segments.some(o=>o.startUpdateId<=t&&t<=o.endUpdateId))return;const e=this.targetLocks.get(t);if(e)return e;const n=this.fetchSegmentContaining(t).finally(()=>{this.targetLocks.delete(t)});this.targetLocks.set(t,n),await n}async fetchSegmentContaining(t){if(this.disposed)return;const e=this.getPlanForUpdateId(t)?.seg;if(!e?.frameSource||e.frameSourceId==null)return;const n=new URLSearchParams({source:e.frameSource,sourceId:String(e.frameSourceId)});e.frameSource==="legacy"&&n.set("targetUpdateId",String(t));const o=`${as}/documents/${this.documentId}/history/frame?${n.toString()}`;try{const i=await this.fetchJson(o);e.snapshotB64=i.snapshotB64||"",e.updatesB64=i.updatesB64||[]}catch(i){i.name!=="AbortError"&&console.warn("[UpdateHistoryManager] Failed to fetch segment:",{updateId:t,error:i})}}async ensureBlobsForSegmentStart(t){const e=this.segments.find(o=>o.startUpdateId===t);if(e?.snapshotB64&&Array.isArray(e.updatesB64))return;let n=this.blobLocks.get(t);n||(n=this.fetchSegmentContaining(t).finally(()=>{this.blobLocks.delete(t)}),this.blobLocks.set(t,n)),await n}async withLoadLock(t){if(this.loadLock)return this.loadLock;this.loadLock=t();try{await this.loadLock}finally{this.loadLock=null}}mergeInSegments(t){if(t.length===0)return;const e=new Map;for(const n of this.segments)e.set(n.startUpdateId,n);for(const n of t){const o=e.get(n.startUpdateId);if(!o){e.set(n.startUpdateId,n);continue}e.set(n.startUpdateId,{startUpdateId:o.startUpdateId,endUpdateId:Math.max(o.endUpdateId,n.endUpdateId),snapshotB64:o.snapshotB64||n.snapshotB64,updatesB64:(n.updatesB64?.length||0)>=(o.updatesB64?.length||0)?n.updatesB64:o.updatesB64,meta:(n.meta?.length||0)>=(o.meta?.length||0)?n.meta:o.meta,frameSource:n.frameSource||o.frameSource,frameSourceId:n.frameSourceId??o.frameSourceId,frameOnly:n.frameOnly||o.frameOnly})}this.segments=Array.from(e.values()).sort((n,o)=>n.startUpdateId-o.startUpdateId),this.maxEndLoaded=0;for(const n of this.segments)n.endUpdateId>this.maxEndLoaded&&(this.maxEndLoaded=n.endUpdateId)}getPlanForUpdateId(t){if(this.segments.length===0)return null;let e=this.segments.find(o=>o.startUpdateId<=t&&t<=o.endUpdateId);if(!e){const o=this.segments[0],i=this.segments[this.segments.length-1];if(t<o.startUpdateId)e=o;else if(t>i.endUpdateId)e=i;else for(let s=0;s<this.segments.length-1;s++)if(t>this.segments[s].endUpdateId&&t<this.segments[s+1].startUpdateId){e=this.segments[s];break}}if(!e)return null;const n=Math.max(0,Math.min(e.updatesB64.length,t-e.startUpdateId+1));return{seg:e,upto:n}}recomputeDerivedData(){this.docCache.clear(),this.recomputeContentIds(),this.recomputeTimestamps(),this.recomputeChunks()}recomputeContentIds(){const t=[];for(let e=0;e<this.segments.length;e++){const n=this.segments[e];if(n.frameOnly){t.push(n.startUpdateId);continue}const o=n.meta,i=Math.max(n.updatesB64.length,o?.length||0),s=e<2;for(let a=0;a<i;a++)(o?.[a]?.content||s&&a===0)&&t.push(n.startUpdateId+a)}this.contentIds=t}recomputeTimestamps(){this.updateTimestamps.clear();for(const t of this.segments){const e=t.meta;if(e)for(let n=0;n<e.length;n++){const o=t.startUpdateId+n,i=Number(e[n]?.ts||0);i>0&&this.updateTimestamps.set(o,i)}}this.contentTimestamps=this.contentIds.map(t=>this.updateTimestamps.get(t)||0)}recomputeChunks(){const t=this.segments.length;if(t===0){this.chunkSegIdx=[],this.chunkEndUpdateIds=[];return}const e=[];for(let o=0;o<t;o++){if(this.segments[o].frameOnly){e.push(o);continue}const i=this.segments[o].meta,s=Array.isArray(i)&&i.some(c=>c?.content),a=o<2;(s||a)&&e.push(o)}const n=t-1;(e.length===0||e[e.length-1]!==n)&&e.push(n),this.chunkSegIdx=e,this.chunkEndUpdateIds=e.map(o=>this.segments[o].endUpdateId)}notifyChange(){if(!this.disposed)for(const t of this.changeObservers.slice())try{t()}catch(e){console.error("[UpdateHistoryManager] Observer error:",e)}}}const $m=()=>{},Bm=async()=>{},_m=new Set;function cs(r,t){for(const e of _m)try{e(r,t)}catch{}}const Lm=new Proxy({track:(r,t)=>cs(r,t),trackAgentToolInvoked:(r,t,e,n=!1)=>cs("Agent Tool Invoked",{tool:r,documentId:t??void 0,directMode:n}),trackDocumentExported:(r,t,e)=>cs("Document Exported",{documentId:r,format:t,source:e}),getCheckoutAttribution:()=>null,flush:Bm},{get(r,t){return t in r?r[t]:$m}});class ks{constructor(t,e,n,o){this.isViewingRevision=!1,this.documentChangeObservers=[],this.isReadOnly=!1,this.timeTravelActive=!1,this.viewModeObservers=[],this.historyOpen=!1,this.historyDiffEnabled=!0,this.historySelection={start:null,end:null},this.historyObservers=[],this.notesObservers=[],this.notesValue="",this.cleanupCallbacks=[],this.disposed=!1,this.historyManager=null,this.sharedWriteAccess=null,this.autocorrectEnabled=!0,this.documentId=t,this.sharedStyleMigrationPermit=o?.sharedStyleMigrationPermit,this.authToken=o?.authToken,this.onTitleChange=n;const i=o?.disableProposalPersistence??!!o?.authToken;if(this.preprocessorSession=new ir,Fr(e)){const c=e;if(this.ydoc=$n(c,this.sharedStyleMigrationPermit?{sharedStyles:this.sharedStyleMigrationPermit.formatGateConfirmed===!0&&this.sharedStyleMigrationPermit.exclusive===!0}:void 0),c.pendingDocxCarrier){const l=c.pendingDocxCarrier;delete c.pendingDocxCarrier,Ru(this.ydoc,l.bytes,{hash:l.hash})}c.pageless!==void 0&&this.ydoc.getMap("metadata").set("pageless",c.pageless),this.currentDocument=this.cloneDoc(c)}else{this.ydoc=e;const c=Tt(this.ydoc);this.currentDocument=this.cloneDoc(c)}yc(this.ydoc),Fr(e)&&(this.sharedWriteAccess=!0),this.documentMutator=new eo(Tt(this.ydoc),(c,l)=>this.updateWorkingDocument(c,l),this.onTitleChange,this.ydoc,t,i,this.preprocessorSession,{canRepairIdentity:()=>this.sharedWriteAccess===!0,deferIdentityRepair:!Fr(e)}),this.documentMutator.identityRepairedOnConstruct&&(this.currentDocument=this.cloneDoc(Tt(this.ydoc))),this.notesValue=this.documentMutator.getDocumentNotes();try{this.documentMutator.backfillLiveSuggestionTreeRecords(),this.documentMutator.reconcileFootnotes(),this.documentMutator.migrateChromeOutOfContent(),this.documentMutator.migrateNotesOutOfContent(),this.documentMutator.migrateLegacyHeaderFooterMetadata(),this.documentMutator.migrateLegacyPageNumbers()}catch{}this.backfillStylesheetSidecar(),this.cleanupCallbacks.push(ru(this.ydoc,c=>{console.warn(`[DocumentSession] repaired a duplicate seed: removed ${c.removedBlocks} blocks from ${c.losingClaims} losing seed(s)`)}));const s=this.ydoc.getMap("metadata"),a=c=>{if(c.keysChanged.has("notes")){const l=this.documentMutator.getDocumentNotes();l!==this.notesValue&&(this.notesValue=l,this.notifyNotesObservers())}};if(s.observe(a),this.cleanupCallbacks.push(()=>s.unobserve(a)),!o?.disableHistory){this.historyManager=new Mm(this.documentId,this.ydoc,{authToken:this.authToken});const c=()=>{this.historyManager?.notifyDocUpdated()};this.ydoc.on("update",c),this.cleanupCallbacks.push(()=>this.ydoc.off("update",c))}}static fromDocRoot(t,e){return new ks("no-id",t,e)}getDocumentId(){return this.documentId}dispose(){if(!this.disposed){this.disposed=!0;for(const t of this.cleanupCallbacks.splice(0))t();this.documentMutator.dispose(),this.historyManager?.dispose(),this.historyManager=null,this.documentChangeObservers=[],this.viewModeObservers=[],this.historyObservers=[],this.notesObservers=[]}}setReadOnly(){this.isReadOnly=!0}setReadWrite(){this.isReadOnly=!1}setSharedWriteAccess(t){const e=t&&this.sharedWriteAccess!==!0;this.sharedWriteAccess=t,e&&this.documentMutator.repairDocumentIdentity()&&this.notifyDocumentChange(this.documentMutator.getDocument(),{origin:"local"}),e&&this.sharedStyleMigrationPermit&&(iu(this.ydoc,this.sharedStyleMigrationPermit),this.sharedStyleMigrationPermit=void 0)}setSuggestingMode(t){this.documentMutator.setSuggestingMode(t)}isSuggestingMode(){return this.documentMutator.isSuggestingMode()}getWorkingDocument(){return this.documentMutator.getDocument()}getDocumentWithoutPendingSuggestions(){return this.documentMutator.getLiveSuggestionIds().length>0?this.documentMutator.getDocumentWithRejectedSuggestions():this.getWorkingDocument()}getWorkingDocumentBeforePendingReview(){return this.getDocumentWithoutPendingSuggestions()}getDocumentWithPendingSuggestionsApplied(t){if(t?.conversationId!==void 0&&this.documentMutator.setDetachedSuggestionConversation(t.conversationId??null,t.serverDetachedSuggestions),this.documentMutator.getLiveSuggestionIds().length>0)return this.documentMutator.getDocumentWithAcceptedSuggestions();const e=this.documentMutator.getDetachedSuggestionStore(),n=e.getPendingSuggestions();if(n.size===0)return this.getWorkingDocument();const o=Array.from(n.keys()),i=e.materializeWithSuggestions(o);return Tt(i)}getCurrentDocument(){return this.currentDocument}updateWorkingDocument(t,e={origin:"unknown"}){!this.isViewingRevision&&!this.historyOpen&&(this.currentDocument=t),this.logUnresolvableLiveSuggestions(e),this.notifyDocumentChange(this.currentDocument,e)}logUnresolvableLiveSuggestions(t){const e=this.documentMutator.getLiveSuggestionIds();if(e.length===0)return;const n=this.documentMutator.getUnresolvableLiveSuggestionRecords(),o=n.filter(i=>i.source==="agent");this.documentId,t.origin,e.length,n.length,o.length}countPrunedByKey(t,e){return t.reduce((n,o)=>{const i=o[e]||"unknown";return n[i]=(n[i]??0)+1,n},{})}trackPrunedUnresolvableLiveSuggestions(t,e,n){const o=this.documentMutator.takeLastPrunedUnresolvableLiveSuggestions();if(o.length===0)return;const i=o.filter(a=>a.source==="agent").length,s={Document:this.documentId,Action:t,RequestedSuggestionCount:new Set(e).size,ResolvedSuggestionCount:n,PrunedSuggestionCount:o.length,PrunedAgentSuggestionCount:i,PrunedSuggestionTypes:this.countPrunedByKey(o,"type"),PrunedSuggestionSources:this.countPrunedByKey(o,"source"),PrunedSuggestions:o};Lm.track("Live Suggestions Pruned",s)}onDocumentChange(t){return this.documentChangeObservers.push(t),()=>{const e=this.documentChangeObservers.indexOf(t);e>-1&&this.documentChangeObservers.splice(e,1)}}notifyDocumentChange(t,e={origin:"unknown"}){const n=t??this.getCurrentDocument();this.documentChangeObservers.forEach(o=>{try{o(n,e)}catch(i){console.error("Error in document change observer:",i)}})}exitRevisionView(){this.isViewingRevision=!1,this.currentDocument=this.getWorkingDocument(),this.notifyViewModeChange(),this.notifyDocumentChange()}getDocumentMutator(){return this.documentMutator}async getDocumentSnapshotAtOrBefore(t){if(!this.historyManager||!Number.isFinite(t)||t<=0)return null;const e=await this.historyManager.findLatestUpdateIdBeforeTimestamp(t);return e===null?null:this.historyManager.materializeAt(e,{excludePendingSuggestions:!0})}getDocumentNotes(){return this.notesValue}setDocumentNotes(t){if(this.isReadOnly)return;const e=typeof t=="string"?t:String(t??"");e!==this.notesValue&&(this.notesValue=e,this.documentMutator.setNotes(e),this.notifyNotesObservers())}onNotesChange(t){return this.notesObservers.push(t),()=>{const e=this.notesObservers.indexOf(t);e>=0&&this.notesObservers.splice(e,1)}}getPreprocessorSession(){return this.preprocessorSession}getRevisionManager(){return null}getYDoc(){return this.ydoc}registerRemoteOrigin(t){this.documentMutator.registerRemoteOrigin(t)}unregisterRemoteOrigin(t){this.documentMutator.unregisterRemoteOrigin(t)}setTimeTravelActive(t){this.timeTravelActive=!!t}isTimeTravelActive(){return this.timeTravelActive}onViewModeChange(t){return this.viewModeObservers.push(t),()=>{const e=this.viewModeObservers.indexOf(t);e>=0&&this.viewModeObservers.splice(e,1)}}openHistory(){this.historyOpen=!0,this.notifyHistoryChange()}closeHistory(){this.historyOpen=!1,this.notifyHistoryChange()}isHistoryOpen(){return this.historyOpen}setDiffEnabled(t){this.historyDiffEnabled=!!t,this.notifyHistoryChange()}isDiffEnabled(){return this.historyDiffEnabled}setSelection(t){this.historySelection={start:t.start??null,end:t.end??null},this.notifyHistoryChange()}getSelection(){return{...this.historySelection}}onHistoryStateChange(t){return this.historyObservers.push(t),()=>{const e=this.historyObservers.indexOf(t);e>=0&&this.historyObservers.splice(e,1)}}notifyHistoryChange(){for(const t of this.historyObservers.slice())try{t()}catch(e){console.error("[DocumentSession] History observer error:",e)}}backfillStylesheetSidecar(){try{const t=this.ydoc.getMap("metadata"),e=t.get("stylesXml");if(typeof e!="string"||e.length===0||t.get("stylesheet")!==void 0)return;import("./DocxConverter-COV6CjUM.js").then(({DocxConverter:n})=>{if(this.isReadOnly||this.isViewingRevision||t.get("stylesheet")!==void 0)return;const o=n.resolveStylesheetFromStylesXml(e,this.currentDocument.pageLayout);o&&this.ydoc.transact(()=>{t.set("stylesheet",o)})}).catch(()=>{})}catch{}}notifyNotesObservers(){const t=this.getDocumentNotes();for(const e of this.notesObservers.slice())try{e(t)}catch(n){console.error("[DocumentSession] Notes observer error:",n)}}async applySelection(t){const e=this.historyManager;if(!e||!t)return;const n=this.historyDiffEnabled,o=this.historySelection;await e.ensureLoaded();const i=e.getTotalUpdates?.()||0;if(i<=0)return;const s=y=>Math.max(1,Math.min(i,Math.floor(y))),a=async y=>await e.materializeAt?.(s(y),{excludePendingSuggestions:!0}),c=()=>this.getDocumentWithoutPendingSuggestions(),l=y=>{try{t.getEditor?.()?.setDisplayDocument?.(y)}catch(b){console.error("[DocumentSession] Failed to set display document:",b)}},d=async y=>{const b=await a(y);if(b){try{t.clearDiffPresentation?.()}catch(k){console.error("[DocumentSession] Failed to clear diff presentation:",k)}l(b)}},u=async(y,b)=>{const k=await a(y),v=await a(b);!k||!v||(t.showDiffBetweenDocuments?.(k,v),l(v))},g=async y=>{const b=await a(y),k=c();!b||!k||(t.showDiffBetweenDocuments?.(b,k),l(k))},p=o.start,h=o.end;if(p!=null&&h!=null&&p!==h){const y=s(p),b=s(h),k=Math.min(y,b),v=Math.max(y,b);n?await u(k,v):await d(v);return}const f=typeof p=="number"?p:null;if(f==null)return;const m=s(f);if(m<=1){await d(1);return}if(n)if(m===i)try{const y=await a(i),b=c();JSON.stringify(y)===JSON.stringify(b)?i>1?await u(i-1,i):await d(1):await g(i)}catch{await g(i)}else m>1?await u(m-1,m):await d(m);else await d(m)}async showDiffBetweenHistoryUpdates(t,e,n){const o=this.historyManager;if(!o||!t)return!1;const i=Math.min(e,n),s=Math.max(e,n);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=0||s<=i||!await o.ensureLoaded())return!1;const a=o.getTotalUpdates?.()??0;return s>a?!1:(this.openHistory(),this.setDiffEnabled(!0),this.setSelection({start:i,end:s}),await this.applySelection(t),!0)}notifyViewModeChange(){const t=this.isViewingRevision;this.viewModeObservers.forEach(e=>{try{e(t)}catch{}})}getStorageType(){return this.ydoc.getMap("metadata").get("storageType")}getParentFolderId(){const t=this.ydoc.getMap("metadata").get("parentFolderId");return typeof t=="string"&&t.length>0?t:null}getHistoryManager(){return this.historyManager}attachDemoHistoryManager(t){this.historyManager=t}async jumpToUpdateId(t){const e=await this.historyManager?.materializeAt(t,{excludePendingSuggestions:!0});return e?(this.currentDocument=this.cloneDoc(e),this.notifyDocumentChange(),!0):!1}async jumpToContentIndex(t){const e=this.historyManager;if(!e?.materializeAtContentIndex)return!1;const n=await e.materializeAtContentIndex(t,{excludePendingSuggestions:!0});return n?(this.currentDocument=this.cloneDoc(n),this.notifyDocumentChange(),!0):!1}cloneDoc(t){return JSON.parse(JSON.stringify(t))}getPagelessMode(){return this.documentMutator.getPagelessMode()}setPagelessMode(t){this.documentMutator.setPagelessMode(t)}getPageLayoutSettings(){return this.documentMutator.getPageLayoutSettings()}setPageLayoutSettings(t){this.documentMutator.setPageLayoutSettings(t)}getIndentStepPx(){return this.documentMutator.getIndentStepPx()}setAutocorrectEnabled(t){this.autocorrectEnabled=t}isAutocorrectEnabled(){return this.autocorrectEnabled}insertText(t,e,n,o){return this.documentMutator.insertText(t,e,n,o)}getAfterOperationSelection(){return this.documentMutator.getAfterOperationSelection()}insertFormattedText(t,e,n,o,i){return this.documentMutator.insertFormattedText(t,e,n,o,i)}deleteText(t,e,n,o){return this.documentMutator.deleteText(t,e,n,o)}deleteSelection(t,e,n,o){return this.documentMutator.deleteSelection(t,e,n,o)}deleteBlock(t,e,n){return this.documentMutator.deleteBlock(t,e,n)}deleteBlockById(t,e,n){return this.documentMutator.deleteBlockById(t,e,n)}insertBlock(t,e,n,o){return this.documentMutator.insertBlock(t,e,n,o)}insertBlockAfterId(t,e,n,o){return this.documentMutator.insertBlockAfterId(t,e,n,o)}insertBlockBeforeId(t,e,n,o){return this.documentMutator.insertBlockBeforeId(t,e,n,o)}insertBlockIntoParent(t,e,n,o){return this.documentMutator.insertBlockIntoParent(t,e,n,o)}insertBlockAtStart(t,e,n){return this.documentMutator.insertBlockAtStart(t,e,n)}insertBlockAtEnd(t,e,n){return this.documentMutator.insertBlockAtEnd(t,e,n)}updateBlock(t,e,n,o){return this.documentMutator.updateBlock(t,e,n,o)}updateBlockById(t,e,n,o){return this.documentMutator.updateBlockById(t,e,n,o)}replaceParagraphById(t,e,n,o){return this.documentMutator.replaceParagraphById(t,e,n,o)}toggleTodoItem(t,e,n,o,i){return this.documentMutator.toggleTodoItem(t,e,n,o,i)}toggleTodoItemById(t,e,n,o,i){return this.documentMutator.toggleTodoItemById(t,e,n,o,i)}setListItemIndent(t,e,n,o,i){return this.documentMutator.setListItemIndent(t,e,n,o,i)}splitParagraph(t,e){return this.documentMutator.splitParagraph(t,e)}applyFormatting(t,e,n,o,i){return this.documentMutator.applyFormatting(t,e,n,o,i)}setSelectionAfterOperation(t){this.documentMutator.setSelectionAfterOperation(t)}setFontFamily(t,e,n,o){return this.documentMutator.setFontFamily(t,e,n,o)}setFontSize(t,e,n,o){return this.documentMutator.setFontSize(t,e,n,o)}setLetterSpacing(t,e,n,o){return this.documentMutator.setLetterSpacing(t,e,n,o)}setTextColor(t,e,n,o){return this.documentMutator.setTextColor(t,e,n,o)}setBackgroundColor(t,e,n,o){return this.documentMutator.setBackgroundColor(t,e,n,o)}clearFormatting(t,e,n){return this.documentMutator.clearFormatting(t,e,n)}setLink(t,e,n,o){return this.documentMutator.setLink(t,e,n,o)}setCodeBlockLanguage(t,e){return this.documentMutator.setCodeBlockLanguage(t,e)}setCodeBlockRenderDiagram(t,e){return this.documentMutator.setCodeBlockRenderDiagram(t,e)}setCodeBlockShowDiagramSource(t,e){return this.documentMutator.setCodeBlockShowDiagramSource(t,e)}setMathBlockContent(t,e){return this.documentMutator.setMathBlockContent(t,e)}setMathBlockDisplayMode(t,e){return this.documentMutator.setMathBlockDisplayMode(t,e)}setMathBlockAlign(t,e){return this.documentMutator.setMathBlockAlign(t,e)}replaceParagraph(t,e,n,o){return this.documentMutator.replaceParagraph(t,e,n,o)}pasteParagraphs(t,e,n,o={}){return this.documentMutator.pasteParagraphs(t,e,n,o)}canUndo(){return this.documentMutator.canUndo()}canRedo(){return this.documentMutator.canRedo()}undo(){return this.documentMutator.undo()}redo(t){return this.documentMutator.redo(t)}getLiveSuggestionIdsBySource(t){return this.documentMutator.getLiveSuggestionIdsBySource(t)}getLiveSuggestionIdsByCommentThread(t){return this.documentMutator.getLiveSuggestionIdsByCommentThread(t)}getInlineSuggestionMetadataFromDocument(t){return this.documentMutator.getInlineSuggestionMetadataFromDocument(t)}decideLiveSuggestions(t){const e=this.documentMutator.decideLiveSuggestions(t);return this.trackPrunedUnresolvableLiveSuggestions(t.decision,e.attemptedSuggestionIds,e.resolvedCount),e}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}})}nativeAgentLiveSuggestionIds(){return this.documentMutator.getLiveSuggestionIdsBySource("agent").filter(t=>Cu(this.documentMutator.getInlineSuggestionMetadataFromDocument(t)?.agentName??this.documentMutator.getLiveSuggestion(t)?.agentName))}rollbackAgentSuggestions(t){const e=this.nativeAgentLiveSuggestionIds().map(s=>{const a=this.documentMutator.getInlineSuggestionMetadataFromDocument(s),c=this.documentMutator.getLiveSuggestion(s);return{suggestionId:s,agentConversationId:a?.agentConversationId??c?.agentConversationId,agentRequestId:a?.agentRequestId??c?.agentRequestId,agentTurn:a?.agentTurn??c?.agentTurn}}).filter(s=>s.agentConversationId===t.agentConversationId&&typeof s.agentRequestId=="number"&&typeof s.agentTurn=="number"),n=t.requestId??e.reduce((s,a)=>{const c=a.agentRequestId;return c>=t.currentRequestId?s:s===void 0||c>s?c:s},void 0);if(n===void 0)return{suggestionIds:[],resolvedCount:0};const o=e.filter(s=>t.turn===void 0&&s.agentRequestId>=n||t.turn!==void 0&&s.agentRequestId===n&&s.agentTurn===t.turn).map(s=>s.suggestionId);if(o.length===0)return{requestId:n,turn:t.turn,suggestionIds:[],resolvedCount:0};const i=this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:o},historyOrigin:`agent-suggestion-rollback:${t.agentConversationId}:${n}:${t.turn??"all"}:by-${t.currentRequestId}:${t.currentTurn}`});return{requestId:n,turn:t.turn,suggestionIds:o,resolvedCount:i.resolvedCount}}setSuggestionAuthorName(t){this.documentMutator.setDefaultSuggestionAuthorName(t)}acceptLiveSuggestionsByAuthor(t){return this.documentMutator.acceptLiveSuggestionsByAuthor(t)}rejectLiveSuggestionsByAuthor(t){return this.documentMutator.rejectLiveSuggestionsByAuthor(t)}acceptLiveSuggestionsByKind(t){return this.documentMutator.acceptLiveSuggestionsByKind(t)}rejectLiveSuggestionsByKind(t){return this.documentMutator.rejectLiveSuggestionsByKind(t)}acceptAgentSuggestions(){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:this.nativeAgentLiveSuggestionIds()}})}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}})}rejectAgentSuggestions(){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:this.nativeAgentLiveSuggestionIds()}})}beginGroup(t){this.documentMutator.beginGroup(t)}endGroup(){this.documentMutator.endGroup()}clearHistory(){this.documentMutator.clearHistory()}getHistoryInfo(){return this.documentMutator.getHistoryInfo()}setCurrentDocument(t){this.currentDocument=this.cloneDoc(t),this.notifyDocumentChange()}hasUncommittedChanges(){return!1}getDetachedSuggestionStore(){return this.documentMutator.getDetachedSuggestionStore()}clearLegacyDetachedSuggestionState(){this.documentMutator.clearLegacyDetachedSuggestionState()}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){return this.documentMutator.migrateLegacyDetachedSuggestionsToLiveSuggestions(t)}applyAgentActions(t,e,n){return n?.startNewTurn!==!1&&this.preprocessorSession.startNewTurn(),this.documentMutator.applyAgentActions(t,e,{optimizeStyleFormatting:n?.optimizeStyleFormatting})}}const ls=new Set(["import_attachment_into_document","insert_block","insert_footnote","replace_block","set_block_attribute","style_blocks","clear_formatting","append_to_paragraph","break_paragraph","join_paragraphs","replace","replace_all","replace_many","rollback_agent_suggestions","leave_comment","remove_blocks","remove_block","set_title","set_notes","set_page_layout","set_header_footer","insert_table_row","remove_table_row","insert_table_column","remove_table_column"]),Pl=[{name:"get_selection",description:"Read the host user's current semantic editor selection. Returns selected text, caret/range positions, portable target segments, active formatting, comment IDs, and pending suggestion IDs. Returns no viewport geometry. Use this when the host has not already supplied selection context.",inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{name:"read_blocks_from_index",description:"Read consecutive blocks from a 0-based start index. Omit document_id for the current document, or pass a known document_id to read another document. If the user names or links a specific document and you know its ID, use this directly instead of search_documents. Client chooses count by budget. Use at most one read/search tool per turn.",inputSchema:{additionalProperties:!1,properties:{context_notes:{description:"Plain-text notes to carry forward from current context before this read/search. Use 'N/A' if none.",type:"string"},document_id:{description:"Optional document ID. Omit for the current document. Other documents are read-only sources: their block IDs cannot be used in mutation tools. To edit another document, ask the user to open it and continue there.",type:"string"},index:{description:"0-based start block index.",minimum:0,type:"integer"}},required:["index","context_notes"],type:"object"}},{name:"search_document",description:"Search text within one document. Call this when you need to locate specific wording, a term, a name, or every occurrence of something and you do not already know which blocks contain it — searching is how you find the target before editing it, and is cheaper and more reliable than reading through the document. Current-document results include a request-scoped search_result_id for the full unpaginated match set; pass it to replace, replace_block, style_blocks, or remove_blocks to target every match without paging through IDs. Omit document_id for the current document, or pass a known document_id to search within another document. If you instead need to read a document start-to-finish and already know its ID, prefer read_blocks_from_index with document_id. Displayed matches are paginated. Use at most one read/search tool per turn.",inputSchema:{additionalProperties:!1,properties:{context_notes:{description:"Plain-text notes to carry forward from current context before this read/search. Use 'N/A' if none.",type:"string"},document_id:{description:"Optional document ID. Omit for the current document. Other documents are read-only sources: their block IDs cannot be used in mutation tools. To edit another document, ask the user to open it and continue there.",type:"string"},page:{description:"0-based result page.",type:"integer"},queries:{description:"Search terms, max 20. Plain strings are case-insensitive; prefix regex patterns with 'regex:'.",items:{type:"string"},type:"array"}},required:["queries","page","context_notes"],type:"object"}},{name:"find_highlights",description:'Find highlighted text blocks, optionally by color. Call this whenever the request refers to highlighted text — "the highlighted parts", "what I marked", "the yellow bits" — before acting on it; highlights are not visible in loaded document content, so this is the only way to learn which blocks the user means. Matching blocks load next turn. Results are paginated at 25 blocks/page. Use at most one read/search tool per turn.',inputSchema:{additionalProperties:!1,properties:{color:{description:"Optional color filter.",enum:["yellow","orange","green","blue","purple","pink","gray"],type:"string"},context_notes:{description:"Plain-text notes to carry forward from current context before this read/search. Use 'N/A' if none.",type:"string"},page:{description:"0-based result page.",type:"integer"}},required:["page","context_notes"],type:"object"}},{name:"read_specific_blocks",description:"Read specific blocks by ID. Omit document_id for the current document, or pass a known document_id to read another document. If you already know both the document ID and block IDs, use this directly instead of search_documents. Use at most one read/search tool per turn.",inputSchema:{additionalProperties:!1,properties:{block_ids:{description:"Block IDs to read, max 50.",items:{type:"string"},type:"array"},context_notes:{description:"Plain-text notes to carry forward from current context before this read/search. Use 'N/A' if none.",type:"string"},document_id:{description:"Optional document ID. Omit for the current document. Other documents are read-only sources: their block IDs cannot be used in mutation tools. To edit another document, ask the user to open it and continue there.",type:"string"}},required:["block_ids","context_notes"],type:"object"}},{name:"measure_document",description:"Measure the current document without loading body text. Use this for total word count, paragraph count, block count, rendered page count, and paginated per-heading section measurements. Primary totals treat pending suggestions as accepted; when pending suggestions change counts, the result also reports the original review projection so you can reconcile the number visible in the user's editor view. Set include_sections=true for per-chapter/per-section counts and inclusive block ranges.",inputSchema:{additionalProperties:!1,properties:{heading_levels:{description:"Optional heading levels to include when include_sections is true. Defaults to h1, h2, and h3.",items:{enum:[1,2,3],type:"integer"},type:"array"},include_sections:{description:"Whether to include heading section measurements. Default false. Use true for per-chapter or per-section counts.",type:"boolean"},section_limit:{description:"Maximum heading sections to return when include_sections is true. Default and maximum 100.",maximum:100,minimum:1,type:"integer"},section_offset:{description:"Zero-based section offset when include_sections is true. Default 0. Use nextSectionOffset from the previous result to continue.",minimum:0,type:"integer"}},type:"object"}},{name:"measure_blocks",description:"Measure inclusive block ranges in the current document without loading document text. Use this for word counts, paragraph counts, block counts, and rendered page ranges. Block IDs may be passed with or without a leading #.",inputSchema:{additionalProperties:!1,properties:{mode:{description:"Range mode. Only inclusive is supported.",enum:["inclusive"],type:"string"},ranges:{description:"Inclusive block ranges to measure. Omit end_block_id to measure only start_block_id.",items:{additionalProperties:!1,properties:{end_block_id:{description:"Last block ID in the inclusive range. Omit to measure only the start block.",type:"string"},start_block_id:{description:"First block ID in the inclusive range.",type:"string"}},required:["start_block_id"],type:"object"},type:"array"}},required:["ranges"],type:"object"}},{name:"view_image",description:'View a document image by block ID when its <img> src is hidden. Viewing is only for seeing pixels; you do not need the hidden source to copy, move, or swap an image—write <img src="IMAGE_ID"> with its exact document id in insert_block or replace_block HTML.',inputSchema:{additionalProperties:!1,properties:{block_id:{description:"Image block ID.",type:"string"}},required:["block_id"],type:"object"}},{name:"insert_block",description:'Insert native block(s) before/after a reference block using HTML. A reference may be nested inside a table cell; inserting <img> (bare or wrapped by a paragraph/presentational span) next to that reference creates a native image block in the same cell. For a web-sourced image, use a verified direct raster URL returned by search for src; never guess or infer an image filename. Add data-source-url="..." to the <img> using the source webpage URL returned by web search, or the original image URL when no webpage URL is available; Revise preserves this provenance across later requests while rehosting the rendered image. For a live table of contents that automatically tracks document headings, insert <toc levels="3"></toc> (levels may be 1-6; omitting the attribute defaults to 3). Never build a table of contents from ordinary paragraphs, tabs, lists, or manually copied headings. For an Arabic/RTL live TOC, keep the toc block and set dir="rtl" and style="text-align:right" on it; direction:rtl and text-align:right also work through style_blocks. RTL places page numbers at the left edge. Do not replace a live TOC with a static table to adjust formatting. Put alignment directly in inserted HTML when needed. To cite inside new content, embed native notes inline: <sup data-footnote="Note body.">1</sup> creates a footnote in this same call (data-note-kind="endnote" for endnotes).',inputSchema:{additionalProperties:!1,properties:{content:{description:'HTML block elements to insert, e.g. <p>, <h1>, <ul>, <img>, <toc levels="3"></toc> (live table of contents), <page-break />, <hr /> (horizontal rule), <pre>. An image may be wrapped in a paragraph/span for alignment and display dimensions. For a web-sourced image, use a verified direct raster URL returned by search for src. Never guess or infer an image filename. Put its source webpage URL in data-source-url on the <img> (fall back to the original image URL). An image whose src is hidden is still usable: to copy or move it, write <img src="IMAGE_ID"> with its exact document id (dimensions and alt may be restated); the source is resolved automatically, so never ask the user for it.',items:{type:"string"},type:"array"},position:{description:"Insert before or after reference block.",enum:["before","after"],type:"string"},referenceId:{description:"Current reference block ID. For a blank document, pass an empty string with position=after; the editor resolves the blank insertion location. Never ask the user to type placeholder text. For a document with content, use an existing block ID.",type:"string"}},required:["content","position","referenceId"],type:"object"}},{name:"insert_footnote",description:"Insert a footnote: a numbered superscript reference placed right after the anchor text in a paragraph, plus the footnote body (rendered at the bottom of the page). Footnote bodies appear in the document as [^n] references with their own blocks — edit them with replace/replace_block and remove them with remove_blocks on the footnote block (removing a body also removes its reference).",inputSchema:{additionalProperties:!1,properties:{find:{description:"Anchor text inside the block; the reference is inserted right after it. Empty string appends at the end of the block.",type:"string"},id:{description:"Paragraph block ID that receives the reference.",type:"string"},kind:{description:"Note stream: footnote (per-page bottom area, numbered 1,2,3 — default) or endnote (grouped on its own page at the document end, numbered i,ii,iii).",enum:["footnote","endnote"],type:"string"},text:{description:"Footnote body text.",type:"string"}},required:["id","find","text"],type:"object"}},{name:"remove_blocks",description:"Remove native footnotes/endnotes by targeting the note ID or its body block ID with id + count=1; this removes the entire note and all its inline references while preserving the surrounding paragraph. To remove multiple notes, use ids containing only note/body IDs (do not mix with main-document block IDs or use a count range). For notes found by search, use their explicit IDs rather than search_result_id. Remove one or more blocks by a direct target (id, optionally with count), an explicit tail range (id + through_end=true), an exact nonconsecutive ID batch (ids), or every block in a full search_document result (search_result_id). through_end removes the starting top-level block and every block after it through the current end of the document; use it only when that entire tail must be removed. The starting id must have appeared in current request context, but through_end does not require reading every interior block. Other direct targets must have appeared in current request context. Prefer search_result_id for large or sparse match sets; search discovers candidates but never deletes them implicitly.",inputSchema:{additionalProperties:!1,properties:{count:{description:"Number of consecutive blocks. Only count blocks available in the current document context; never use the document total block count.",minimum:1,type:"integer"},id:{description:"First block ID to remove.",type:"string"},ids:{description:"Exact nonconsecutive block IDs to remove. Each ID must have appeared in document context during this request. Do not infer IDs from a query.",items:{type:"string"},maxItems:50,minItems:1,type:"array"},search_result_id:{description:"Request-scoped ID returned by search_document for the current document. Applies this operation to every block in the full unpaginated result set. Use instead of id or ids. Rerun search_document if the reference is unavailable or stale.",type:"string"},through_end:{description:"Set true with id to remove that top-level block and the entire document tail after it. Mutually exclusive with count, ids, and search_result_id. Omit unless the whole tail is intentionally in scope.",type:"boolean"}},type:"object"}},{name:"append_to_paragraph",description:"Append HTML content to a paragraph.",inputSchema:{additionalProperties:!1,properties:{content:{description:"HTML content to append.",type:"string"},id:{description:"Paragraph ID.",type:"string"}},required:["id","content"],type:"object"}},{name:"break_paragraph",description:"Split a paragraph at the first occurrence of substring; second paragraph starts there.",inputSchema:{additionalProperties:!1,properties:{id:{description:"Paragraph ID.",type:"string"},substring:{description:"Substring where split begins.",type:"string"}},required:["id","substring"],type:"object"}},{name:"join_paragraphs",description:"Join two adjacent paragraphs without rewriting their text. The second paragraph is appended to the first, preserving inline formatting from both paragraphs, then removed. Use this to repair an accidental paragraph break or hard return.",inputSchema:{additionalProperties:!1,properties:{firstId:{description:"ID of the first paragraph. This paragraph and its block formatting are preserved.",type:"string"},secondId:{description:"ID of the immediately following sibling paragraph. Its inline-formatted text is appended, then this block is removed.",type:"string"},separator:{description:"Text placed between the paragraphs. Defaults to one space between non-empty paragraphs. A non-empty separator replaces existing boundary whitespace so it is not duplicated. Pass an empty string to add nothing and preserve existing boundary whitespace.",type:"string"}},required:["firstId","secondId"],type:"object"}},{name:"replace_block",description:'Replace entire consecutive block(s) with HTML block(s), or apply the same one-block replacement independently to every block in a full search_document result via search_result_id. Use this only when the whole block must be replaced, its block type must change, or multiple consecutive blocks must become a different block structure. Prefer replace for ordinary wording, sentence, paragraph-text, typo, punctuation, or formatting-preserving edits—even when most or all visible text in one paragraph changes—because replace preserves block identity and untouched formatting. Preserve the existing block type unless the user asks to change it: use <pre language="..."> for code, <latex> for display math, and <latex-inline> for inline math. Put alignment in replacement HTML. For a web-sourced replacement image, use a verified direct raster URL returned by search for src; never guess or infer an image filename. Put its source webpage URL in data-source-url on the <img> (fall back to the original image URL).',inputSchema:{additionalProperties:!1,properties:{content:{description:'Replacement HTML block elements, e.g. <p>, <h1>, <ul>, <pre language="typescript">code</pre>, <img>, or <latex>E = mc^2</latex>. Match the original block type unless a type change was requested. For a web-sourced image, use a verified direct raster URL returned by search for src. Never guess or infer an image filename. Put its source webpage URL in data-source-url on the <img> (fall back to the original image URL). An image whose src is hidden is still usable: to copy or move it, write <img src="IMAGE_ID"> with its exact document id (dimensions and alt may be restated); the source is resolved automatically, so never ask the user for it.',items:{type:"string"},type:"array"},count:{description:"Number of consecutive sibling blocks to replace. Only count blocks available in the current document context; never use the document total block count.",minimum:1,type:"integer"},id:{description:"First block ID to replace.",type:"string"},search_result_id:{description:"Request-scoped ID returned by search_document for the current document. Applies this operation to every block in the full unpaginated result set. Use instead of id or ids. Rerun search_document if the reference is unavailable or stale.",type:"string"}},required:["content"],type:"object"}},{name:"style_blocks",description:'Style existing content with forgiving CSS-lite selectors and values. Use one bulk style_blocks call instead of per-block replace calls when matching content shares a selector or search result. Pass search_result_id to scope selectors to every block in the full unpaginated search_document result; * then means each matched block. Block selectors include *, #blockId, p, h1-h6, li, lists, tables, and descendants. Inline selectors such as span, b/strong, i/em, u, s/strike/del, code, sup, sub, mark, and a target text ranges; they may be scoped, for example p span, p b, or #blockId strong. Text color accepts CSS named colors, hex colors, and CSS color functions and stores an absolute hex color. For text highlighting, use backgroundColor with one of the seven canonical values yellow, orange, green, blue, purple, pink, or gray; other names and CSS colors normalize to this palette and may be the same color. A backgroundColor on a table-cell selector sets the cell fill; on text blocks or inline selectors it highlights text. Table-cell selectors apply text styles, alignment, and spacing to their descendant paragraphs. Examples: highlight all h3 headings orange with selectors="h3" and attrs=[{"name":"backgroundColor","value":"orange"}]; remove all bold with selectors="b" and attrs=[{"name":"fontWeight","value":"normal"}]; set the entire document to Century Schoolbook 14pt double-spaced with selectors="*" and fontFamily/fontSize/lineSpacing attrs; bold headings with selectors=["h1","h2","h3"] and fontWeight="bold".',inputSchema:{additionalProperties:!1,properties:{attrs:{description:"Use CSS/Revise names. Text colors accept CSS names, hex, or functions. Highlights: yellow, orange, green, blue, purple, pink, or gray. Supports text typography, block alignment, hanging indents, list presentation, image sizing with CSS lengths, and table/cell sizing with percentage widths. CSS maps to durable document equivalents; feedback lists approximations and unsupported values. Null resets.",items:{additionalProperties:!1,properties:{name:{description:"Attribute/style name, e.g. fontSize, font-size, fontFamily, text-align.",type:"string"},value:{description:"Value to set, or null to remove/reset.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["name","value"],type:"object"},minItems:1,type:"array"},search_result_id:{description:"Request-scoped ID returned by search_document for the current document. Applies this operation to every block in the full unpaginated result set. Use instead of id or ids. Rerun search_document if the reference is unavailable or stale.",type:"string"},selectors:{description:'CSS-lite selectors over the document HTML: * (also all, document, or :root), #blockId, p, h1-h6, li, ul, ol, pre, latex, img, table, tr, td/th, div, p[data-style-id="StyleName"], and inline formatting tags span, b/strong, i/em, u, s/strike/del, code, sup, sub, mark, a. Simple descendants, general siblings, descendant wildcards, :first-child, and :nth-child(n) are accepted, e.g. table tr:first-child td, table td:nth-child(2) p, #blockId td p, #blockId *, #blockId ~ p, p span, p b, or #blockId strong. Inline selectors affect matching text ranges; span means all text in its scope. Arrays and comma grouping are allowed.',oneOf:[{type:"string"},{items:{type:"string"},minItems:1,type:"array"}]}},required:["selectors","attrs"],type:"object"}},{name:"clear_formatting",description:"Clear removable inline emphasis from paragraph/list-item target(s): bold, italic, underline, code, LaTeX, superscript/subscript, background highlight, and links. Preserve font family, font size, text color, and paragraph attributes.",inputSchema:{additionalProperties:!1,properties:{id:{description:"Target paragraph/list-item/list ID or IDs.",oneOf:[{type:"string"},{items:{type:"string"},minItems:1,type:"array"}]}},required:["id"],type:"object"}},{name:"set_title",description:"Change the document title",inputSchema:{additionalProperties:!1,properties:{title:{description:"The new document title",maxLength:300,type:"string"}},required:["title"],type:"object"}},{name:"set_page_layout",description:"Patch page or section layout: preset, size, margins, 1-3 columns, page numbers, spacing, pageless mode. ONLY the fields you pass change; everything else keeps its current or inherited value (a section keeps inheriting document-level settings for fields you don't pass). Pass sectionIndex to change one section; omit it to apply the passed fields to the document defaults and every section. Length fields must be strings with explicit px/in/cm units. Preset 'apa7' applies standard APA layout.",inputSchema:{additionalProperties:!1,properties:{blockSpacing:{description:'Vertical spacing between adjacent blocks, shown in the UI in inches or centimeters. Typical values are "0.08in" to "0.25in" (about "0.2cm" to "0.64cm"); do not use whole-inch values like "2in" or "4in" for normal paragraph spacing. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},clearPageBorders:{description:"Set true to remove all page borders from the target section(s), including preserved Word art borders.",type:"boolean"},columnCount:{description:"Number of newspaper-style columns in the target section.",enum:[1,2,3],type:"integer"},columnGap:{description:'Gap between columns. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},indentStep:{description:'Paragraph indent step. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},margin:{description:'Uniform page margin applied to all sides. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},marginBottom:{description:'Bottom page margin. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},marginLeft:{description:'Left page margin. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},marginRight:{description:'Right page margin. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},marginTop:{description:'Top page margin. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},noteMode:{description:"Bulk-convert existing native notes to this stream: footnotes (per-page areas, 1,2,3) or endnotes (own page at document end, i,ii,iii). Does not convert manually typed superscript numbers or note paragraphs; create native notes with their complete bodies and references first. Individual notes choose a stream at insert time.",enum:["footnotes","endnotes"],type:"string"},orientation:{description:"Page orientation.",enum:["portrait","landscape"],type:"string"},pageBorders:{additionalProperties:!1,description:"Native page border for the target section(s), rendered in the editor and PDF and preserved in DOCX. Replaces the whole border configuration; omitted sides have no border. To remove borders use clearPageBorders=true. Measurements are points (1/72 inch).",properties:{bottom:{additionalProperties:!1,properties:{color:{pattern:"^#[0-9a-fA-F]{6}$",type:"string"},spacePt:{maximum:31,minimum:0,type:"number"},style:{enum:["single","double","dotted","dashed"],type:"string"},widthPt:{maximum:12,minimum:.25,type:"number"}},required:["style","color","widthPt","spacePt"],type:"object"},display:{enum:["allPages","firstPage","notFirstPage"],type:"string"},left:{additionalProperties:!1,properties:{color:{pattern:"^#[0-9a-fA-F]{6}$",type:"string"},spacePt:{maximum:31,minimum:0,type:"number"},style:{enum:["single","double","dotted","dashed"],type:"string"},widthPt:{maximum:12,minimum:.25,type:"number"}},required:["style","color","widthPt","spacePt"],type:"object"},offsetFrom:{enum:["page","text"],type:"string"},right:{additionalProperties:!1,properties:{color:{pattern:"^#[0-9a-fA-F]{6}$",type:"string"},spacePt:{maximum:31,minimum:0,type:"number"},style:{enum:["single","double","dotted","dashed"],type:"string"},widthPt:{maximum:12,minimum:.25,type:"number"}},required:["style","color","widthPt","spacePt"],type:"object"},top:{additionalProperties:!1,properties:{color:{pattern:"^#[0-9a-fA-F]{6}$",type:"string"},spacePt:{maximum:31,minimum:0,type:"number"},style:{enum:["single","double","dotted","dashed"],type:"string"},widthPt:{maximum:12,minimum:.25,type:"number"}},required:["style","color","widthPt","spacePt"],type:"object"},zOrder:{enum:["front","back"],type:"string"}},required:["offsetFrom","display","zOrder"],type:"object"},pageHeight:{description:'Explicit page height. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},pageNumberFormat:{description:"Page number style: decimal (1, 2, 3), lowerRoman (i, ii, iii), or upperRoman (I, II, III). Applies to page-number fields, the table of contents, and exports. Use sectionIndex for front matter.",enum:["decimal","lowerRoman","upperRoman"],type:"string"},pageNumberPosition:{description:"Page number position.",enum:["top-left","top-right","bottom-left","bottom-right"],type:"string"},pageNumberRestart:{description:"Section numbering mode (use with sectionIndex, including the final section): true restarts at pageNumberStart (default 1); false continues from the previous section. Typical thesis: Roman front matter, then the final body section restarts at 1.",type:"boolean"},pageNumberStart:{description:"First page number. With sectionIndex it restarts numbering at that section (e.g. body starts again at 1 after Roman front matter).",minimum:1,type:"integer"},pageSize:{description:"Named page-size preset.",enum:["letter","tabloid","legal","statement","executive","folio","a3","a4","a5","b4","b5"],type:"string"},pageWidth:{description:'Explicit page width. Include an explicit unit: in, cm, or px (examples: "1in", "3cm", "72px"). Prefer in/cm for page layout values shown in the UI. Do not send bare numbers.',type:"string"},pageless:{description:"Enable pageless mode.",type:"boolean"},preset:{description:"Preset applied before overrides.",enum:["apa7"],type:"string"},sectionIndex:{description:"One-based section number to patch (invalid indexes fail the call). Omit to apply the passed fields to the document defaults and every section.",minimum:1,type:"integer"},showPageNumbers:{description:"Show or hide page numbers. Page numbers are header/footer content: this manages an automatic page-number field slot (combine with pageNumberPosition). Hand-authored header/footer content is never overwritten.",type:"boolean"}},required:[],type:"object"}},{name:"set_header_footer",description:'Edit page header/footer content. Each side has three zones (left, center, right); provide only the zones to change - untouched zones keep their content and formatting. Use the literal token {PAGE} for a live page number and {PAGES} for the total page count, anywhere in any zone (e.g. right: "Page {PAGE} of {PAGES}"). An empty string clears a zone; clear=true removes the whole header or footer. For a plain bottom-right page number, set_page_layout with showPageNumbers also works.',inputSchema:{properties:{center:{description:"Center zone text ({PAGE}/{PAGES} tokens allowed). Omit to keep unchanged; empty string clears.",type:"string"},clear:{description:"Remove this side's header/footer entirely.",type:"boolean"},left:{description:"Left zone text ({PAGE}/{PAGES} tokens allowed). Omit to keep unchanged; empty string clears.",type:"string"},right:{description:"Right zone text ({PAGE}/{PAGES} tokens allowed). Omit to keep unchanged; empty string clears.",type:"string"},side:{description:"Which band to edit.",enum:["header","footer"],type:"string"},slot:{description:"Which pages this applies to (Word slot model). Default: all pages.",enum:["default","first","even"],type:"string"}},required:["side"],type:"object"}},{name:"replace",description:"Preferred/default tool for editing text inside an existing block, including wording, sentences, typos, punctuation, formatting-preserving rewrites, and even replacing all visible text in one paragraph when its block type/structure should stay the same. It preserves block identity and untouched formatting; use replace_block only for whole-block structural or block-type changes. Supports one or more in-place edits inside one block, uniquely identifiable edits across loaded blocks when id is omitted, or the same edits independently in every block from a full search_document result via search_result_id. An empty find safely fills a direct-id target only when that target is truly empty. Each operation may include its own comment, which is attached to every suggestion produced by that operation. For each edit, occurrence defaults to unique: its find HTML/text must be specific enough to match exactly one location in each target block or the entire call fails without changing the document. Use occurrence=all only when every exact occurrence should change. Omit no-op replacements where find and replace are identical.",inputSchema:{additionalProperties:!1,properties:{id:{description:"Target block ID. May be omitted only when every non-empty find uniquely identifies one loaded block, or when search_result_id is used.",type:"string"},replacements:{description:"Ordered replacement operations. Use one item for one edit and multiple items to batch edits in the same block.",items:{additionalProperties:!1,properties:{comment:{description:"Optional comment explaining this operation. It is attached separately to every resulting suggestion from this operation, including every match when occurrence=all. Prefer this over a separate leave_comment when the feedback explains the suggested edit.",type:"string"},find:{description:"Exact text to find; HTML allowed for formatted targets. With occurrence=unique or when occurrence is omitted, include enough surrounding context to match exactly one location.",type:"string"},occurrence:{description:"unique (default when omitted) requires exactly one match; all replaces every exact match.",enum:["unique","all"],type:"string"},replace:{description:"Replacement text; HTML allowed for formatting changes. Must differ from find unless the replacement HTML creates a real formatting change.",type:"string"}},required:["find","replace"],type:"object"},maxItems:50,minItems:1,type:"array"},search_result_id:{description:"Request-scoped ID returned by search_document for the current document. Applies this operation to every block in the full unpaginated result set. Use instead of id or ids. Rerun search_document if the reference is unavailable or stale.",type:"string"}},required:["replacements"],type:"object"}},{name:"leave_comment",description:"Leave granular review feedback on the current document without changing its text. Prefer this for substantive passage-specific critique, feedback, annotations, issues, or improvements instead of putting that feedback in a long chat response. Two modes. To START a thread: target one block with id and exactly one anchor form — unique exact text for a short range, start/end boundary text for a longer range without reproducing it, or the whole block for structural/empty content. To REPLY to a thread that already exists: pass reply_to_comment_id (a <comment-thread> id from loaded document content) and comment, with no id and no anchor. Existing threads are visible as <comment-thread> elements in loaded document content; when text already carries one, reply to it rather than starting a second thread that repeats the same point.",inputSchema:{additionalProperties:!1,properties:{acknowledge_existing_thread_ids:{description:"Only for a NEW thread that deliberately overlaps existing unresolved threads: list their ids to confirm you read them and are raising a genuinely different point. Without this, a new thread overlapping an existing one is rejected. Do not use it to restate a point an existing thread already makes — reply to that thread instead.",items:{type:"string"},type:"array"},anchor:{description:"Exactly one single-block anchor. Required for a new thread; omit when replying.",oneOf:[{additionalProperties:!1,properties:{text:{description:"Exact text or HTML fragment that identifies exactly one occurrence in the block. When words repeat with different formatting, include the formatting, for example <b>claim</b> for the bold occurrence or <i>claim</i> for the italic occurrence. Include only the text to be commented on.",type:"string"}},required:["text"],type:"object"},{additionalProperties:!1,properties:{end_text:{description:"Exact text or HTML fragment at the end of the range. This boundary is included in the comment; do not use surrounding separators unless they should also be commented on.",type:"string"},start_text:{description:"Exact text or HTML fragment at the beginning of the range. This boundary is included in the comment; do not use surrounding separators unless they should also be commented on.",type:"string"}},required:["start_text","end_text"],type:"object"},{additionalProperties:!1,properties:{whole_block:{const:!0,description:"Anchor the comment to the entire block.",type:"boolean"}},required:["whole_block"],type:"object"}]},comment:{description:"Comment body.",type:"string"},id:{description:"Target block ID for a NEW thread. The block must be present in loaded document context. Omit when replying.",type:"string"},reply_to_comment_id:{description:"Reply to an existing thread instead of starting a new one: any comment id in that thread (the reply attaches to the thread root). A reply inherits the thread's anchor, so omit id and anchor when replying.",type:"string"}},required:["comment"],type:"object"}},{name:"insert_table_row",description:"Insert a new row into an existing table. Prefer referenceRowId from the visible <tr id> for a named row; this remains stable when earlier rows are inserted. Use position=before for above/before that row and after for below/after. Only call this when the target <table> block is visible in the loaded document content; read the table's blocks first if it is not loaded.",inputSchema:{additionalProperties:!1,properties:{content:{description:"HTML indexed by grid column (0-based); use an empty string as a placeholder for a position covered by a merged cell, or an empty array to insert empty cells. Nonempty content at covered positions and entries beyond the table dimensions are rejected without changing the table.",items:{type:"string"},type:"array"},position:{description:"Whether to insert before or after the reference row",enum:["before","after"],type:"string"},referenceIndex:{description:"Optional 0-based row index, counting header and empty rows. Required only without referenceRowId. If both are supplied, they must identify the same current row.",type:"integer"},referenceRowId:{description:"Preferred stable row ID from <tr id> in the loaded table. Supply this or referenceIndex.",type:"string"},tableId:{description:"The table block ID",type:"string"}},required:["tableId","position","content"],type:"object"}},{name:"remove_table_row",description:"Remove a row from an existing table. Only call this when the target <table> block is visible in the loaded document content; read the table's blocks first if it is not loaded.",inputSchema:{additionalProperties:!1,properties:{rowIndex:{description:"The index of the row to remove (0-based)",type:"integer"},tableId:{description:"The table block ID",type:"string"}},required:["tableId","rowIndex"],type:"object"}},{name:"insert_table_column",description:"Insert a new column into an existing table. Only call this when the target <table> block is visible in the loaded document content; read the table's blocks first if it is not loaded.",inputSchema:{additionalProperties:!1,properties:{content:{description:"HTML indexed by grid row (0-based); use an empty string as a placeholder for a position covered by a merged cell, or an empty array to insert empty cells. Nonempty content at covered positions and entries beyond the table dimensions are rejected without changing the table.",items:{type:"string"},type:"array"},position:{description:"Whether to insert before or after the reference column",enum:["before","after"],type:"string"},referenceIndex:{description:"The column index to insert relative to (0-based)",type:"integer"},tableId:{description:"The table block ID",type:"string"}},required:["tableId","referenceIndex","position","content"],type:"object"}},{name:"remove_table_column",description:"Remove a column from an existing table. Only call this when the target <table> block is visible in the loaded document content; read the table's blocks first if it is not loaded.",inputSchema:{additionalProperties:!1,properties:{columnIndex:{description:"The index of the column to remove (0-based)",type:"integer"},tableId:{description:"The table block ID",type:"string"}},required:["tableId","columnIndex"],type:"object"}}],Ml=50,Nm="out_of_context_edit";function Fm(r){const{toolCall:t,docBefore:e,isTargetAllowed:n}=r;if(t.name!=="remove_block")return null;const o=t.arguments;if(!o||typeof o!="object")return null;const i=o.through_end;if(i==null||i===!1)return null;if(i!==!0)return{toolCall:t,targetBlockIds:[],error:"remove_blocks through_end must be true when provided."};const s=o.id,a=o.count,c=o.ids,l=o.search_result_id;if(typeof s!="string"||s.trim().length===0)return{toolCall:t,targetBlockIds:[],error:"remove_blocks through_end requires a non-empty top-level id."};if(a!=null||c!=null||l!=null)return{toolCall:t,targetBlockIds:[],error:"remove_blocks through_end is mutually exclusive with count, ids, and search_result_id."};const d=s.trim(),u=ee(e,d);if(u<0||e.children[u]?.id!==d)return{toolCall:t,targetBlockIds:[],error:`remove_blocks through_end target '${d}' must be a current top-level block.`};if(!n(d))return{toolCall:t,targetBlockIds:[],error:`remove_blocks through_end start '${d}' is outside the request-level document context. Read or search for that boundary block first, then retry.`,errorCode:Nm};const g=e.children.slice(u).map(p=>p.id).filter(p=>typeof p=="string"&&p.length>0);return{toolCall:{...t,arguments:{id:d,count:g.length}},targetBlockIds:g}}function Em(r,t,e){if(r.name!=="remove_block")return{actions:[r]};const n=r.arguments;if(!n||typeof n!="object")return{actions:[],error:"remove_blocks requires object arguments"};const o=n.ids;if(o==null)return{actions:[r]};if(typeof n.id=="string")return{actions:[],error:"remove_blocks accepts either id + count or ids, not both."};if(!Array.isArray(o)||o.length===0)return{actions:[],error:"remove_blocks ids must be a non-empty array"};if(o.length>Ml)return{actions:[],error:`remove_blocks supports at most ${Ml} exact IDs per call`};const i=[],s=new Set;for(const c of o){if(typeof c!="string"||c.trim().length===0)return{actions:[],error:"remove_blocks ids must all be non-empty strings"};const l=c.trim();if(!s.has(l)){if(!z(t,l))return{actions:[],error:`remove_blocks target '${l}' was not found`};if(!e(l))return{actions:[],error:`remove_blocks target '${l}' is outside the request-level document context. Read or search for that block first, then retry the exact ID batch.`};s.add(l),i.push(l)}}const a=i.filter(c=>gn(t,c)).length;return a>0&&a<i.length?{actions:[],error:"Remove footnotes/endnotes separately from main-document blocks. Pass only note IDs in this batch so each note and its references are removed together."}:{actions:i.map((c,l)=>({id:`${r.id||"remove_block"}-${l+1}`,name:"remove_block",arguments:{id:c,count:1}}))}}function $l(r){const t=new URLSearchParams;r.query!==void 0&&t.set("q",r.query),t.set("includeContent","false");for(const e of["page","limit","currentFolderId","parentFolderId","sortBy","order"]){const n=r[e];n!=null&&n!==""&&t.set(e,String(n))}return r.includeFolders&&t.set("includeFolders","1"),t}function Bl(r,t=10){const e=r,n=Array.isArray(e?.items)?e.items:[],o=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0;return{items:n,totalCount:o(e?.pagination?.totalCount)?e.pagination.totalCount:n.length,totalPages:o(e?.pagination?.totalPages)?e.pagination.totalPages:Math.max(1,Math.ceil(n.length/Math.max(1,t))),hasMore:e?.pagination?.hasMore===!0}}function _l(r){return typeof r=="object"&&r!==null&&r.type==="doc"&&Array.isArray(r.children)}function Rm(r,t=[]){const e=new x.Doc;x.applyUpdate(e,Or(r));for(const n of t)n&&x.applyUpdate(e,Or(n));return Tt(e)}function Dm({content:r,yjsState:t,yjsUpdates:e,source:n}){const o=Array.isArray(e)?e.filter(i=>i.length>0):[];if(typeof t=="string"&&t.length>0||o.length>0)try{if(typeof t=="string"&&t.length>0)return Rm(t,o);const i=_l(r)?$n(r):new x.Doc;if(o.length>0){for(const s of o)x.applyUpdate(i,Or(s));return Tt(i)}}catch(i){console.error(`[resolveDocRootFromSerializedState] Failed to decode yjs updates${n?` for ${n}`:""}`,i)}return _l(r)?r:null}const Om="revise_conversations",jm=2,Ll="conversations",no="attachments";let Oe=null;function Nl(){return typeof indexedDB<"u"}function Fl(r){return Oe||(Oe=new Promise((t,e)=>{if(!Nl()){e(new Error("IndexedDB not available"));return}const n=indexedDB.open(Om,r??jm);n.onerror=()=>{Oe=null,e(n.error)},n.onblocked=()=>{console.warn("[LocalConversationStorage] Database upgrade blocked - close other tabs")},n.onsuccess=()=>{const o=n.result;if(!o.objectStoreNames.contains(no)){if(r!==void 0){o.close(),Oe=null,e(new Error("Attachments store still missing after version bump"));return}console.warn("[LocalConversationStorage] Attachments store missing, bumping version to create it");const i=o.version+1;o.close(),Oe=null,Fl(i).then(t).catch(e);return}o.onclose=()=>{Oe=null},o.onerror=()=>{Oe=null},t(o)},n.onupgradeneeded=o=>{const i=o.target.result;if(!i.objectStoreNames.contains(Ll)){const s=i.createObjectStore(Ll,{keyPath:"id"});s.createIndex("documentId","documentId",{unique:!1}),s.createIndex("updatedAt","updatedAt",{unique:!1})}i.objectStoreNames.contains(no)||i.createObjectStore(no,{keyPath:"id"}).createIndex("conversationId","conversationId",{unique:!1})}}),Oe)}async function Um(r){if(!Nl())return null;try{const t=await Fl();return new Promise((e,n)=>{const o=t.transaction(no,"readonly").objectStore(no).get(r);o.onsuccess=()=>{e(o.result??null)},o.onerror=()=>n(o.error)})}catch(t){return console.warn("[LocalConversationStorage] Failed to get attachment:",t),null}}const ds=/(<img\b[^>]*?\bsrc\s*=\s*)(["'])([\s\S]*?)\2/gi,El=/(!\[[^\]]*\]\(\s*)(<[^>]+>|[^)\s]+)((?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\))/g;function kr(r){const t=r.trim();return t.startsWith("<")&&t.endsWith(">")?t.slice(1,-1).trim():t}function qm(r){const t=new Set(["images.revise.io"]);for(const e of r.flatMap(n=>(n??"").split(",")))if(e.trim())try{t.add(new URL(e.includes("://")?e.trim():"https://"+e.trim()).host)}catch{}return t}function zm(r,t,e){try{const n=new URL(kr(r),e);return!["http:","https:"].includes(n.protocol)||t.has(n.host)?!1:!e||n.origin!==new URL(e).origin}catch{return!1}}function Xm(r,t,e,n=!1){for(const o of r.matchAll(ds)){const i=kr(o[3]);e(i)&&t.add(i)}if(n)for(const o of r.matchAll(El)){const i=kr(o[2]);e(i)&&t.add(i)}}function Hm(r){try{const t=new URL(r);if(t.hostname!=="upload.wikimedia.org")return r;const e=t.pathname.split("/");return e.length<8||e[1]!=="wikipedia"||e[2]!=="commons"||e[3]!=="thumb"?r:(t.pathname=["","wikipedia","commons",...e.slice(4,-1)].join("/"),t.toString())}catch{return r}}function Wm(r){return r.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Jm(r,t){return r.replace(/<img\b[^>]*>/gi,e=>{const n=Array.from(e.matchAll(ds))[0];if(!n)return e;const o=n[3].trim(),i=t.get(o);if(!i)return e;let s=e.replace(ds,(c,l,d)=>`${l}${d}${i.url}${d}`);const a=[];return/\bdata-source-url\s*=/i.test(s)||a.push(`data-source-url="${Wm(o)}"`),i.naturalWidth&&i.naturalHeight&&!/\bdata-revise-natural-(?:width|height)\s*=/i.test(s)&&a.push(`data-revise-natural-width="${i.naturalWidth}"`,`data-revise-natural-height="${i.naturalHeight}"`),a.length>0&&(s=s.replace(/\s*\/?>$/,c=>` ${a.join(" ")}${c}`)),s})}function Rl(r,t,e=!1){const n=e?r.replace(El,(o,i,s,a)=>{const c=t.get(kr(s));return c?i+"<"+c.url+">"+a:o}):r;return Jm(n,t)}const Ym="https://app-api.revise-sdk.invalid";function Km(r){return zm(r,qm([""]),typeof window<"u"?window.location.href:void 0)}function Dl(r){return typeof r=="number"&&Number.isInteger(r)&&r>0?r:void 0}async function Vm(r){try{const t=await fetch(`${Ym}/uploads/images/rehost`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:Hm(r)}),signal:AbortSignal.timeout(3e4)});if(!t.ok){let i=`Image copy request failed (HTTP ${t.status}).`;try{const s=await t.json();typeof s.error=="string"&&s.error.trim().length>0&&(i=s.error.trim())}catch{}return{ok:!1,failure:{url:r,status:t.status,message:i}}}const e=await t.json();if(typeof e.fileUrl!="string"||!e.fileUrl)return{ok:!1,failure:{url:r,status:t.status,message:"Image copy response did not include a file URL."}};const n=Dl(e.width),o=Dl(e.height);return{ok:!0,image:{url:e.fileUrl,...n&&o?{naturalWidth:n,naturalHeight:o}:{}}}}catch{return{ok:!1,failure:{url:r,message:"Image copy request could not reach Revise storage."}}}}const Ol=new Set(["insert_block","replace_block"]);function Gm(r){const t=new Set;for(const e of r??[]){if(!e?.name||!Ol.has(e.name))continue;const n=e.arguments?.content;for(const o of Array.isArray(n)?n:[n])typeof o=="string"&&Xm(o,t,Km)}return t}async function Zm(r){const t={attempted:0,rehosted:0,failedUrls:[],failures:[]};if(!Array.isArray(r)||r.length===0)return t;const e=Gm(r);if(e.size===0)return t;const n=new Map,o=[];await Promise.all([...e].map(async s=>{const a=await Vm(s);a.ok?n.set(s,a.image):o.push(a.failure)}));const i=[...e].filter(s=>!n.has(s));if(n.size===0)return{attempted:e.size,rehosted:0,failedUrls:i,failures:o};for(const s of r){if(!s?.name||!Ol.has(s.name))continue;const a=s.arguments;a&&(typeof a.content=="string"?a.content=Rl(a.content,n):Array.isArray(a.content)&&(a.content=a.content.map(c=>typeof c=="string"?Rl(c,n):c)))}return{attempted:e.size,rehosted:n.size,failedUrls:i,failures:o}}function Qm(r,t){const e=r.children.flatMap((n,o)=>n.type==="paragraph"&&n.heading?[{index:o,level:n.heading,blockId:n.id,title:Ft(n).replace(/\s+/g," ").trim()}]:[]);return e.filter(n=>n.level<=t?.maxDepth).map(n=>({...n,endIndex:(e.find(o=>o.index>n.index&&(t?.flat||o.level<=n.level))?.index??r.children.length)-1}))}const tb=new Set([8203,8204,8205,8288,65279]);function eb(){return{wordCount:0,paragraphCount:0,characterCount:0,hasVisibleText:!1,inWord:!1}}function jl(r,t){for(let e=0;e<r.length;e+=1){const n=r.codePointAt(e);if(n===void 0||(n>65535&&(e+=1),tb.has(n)))continue;const o=String.fromCodePoint(n);if(t.characterCount+=o.length,/\s/.test(o)){t.inWord=!1;continue}t.hasVisibleText=!0,t.inWord||(t.wordCount+=1,t.inWord=!0)}}function Ul(r,t){if(!r||typeof r!="object")return;const e=r;if(e.type==="text"&&typeof e.text=="string"){jl(e.text,t);return}if(e.type==="paragraph"&&(t.paragraphCount+=1),(e.type==="code"||e.type==="math")&&typeof e.content=="string"){jl(e.content,t),t.inWord=!1;return}if(e.type==="placeholder"||e.type==="image"||e.type==="page-break"||e.type==="section-break"){t.inWord=!1;return}if(Array.isArray(e.children))for(const n of e.children)Ul(n,t),n&&typeof n=="object"&&"type"in n&&n.type!=="text"&&(t.inWord=!1)}function nb(r){const t=eb();for(const n of r)Ul(n,t),t.inWord=!1;const e={parts:[],paragraphCount:0,containsSentinel:!1};for(const n of r)ql(n,e),e.parts.push(" ");return t.wordCount=ku(e.parts.join("")),t}const oo="\0";function ql(r,t){if(!r||typeof r!="object")return;const e=r;if(e.type==="text"&&typeof e.text=="string"){e.text.includes(oo)&&(t.containsSentinel=!0),t.parts.push(e.text);return}if(e.type==="paragraph"&&(t.paragraphCount+=1),(e.type==="code"||e.type==="math")&&typeof e.content=="string"){e.content.includes(oo)&&(t.containsSentinel=!0),t.parts.push(e.content,oo);return}if(e.type==="placeholder"||e.type==="image"||e.type==="page-break"||e.type==="section-break"){t.parts.push(oo);return}if(Array.isArray(e.children))for(const n of e.children)ql(n,t),n&&typeof n=="object"&&"type"in n&&n.type!=="text"&&t.parts.push(oo)}function zl(r){return nb(r)}function Xl(r){const t=be(r.pageLayout),e=Ar(t);return{layout:yu({pageWidth:e.pageWidth,pageHeight:e.pageHeight,pageMargin:t.marginLeftPx,pageMarginTop:t.marginTopPx,pageMarginRight:t.marginRightPx,pageMarginBottom:t.marginBottomPx,pageMarginLeft:t.marginLeftPx,availableWidth:Math.max(1,e.pageWidth-t.marginLeftPx-t.marginRightPx),textStartY:t.marginTopPx,indentStepPx:t.indentStepPx,blockSpacingPx:t.blockSpacingPx,hyphenationEnabled:t.hyphenationEnabled,lineNumbering:t.lineNumbering,columnCount:t.columnCount,columnGapPx:su(t.columnGapTwips),pageless:r.pageless===!0}),resolved:t}}function Hl(r){if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;const e=fu(t),{layout:n}=Xl(r);return mu(r,e,n)}function Wl(r,t){const e=new Map;if(!t||r.pageless===!0)return new Map;const n=(s,a)=>{if(!s||typeof a!="number"||!Number.isFinite(a))return;const c=Math.max(1,Math.floor(a)),l=e.get(s);if(!l){e.set(s,{min:c,max:c});return}l.min=Math.min(l.min,c),l.max=Math.max(l.max,c)};for(const s of t.fragments)n(s.blockId,s.pageNumber);for(const s of t.blocks)n(s.blockId,s.pageNumber);const o=be(r.pageLayout),i=new Map;for(const[s,a]of e)i.set(s,{pageStart:Es(o,a.min-1),pageEnd:Es(o,a.max-1)});return i}function ob(r,t){let e,n;for(const o of r){const i=t.get(o);i&&(e=e===void 0?i.pageStart:Math.min(e,i.pageStart),n=n===void 0?i.pageEnd:Math.max(n,i.pageEnd))}return e!==void 0&&n!==void 0?{pageStart:e,pageEnd:n}:void 0}function Jl(r,t,e,n){const o=Math.max(0,Math.min(t,r.children.length-1)),i=Math.max(0,Math.min(e,r.children.length-1));if(o>i||r.children.length===0)return null;const s=r.children.slice(o,i+1),a=r.children[o],c=r.children[i];if(!a?.id||!c?.id)return null;const l=zl(s),d=s.map(g=>g.id).filter(Boolean),u=ob(d,n);return{startIndex:o,endIndex:i,startBlockId:a.id,endBlockId:c.id,inclusive:!0,blockCount:s.length,wordCount:l.wordCount,paragraphCount:l.paragraphCount,characterCount:l.characterCount,...u?{pageStart:u.pageStart,pageEnd:u.pageEnd}:{}}}function rb(r,t,e){const n=[],o=e?new Set(e):null;for(const i of Qm(r,{maxDepth:3})){const s=i.index,a=i.endIndex,c=i.level;if(o&&!o.has(c))continue;const l=Jl(r,s,a,t);l&&n.push({startIndex:l.startIndex,endIndex:l.endIndex,startBlockId:l.startBlockId,endBlockId:l.endBlockId,headingLevel:c,title:i.title,wordCount:l.wordCount,paragraphCount:l.paragraphCount,characterCount:l.characterCount,...l.pageStart!==void 0?{pageStart:l.pageStart,pageEnd:l.pageEnd}:{}})}return n}function Yl(r,t){const e=t&&"layout"in t?t.layout??null:r.pageless===!0?null:Hl(r),n=zl(r.children),o=r.pageless===!0?null:e,i=t?.includeSections===!0?Wl(r,e):new Map;return{inclusive:!0,totalBlocks:r.children.length,wordCount:n.wordCount,paragraphCount:n.paragraphCount,characterCount:n.characterCount,...o?{pageCount:o.pageCount}:{},...t?.includeFractionalPageCount===!0&&o?{fractionalPageCount:ib(r,o)}:{},...t?.includeSections===!0?{sections:rb(r,i,t.headingLevels).map(s=>({...s,inclusive:!0,blockCount:s.endIndex-s.startIndex+1}))}:{}}}function ib(r,t){const{layout:e}=Xl(r);return bu(e,t)}function Kl(r){return typeof r!="string"?"":r.trim().replace(/^#+/,"")}function sb(r,t,e){const n=Hl(r),o=Wl(r,n),i=new Map;for(let c=0;c<r.children.length;c+=1){const l=r.children[c]?.id;l&&i.set(l,c)}const s=[],a=[];for(const c of t){const l=Kl(c.startBlockId),d=Kl(c.endBlockId??l),u=i.get(l),g=i.get(d);if(!l){a.push({error:"start_block_id is required."});continue}if(u===void 0){a.push({startBlockId:l,endBlockId:d,error:`start_block_id "${l}" was not found.`});continue}if(g===void 0){a.push({startBlockId:l,endBlockId:d,error:`end_block_id "${d}" was not found.`});continue}if(g<u){a.push({startBlockId:l,endBlockId:d,error:`end_block_id "${d}" comes before start_block_id "${l}". Ranges must be forward and inclusive.`});continue}const p=Jl(r,u,g,o);if(!p){a.push({startBlockId:l,endBlockId:d,error:`Could not measure inclusive range "${l}"-"${d}".`});continue}s.push(p)}return{inclusive:!0,totalBlocks:r.children.length,ranges:s,errors:a}}const ab="The agent had trouble completing this request. Please try again.",Vl="Document session unavailable after waiting for document load",cb="document_session_unavailable";class lb extends Error{constructor(t){super("Open the source document linked in the conversation to continue these edits."),this.sourceDocumentId=t,this.name="ForeignDocumentTargetError"}}const db="InvalidAssistantResponseError",ub="Couldn't reach the server. Please check your connection and try again.",gb=["aborted without reason","bodystreambuffer was aborted","client.timeout","connection reset by peer","context canceled","context cancellation","context cancelled","context deadline exceeded","econnreset","etimedout","failed to fetch","failed to execute 'fetch'","fetch is aborted","gateway timeout","http error! status:","illegal access","illegal invocation","load failed","network request failed","socket hang up","upstream request timeout","while reading body"],hb=["function call is missing a thought_signature","does not support the effort parameter","response with id=","gemini api error: 400","xai api error: 404","anthropic api error: 400"],pb=["server_error","service_unavailable","server_is_overloaded","503 service unavailable","error in input stream"],fb=["context_length_exceeded","input token count exceeds","exceeds the context window","maximum number of tokens","maximum context length","prompt is too long","too many input tokens"],mb=['attachment "',"attachment not found","unable to download the file","failed to fetch attachment","expected a valid url","invalid 'input","image_url"],bb=['block id "',"document changed while","reference block","not found in document","not found in the document","insert_block"];function yb(r){const t=r.toLowerCase();return t.includes("network")||gb.some(e=>t.includes(e))}function kb(r){if(r?.name==="AbortError"||r instanceof DOMException&&r.code===20)return{isAbort:!0,isRateLimited:!1,isNetworkError:!1,kind:"abort",rawMessage:"",message:"",shouldRetryWithStableModel:!1,shouldTrackConversationError:!1};const t=r instanceof Error?r.message:typeof r?.toString=="function"?r.toString():String(r??""),e=t.toLowerCase(),n=t==="RATE_LIMITED"||r?.message==="RATE_LIMITED",o=r instanceof TypeError||yb(t),i=r instanceof Error&&r.name===db,s=l=>l.some(d=>e.includes(d)),a=r instanceof lb?"document_target":n?"rate_limited":i?"invalid_assistant_response":t.trim().length===0?"unknown_empty":s(fb)?"context_limit":s(mb)?"attachment":e.includes(Vl.toLowerCase())?"document_loading":s(bb)?"document_state":s(hb)?"provider_protocol":s(pb)?"provider_transient":o?"connection":"unknown";let c;return n?c="Rate limit reached":i?c="The agent sent an invalid response. Please try again.":a==="connection"?c=ub:a==="provider_protocol"||a==="provider_transient"?c="The model service had trouble completing this request. Please try again.":a==="context_limit"?c="This request is too large for the model. Try a smaller request or attach fewer files.":a==="attachment"?c="The agent could not read one of the attached files.":a==="document_loading"?c="The document is still loading. Please wait a moment and try again.":a==="document_target"?c=t:a==="document_state"?c="Document state changed during the request.":a==="unknown_empty"?c="The agent stopped unexpectedly. Your prompt is saved.":c=ab,{isAbort:!1,isRateLimited:n,isNetworkError:o,kind:a,rawMessage:t,message:c,shouldRetryWithStableModel:a==="provider_protocol"||a==="provider_transient",shouldTrackConversationError:a!=="rate_limited"&&a!=="connection"&&a!=="document_loading"}}const Sb=new Map(Pl.map(r=>[r.name,r.inputSchema]));function us(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Gl(r,t){return Object.prototype.hasOwnProperty.call(r,t)}function Ib(r,t){switch(t){case"null":return r===null;case"object":return us(r);case"array":return Array.isArray(r);case"string":return typeof r=="string";case"number":return typeof r=="number"&&Number.isFinite(r);case"integer":return typeof r=="number"&&Number.isInteger(r);case"boolean":return typeof r=="boolean";default:return!0}}function wn(r,t){return!(r.const!==void 0&&!Object.is(r.const,t)||r.enum&&!r.enum.some(e=>Object.is(e,t))||r.type&&!(Array.isArray(r.type)?r.type:[r.type]).some(e=>Ib(t,e))||r.allOf?.some(e=>!wn(e,t))||r.anyOf&&!r.anyOf.some(e=>wn(e,t))||r.oneOf&&r.oneOf.filter(e=>wn(e,t)).length!==1||r.not&&wn(r.not,t)||us(t)&&r.required&&!r.required.every(e=>Gl(t,e)))}function ro(r,t){let e=r;if(Array.isArray(e)&&t.items)e=e.map(n=>ro(n,t.items));else if(us(e)&&t.properties){const n=new Set(t.required??[]),o={...e};for(const[i,s]of Object.entries(t.properties))if(Gl(o,i)){if(o[i]===null&&!n.has(i)&&!wn(s,null)){delete o[i];continue}o[i]=ro(o[i],s)}e=o}for(const n of t.allOf??[])e=ro(e,n);for(const n of[t.anyOf,t.oneOf]){const o=n?.filter(i=>wn(i,e));o?.length===1&&(e=ro(e,o[0]))}return e}function vb(r,t){const e=Sb.get(r);return e?ro(t,e):t}const xb="This request is non-interactive. Continue the supported work using the supplied context and reasonable assumptions. Explain material gaps in the final response or permitted comments; do not invent facts or ask for clarification or approval.",wb=new Set(["read_blocks","read_blocks_from_index","read_specific_blocks","search_document","find_highlights","measure_document","measure_blocks","list_documents","search_documents","get_attachment","view_image","render_document_pages","set_status","request_user_input","end_agent_run","finish_response","ready_for_verification"]),Ab=new Set(["missed_requirements","verification_passed"]);function Zl(r){const t=r.trim();return t==="remove_blocks"?"remove_block":t}function Tb(r){return Array.from(new Set(r.map(Zl).filter(Boolean)))}function Cb(r,t){const e=Zl(t);return Ab.has(e)?{code:"agent_tool_not_allowed",message:"This legacy verification tool is unavailable. Continue supported work or finish with end_agent_run."}:e==="request_user_input"&&r.interaction==="best_effort"?{code:"agent_interaction_not_allowed",message:xb}:r.allowedTools!=null&&!Tb(r.allowedTools).includes(e)?{code:"agent_tool_not_allowed",message:"This tool is outside the host's execution allowlist. Continue using permitted tools or finish with the best supported response."}:ls.has(e)?r.documentAccess==="edit"||r.documentAccess==="comment"&&e==="leave_comment"?null:{code:"agent_document_access_denied",message:"This request does not permit this document mutation. Continue within the granted document access and explain any work that could not be completed."}:wb.has(e)?null:{code:"agent_tool_not_allowed",message:"This tool has no execution-policy classification and cannot run. Continue using permitted tools."}}const Sr="no_new_read_context",on={scanDocumentFontFamily:!1};function An(r){return r.getAgentAuthorName?.()?.trim()||Ae}const Ql=2,Pb=48,Mb=.4,rn=10,$b=100,Bb=100,Tn=48e3,gs="out_of_context_edit",je="document_state_changed",_b="duplicate_comment_anchor",Lb="one_read_search_per_turn",td="terminal_tool_requires_turn_two_continuation",ed="terminal_response_status_only",Nb="end_agent_run",Fb="finish_response",Eb="ready_for_verification",Rb=new Set(["read_blocks","read_blocks_from_index","read_specific_blocks","search_document","search_documents","find_highlights","render_document_pages"]);function Db(r){return r===Nb||r===Fb}function nd(r){return r.replace(/<status\b[^>]*>[\s\S]*?<\/status>/gi,"").trim().length===0}const hs="https://app-api.revise-sdk.invalid";function Ob(r){if(r&&typeof r=="object"&&!Array.isArray(r))return r;if(typeof r!="string")return null;const t=r.trim();if(!t)return null;if(!t.startsWith("{")||!t.endsWith("}"))return{text:t};try{const e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function jb(r){const t=Se(r.doc,r.requestedBlockId);if(!t||!Array.isArray(t.children))return null;const e=[],n=o=>{if(!(!o||typeof o!="object")&&(o.id!==r.requestedBlockId&&typeof o.id=="string"&&ma(o)&&e.push({blockId:o.id,text:Ft(o),html:Te(r.anchorText)?Co(o):void 0}),Array.isArray(o.children)))for(const i of o.children)n(i)};return n(t),Gr(e,r.anchorText)}function Ub(r){return!r.loadedBlockIds||r.loadedBlockIds.size===0?null:Gr(ba(r.doc).filter(t=>t.blockId!==r.requestedBlockId&&ya(t,r.loadedBlockIds)).map(t=>({...t,html:Te(r.anchorText)?Co(Se(r.doc,t.blockId)):void 0})),r.anchorText)}function qb(r,t,e,n,o,i,s){if(s.hasBlockId||s.hasAnchor)return K(r,"A reply inherits its thread's anchor: pass reply_to_comment_id and comment alone, without id or anchor.");const a=ga(n,o);if(!a)return K(r,`Comment '${o}' was not found. Reply only to a <comment-thread> id you can see in loaded document content.`,je);if(a.resolved===!0)return K(r,`Comment thread '${a.id}' is resolved. Leave a new anchored comment instead of replying to a settled thread.`);const c=e.getDocumentMutator(),l=Qu(n,c,a.id,i,{author:An(t),authorType:"ai",agentName:An(t),...t.getAgentModel?{agentModel:t.getAgentModel()}:{}}).commentId;if(!l)return K(r,`Could not reply to comment thread '${a.id}'.`);const d=zb(n,a);return d&&t.toolState.editedBlockIds.add(d),t.turnState.hasMutatedSinceLastRead=!0,t.metrics?.count("agent.comment.reply",1),Mt(r,`Replied ${l} in comment thread ${a.id}.`,void 0,void 0,JSON.stringify({commentId:l,threadId:a.id,mode:"reply",...d?{blockId:d}:{}}))}function zb(r,t){if(t.anchorBlockId){const e=ee(r,t.anchorBlockId);return e>=0?r.children[e]?.id??t.anchorBlockId:t.anchorBlockId}for(const e of r.children)if(e.id&&la(e).has(t.id))return e.id;return null}function Xb(r,t,e,n){const o=r.arguments??{};let i=typeof o.id=="string"?o.id.trim():"";const s=typeof o.comment=="string"?o.comment.trim():"",a=Ob(o.anchor),c=typeof o.reply_to_comment_id=="string"?o.reply_to_comment_id.trim():"",l=new Set((Array.isArray(o.acknowledge_existing_thread_ids)?o.acknowledge_existing_thread_ids:[]).filter(S=>typeof S=="string").map(S=>S.trim()).filter(Boolean));if(!s)return K(r,"leave_comment requires a non-empty comment.");if(c)return qb(r,t,e,n,c,s,{hasBlockId:!!i,hasAnchor:!!a});if(!i)return K(r,"leave_comment requires id.");if(!a)return K(r,"leave_comment requires an anchor.");let d=Se(n,i);const u=sd(t.turnState),g=typeof a.text=="string"&&a.text.length>0?a.text:null;if(g&&d){const S=jb({doc:n,requestedBlockId:i,anchorText:g});S&&(i=S,d=Se(n,i))}if(g&&(!d||Po(d,g).length===0)){const S=Ub({doc:n,requestedBlockId:i,anchorText:g,loadedBlockIds:u});S&&(i=S,d=Se(n,i))}if(!d)return K(r,`Block '${i}' was not found.`,je);const p=ee(n,i),h=p>=0?n.children[p]?.id:void 0;if(!u||!u.has(i)&&(!h||!u.has(h)))return K(r,`leave_comment targets block '${i}', which is outside the loaded <document_content> context. Read that block first, then retry.`,gs);const f=e.getDocumentMutator(),m={author:An(t),authorType:"ai",agentName:An(t),...t.getAgentModel?{agentModel:t.getAgentModel()}:{}},y=Zu(e.getWorkingDocument(),n,f,i,s,a,m,Array.from(l));if(!y.success)return y.overlappingThreadIds?.length&&t.metrics?.count("agent.comment.overlap_blocked",1),K(r,y.error??"Could not attach comment.",y.overlappingThreadIds?.length?_b:y.errorCode);const b=y.commentId,k=a.whole_block===!0,v=y.range;return l.size&&t.metrics?.count("agent.comment.overlap_acknowledged",1),t.toolState.editedBlockIds.add(h??i),t.turnState.hasMutatedSinceLastRead=!0,Mt(r,`Left comment ${b} on block ${i}.`,void 0,void 0,JSON.stringify({commentId:b,blockId:i,anchor:k?{wholeBlock:!0}:v}))}function K(r,t,e){return{toolCall:r,success:!1,error:t,...e?{errorCode:e}:{}}}function Hb(r){return r&&kb(new Error(r)).kind==="document_state"?je:void 0}function Mt(r,t,e,n,o){return{toolCall:r,success:!0,agentFeedback:t,...e?{imageAttachment:e}:{},...n?{nonMeaningful:!0}:{},...o?{toolOutput:o}:{}}}function Wb(r){return r.tool||r.name}function Jb(r){if(!r||typeof r!="object")return null;const t=typeof r.status=="string"?r.status:typeof r.message=="string"?r.message:null;if(!t)return null;const e=t.replace(/[\s\n]+/g," ").trim();return e.length>0?e:null}function Yb(r){if(!r||typeof r!="object")return null;const t=typeof r.context_notes=="string"?r.context_notes:null;if(!t)return null;const e=t.trim();return e.length>0?e:null}function od(r,t){for(const e of r){if(e.type==="image"&&e.id===t)return{src:e.src,sourceUrl:e.sourceUrl,alt:e.alt,width:e.width,height:e.height};if(Array.isArray(e.children)&&e.children.length>0){const n=od(e.children,t);if(n)return n}}return null}function io(r){if(!r||typeof r!="object")return[];const t=r,e=[],n=new Set,o=s=>{if(typeof s!="string")return;const a=s.trim();!a||n.has(a)||(n.add(a),e.push(a))};if(o(t.id),o(t.referenceId),o(t.firstId),o(t.secondId),o(t.from_id),o(t.block_id),o(t.tableId),o(t.referenceRowId),o(t.after_block_id),Array.isArray(t.id))for(const s of t.id)o(s);if(Array.isArray(t.block_ids))for(const s of t.block_ids)o(s);Array.isArray(t.ids)&&t.ids.forEach(o);const i=Array.isArray(t.selectors)?t.selectors:[t.selectors];for(const s of i)if(typeof s=="string")for(const a of s.split(",")){const c=a.trim().match(/^#([A-Za-z0-9_-]+)(?=$|[\s:>~+])/);c&&o(c[1])}if(t.selector&&typeof t.selector=="object"&&io(t.selector).forEach(o),Array.isArray(t.replacements))for(const s of t.replacements)io(s).forEach(o);return e}function rd(r){const t=io(r.arguments),e=t.length===0?"the target block":t.length===1?`block ${t[0]}`:`${t.length} blocks`;if(r.name==="set_block_attribute"||r.name==="style_blocks"){const n=r.arguments&&typeof r.arguments=="object"?r.arguments:{},o=typeof n.attribute=="string"&&n.attribute.trim().length>0?n.attribute.trim():"attribute";return(typeof n.operation=="string"&&n.operation.trim().length>0?n.operation.trim():"set")==="remove"?`No document mutation occurred; ${o} was already removed on ${e}.`:`No document mutation occurred; ${o} was already set on ${e}.`}return r.name==="clear_formatting"?`No document mutation occurred; formatting was already clear on ${e}.`:r.name==="replace_block"?`No document mutation occurred; replacing ${e} produced no document change. This result does not prove that the requested content is present; verify the current block before deciding no change is needed.`:r.name==="replace"||r.name==="replace_all"||r.name==="replace_many"?`No document mutation occurred; the replacement on ${e} produced no document change. This result does not prove that the requested content is present; verify the current block before deciding no change is needed.`:"No document mutation occurred; the document already matched the requested update."}function Kb(r){const t=Wb(r);return{id:r.id,name:t,arguments:vb(t,r.arguments)}}function Vb(r){return r.replace(/<[^>]*>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;|&apos;/gi,"'").replace(/\s+/g," ").trim()}function id(r){return r.replace(/\s+/g," ").trim()}function sd(r){const t=new Set;for(const e of[r.lastReadBlockIds,r.requestedBlockIds])if(e)for(const n of e)t.add(n);for(const e of r.docContextLedger?.delivered.keys()??[])t.add(e);return t.size>0?t:null}function Gb(r){const t=[],e=new Set;for(const n of r)for(const o of io(n.arguments))e.has(o)||(e.add(o),t.push(o));return t}function ad(r,t){const e=new Set(t),n=new Set(t),o=i=>{const s="id"in i?i.id:void 0;let a=!!(s&&e.has(s));if("children"in i)for(const c of i.children)o(c)&&(a=!0);return a&&s&&n.add(s),a};for(const i of[...r.children,...r.chrome??[],...r.notes??[]])o(i);return n}function Zb(r,t){if(r.length===1)return`block ${r[0]}`;if(r.length>1){const e=r.slice(0,4).join(", "),n=r.length>4?` (+${r.length-4} more)`:"";return`blocks ${e}${n}`}return t?`block ${t}`:"the target block"}function Qb(r){if(r.length===0)return"";const t=Array.from(new Set(r.map(o=>`${o.fromBlockId}->${o.toBlockId}`))).map(o=>{const[i,s]=o.split("->");return`${i} -> ${s}`}),e=t.slice(0,4).join(", "),n=t.length>4?` (+${t.length-4} more)`:"";return`Retargeted ${r.length} replacement ${r.length===1?"operation":"operations"} to the unique loaded-context block match${r.length===1?"":"es"}: ${e}${n}.`}function ty(r,t,e){if(typeof r!="number"||!Number.isFinite(r))return t;const n=Math.floor(r);return n<=0?t:Math.min(n,e)}function so(r,t){if(typeof r!="number"||!Number.isFinite(r))return t;const e=Math.floor(r);return Math.max(0,e)}function cd(r,t,e,n,o,i){let s=[...i?.targetBlockIds??n];if(s.length===0&&r.arguments&&typeof r.arguments=="object"&&typeof r.arguments.id=="string"&&(s=[r.arguments.id.trim()].filter(Boolean)),s.length===1&&r.name==="remove_block"&&r.arguments&&typeof r.arguments=="object"){const y=s[0],b=ty(r.arguments.count,1,50),k=ee(t,y);k!==-1&&b>1&&(s=t.children.slice(k,k+b).map(v=>v.id).filter(v=>typeof v=="string"&&v.length>0))}const a=r.arguments&&typeof r.arguments=="object"&&typeof r.arguments.search_result_id=="string"?r.arguments.search_result_id:null,c=a!==null||s.length>rn,l=!c&&r.name!=="replace"&&r.name!=="replace_many"&&r.name!=="replace_all"&&s.length>0?it.extractSpecificBlocks(t,s,void 0,on).html:"",d=s.filter(y=>z(t,y)&&!z(e,y)),u=i?.changedBlockIds??s.filter(y=>{const b=z(t,y),k=z(e,y);return JSON.stringify(b??null)!==JSON.stringify(k??null)}),g=new Set,p=y=>{for(const b of y)"id"in b&&b.id&&g.add(b.id),"children"in b&&p(b.children)};p(pe(t));const h=[],f=y=>{for(const b of y)"id"in b&&b.id&&!g.has(b.id)?h.push(b.id):"children"in b&&f(b.children)};f(pe(e));const m=(y,b,k=!1)=>c||k&&b.length>rn?{[`${y}_sample`]:b.slice(0,rn),[`${y}_omitted_count`]:Math.max(0,b.length-rn)}:{[y]:b};return JSON.stringify({tool:r.name,...a?{target_reference:a}:{},...o?{summary:o}:{},...i?{style_outcome:i.outcome,attribute_effects:i.attributes.map(y=>({name:y.name,applied_target_count:y.appliedBlockIds.length,skipped_target_count:new Set(y.skipped.map(b=>b.blockId)).size,...m("applied_block_ids",y.appliedBlockIds,!0),skipped:y.skipped.slice(0,rn),skipped_omitted_count:Math.max(0,y.skipped.length-rn)}))}:{},effect:{...i?m("affected_block_ids",i.affectedBlockIds,!0):{},requested_target_count:s.length,changed_target_count:u.length,removed_target_count:d.length,inserted_block_count:h.length,...m("target_block_ids",s),...m("changed_block_ids",u),...m("removed_block_ids",d),...m("inserted_block_ids",h),top_level_blocks_before:pe(t).length,top_level_blocks_after:pe(e).length},...!c&&l.trim()?{before_block:l}:{}})}function pe(r){return[...r.children,...r.notes??[]]}function ps(r,t){return it.extractSpecificBlocks(r,[t],void 0,on).foundBlocks[0]?.blockIndex??-1}function ey(r){return`(${r} ${r===1?"block":"blocks"} omitted...)`}function fs(r,t){const e=pe(r)[t];return e?.id?it.extractSpecificBlocks(r,[e.id],void 0,on).foundBlocks[0]??null:null}function Ir(r){if(r.length===0)return 0;let t=`Showing ${r.length} block(s):
33
-
34
- `.length+r[0].html.length;for(let e=1;e<r.length;e+=1){const n=r[e-1],o=r[e],i=o.blockIndex-n.blockIndex-1;i>0&&(t+=1+ey(i).length),t+=1+o.html.length}return t}function ld(r){const{doc:t,startIndex:e,maxTokens:n}=r,o=[];let i=0,s=e-1,a=!1;for(let c=e;c<pe(t).length;c+=1){const l=fs(t,c);if(!l)continue;const d=Ir([...o,l]),u=d>n;if(u&&o.length>0){a=!0;break}if(o.push(l),i=d,s=l.blockIndex,u){a=!0;break}}return{blockIds:o.map(c=>c.id),endIndex:s,estimatedTokens:i,reachedTokenBudget:a}}function ny(r){const{doc:t,requestedBlockIds:e,maxTokens:n}=r,o=[],i=new Set,s=new Map,a=(g,p)=>(s.has(g)||s.set(g,fs(t,p)),s.get(g)??null),c=[];let l=0,d=!1,u=0;for(const g of e){const p=gy(t,g);if(!p){u+=1;continue}if(i.has(p.topLevelBlockId))continue;const h=a(p.topLevelBlockId,p.topLevelIndex);if(!h){u+=1;continue}const f=Ir([...c,h]),m=f>n;if(m&&o.length>0){d=!0;break}if(o.push(p.topLevelBlockId),i.add(p.topLevelBlockId),c.push(h),l=f,m){d=!0;break}}return{blockIds:o,estimatedTokens:l,reachedTokenBudget:d,missingRequestedBlocks:u}}function dd(r){const{doc:t,results:e,pageSize:n,maxTokens:o}=r;if(e.length===0)return[];const i=new Map,s=g=>(i.has(g.blockId)||i.set(g.blockId,fs(t,g.blockIndex)),i.get(g.blockId)??null),a=[];let c=[],l=[],d=0;const u=g=>{c.length!==0&&(a.push({results:c,startResultIndex:d,endResultIndexExclusive:g,estimatedTokens:Ir(l)}),c=[],l=[])};for(let g=0;g<e.length;g+=1){const p=e[g],h=s(p);if(!h)continue;c.length===0&&(d=g);const f=Ir([...l,h]),m=c.length>=n,y=f>o;c.length>0&&(m||y)&&(u(g),d=g),c=[...c,p],l=[...l,h]}return u(e.length),a}function ud(r){if(r.length===0)return[];const t=[...r].sort((i,s)=>i-s),e=[];let n=t[0],o=t[0];for(let i=1;i<t.length;i+=1){const s=t[i];if(s<=o+1){o=s;continue}e.push({start:n,end:o}),n=s,o=s}return e.push({start:n,end:o}),e}function ms(r,t){const e=new Set;for(const n of t){const o=ps(r,n);o!==-1&&e.add(o)}return Array.from(e).sort((n,o)=>n-o)}function ao(r,t){const e=r.turnState.requestedBlockIds??new Set,n=ms(t,e),o=ud(n),i=n.length,s=r.toolState.everReadFullDocument||pe(t).length>0&&i>=pe(t).length;return{requestedBlockCount:i,readBlocksThisTurn:r.turnState.readBudgetBlockIds?.size??0,readTokenBudgetMax:Tn,requestedRanges:o,fullDocumentLoaded:s}}function co(r){return JSON.stringify({kind:"read_context",tool:r.tool,loaded:r.loaded,next:r.next??null,endOfDocument:r.endOfDocument,coverage:r.coverage})}function gd(r){return JSON.stringify({kind:"search_context",tool:r.tool,...r.queries?{queries:r.queries}:{},...r.color?{color:r.color}:{},totalMatches:r.totalMatches,...r.searchResultId?{search_result_id:r.searchResultId}:{},page:{current:r.currentPage,total:r.totalPages,startResult:r.pageStart+1,endResult:r.pageEnd},nextPage:r.nextPage,matches:r.pageResults.map(t=>({blockId:t.blockId,blockIndex:t.blockIndex,...t.matchedQueries?{matchedQueries:t.matchedQueries}:{},...t.matchedColors?{matchedColors:t.matchedColors}:{}})),coverage:r.coverage})}function oy(r){return r==="account"||r==="folder"?r:"current_folder"}function Cn(r){return r.getAuthToken?.().trim()??""}function hd(r){return typeof r.document_id=="string"?r.document_id.trim():""}function pd(r){return r.replaceAll("-","").toLowerCase()}function Pe(r,t){const e=hd(r);if(!e)return"";const n=t.getCurrentDocumentId?.().trim()??"";return n&&pd(e)===pd(n)?"":e}async function ry(r){const t=r.scope==="folder"?r.folderId:r.currentFolderId,e=$l({query:r.query,page:r.page+1,limit:10,currentFolderId:r.scope==="account"?void 0:t}),n=await fetch(`${hs}/documents/search?${e.toString()}`,{headers:{Authorization:`Bearer ${r.token}`}});if(!n.ok)throw new Error(`Document search failed with ${n.status}`);return Bl(await n.json(),10)}async function iy(r){const t=$l({includeFolders:!0,page:r.page+1,limit:r.limit,parentFolderId:r.parentFolderId}),e=await fetch(`${hs}/documents?${t.toString()}`,{headers:{Authorization:`Bearer ${r.token}`}});if(!e.ok)throw new Error(`Document listing failed with ${e.status}`);return Bl(await e.json(),r.limit)}async function vr(r){const t=await fetch(`${hs}/documents/${encodeURIComponent(r.documentId)}?includeTailUpdates=1&trackAccess=0`,{headers:{Authorization:`Bearer ${r.token}`}});if(!t.ok)throw new Error(`Document open failed with ${t.status}`);const e=await t.json(),n=Dm({content:e.content,yjsState:e.yjsState,yjsUpdates:e.yjsUpdates,source:`agent read document ${r.documentId}`})??{type:"doc",children:[]};return n.title=e.title||n.title||"Untitled",{id:e.id||r.documentId,title:e.title||"Untitled",canonicalPath:e.canonicalPath,parentFolderId:e.parentFolderId??null,content:n}}function sy(r){return JSON.stringify({kind:"account_document_search",query:r.query,scope:r.scope,searchedCurrentFolder:r.searchedCurrentFolder,folderId:r.folderId??null,page:{current:r.page,total:r.totalPages},totalMatches:r.totalCount,results:r.results.map(t=>({itemType:t.itemType==="folder"?"folder":"document",...t.itemType==="folder"?{folderId:t.id}:{documentId:t.id},title:t.title,canonicalPath:t.canonicalPath||`/${t.title||t.id}`,snippet:t.snippet||"",href:t.itemType==="folder"?`/docs/folders/${t.id}`:`/docs/${t.id}`,parentFolderId:t.parentFolderId??null}))})}function ay(r){return JSON.stringify({kind:"document_tree_listing",parentFolderId:r.parentFolderId,page:{current:r.page,total:r.totalPages},totalItems:r.totalCount,hasMore:r.hasMore,items:r.items.map(t=>({type:t.itemType==="folder"?"folder":"document",id:t.id,title:t.title||t.name||"Untitled",name:t.name||t.title||"Untitled",canonicalPath:t.canonicalPath||`/${t.title||t.name||t.id}`,href:t.itemType==="folder"?`/docs?folder=${t.id}`:`/docs/${t.id}`,parentFolderId:t.parentFolderId??null,childCount:typeof t.childCount=="number"?t.childCount:void 0,updatedAt:t.updatedAt}))})}function bs(r){return{editable:!1,editInstructions:`Read-only source. Mutation tools only edit the active document. To edit this source, give the user a clickable link to /docs/${r} and ask them to open it and continue there. Never use these block IDs to edit the active document.`}}function ys(r){return JSON.stringify({kind:"document_read",document:{documentId:r.documentId,title:r.title,canonicalPath:r.canonicalPath||`/${r.title}`,href:`/docs/${r.documentId}`,...bs(r.documentId)},loaded:{startIndex:r.startIndex,endIndex:r.endIndex,estimatedTokens:r.estimatedTokens},next:r.nextIndex===null?null:{index:r.nextIndex},endOfDocument:r.endOfDocument,documentContent:r.content})}function fd(r,t){if(r==="search_document"){const n=Array.isArray(t.queries)?t.queries.filter(i=>typeof i=="string"):[],o=typeof t.document_id=="string"&&t.document_id.trim().length>0?t.document_id.trim():null;return JSON.stringify({documentId:o,queries:n})}const e=typeof t.color=="string"&&t.color.trim().length>0?t.color.trim().toLowerCase():null;return JSON.stringify({color:e})}function cy(r){const t=new Map;for(const e of r)for(const n of e.matchedColors??[])t.set(n,(t.get(n)??0)+1);return t.size===0?"":Array.from(t.entries()).sort((e,n)=>n[1]-e[1]||e[0].localeCompare(n[0])).map(([e,n])=>`${n} ${e}`).join(", ")}function ly(r,t){let e=0;for(;e<r.length&&e<t.length&&r[e]===t[e];)e+=1;let n=r.length-1,o=t.length-1;for(;n>=e&&o>=e&&r[n]===t[o];)n-=1,o-=1;const i=Math.max(0,n-e+1),s=Math.max(0,o-e+1);return Math.max(i,s)}function dy(r,t){if(r.name!=="replace_block"||!r.arguments||typeof r.arguments!="object")return null;const e=r.arguments.id,n=r.arguments.content,o=r.arguments.count;if(typeof e!="string"||typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)>1||!Array.isArray(n)||n.length!==1||typeof n[0]!="string")return null;const i=t.children.find(u=>u.id===e);if(!i)return null;const s=id(Ft(i)),a=id(Vb(n[0]));if(!s||!a||s===a)return null;const c=ly(s,a),l=Math.max(s.length,a.length);if(l<=0)return null;const d=c/l;return c>Pb||d>Mb?null:`WARNING: replace_block only changed a small span (~${c} chars, ${(d*100).toFixed(0)}% of block). Prefer replace for typo, punctuation, and wording edits; reserve replace_block for full rewrites.`}function md(r,t,e){if(!e||e.size===0)return!1;if(e.has(t))return!0;const n=gn(r,t);if(n&&e.has(n))return!0;const o=ee(r,t),i=o>=0?r.children[o]?.id:void 0;return typeof i=="string"&&e.has(i)}function uy(r,t,e){if(r.name!=="replace_block"&&r.name!=="remove_block")return{toolCall:r};if(!r.arguments||typeof r.arguments!="object")return{toolCall:r};const n=r.arguments.id;if(typeof n!="string"||n.trim().length===0)return{toolCall:r};const o=r.arguments.count;if(o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||Math.floor(o)<1))return{toolCall:r};const i=o===void 0?1:Math.floor(o);if(i<=1)return{toolCall:r};const s=ke(t,n),a=s&&"children"in s?Su(s,n):-1;if(!s||a===-1)return{toolCall:r};if(!e||e.size===0)return{toolCall:r,error:`${r.name} requested ${i} consecutive blocks, but no request-level multi-block document context is available. Read the complete range first, then retry without narrowing the count.`};const c=new Set(Array.from(e).map(d=>ee(t,d)).filter(d=>d!==-1));let l=0;for(let d=a;d<s.children.length;d++){const u=s.children[d]?.id;if(typeof u!="string"||u.length===0)break;const g=ee(t,u);if(g===-1||!c.has(g))break;l+=1}return l<=0?{toolCall:r,error:`${r.name} targets block '${n}', which is outside the loaded <document_content> context. Read that block first, then retry.`}:l>=i?{toolCall:r}:{toolCall:r,error:`${r.name} requested ${i} consecutive blocks, but only ${l} were seen in request-level document context. Read the remaining range and retry; no partial mutation was applied.`}}function gy(r,t){const e=ps(r,t);if(e===-1)return null;const n=pe(r)[e];return n?.id?{block:n,topLevelBlockId:n.id,topLevelIndex:e}:null}function hy(r){const t=r.toolState.editedBlockIds.size;if(t===0)return{loadedBlockCount:0,editedBlockCount:0};const e=r.getLatestDocument(),n=e.children.length,o=new Set;for(const c of r.toolState.editedBlockIds){const l=ee(e,c);l!==-1&&o.add(l)}const i=new Set;for(const c of o)for(let l=Math.max(0,c-Ql);l<=Math.min(n-1,c+Ql);l++)i.add(l);const s=[],a=Array.from(i).sort((c,l)=>c-l);for(const c of a){const l=e.children[c];l?.id&&s.push(l.id)}r.turnState.requestedBlockIds||(r.turnState.requestedBlockIds=new Set);for(const c of s)r.turnState.requestedBlockIds.add(c);return r.turnState.documentRequested=!0,{loadedBlockCount:s.length,editedBlockCount:t}}async function py(r){const t=await Um(r);if(t)return{id:t.id,type:t.type,content:t.content,preview:t.preview,charCount:t.charCount,...t.fileName?{fileName:t.fileName}:{},...t.mimeType?{mimeType:t.mimeType}:{},...t.fileSize?{fileSize:t.fileSize}:{},...t.urls?{urls:t.urls}:{},...t.dimensions?{dimensions:t.dimensions}:{}}}function fy(r){const t=r.loadAttachment??py,e=r.metrics??qh;if(!r.toolState.foreignBlockSources){r.toolState.foreignBlockSources=new Map;for(const y of r.getConversationHistory?.()??[])if(!(!y.toolResult?.success||!y.toolResult.output))try{const b=JSON.parse(y.toolResult.output),k=b.document?.documentId;if(typeof k!="string"||!["document_read","document_search_context"].includes(b.kind)||typeof b.documentContent!="string"||!Pe({document_id:k},r))continue;const v=new DOMParser().parseFromString(b.documentContent,"text/html");for(const S of v.querySelectorAll("[id]"))r.toolState.foreignBlockSources.set(S.id,k)}catch{}}const n=r.toolState.foreignBlockSources,o=(y,b,k)=>{const v=S=>{if(S.id&&k(S.id),"children"in S&&Array.isArray(S.children))for(const I of S.children)"id"in I&&v(I)};for(const S of b){const I=z(y,S);I&&v(I)}},i=(y,b,k)=>o(y,b,v=>n.set(v,k)),s=y=>{const b=r.tryAddRequestedBlocks(y);return(!b||b.code===Sr)&&o(r.getLatestDocument(),y,k=>n.delete(k)),b};let a=r.turnState.currentTurn??0,c=0,l=0;const d=new Map;let u=1;const g=async()=>{r.getDocumentSession()||await r.waitForDocumentSession?.();const y=r.getDocumentSession(),b=y?.getDocumentId?.(),k=r.getCurrentDocumentId?.();return y&&(!b||!k||Pe({document_id:b},r)==="")?y:null},p=y=>K(y,Vl,cb),h=new Set(["read_blocks","read_blocks_from_index","read_specific_blocks","search_document","find_highlights","measure_document","measure_blocks","view_image","render_document_pages"]),f=new Set(["read_blocks","read_blocks_from_index","read_specific_blocks","search_document"]),m=()=>{const y=r.turnState.currentTurn??0;y!==a&&(a=y,c=0,l=0)};return async y=>{var b,k;const v=Kb(y),S=v.name==="remove_blocks"?{...v,name:"remove_block"}:v,I=S.name,w=r.getExecutionPolicy?.(),A=w?Cb(w,I):null;if(A)return K(S,A.message,A.code);if(r.allowCrossDocumentReads===!1&&(hd(S.arguments??{}).length>0||I==="list_documents"||I==="search_documents"))return K(S,"This host only permits the supplied document. document_id routing is unavailable.","agent_tool_not_allowed");if(m(),r.mutationTools.includes(I)||I==="remove_block"){const E=Pe(S.arguments??{},r),U=io(S.arguments).filter(ot=>n.has(ot)&&Pe({document_id:n.get(ot)},r)!==""),X=E||(U.length?n.get(U[0]):void 0);if(X){if(!E&&U.every(st=>z(r.getLatestDocument(),st)))return{...K(S,`These IDs occur in both the source and active documents. If this edit is intended for the source, do not edit here: give the user a clickable link to /docs/${X} and ask them to open it. Only if the edit belongs in the active document, re-read the target IDs without document_id before editing.`,"foreign_document_id_collision"),sourceDocumentId:X};const ot=r.turnState.currentRequestId??0;r.toolState.foreignTargetFailureState?.requestId!==ot&&(r.toolState.foreignTargetFailureState={requestId:ot,count:0});const V=++r.toolState.foreignTargetFailureState.count;return{...K(S,`These edits target a read-only source document. Open /docs/${X} and continue there to edit it. The active document has not been changed by this call. Do not retry these IDs with another mutation tool. To edit the active document instead, read its target blocks without document_id first.`,V>=2?"foreign_document_target_repeated":"foreign_document_target"),sourceDocumentId:X}}}const _=f.has(I)&&Pe(S.arguments??{},r)!=="";if(r.requireDocumentSessionForReads&&h.has(I)&&!_&&!await g())return p(S);if(I==="import_attachment_into_document"){const E=typeof S.arguments?.attachment_id=="string"?S.arguments.attachment_id.trim():"";if(!E)return K(S,"attachment_id is required.");const U=S.arguments?.after_block_id;if(U!=null&&typeof U!="string")return K(S,"after_block_id must be a block ID string.");const X=typeof U=="string"&&U.trim()||void 0,ot=r.getAllAttachments().get(E)??await t(E);if(!ot)return K(S,`Attachment "${E}" was not found.`);if(ot.type!=="docx"&&ot.type!=="pdf")return K(S,"Only DOCX and PDF attachments can be imported into the document.");if(!r.importAttachmentIntoDocument)return K(S,"Attachment import is unavailable in this document.");try{r.toolState.statusMessage=`Importing ${ot.fileName||"attachment"}…`,r.notifyListeners();const V=await r.importAttachmentIntoDocument(ot,X);return r.toolState.editedBlockIds.clear(),r.toolState.hasImportedAttachment=!0,r.turnState.documentRequested=!1,r.turnState.requestedBlockIds=null,r.turnState.lastReadBlockIds=null,r.toolState.everReadFullDocument=!1,r.toolState.sequentialReadBlockIds=new Set,r.toolState.statusMessage=null,r.markConversationDirty(),r.notifyListeners(),Mt(S,`Imported "${V.fileName}" into the current document (${V.blockCount} blocks)${X?` after block "${X}"`:""}. The URL stayed the same. Continue the user's request by reading the imported content, then edit it.`)}catch(V){return r.toolState.statusMessage=null,r.notifyListeners(),K(S,V instanceof Error?V.message:"Attachment import failed.")}}if(Rb.has(I)){if(!Yb(S.arguments))return K(S,'context_notes is required on every read/search call. Use "N/A" if nothing from the previous context needs to carry forward.');if(c>=1)return K(S,'Use at most one read/search tool call per turn. Continue with edits in this turn, then read/search again in the next turn with context_notes or "N/A".',Lb);c+=1}if(I==="measure_document"){const E=S.arguments||{},U=E.include_sections===!0,X=Number(E.section_offset),ot=Number.isFinite(X)&&X>0?Math.floor(X):0,V=Number(E.section_limit),st=Number.isFinite(V)&&V>0?Math.min(Math.floor(V),Bb):$b,nt=(Array.isArray(E.heading_levels)?E.heading_levels:[]).map(me=>typeof me=="number"?me:typeof me=="string"?Number.parseInt(me,10):Number.NaN).filter(me=>me===1||me===2||me===3),Z=r.getLatestDocument(),Y=Yl(Z,{includeSections:U,...nt.length>0?{headingLevels:nt}:{}}),tt=r.getDocumentSession()?.getDocumentWithoutPendingSuggestions(),lt=tt&&tt!==Z?Yl(tt,{includeSections:!1}):null,pt=lt&&(lt.wordCount!==Y.wordCount||lt.characterCount!==Y.characterCount)?{wordCount:lt.wordCount,characterCount:lt.characterCount,paragraphCount:lt.paragraphCount,pageCount:lt.pageCount}:void 0,Ot=Y.sections??[],St=Ot.length,ht=Math.min(ot,St),$t=U?Ot.slice(ht,ht+st):void 0,At=$t?.length??0,Rt=U&&ht+At<St,jt=JSON.stringify({kind:"document_measurement",tool:"measure_document",measurementBasis:"pending_suggestions_applied",...Y,...pt?{originalReviewProjection:pt}:{},...U?{sections:$t,sectionCount:St,sectionOffset:ht,sectionLimit:st,returnedSectionCount:At,hasMoreSections:Rt,...Rt?{nextSectionOffset:ht+At}:{}}:{}});e.count("agent.measure.call",1,{tool_name:I}),e.distribution("agent.measure.sections",St,void 0,{tool_name:I});const te=U?`Measured document totals and ${St} heading section(s).`:"Measured document totals.",fe=U&&St>0?` Returned sections ${ht+1}-${ht+At} of ${St}.${Rt?` Use section_offset=${ht+At} to continue.`:""}`:"",Kt=U?"heading titles, counts, and page ranges only; it does not include body document text":"counts and page ranges only; it does not include document text",uo=pt?` The primary totals treat pending suggestions as accepted. The original review projection has ${pt.wordCount} words and ${pt.characterCount} characters because it excludes pending suggestions; use the projection matching the user's editor view when reconciling a reported count.`:"";return{toolCall:S,success:!0,toolOutput:jt,agentFeedback:`${te}${fe}${uo} The result includes ${Kt}.`,control:{shouldContinue:!0}}}if(I==="measure_blocks"){const E=S.arguments||{},U=typeof E.mode=="string"?E.mode.trim():"inclusive";if(U!==""&&U!=="inclusive")return K(S,'measure_blocks only supports mode="inclusive".');const X=Array.isArray(E.ranges)?E.ranges:[];if(X.length===0)return K(S,"measure_blocks requires at least one range.");const ot=X.map(tt=>{const lt=tt&&typeof tt=="object"?tt:{};return{startBlockId:typeof lt.start_block_id=="string"?lt.start_block_id:"",endBlockId:typeof lt.end_block_id=="string"?lt.end_block_id:void 0}}),V=sb(r.getLatestDocument(),ot),st=V.ranges.length,nt=V.errors.length,Z=JSON.stringify({kind:"document_measurement",tool:"measure_blocks",...V});if(e.count("agent.measure.call",1,{tool_name:I}),e.distribution("agent.measure.ranges",st,void 0,{tool_name:I}),st===0){const tt=V.errors.map(lt=>lt.error).join(" ")||"No valid inclusive ranges were measured.";return K(S,tt,je)}const Y=nt>0?`Measured ${st} inclusive block range(s); ${nt} range(s) had errors.`:`Measured ${st} inclusive block range(s).`;return Mt(S,Y,void 0,void 0,Z)}if(I==="read_blocks"){const E=S.arguments||{},U=Pe(E,r),X=E.from_id,ot=U?Cn(r):"";if(U&&!ot&&!r.loadRemoteDocument)return K(S,"Cross-document access is only available for signed-in documents.");let V=null;try{V=U?await(r.loadRemoteDocument?.(U)??vr({token:ot,documentId:U})):null}catch(ht){return K(S,ht instanceof Error?ht.message:"Document read failed.")}const st=V?.content??r.getLatestDocument(),nt=pe(st),Z=nt.length,Y=typeof X=="string"?ps(st,X):-1;if(Y===-1)return K(S,`Block ID "${X}" not found`,je);if(Y>=Z)return K(S,`Start index ${Y} is out of range for ${Z} blocks.`);const tt=ld({doc:st,startIndex:Y,maxTokens:Tn});if(tt.blockIds.length===0||tt.endIndex<Y)return K(S,`No readable blocks found from index ${Y}.`);if(V){i(st,tt.blockIds,V.id);const ht=it.extractSpecificBlocks(st,tt.blockIds,void 0,on),$t=it.formatSpecificBlocks(ht),At=tt.endIndex+1<Z?tt.endIndex+1:null,Rt=ys({documentId:V.id,title:V.title,canonicalPath:V.canonicalPath,startIndex:Y,endIndex:tt.endIndex,estimatedTokens:tt.estimatedTokens,content:$t,nextIndex:At,endOfDocument:At===null}),jt=tt.reachedTokenBudget?" Reached per-call token budget.":"";return Mt(S,`Read ${tt.blockIds.length} blocks from "${V.title}" (index ${Y}-${tt.endIndex}). Estimated tokens: ~${tt.estimatedTokens}.${jt}${At!==null?` Next: read_blocks_from_index(document_id="${V.id}", index=${At}).`:" End of document."}`,void 0,void 0,Rt)}const lt=(b=r.toolState).sequentialReadBlockIds??(b.sequentialReadBlockIds=new Set);if(lt.size>0&&tt.blockIds.every(ht=>lt.has(ht)))return K(S,`This sequential read window (index ${Y}-${tt.endIndex}) contains only blocks already returned by earlier sequential read calls in this request. Do not cycle among previously read indices. Follow the last successful nextIndex, use read_specific_blocks for an intentional exact revisit, make the pending edits, or finish.`,Sr);const pt=s(tt.blockIds);if(pt)return K(S,pt.message,pt.code);for(const ht of tt.blockIds)lt.add(ht);r.turnState.documentRequested=!0,e.count("agent.read.call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",tt.blockIds.length,void 0,{tool_name:I}),e.distribution("agent.read.tokens_loaded_estimate",tt.estimatedTokens,void 0,{tool_name:I}),tt.reachedTokenBudget&&e.count("agent.read.token_budget_reached",1,{tool_name:I});const Ot=ao(r,st);if(tt.endIndex+1<Z){const ht=tt.endIndex+1,$t=nt[ht]?.id,At=co({tool:I,loaded:{count:tt.blockIds.length,startIndex:Y,endIndex:tt.endIndex,estimatedTokens:tt.estimatedTokens},next:{index:ht,...$t?{blockId:$t}:{}},endOfDocument:!1,coverage:Ot}),Rt=tt.reachedTokenBudget?" Reached per-call token budget.":"",jt=$t?` Next block ID: ${$t}.`:"";return Mt(S,`Read ${tt.blockIds.length} blocks (index ${Y}-${tt.endIndex}). Estimated tokens: ~${tt.estimatedTokens}.${Rt} Next: read_blocks_from_index(index=${ht}).${jt}`,void 0,void 0,At)}const St=co({tool:I,loaded:{count:tt.blockIds.length,startIndex:Y,endIndex:tt.endIndex,estimatedTokens:tt.estimatedTokens},endOfDocument:!0,coverage:Ot});return Mt(S,`Read ${tt.blockIds.length} blocks (index ${Y}-${tt.endIndex}). Estimated tokens: ~${tt.estimatedTokens}. End of document.`,void 0,void 0,St)}if(I==="read_blocks_from_index"){const E=S.arguments||{},U=Pe(E,r),X=so(E.index,0),ot=U?Cn(r):"";if(U&&!ot&&!r.loadRemoteDocument)return K(S,"Cross-document access is only available for signed-in documents.");let V=null;try{V=U?await(r.loadRemoteDocument?.(U)??vr({token:ot,documentId:U})):null}catch(St){return K(S,St instanceof Error?St.message:"Document read failed.")}const st=V?.content??r.getLatestDocument(),nt=pe(st),Z=nt.length;if(!V&&r.toolState.everReadFullDocument)return K(S,"You have already read the entire current document in this request. Continue by making edits if needed. If you need to revisit exact known blocks, use read_specific_blocks instead of restarting a sequential read.",Sr);if(V&&Z===0&&X===0)return Mt(S,`Read 0 blocks from "${V.title}". End of document.`,void 0,void 0,ys({documentId:V.id,title:V.title,canonicalPath:V.canonicalPath,startIndex:0,endIndex:-1,estimatedTokens:0,content:"",nextIndex:null,endOfDocument:!0}));if(X>=Z)return K(S,`Start index ${X} is out of range for ${Z} blocks${V?` in "${V.title}"`:""}.`);const Y=ld({doc:st,startIndex:X,maxTokens:Tn});if(Y.blockIds.length===0||Y.endIndex<X)return K(S,`No readable blocks found from index ${X}.`);if(V){i(st,Y.blockIds,V.id);const St=it.extractSpecificBlocks(st,Y.blockIds,void 0,on),ht=it.formatSpecificBlocks(St),$t=Y.endIndex+1<Z?Y.endIndex+1:null,At=ys({documentId:V.id,title:V.title,canonicalPath:V.canonicalPath,startIndex:X,endIndex:Y.endIndex,estimatedTokens:Y.estimatedTokens,content:ht,nextIndex:$t,endOfDocument:$t===null}),Rt=Y.reachedTokenBudget?" Reached per-call token budget.":"";return e.count("agent.read.call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",Y.blockIds.length,void 0,{tool_name:I}),Mt(S,`Read ${Y.blockIds.length} blocks from "${V.title}" (index ${X}-${Y.endIndex}). Estimated tokens: ~${Y.estimatedTokens}.${Rt}${$t!==null?` Next: read_blocks_from_index(document_id="${V.id}", index=${$t}).`:" End of document."}`,void 0,void 0,At)}const tt=(k=r.toolState).sequentialReadBlockIds??(k.sequentialReadBlockIds=new Set);if(tt.size>0&&Y.blockIds.every(St=>tt.has(St)))return K(S,`This sequential read window (index ${X}-${Y.endIndex}) contains only blocks already returned by earlier sequential read calls in this request. Do not cycle among previously read indices. Follow the last successful nextIndex, use read_specific_blocks for an intentional exact revisit, make the pending edits, or finish.`,Sr);const lt=s(Y.blockIds);if(lt)return K(S,lt.message,lt.code);for(const St of Y.blockIds)tt.add(St);r.turnState.documentRequested=!0,e.count("agent.read.call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",Y.blockIds.length,void 0,{tool_name:I}),e.distribution("agent.read.tokens_loaded_estimate",Y.estimatedTokens,void 0,{tool_name:I}),Y.reachedTokenBudget&&e.count("agent.read.token_budget_reached",1,{tool_name:I});const pt=ao(r,st);if(Y.endIndex+1<Z){const St=Y.endIndex+1,ht=nt[St]?.id,$t=co({tool:I,loaded:{count:Y.blockIds.length,startIndex:X,endIndex:Y.endIndex,estimatedTokens:Y.estimatedTokens},next:{index:St,...ht?{blockId:ht}:{}},endOfDocument:!1,coverage:pt}),At=Y.reachedTokenBudget?" Reached per-call token budget.":"",Rt=ht?` Next block ID: ${ht}.`:"";return Mt(S,`Read ${Y.blockIds.length} blocks (index ${X}-${Y.endIndex}). Estimated tokens: ~${Y.estimatedTokens}.${At} Next: read_blocks_from_index(index=${St}).${Rt}`,void 0,void 0,$t)}const Ot=co({tool:I,loaded:{count:Y.blockIds.length,startIndex:X,endIndex:Y.endIndex,estimatedTokens:Y.estimatedTokens},endOfDocument:!0,coverage:pt});return Mt(S,`Read ${Y.blockIds.length} blocks (index ${X}-${Y.endIndex}). Estimated tokens: ~${Y.estimatedTokens}. End of document.`,void 0,void 0,Ot)}if(I==="search_document"){const E=S.arguments||{},U=Pe(E,r),X=E.queries,ot=Array.isArray(X)?X.filter(Ht=>typeof Ht=="string"&&Ht.length>0):typeof X=="string"&&X.length>0?[X]:[];if(ot.length===0)return K(S,'search_document requires "queries": a non-empty array of search strings.');const V=typeof E.page=="number"?E.page:0,st=U?Cn(r):"";if(U&&!st&&!r.loadRemoteDocument)return K(S,"Cross-document access is only available for signed-in documents.");let nt=null;try{nt=U?await(r.loadRemoteDocument?.(U)??vr({token:st,documentId:U})):null}catch(Ht){return K(S,Ht instanceof Error?Ht.message:"Document search failed.")}const Z=nt?.content??r.getLatestDocument(),Y=r.searchPageSize,tt=fd("search_document",E);let lt;V>0&&r.toolState.lastSearchState&&r.toolState.lastSearchState.toolName==="search_document"&&r.toolState.lastSearchState.requestKey===tt?lt=r.toolState.lastSearchState.allResults:lt=it.searchDocument(Z,ot);let pt;if(!nt&&lt.length>0){const Ht=V>0&&r.toolState.lastSearchState?.requestKey===tt?r.toolState.lastSearchState.resultSetId:void 0;if(Ht&&d.has(Ht))pt=Ht;else{pt=`search_result_${u++}`;const go=Array.from(new Set(lt.map(xr=>xr.blockId)));d.set(pt,{id:pt,blockIds:go,blockHashes:ei(Z,go)})}}const Ot=dd({doc:Z,results:lt,pageSize:Y,maxTokens:Tn}),St=Math.max(1,Ot.length),ht=Math.min(V,Math.max(0,St-1)),$t=Ot[ht]??{results:[],startResultIndex:0,endResultIndexExclusive:0},At=$t.startResultIndex,Rt=$t.endResultIndexExclusive,jt=$t.results,te=jt.map(Ht=>Ht.blockId),fe=nt||te.length===0?null:s(te);r.toolState.lastSearchState={toolName:"search_document",requestKey:tt,allResults:lt,currentPage:ht,totalPages:St,...pt?{resultSetId:pt}:{}};let Kt;lt.length===0?Kt=`No matches found${nt?` in "${nt.title}"`:""} for: ${ot.join(", ")}`:(Kt=`Found ${lt.length} matching blocks${nt?` in "${nt.title}"`:""}. Showing page ${ht+1}/${St} (results ${At+1}-${Rt} of ${lt.length}).`,!nt&&pt&&(Kt+=` The full unpaginated result set is saved as ${pt}; pass search_result_id="${pt}" to replace, replace_block, style_blocks, or remove_blocks to target all ${lt.length} matches in one call.`),ht<St-1&&nt&&(Kt+=nt?` Call search_document with document_id="${nt.id}" and page=${ht+1} to see next page.`:` Call search_document with page=${ht+1} to see next page.`));const uo=fe?.code==="no_new_read_context";if(fe&&!uo){if(lt.length>0){let Ht=`Found ${lt.length} matching blocks. Showing page ${ht+1}/${St} (blocks ${At+1}-${Rt} of ${lt.length}). Matching blocks could not be loaded this turn.`;return ht<St-1&&(Ht+=` Call search_document with page=${ht+1} to see next page.`),K(S,`${fe.message} ${Ht}`,fe.code)}return K(S,`${fe.message} ${Kt}`,fe.code)}if(uo&&lt.length>0&&(Kt+=" Matching block content is already available in this request's cached context."),nt){i(Z,te,nt.id);const Ht=it.extractSpecificBlocks(Z,te,void 0,on),go=it.formatSpecificBlocks(Ht),xr=JSON.stringify({kind:"document_search_context",tool:"search_document",document:{documentId:nt.id,title:nt.title,canonicalPath:nt.canonicalPath||`/${nt.title}`,href:`/docs/${nt.id}`,...bs(nt.id)},queries:ot,totalMatches:lt.length,page:{current:ht,total:St,startResult:At+1,endResult:Rt},nextPage:ht<St-1?ht+1:null,matches:jt.map(wr=>({blockId:wr.blockId,blockIndex:wr.blockIndex,matchedQueries:wr.matchedQueries??[]})),documentContent:go});return e.count("agent.read.search_call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",te.length,void 0,{tool_name:I}),Mt(S,Kt,void 0,void 0,xr)}r.turnState.documentRequested=!0,e.count("agent.read.search_call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",te.length,void 0,{tool_name:I});const me=gd({tool:"search_document",queries:ot,totalMatches:lt.length,currentPage:ht,totalPages:St,pageStart:At,pageEnd:Rt,pageResults:jt,nextPage:ht<St-1?ht+1:null,...pt?{searchResultId:pt}:{},coverage:ao(r,r.getLatestDocument())});return Mt(S,Kt,void 0,void 0,me)}if(I==="list_documents"){const E=S.arguments||{},U=typeof E.parent_folder_id=="string"&&E.parent_folder_id.trim().length>0?E.parent_folder_id.trim():null,X=so(E.page,0),ot=Cn(r);if(!ot)return K(S,"Document tree listing is only available for signed-in documents.");try{const V=await iy({token:ot,parentFolderId:U,page:X,limit:50}),st=V.hasMore?` Call list_documents with page=${X+1} for more.`:"",nt=V.items.filter(lt=>lt.itemType==="folder").length,Z=V.items.length-nt,Y=V.totalCount===0?`No items found in ${U?"that folder":"the account root"}.`:`Listed ${V.items.length} of ${V.totalCount} items in ${U?"the folder":"the account root"} (${nt} folders, ${Z} documents).${st}`,tt=ay({parentFolderId:U,page:X,totalCount:V.totalCount,totalPages:Math.max(1,V.totalPages),hasMore:V.hasMore,items:V.items});return e.count("agent.read.document_tree_list",1,{tool_name:I}),Mt(S,Y,void 0,void 0,tt)}catch(V){return K(S,V instanceof Error?V.message:"Document listing failed.")}}if(I==="search_documents"){const E=S.arguments||{},U=typeof E.query=="string"?E.query.trim():"";if(!U)return K(S,"search_documents requires a query.");const X=Cn(r);if(!X)return K(S,"Cross-document search is only available for signed-in documents.");const ot=oy(E.scope),V=r.getCurrentFolderId?.()??null,st=typeof E.folder_id=="string"&&E.folder_id.trim().length>0?E.folder_id.trim():null,nt=ot==="current_folder"&&!V||ot==="folder"&&!st?"account":ot,Z=so(E.page,0);try{const Y=await ry({token:X,query:U,scope:nt,page:Z,currentFolderId:V,folderId:st}),tt=nt==="current_folder"&&!!V,lt=nt==="folder"&&st?"the selected folder tree":tt?"the current folder tree":"the account",pt=Z+1<Y.totalPages?` Call search_documents with page=${Z+1} for more.`:"",Ot=Y.totalCount===0?`No documents found for "${U}" in ${lt}.`:`Found ${Y.totalCount} documents for "${U}" in ${lt}. Showing page ${Z+1}/${Math.max(1,Y.totalPages)}.${pt}`,St=sy({query:U,scope:nt,searchedCurrentFolder:tt,folderId:nt==="folder"?st:null,page:Z,totalCount:Y.totalCount,totalPages:Math.max(1,Y.totalPages),results:Y.items});return e.count("agent.read.account_search_call",1,{tool_name:I}),Mt(S,Ot,void 0,void 0,St)}catch(Y){return K(S,Y instanceof Error?Y.message:"Document search failed.")}}if(I==="find_highlights"){const E=S.arguments||{},U=typeof E.color=="string"&&E.color.trim().length>0?E.color.trim().toLowerCase():void 0,X=typeof E.page=="number"?E.page:0,ot=r.getLatestDocument(),V=r.searchPageSize,st=fd("find_highlights",E);let nt;X>0&&r.toolState.lastSearchState&&r.toolState.lastSearchState.toolName==="find_highlights"&&r.toolState.lastSearchState.requestKey===st?nt=r.toolState.lastSearchState.allResults:nt=it.findHighlights(ot,U);const Z=dd({doc:ot,results:nt,pageSize:V,maxTokens:Tn}),Y=Math.max(1,Z.length),tt=Math.min(X,Math.max(0,Y-1)),lt=Z[tt]??{results:[],startResultIndex:0,endResultIndexExclusive:0},pt=lt.startResultIndex,Ot=lt.endResultIndexExclusive,St=lt.results,ht=St.map(Kt=>Kt.blockId),$t=ht.length===0?null:s(ht);r.toolState.lastSearchState={toolName:"find_highlights",requestKey:st,allResults:nt,currentPage:tt,totalPages:Y};const At=U?`${U} highlight`:"highlighted content",Rt=U||nt.length===0?"":` Colors: ${cy(nt)}.`;let jt;nt.length===0?jt=`No blocks found with ${At}.`:(jt=`Found ${nt.length} blocks with ${At}. Showing page ${tt+1}/${Y} (results ${pt+1}-${Ot} of ${nt.length}).${Rt}`,tt<Y-1&&(jt+=` Call find_highlights with page=${tt+1} to see next page.`));const te=$t?.code==="no_new_read_context";if($t&&!te){if(nt.length>0){let Kt=`Found ${nt.length} blocks with ${At}. Showing page ${tt+1}/${Y} (blocks ${pt+1}-${Ot} of ${nt.length}). Matching blocks could not be loaded this turn.`;return tt<Y-1&&(Kt+=` Call find_highlights with page=${tt+1} to see next page.`),K(S,`${$t.message} ${Kt}`,$t.code)}return K(S,`${$t.message} ${jt}`,$t.code)}te&&nt.length>0&&(jt+=" Matching block content is already available in this request's cached context."),r.turnState.documentRequested=!0,e.count("agent.read.search_call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",ht.length,void 0,{tool_name:I});const fe=gd({tool:"find_highlights",color:U??null,totalMatches:nt.length,currentPage:tt,totalPages:Y,pageStart:pt,pageEnd:Ot,pageResults:St,nextPage:tt<Y-1?tt+1:null,coverage:ao(r,r.getLatestDocument())});return Mt(S,jt,void 0,void 0,fe)}if(I==="read_specific_blocks"){const E=S.arguments||{},U=Pe(E,r),X=E.block_ids,ot=Array.isArray(X)?X.filter(At=>typeof At=="string"&&At.length>0):typeof X=="string"&&X.length>0?[X]:[];if(ot.length===0)return K(S,"No block IDs provided");const V=U?Cn(r):"";if(U&&!V&&!r.loadRemoteDocument)return K(S,"Cross-document access is only available for signed-in documents.");let st=null;try{st=U?await(r.loadRemoteDocument?.(U)??vr({token:V,documentId:U})):null}catch(At){return K(S,At instanceof Error?At.message:"Document read failed.")}const nt=st?.content??r.getLatestDocument(),{blockIds:Z,estimatedTokens:Y,reachedTokenBudget:tt,missingRequestedBlocks:lt}=ny({doc:nt,requestedBlockIds:ot,maxTokens:Tn});if(Z.length===0)return lt>0?K(S,"None of the requested block IDs were found in the document.",je):K(S,"No readable blocks could be loaded.");if(st){i(nt,Z,st.id);const At=it.extractSpecificBlocks(nt,Z,void 0,on),Rt=it.formatSpecificBlocks(At),jt=ms(nt,new Set(Z)),te=JSON.stringify({kind:"document_read",tool:I,document:{documentId:st.id,title:st.title,canonicalPath:st.canonicalPath||`/${st.title}`,href:`/docs/${st.id}`,...bs(st.id)},loaded:{count:Z.length,blockIds:Z,blockIndices:jt,estimatedTokens:Y},reachedTokenBudget:tt,documentContent:Rt});return e.count("agent.read.call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",Z.length,void 0,{tool_name:I}),Mt(S,`Read ${Z.length} specific blocks from "${st.title}". Estimated tokens: ~${Y}.${tt?" Reached per-call token budget.":""}`,void 0,void 0,te)}const pt=s(Z);if(pt)return K(S,pt.message,pt.code);r.turnState.documentRequested=!0,e.count("agent.read.call",1,{tool_name:I}),e.distribution("agent.read.blocks_loaded",Z.length,void 0,{tool_name:I}),e.distribution("agent.read.tokens_loaded_estimate",Y,void 0,{tool_name:I}),tt&&e.count("agent.read.token_budget_reached",1,{tool_name:I});const Ot=ms(nt,new Set(Z)),St=co({tool:I,loaded:{count:Z.length,requestedCount:ot.length,estimatedTokens:Y,ranges:ud(Ot)},endOfDocument:!1,coverage:ao(r,nt)}),ht=tt?` Reached per-call token budget; loaded ${Z.length}/${ot.length} requested blocks.`:"",$t=lt>0?` ${lt} requested block IDs were not found.`:"";return Mt(S,`Loaded ${Z.length} specific blocks.${ht}${$t} Estimated tokens: ~${Y}.`,void 0,void 0,St)}if(I==="get_attachment"){const E=(S.arguments||{}).attachment_id;if(!E)return K(S,"No attachment_id provided");let U=r.getAllAttachments().get(E);return U||(U=await t(E),U&&r.getAllAttachments().set(E,U)),U?U.content?.trim()??""?Mt(S,`Loaded attachment "${U.id}" (${U.charCount} chars).`,void 0,void 0,`<attachment id="${U.id}" type="${U.type}"${U.fileName?` filename="${U.fileName}"`:""} chars="${U.charCount}">
35
- ${U.content}
36
- </attachment>`):Mt(S,`Attachment "${U.id}" has no text content to retrieve; it is a hosted file already visible in the conversation history.`):K(S,`Attachment "${E}" not found. Available attachments: ${Array.from(r.getAllAttachments().keys()).join(", ")||"none"}`)}if(I==="view_image"){const E=(S.arguments||{}).block_id;if(!E)return K(S,"No block_id provided");const U=r.getLatestDocument(),X=od(U.children,E);if(!X)return K(S,`Image block "${E}" not found in document`,je);const ot={id:`view_image_${E}`,type:"image",content:"",preview:"",charCount:0,fileName:X.alt||`image_${E}`,urls:[X.src],dimensions:[{width:X.width,height:X.height}]};return Mt(S,`Image retrieved: ${X.alt?`"${X.alt}" `:""}(${X.width}x${X.height}px)${X.sourceUrl?` Source: ${X.sourceUrl}`:""}`,ot)}if(I==="render_document_pages"){if(!r.renderDocumentPages)return K(S,"Rendered page inspection is unavailable until the document canvas is ready.");const E=S.arguments||{},U=so(E.start_page,1),X=so(E.page_count,1),ot=E.mode==="layout"?"layout":"appearance";let V=E.quality==="compact"?"compact":"detailed";if(U<1)return K(S,"start_page must be 1 or greater.");const st=V==="detailed"&&X>2;st&&X<=4&&(V="compact");const nt=V==="compact"?4:2;if(X<1||X>nt)return K(S,`page_count must be between 1 and ${nt} for ${V} quality.`);try{const Z=await r.renderDocumentPages({startPage:U,pageCount:X,mode:ot,quality:V});if(Z.placeholderImageCount||Z.failedImageCount||Z.mathPlaceholderCount)return{...K(S,`Visual inspection is incomplete: ${Z.placeholderImageCount} image placeholders, ${Z.failedImageCount} failed images, and ${Z.mathPlaceholderCount} formula placeholders. Resolve the unavailable resources before a retry: allow pending resources to finish loading, re-upload broken images, or correct unsupported formulas. Repeating this call without fixing them will not verify the document.`,"visual_resource_unavailable"),failure:{code:"visual_resource_unavailable",phase:"verification",retryable:!1,mutationOutcome:"unchanged"}};const Y=Z.pages.length===1?`page ${Z.pages[0]}`:`pages ${Z.pages[0]}-${Z.pages[Z.pages.length-1]}`,tt={id:`render_document_pages_${S.id}`,type:"image",content:"",preview:"",charCount:0,fileName:`Rendered document ${Y} (${ot}, ${V})`,mimeType:Z.dataUrl.startsWith("data:image/png")?"image/png":"image/jpeg",urls:[Z.dataUrl],dimensions:[{width:Z.width,height:Z.height}],visionDetail:V==="compact"?"low":"high"};return Mt(S,`Rendered ${Y} of ${Z.totalPages} in ${ot} mode at ${V} quality.${st?" The request was downgraded from detailed to compact quality so all requested pages fit in one bounded render.":""}`,tt,void 0,JSON.stringify({pages:Z.pages,totalPages:Z.totalPages,mode:ot,quality:V,placeholderImageCount:Z.placeholderImageCount,failedImageCount:Z.failedImageCount,mathPlaceholderCount:Z.mathPlaceholderCount}))}catch(Z){return K(S,Z instanceof Error?Z.message:"Document page rendering failed.",Z instanceof Error&&"code"in Z?String(Z.code):void 0)}}if(I==="set_status"){const E=Jb(S.arguments);return r.toolState.statusMessage=E,r.markConversationDirty(),r.notifyListeners(),Mt(S,E?`Status set to "${E}".`:"Status updated.")}if(I==="request_user_input"){const E=S.arguments??{},U=typeof E.chat_response=="string"?E.chat_response.trim():"";return!U||nd(U)?K(S,"request_user_input requires a concrete user-facing question, not only a status update.",ed):!Array.isArray(E.suggested_next_prompts)&&!Array.isArray(E.followups)?K(S,"request_user_input requires suggested_next_prompts as an array."):Mt(S,"User input requested.")}if(I===Eb)return!r.skipSameTurnCompletionGuard&&l>0?K(S,`${I} cannot be used in the same tool batch as document edits. Inspect the successful mutation results on the next turn, then call end_agent_run if the request is complete.`,td):Mt(S,"Legacy completion handoff acknowledged. Call end_agent_run on the next turn.");if(Db(I)){if(!r.skipSameTurnCompletionGuard&&l>0)return K(S,`${I} cannot be used in the same tool batch as document edits. Inspect the successful mutation results on the next turn, then continue concrete work or call end_agent_run if the request is complete.`,td);const E=S.arguments??{},U=typeof E.chat_response=="string"?E.chat_response.trim():"";return U?nd(U)?K(S,`${I} requires a final user-facing response, not only a status update.`,ed):!Array.isArray(E.suggested_next_prompts)&&!Array.isArray(E.followups)?K(S,`${I} requires suggested_next_prompts as an array.`):Mt(S,"Final response recorded."):K(S,`${I} requires a non-empty chat_response.`)}const B=await g();if(!B)return p(S);const P=r.getLatestDocument();if(I==="rollback_agent_suggestions"){const E=S.arguments??{},U=E.request_id==null?void 0:E.request_id,X=E.turn==null?void 0:E.turn;if(U!==void 0&&(!Number.isInteger(U)||Number(U)<1))return K(S,"request_id must be a positive integer.");if(X!==void 0&&(!Number.isInteger(X)||Number(X)<1))return K(S,"turn must be a positive integer.");if(X!==void 0&&U===void 0)return K(S,"turn requires request_id.");const ot=r.turnState.currentRequestId??0,V=r.turnState.currentTurn??0;if(U!==void 0&&Number(U)>ot)return K(S,`request_id ${U} is in the future; the current request is ${ot}.`);const st=r.getConversationId?.().trim()??"";if(!st)return K(S,"This conversation has no stable ID, so its suggestions cannot be rolled back safely.");const nt=B.getDocumentWithPendingSuggestionsApplied(),Z=B.rollbackAgentSuggestions({agentConversationId:st,requestId:U===void 0?void 0:Number(U),turn:X===void 0?void 0:Number(X),currentRequestId:ot,currentTurn:V});if(Z.resolvedCount===0){const pt=Z.requestId===void 0?"any prior request":`request ${Z.requestId}${Z.turn===void 0?"":` turn ${Z.turn}`}`;return Mt(S,`No still-pending suggestions from this conversation matched ${pt}. Accepted edits and other authors' work were left untouched. Recover omitted text from historical_edit_evidence or earlier before_block snapshots, then propose a targeted correction against the current document while preserving later edits. Searching the current document cannot recover text that was deleted.`,void 0,!0)}const Y=B.getDocumentWithPendingSuggestionsApplied(),tt=new Map(nt.children.map(pt=>[pt.id,pt])),lt=new Map(Y.children.map(pt=>[pt.id,pt]));for(const pt of new Set([...tt.keys(),...lt.keys()]))JSON.stringify(tt.get(pt))!==JSON.stringify(lt.get(pt))&&r.toolState.editedBlockIds.add(pt);return r.turnState.hasMutatedSinceLastRead=!0,l+=1,r.markConversationDirty(),r.notifyListeners(),Mt(S,`Rolled back ${Z.resolvedCount} pending suggestion${Z.resolvedCount===1?"":"s"} ${Z.turn===void 0?`to before request ${Z.requestId}`:`from request ${Z.requestId} turn ${Z.turn}`}. The rollback is one user-undoable history item. Now make the corrected edits; do not ask the user to reject the old suggestions.`)}if(I==="leave_comment"){const E=Xb(S,r,B,P);return E.success&&(l+=1),E}if((I==="insert_block"||I==="insert_table_row"||I==="insert_table_column")&&S.arguments?.position!=="before"&&S.arguments?.position!=="after")return K(S,`${I} has invalid "position" ${JSON.stringify(S.arguments?.position??null)}; use "before" or "after".`);if(I==="set_header_footer"&&S.arguments?.side!=="header"&&S.arguments?.side!=="footer")return K(S,`set_header_footer has invalid "side" ${JSON.stringify(S.arguments?.side??null)}; use "header" or "footer".`);const $=sd(r.turnState),T=Fm({toolCall:S,docBefore:P,isTargetAllowed:E=>md(P,E,$)});if(T?.error)return K(S,T.error,T.errorCode);const C=T?.toolCall??S,N=new Set($??[]);for(const E of T?.targetBlockIds??[])N.add(E);const L=mg({toolCall:C,docBefore:P,resultSets:d});if(L?.error)return K(S,L.error,L.errorCode);const R=uy(C,P,N);if(R.error)return K(S,R.error,gs);const M=R.toolCall;if(M.name==="replace"&&M.arguments&&Array.isArray(M.arguments.replacements)&&Object.prototype.hasOwnProperty.call(M.arguments,"comment"))return K(M,'replace comment belongs on each operation inside "replacements", alongside find, replace, and occurrence.');const F=new Set(P.children.map(E=>E.id)),j=new Set($??[]);for(const E of T?.targetBlockIds??[])j.add(E);for(const E of L?.targetBlockIds??[])j.add(E);const D=Em(M,P,E=>md(P,E,j));if(D.error)return K(M,D.error,D.error.includes("request-level document context")?gs:void 0);const O=L?{actions:L.actions,blockId:void 0,error:void 0}:M.name==="remove_block"&&Array.isArray(M.arguments?.ids)?{actions:D.actions,blockId:void 0,error:void 0}:ni(M,{doc:P,loadedBlockIds:j});if(O.error){const E="failure"in O?O.failure:void 0;return{...K(M,O.error,E?.code),failure:E}}if(O.actions.length===0)return Mt(M,`${rd(M)} Continue with the remaining work; do not repeat this unchanged operation.`,void 0,!0);const H=cg({actions:O.actions,doc:P,loadedBlockIds:j}),q=H.actions,W=Array.from(new Set([...L?.targetBlockIds??[],...T?.targetBlockIds??[],...Gb(q)])),ct=["insert_table_row","remove_table_row","insert_table_column","remove_table_column"].includes(M.name),vt=new Map;if((M.name==="replace_block"||M.name==="remove_block"||ct)&&r.turnState.promptBlockContentHashes)for(const E of ad(P,W)){const U=r.turnState.promptBlockContentHashes.get(E);U&&vt.set(E,U)}const Dt=E=>{for(const[U,X]of vt){const ot=Dn(E,U);if(ot!==null&&ot!==X)return K(M,`Block '${U}' was edited (likely by the user) after you last read it. Re-read the block and re-apply your change against its current content.`,je)}},Qt=Dt(P);if(Qt)return Qt;const Vt=M.id||`tool-${Date.now()}`,G=await(r.rehostImages??Zm)(q);if(G.failedUrls.length>0){const E=G.failedUrls.length===1?"1 external image":`${G.failedUrls.length} external images`,U=G.failures.some(V=>V.status===429),X=G.failures.length===1?G.failures[0]:void 0,ot=X?` Reason: ${X.message}${X.status?` (HTTP ${X.status})`:""}.`:"";return K(M,`${E} could not be copied into Revise storage, so no document changes were applied.${ot} ${U?"Do not attempt more external image insertions in this request. Keep any earlier successful changes and tell the user which image remains incomplete.":"Do not retry this URL. Use a different verified direct raster image URL or upload the image before trying again."}`,G.unavailable?"agent_tool_not_allowed":void 0)}const gt=r.getLatestDocument(),yt=Dt(gt);if(yt)return yt;let Q;const wt=M.name==="remove_block"?[...new Set(q.map(E=>typeof E.arguments?.id=="string"?gn(P,E.arguments.id):null).filter(E=>E!==null))]:[];if(wt.length>0&&q.some(E=>E.arguments?.count!=null&&E.arguments.count!==1||typeof E.arguments?.id!="string"||!gn(P,E.arguments.id)))return K(M,"To remove footnotes/endnotes, pass their exact note IDs in ids, or one note ID with count 1. Remove main-document blocks separately.");for(const E of q){if(E.name!=="replace_block")continue;const U=gt.notes?.find(X=>X.id===E.arguments?.id);if(U&&Qr(gt,U.id)===U.id)return K(M,`Note '${U.id}' contains multiple body blocks or no single editable text block. Use replace_block with an exact body block ID (${U.children.map(X=>X.id).join(", ")}) instead of replacing the note wrapper.`)}if(wt.length>0){const E=B.getDocumentMutator(),U=new Set(E.getLiveSuggestionIds()),X=E.suggestingMode;E.suggestingMode=!0;let ot=!1;try{const{result:st}=E.withSuggestionMetadata({source:"agent",authorType:"ai",agentName:An(r),...r.getAgentModel?{agentModel:r.getAgentModel()}:{},agentConversationId:r.getConversationId?.(),agentRequestId:r.turnState.currentRequestId,agentTurn:r.turnState.currentTurn,commentThreadId:r.commentThreadId,historyOrigin:`live-suggestions:${Vt}`},()=>wt.every(nt=>E.removeFootnote(nt)));ot=st}finally{E.suggestingMode=X}const V=E.getLiveSuggestionIds().filter(st=>!U.has(st));Q=ot?{success:!0,suggestionIds:V,agentFeedback:`Removed footnote/endnote blocks ${wt.join(", ")} and their inline references.`}:{success:!1,error:`Footnote/endnote blocks '${wt.join(", ")}' could not be removed.`}}else Q=B.applyAgentActions({message:"AI Assistant",actions:q.map(E=>{if((E.name==="replace"||E.name==="replace_all"||E.name==="replace_block")&&typeof E.arguments?.id=="string"){const U=Qr(gt,E.arguments.id);if(U&&U!==E.arguments.id)return{...E,arguments:{...E.arguments,id:U}}}return E}),agentName:An(r),agentModel:r.getAgentModel?.(),agentConversationId:r.getConversationId?.(),agentRequestId:r.turnState.currentRequestId,agentTurn:r.turnState.currentTurn,commentThreadId:r.commentThreadId},Vt,{optimizeStyleFormatting:r.getOptimizeStyleFormatting?.()??!1});if(Q.resultCode==="already_satisfied")return Mt(M,Q.styleEffects&&Q.agentFeedback?Q.agentFeedback:"Verified that the requested state is already satisfied; no document mutation occurred. "+rd(M),void 0,!0,JSON.stringify({code:"already_satisfied",mutationOutcome:"unchanged",...Q.styleEffects?JSON.parse(cd(M,P,P,Q.styleEffects.targetBlockIds,Q.agentFeedback,Q.styleEffects)):{}}));if(Q.success!==!1&&Q.styleEffects){const E=new Set([...Q.styleEffects.changedBlockIds,...Q.styleEffects.affectedBlockIds]);E.size<=rn&&W.splice(0,W.length,...E)}const ft=Q.success!==!1;let dt=Q.agentFeedback,Pt;if(ft&&L?.resultSet){const E=L.resultSet,U=`Applied ${M.name} to all ${E.blockIds.length} blocks in ${E.id}.`;dt=dt?.includes(U)?dt:dt?`${U}
37
- ${dt}`:U}if(ft&&(M.name==="replace_many"||M.name==="replace"&&Array.isArray(M.arguments?.replacements))){const E=q.length,U=Zb(W,O.blockId),X=`Applied ${E} replacement ${E===1?"operation":"operations"} in ${U}.`;dt=dt?.includes(X)?dt:dt?`${X}
38
- ${dt}`:X}if(ft&&R.feedback&&(dt=dt?`${dt}
39
- ${R.feedback}`:R.feedback),ft&&H.retargets.length>0){const E=Qb(H.retargets);E&&(dt=dt?`${dt}
40
- ${E}`:E)}if(ft&&((Q.commentedSuggestionIds?.length??0)>0||(Q.commentAttachmentFailureCount??0)>0)){const E=Q.attachedCommentIds??[],U=Q.commentAttachmentFailureCount??0,X=E.length>0?`Attached ${E.length===1?"comment":`${E.length} separate comments`} to the resulting ${E.length===1?"suggestion":"suggestions"} (${E.join(", ")}).${U>0?` ${U} requested ${U===1?"comment":"comments"} could not be anchored; do not repeat the edits.`:""}`:"The edits were suggested, but their requested comments could not be anchored. Do not repeat the edits; use leave_comment on the affected text instead.";dt=dt?`${dt}
41
- ${X}`:X}if(ft){const E=dy(M,P);E&&(dt=dt?`${dt}
42
- ${E}`:E)}if(r.toolState.directMode&&ft){const E=new Set(Q.commentedSuggestionIds??[]),U=(Q.suggestionIds??[]).filter(X=>!E.has(X));if(U.length>0&&B.acceptLiveSuggestions(U),U.length>0&&E.size===0){const X=B.getDocumentMutator();X?.resetToolCallHistory&&X.resetToolCallHistory()}}if(ft){r.mutationTools.includes(I)&&(l+=1);const E=B.getDocumentWithPendingSuggestionsApplied();if(L?.resultSet&&(L.resultSet.blockHashes=ei(E,L.resultSet.blockIds)),Pt=cd(M,P,E,W,dt,Q.styleEffects),r.turnState.hasMutatedSinceLastRead=!0,r.mutationTools.includes(I)&&I!=="set_title"&&I!=="set_notes"&&I!=="set_page_layout"){if(!L)for(const U of W)r.toolState.editedBlockIds.add(U);if(!L)for(const U of E.children)U.id&&!F.has(U.id)&&r.toolState.editedBlockIds.add(U.id);if(r.turnState.promptBlockContentHashes){const U=ad(gt,W);for(const X of U){const ot=r.turnState.promptBlockContentHashes.get(X);if(ot&&Dn(gt,X)!==ot||!ot&&!W.includes(X))continue;const V=Dn(E,X);V!==null?r.turnState.promptBlockContentHashes.set(X,V):r.turnState.promptBlockContentHashes.delete(X)}}L||hy(r)}}const Et=Hb(Q.error);return{toolCall:M,success:ft,error:Q.error,failure:Q.failure,...Q.failure?{errorCode:Q.failure.code}:{},...!ft&&Et?{errorCode:Et}:{},documentStateAfter:B.getDocumentWithPendingSuggestionsApplied(),agentFeedback:dt,...Pt?{toolOutput:Pt}:{}}}}function my(r,t){return r.success?{ok:!0,value:{callId:r.toolCallId,tool:r.name,message:r.agentFeedback??null,data:r.output??null,context:r.documentContent?{format:"revise-html",html:r.documentContent}:null,suggestionIds:t}}:{ok:!1,error:{callId:r.toolCallId,tool:r.name,code:r.errorCode??"tool_failed",message:r.error??r.agentFeedback??`${r.name} failed.`}}}function by(r){if(r)try{return JSON.parse(r)}catch{return r}}class yy{constructor(t){this.options=t,this.toolState={editedBlockIds:new Set,hasImportedAttachment:!1,everReadFullDocument:!1,lastSearchState:null,statusMessage:null,directMode:!1,directModeForced:!1},this.turnState={currentTurn:0,requestedBlockIds:null,readBudgetBlockIds:null,lastReadBlockIds:null,promptBlockContentHashes:new Map,documentRequested:!1,hasMutatedSinceLastRead:!1},this.deliveredBlockIds=[],this.handler=null}async run(t,e={}){this.turnState.currentTurn+=1,this.deliveredBlockIds=[];const n=this.handler??(this.handler=this.createHandler()),o=this.toolState.directMode,i=this.toolState.directModeForced;e.directMode!==void 0&&(this.toolState.directMode=e.directMode,this.toolState.directModeForced=!0);try{return await n(t)}finally{this.toolState.directMode=o,this.toolState.directModeForced=i}}buildResult(t,e,n){const o=n.success&&this.deliveredBlockIds.length>0?it.formatSpecificBlocks(it.extractSpecificBlocks(this.options.getDocumentSession().getDocumentWithPendingSuggestionsApplied(),this.deliveredBlockIds)):void 0;return{toolCallId:t,name:e,success:n.success,...n.error?{error:n.error}:{},...n.errorCode?{errorCode:n.errorCode}:{},...n.agentFeedback?{agentFeedback:n.agentFeedback}:{},...n.toolOutput?{output:by(n.toolOutput)}:{},...o?{documentContent:o}:{}}}createHandler(){return fy({toolState:this.toolState,turnState:this.turnState,getAllAttachments:()=>new Map,getFlaggedAttachmentIds:()=>new Set,getLatestDocument:()=>this.options.getDocumentSession().getDocumentWithPendingSuggestionsApplied(),getDocumentSession:()=>this.options.getDocumentSession(),markConversationDirty:()=>{},notifyListeners:()=>{},tryAddRequestedBlocks:t=>{const e=this.turnState.requestedBlockIds??new Set,n=this.turnState.readBudgetBlockIds??new Set;for(const i of t)e.add(i),n.add(i);this.turnState.requestedBlockIds=e,this.turnState.readBudgetBlockIds=n,this.turnState.lastReadBlockIds=new Set(t);const o=this.options.getDocumentSession().getDocumentWithPendingSuggestionsApplied();for(const[i,s]of ei(o,t))this.turnState.promptBlockContentHashes.set(i,s);return this.deliveredBlockIds=[...t],null},mutationTools:[...this.options.mutationTools],searchPageSize:this.options.searchPageSize??25,getAgentAuthorName:()=>this.options.getAgentName?.()})}}const bd=new Set(["get_selection","view_image"]),ky=new Set(["remove_block"]),Sy=["document_id","search_documents",...bd];function Iy(r){const t=structuredClone(r),e=t.properties;return delete e?.document_id,Array.isArray(t.required)&&(t.required=t.required.filter(n=>n!=="document_id")),t}function vy(r){return r.split(/(?<=\.)\s+/).filter(t=>!Sy.some(e=>t.includes(e))).join(" ")}const yd=Pl.filter(r=>!bd.has(r.name)).map(r=>({name:r.name,description:vy(r.description),inputSchema:Iy(r.inputSchema)}));function xy(r,t){if(!t.documentId.trim())throw new Error("Revise: documentId is required for a server session.");const e=new ks(t.documentId,r,void 0,{disableHistory:!0,disableProposalPersistence:!0}),n=new Set(ls);let o=t.mode??"suggesting";e.setSuggestingMode(o==="suggesting");const i=new yy({getDocumentSession:()=>e,mutationTools:Array.from(ls),searchPageSize:t.searchPageSize});let s=1,a=!1,c=Promise.resolve();const l=()=>{if(a)throw new Error("Revise: server document session is disposed.")},d=(m,y,b,k)=>({ok:!1,error:{callId:m,tool:y,code:b,message:k}}),u=async(m,y,b,k)=>{l();const v=`server-tool-${s++}`;if(!yd.some(I=>I.name===m)&&!ky.has(m))return d(v,m,"unknown_tool",`Unknown or unavailable server document tool: ${m}`);if("document_id"in y)return d(v,m,"document_id_not_supported","document_id is not accepted: a server document session is bound to one document. Omit it and retry.");await cu(),l(),e.setSuggestingMode(k==="suggesting");const S=n.has(m)?new Set(e.getDocumentMutator().getLiveSuggestionIds()):null;try{const I=await i.run({id:v,name:m,arguments:y},{directMode:b.directMode??k==="editing"}),w=i.buildResult(v,m,I);return my(w,S?e.getDocumentMutator().getLiveSuggestionIds().filter(A=>!S.has(A)):null)}catch(I){return d(v,m,"internal_error",I instanceof Error?I.message:String(I))}finally{e.setSuggestingMode(o==="suggesting")}},g=(m,y,b)=>{const k=o,v=c.then(()=>u(m,y,b,k));return c=v.then(()=>{},()=>{}),v},p={getDefinitions:()=>(l(),yd.map(m=>({...m,inputSchema:structuredClone(m.inputSchema)}))),execute:(m,...y)=>{const[b={},k={}]=y;return g(m,b,k)},executeDynamic:(m,y={},b={})=>g(m,y,b),call:async(m,...y)=>{const[b={},k={}]=y,v=await g(m,b,k);if(!v.ok)throw new au(v.error);return v.value}},h=()=>{l();const m=e.getDocumentMutator();return m.getLiveSuggestionIds().map(y=>{const b=m.getLiveSuggestion(y),k=m.getInlineSuggestionMetadataFromDocument(y),v=b&&"blockId"in b?b.blockId:b?.type==="paragraph-merge"?b.firstBlockId:void 0,S={id:y,...b?.type?{type:b.type}:{},...v?{blockId:v}:{},...b?.type==="table-change"?{tableId:b.tableId}:{}};for(const I of["authorType","agentName","agentModel","source","label","createdAt"]){const w=k?.[I]??b?.[I];w!==void 0&&Object.assign(S,{[I]:w})}return S})},f=(m,y)=>{l();const b=Array.from(new Set(y.filter(A=>typeof A=="string"&&A.trim().length>0))),k=e.getDocumentMutator(),v=new Set(k.getLiveSuggestionIds()),S=b.filter(A=>!v.has(A)),I=b.filter(A=>v.has(A));I.length>0&&(m==="accept"?e.acceptLiveSuggestions(I):e.rejectLiveSuggestions(I));const w=new Set(k.getLiveSuggestionIds());return{resolved:I.filter(A=>!w.has(A)),missing:S,unresolved:I.filter(A=>w.has(A))}};return{getMode:()=>(l(),o),setSuggestingMode:()=>{l(),o="suggesting"},setEditingMode:()=>{l(),o="editing"},tools:p,getPendingSuggestionIds:()=>(l(),e.getDocumentMutator().getLiveSuggestionIds()),listSuggestions:h,acceptSuggestions:m=>f("accept",m),rejectSuggestions:m=>f("reject",m),acceptAllSuggestions:()=>(l(),f("accept",e.getDocumentMutator().getLiveSuggestionIds())),rejectAllSuggestions:()=>(l(),f("reject",e.getDocumentMutator().getLiveSuggestionIds())),dispose:()=>{a||(a=!0,e.dispose())}}}export{xy as createServerDocumentSession};